refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,48 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Archiving;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies are files under the sequence's <c>proxies/</c> folder; a thumbnail is the JPEG byte range of its entry in
|
||||
/// <c>thumbs.pack</c>. A thumbnail made from a different original (the frame was renumbered or replaced) counts as not
|
||||
/// built yet, like a missing one (<see cref="ThumbPack.IsFrom"/>: one drawn before a verify hashed the photo is still its
|
||||
/// own), and so does a proxy whose capture time is another frame's, or one smaller than the archive's policy sent for a
|
||||
/// frame the server cannot decode (<see cref="ServerProxies.HasProxy"/>).
|
||||
/// </summary>
|
||||
internal sealed class ArchiveAssetLocator : IFrameAssetLocator
|
||||
{
|
||||
private const string Jpeg = "image/jpeg";
|
||||
|
||||
public ValueTask<AssetLocation?> LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken)
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath).Sequence(sequence.Folder);
|
||||
return ValueTask.FromResult(asset == FrameAsset.Proxy ? Proxy(archive, paths, frame) : Thumbnail(paths, frame));
|
||||
}
|
||||
|
||||
private static AssetLocation? Proxy(Archive archive, SequencePaths paths, Frame frame)
|
||||
{
|
||||
var file = new FileInfo(paths.Proxy(frame.Index));
|
||||
if (!file.Exists) return null;
|
||||
var own = ServerProxies.CannotDecode(frame.Format)
|
||||
? ServerProxies.HasProxy(paths, frame, ServerProxies.Spec(archive))
|
||||
: ArchiveImages.IsProxyOf(file.FullName, frame.CapturedAt, frame.Width, frame.Height, policy: null);
|
||||
return own ? new AssetLocation(file.FullName, 0, file.Length, Jpeg) : null;
|
||||
}
|
||||
|
||||
private static AssetLocation? Thumbnail(SequencePaths paths, Frame frame)
|
||||
{
|
||||
using var pack = ThumbPackReader.Open(paths.ThumbsPackPath);
|
||||
if (!pack.Entries.TryGetValue(frame.Index, out var entry) || entry.Offset + entry.Length > pack.Length) return null;
|
||||
if (frame.Sha256 is { Length: ThumbPack.HashLength * 2 } sha && !ThumbPack.IsFrom(entry.SourceHash, sha, SequenceFile(paths, frame), frame.Size)) return null;
|
||||
return new AssetLocation(paths.ThumbsPackPath, entry.Offset, entry.Length, Jpeg);
|
||||
}
|
||||
|
||||
/// <summary>The frame's file as its sidecar names it (relative to the sequence folder), which a thumbnail drawn before the photo was hashed is fingerprinted with.</summary>
|
||||
private static string SequenceFile(SequencePaths paths, Frame frame)
|
||||
{
|
||||
var prefix = paths.ArchiveRelative(string.Empty);
|
||||
return frame.RelativePath.StartsWith(prefix, StringComparison.Ordinal) ? frame.RelativePath[prefix.Length..] : frame.RelativePath;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
|
||||
/// thumbnails, its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance) and the periodic
|
||||
/// incremental scan (<see cref="ArchivePolling"/>); a scan queues thumbnails and proxies of what it indexes, as an upload
|
||||
/// does. Decoding is managed only (BRIEF §4.2). The daily backup of an SQLite index runs with it
|
||||
/// (<see cref="DatabaseBackupService"/>).
|
||||
/// </summary>
|
||||
public static class ArchiveModule
|
||||
{
|
||||
/// <summary>Name the server writes into the archive's lease files.</summary>
|
||||
public static string Owner { get; } = "server@" + Environment.MachineName;
|
||||
|
||||
public static void Register(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
// Photos the running job processes at once: the settings' value as it is when each sequence starts (owner review 1).
|
||||
return new ArchiveService(sp.GetRequiredService<ChronosDatabase>(),
|
||||
new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = Owner, ImagesAfterScan = true, Parallelism = () => options.Parallelism });
|
||||
});
|
||||
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
|
||||
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
|
||||
services.AddHostedService<DatabaseBackupService>();
|
||||
services.AddSingleton<ArchivePolling>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<ArchivePolling>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Archive-relative paths from the database → absolute paths, refusing anything that would leave the archive root
|
||||
/// (BRIEF §14.2: path traversal impossible). Clients never send paths; only ids that the database maps to these.
|
||||
/// </summary>
|
||||
public static class ArchivePathGuard
|
||||
{
|
||||
private static readonly StringComparison PathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
|
||||
|
||||
/// <summary>The absolute path of <paramref name="relative"/> under <paramref name="root"/>, or null when it escapes the root.</summary>
|
||||
public static string? Resolve(string root, string? relative)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(relative) || relative.Contains('\0', StringComparison.Ordinal)) return null;
|
||||
var portable = relative.Replace('\\', '/');
|
||||
if (Path.IsPathRooted(portable) || portable.StartsWith('/')) return null;
|
||||
string full;
|
||||
try
|
||||
{
|
||||
full = Path.GetFullPath(Path.Combine(Root(root), portable));
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return IsInside(root, full) ? full : null;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="path"/> lies strictly inside <paramref name="root"/>.</summary>
|
||||
public static bool IsInside(string root, string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
return full.StartsWith(Root(root) + Path.DirectorySeparatorChar, PathComparison);
|
||||
}
|
||||
|
||||
/// <summary>A file of the archive that may be served: inside the root, existing, and not a symbolic link.</summary>
|
||||
public static FileInfo? ExistingFile(string root, string? relative)
|
||||
{
|
||||
if (Resolve(root, relative) is not { } full) return null;
|
||||
var file = new FileInfo(full);
|
||||
return file.Exists && file.LinkTarget is null ? file : null;
|
||||
}
|
||||
|
||||
private static string Root(string root) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(root));
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Server.Jobs;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
|
||||
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
|
||||
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
|
||||
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
|
||||
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
|
||||
/// </summary>
|
||||
public sealed class ArchivePolling(ChronosDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
|
||||
ILogger<ArchivePolling> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
|
||||
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(10);
|
||||
|
||||
private static readonly JobState[] Pending = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
|
||||
/// <summary>Queues an incremental scan of an online archive unless one is pending; returns it, or null when none was queued.</summary>
|
||||
public async Task<Job?> PollAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (!jobs.CanRun(JobKind.Scan)) return null;
|
||||
var current = archive.Current;
|
||||
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
|
||||
current = await archive.RefreshAsync(archives, db, cancellationToken);
|
||||
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
|
||||
{
|
||||
foreach (var state in Pending)
|
||||
{
|
||||
if ((await db.Jobs.ListAsync(state, kind, 50, null, cancellationToken)).Items.Any(j => j.TargetIds.Contains(current.Id))) return null;
|
||||
}
|
||||
}
|
||||
var scan = ArchiveJobs.Scan(current);
|
||||
// Behind what users asked for (BRIEF §14.6).
|
||||
return await jobs.Engine.EnqueueAsync(scan.Kind, scan.Targets, scan.Label, scan.ParametersJson, JobPriority.Background,
|
||||
cancellationToken: cancellationToken);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "The archive could not be polled");
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using Chronos.Data;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The daily <c>VACUUM INTO</c> copy of the index of a Windows server on SQLite (BRIEF §6.2: nightly, kept ×3) into
|
||||
/// <c>{DataPath}/backups</c>. A server on PostgreSQL is backed up with PostgreSQL's own tools; this service then does nothing.
|
||||
/// </summary>
|
||||
public sealed class DatabaseBackupService(ChronosDatabase db, ServerOptions options, TimeProvider time, ILogger<DatabaseBackupService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>Folder of the copies.</summary>
|
||||
public string Directory => Path.Combine(options.DataPath, "backups");
|
||||
|
||||
protected override Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
if (db.Dialect != Dialect.Sqlite) return Task.CompletedTask;
|
||||
logger.LogInformation("Daily index backups go to {Directory}", Directory);
|
||||
return DatabaseBackups.RunDailyAsync(db, Directory, time, stoppingToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
using System.Collections.Frozen;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Streams archive files (originals, proxies, thumbnails, exports) with Range, If-Range and conditional GET support.</summary>
|
||||
public static class FileResponses
|
||||
{
|
||||
private static readonly FrozenDictionary<string, string> Types = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".jpg"] = "image/jpeg",
|
||||
[".jpeg"] = "image/jpeg",
|
||||
[".png"] = "image/png",
|
||||
[".gif"] = "image/gif",
|
||||
[".tif"] = "image/tiff",
|
||||
[".tiff"] = "image/tiff",
|
||||
[".dng"] = "image/x-adobe-dng",
|
||||
[".heic"] = "image/heic",
|
||||
[".heif"] = "image/heif",
|
||||
[".webp"] = "image/webp",
|
||||
[".avif"] = "image/avif",
|
||||
[".mp4"] = "video/mp4",
|
||||
[".mov"] = "video/quicktime",
|
||||
[".avi"] = "video/x-msvideo",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static string ContentTypeOf(string fileName) =>
|
||||
Types.TryGetValue(Path.GetExtension(fileName), out var type) ? type : "application/octet-stream";
|
||||
|
||||
/// <summary>
|
||||
/// The byte range [<paramref name="offset"/>, offset + <paramref name="length"/>) of <paramref name="file"/> as a
|
||||
/// range-capable response; null when the range does not fit the file (the asset changed under the index).
|
||||
/// </summary>
|
||||
public static IResult? Serve(HttpContext context, FileInfo file, long offset, long length, string contentType, string cacheControl,
|
||||
string? etag = null, string? downloadName = null)
|
||||
{
|
||||
if (offset < 0 || length < 0 || offset > file.Length - length) return null;
|
||||
context.Response.Headers.CacheControl = cacheControl;
|
||||
return Results.Stream(new FileSlice(file.FullName, offset, length), contentType, downloadName, file.LastWriteTimeUtc,
|
||||
etag is null ? null : new EntityTagHeaderValue("\"" + etag + "\""), enableRangeProcessing: true);
|
||||
}
|
||||
|
||||
/// <summary>Read-only, seekable view of part of a file (one thumbnail inside a pack, or the whole file).</summary>
|
||||
private sealed class FileSlice : Stream
|
||||
{
|
||||
private readonly FileStream _file;
|
||||
private readonly long _offset;
|
||||
private readonly long _length;
|
||||
private long _position;
|
||||
|
||||
public FileSlice(string path, long offset, long length)
|
||||
{
|
||||
_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
_offset = offset;
|
||||
_length = length;
|
||||
}
|
||||
|
||||
public override bool CanRead => true;
|
||||
public override bool CanSeek => true;
|
||||
public override bool CanWrite => false;
|
||||
public override long Length => _length;
|
||||
|
||||
public override long Position
|
||||
{
|
||||
get => _position;
|
||||
set => _position = Math.Clamp(value, 0, _length);
|
||||
}
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count));
|
||||
|
||||
public override int Read(Span<byte> buffer)
|
||||
{
|
||||
var count = Available(buffer.Length);
|
||||
if (count == 0) return 0;
|
||||
_file.Position = _offset + _position;
|
||||
var read = _file.Read(buffer[..count]);
|
||||
_position += read;
|
||||
return read;
|
||||
}
|
||||
|
||||
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
|
||||
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
|
||||
|
||||
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var count = Available(buffer.Length);
|
||||
if (count == 0) return 0;
|
||||
_file.Position = _offset + _position;
|
||||
var read = await _file.ReadAsync(buffer[..count], cancellationToken).ConfigureAwait(false);
|
||||
_position += read;
|
||||
return read;
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin) => Position = origin switch
|
||||
{
|
||||
SeekOrigin.Begin => offset,
|
||||
SeekOrigin.Current => _position + offset,
|
||||
_ => _length + offset,
|
||||
};
|
||||
|
||||
public override void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
public override void SetLength(long value) => throw new NotSupportedException();
|
||||
|
||||
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) _file.Dispose();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await _file.DisposeAsync().ConfigureAwait(false);
|
||||
await base.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private int Available(int requested) => (int)Math.Min(requested, _length - _position);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Regenerable images derived from an original (BRIEF §8.5).</summary>
|
||||
public enum FrameAsset
|
||||
{
|
||||
/// <summary>JPEG proxy under the sequence's <c>proxies/</c> folder.</summary>
|
||||
Proxy,
|
||||
|
||||
/// <summary>Thumbnail inside the sequence's packed thumbnail file.</summary>
|
||||
Thumbnail,
|
||||
}
|
||||
|
||||
/// <summary>Where a derived image lives: a byte range of a file inside the archive (a whole proxy file or one thumbnail of a pack).</summary>
|
||||
public sealed record AssetLocation(string Path, long Offset, long Length, string ContentType);
|
||||
|
||||
/// <summary>
|
||||
/// Finds proxies and thumbnails in the archive layout, which the archive module owns (BRIEF §7). The server streams
|
||||
/// what it returns with Range support after checking the path stays inside the archive root; null means not built yet.
|
||||
/// Registered by the host composition alongside <see cref="Chronos.Data.Archiving.IArchiveIngest"/>.
|
||||
/// </summary>
|
||||
public interface IFrameAssetLocator
|
||||
{
|
||||
ValueTask<AssetLocation?> LocateAsync(Archive archive, Sequence sequence, Frame frame, FrameAsset asset, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging.Decoders;
|
||||
using Chronos.Core.Video.Managed;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Analysis and render engine of the server (BRIEF §4.2, §10, §14.5, §14.6): light and deep analysis with managed
|
||||
/// decoders (the light analysis queued after uploads runs here) and renders with managed encoders only. The render
|
||||
/// handler takes the jobs whose every output a managed encoder produces (AVI MJPEG, image sequences, GIF, APNG); MP4
|
||||
/// jobs wait for render nodes until none can take them (<see cref="RenderNodeAvailability"/>), and then render here as
|
||||
/// MJPEG in AVI with a line in the job log (BRIEF §14.7). Renders recorded and Auto values changed here reach connected
|
||||
/// clients as <c>sequenceChanged</c> events (§14.3).
|
||||
/// </summary>
|
||||
public static class ProcessingModule
|
||||
{
|
||||
public static void Register(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<RenderNodeAvailability>();
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var db = sp.GetRequiredService<ChronosDatabase>();
|
||||
var events = sp.GetRequiredService<EventHub>();
|
||||
var options = sp.GetRequiredService<ServerOptions>();
|
||||
return new ProcessingService(db, new ProcessingOptions
|
||||
{
|
||||
Archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateServer(), Owner = ArchiveModule.Owner, Parallelism = () => options.Parallelism },
|
||||
// Analyses and renders take the parallelism as it is when they start, and the one job that runs has the host's
|
||||
// memory budget for its frame window, as on the desktop (owner review 1).
|
||||
Tune = basis =>
|
||||
{
|
||||
var tuned = basis.WithParallelism(options.Parallelism);
|
||||
return tuned with { FrameWindow = tuned.FrameWindow with { MemoryBudget = basis.Archive.MemoryBudget() } };
|
||||
},
|
||||
Encoders = [new ManagedEncoderProvider()],
|
||||
Host = EncoderHost.Server,
|
||||
AwaitsRenderNode = sp.GetRequiredService<RenderNodeAvailability>().AwaitsNodeAsync,
|
||||
ProducedBy = options.ServerName,
|
||||
SequenceChanged = async (id, change, ct) =>
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is { } sequence)
|
||||
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
|
||||
},
|
||||
});
|
||||
});
|
||||
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ProcessingService>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Files a verified render output under the sequence's <c>exports/</c> folder (BRIEF §7) and records it.</summary>
|
||||
public sealed class RenderStore(ChronosDatabase db, ServerArchive archive, TimeProvider time)
|
||||
{
|
||||
/// <summary>
|
||||
/// Moves <paramref name="stagedFile"/> (on the archive volume) to <c><sequence folder>/exports/</c>, never
|
||||
/// replacing an existing export, and inserts the render row. Null when the sequence has no folder in the archive yet.
|
||||
/// </summary>
|
||||
public Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, CancellationToken cancellationToken) =>
|
||||
CommitAsync(sequence, stagedFile, output, producedBy, Guid.CreateVersion7(), cancellationToken);
|
||||
|
||||
/// <summary>As above, keeping <paramref name="id"/>: a render a client sends keeps the id it has on that client.</summary>
|
||||
public async Task<Render?> CommitAsync(Sequence sequence, string stagedFile, RenderResultRequest output, string producedBy, Guid id,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sequence.Folder) || ArchivePathGuard.Resolve(archive.Root, sequence.Folder.TrimEnd('/') + "/exports") is not { } exports)
|
||||
return null;
|
||||
Directory.CreateDirectory(exports);
|
||||
var target = Unique(exports, output.FileName);
|
||||
File.Move(stagedFile, target);
|
||||
var render = new Render
|
||||
{
|
||||
Id = id,
|
||||
SequenceId = sequence.Id,
|
||||
PresetName = output.PresetName,
|
||||
OutputPath = LongPath.ToPortableRelative(archive.Root, target),
|
||||
Codec = output.Codec,
|
||||
Width = output.Width,
|
||||
Height = output.Height,
|
||||
Fps = output.Fps,
|
||||
DurationSeconds = output.DurationSeconds,
|
||||
Bytes = output.Size,
|
||||
Created = time.GetUtcNow(),
|
||||
ProducedBy = producedBy,
|
||||
};
|
||||
await db.Renders.InsertAsync(render, cancellationToken);
|
||||
return render;
|
||||
}
|
||||
|
||||
private static string Unique(string folder, string fileName)
|
||||
{
|
||||
var candidate = Path.Combine(folder, fileName);
|
||||
var stem = Path.GetFileNameWithoutExtension(fileName);
|
||||
var extension = Path.GetExtension(fileName);
|
||||
for (var n = 2; File.Exists(candidate); n++) candidate = Path.Combine(folder, $"{stem} ({n}){extension}");
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Security;
|
||||
using UploadState = Chronos.Data.Repositories.UploadState;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Renders a client sends on request (BRIEF §14.5): chunked like frame uploads (same store, chunk endpoint and
|
||||
/// retention), verified against their SHA-256 at completion and filed by <see cref="RenderStore"/> under the
|
||||
/// sequence's exports with the client's render id, so both sides recognise the same render.
|
||||
/// </summary>
|
||||
public sealed class RenderUploads(
|
||||
ChronosDatabase db,
|
||||
ServerOptions options,
|
||||
UploadService uploads,
|
||||
UploadStore store,
|
||||
RenderStore renders,
|
||||
EventHub events,
|
||||
TimeProvider time)
|
||||
{
|
||||
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, Guid sequenceId, RenderUploadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(sequenceId, cancellationToken) is null) return Outcome<StartUploadResponse>.Fail(404, "not_found", "sequence");
|
||||
if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Outcome<StartUploadResponse>.Fail(400, "invalid_file_name");
|
||||
if (!UploadRules.IsSha256(request.Sha256)) return Outcome<StartUploadResponse>.Fail(400, "invalid_hash");
|
||||
if (request.Size <= 0) return Outcome<StartUploadResponse>.Fail(400, "bad_request", "size");
|
||||
if (request.Size > options.MaxUploadBytes)
|
||||
return Outcome<StartUploadResponse>.Fail(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
|
||||
if (string.IsNullOrWhiteSpace(request.PresetName) || request.PresetName.Length > 200) return Outcome<StartUploadResponse>.Fail(400, "bad_request", "presetName");
|
||||
if (request.RenderId == Guid.Empty) return Outcome<StartUploadResponse>.Fail(400, "bad_request", "renderId");
|
||||
|
||||
if (await db.Renders.GetAsync(request.RenderId, cancellationToken) is { } known)
|
||||
{
|
||||
return known.SequenceId == sequenceId
|
||||
? new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, null)
|
||||
: Outcome<StartUploadResponse>.Fail(409, "render_exists");
|
||||
}
|
||||
var sha = request.Sha256.ToLowerInvariant();
|
||||
if (await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken) is { } open && open.SequenceId == sequenceId && open.Size == request.Size
|
||||
&& Read(open)?.RenderId == request.RenderId && store.Exists(open.Id))
|
||||
return Started(open);
|
||||
if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size) return Outcome<StartUploadResponse>.Fail(507, "insufficient_storage");
|
||||
|
||||
var now = time.GetUtcNow();
|
||||
var upload = await db.Uploads.CreateAsync(new Upload
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
UserId = caller.Id,
|
||||
SequenceId = sequenceId,
|
||||
FileName = fileName,
|
||||
Size = request.Size,
|
||||
Sha256 = sha,
|
||||
ChunkSize = options.ChunkSizeBytes,
|
||||
State = UploadState.Receiving,
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
RenderJson = JsonSerializer.Serialize(request with { FileName = fileName, Sha256 = sha }, ProtocolJson.Default.RenderUploadRequest),
|
||||
}, cancellationToken);
|
||||
store.Create(upload.Id, upload.Size);
|
||||
return Started(upload);
|
||||
}
|
||||
|
||||
/// <summary>Verifies a fully received render and files it; completing a committed one answers it again (a lost response).</summary>
|
||||
public async Task<Outcome<RenderDto>> CompleteAsync(Caller caller, Guid sequenceId, Guid uploadId, CancellationToken cancellationToken)
|
||||
{
|
||||
var upload = await db.Uploads.GetAsync(uploadId, cancellationToken);
|
||||
if (upload is null || upload.UserId != caller.Id || upload.SequenceId != sequenceId || upload.JobId is not null || Read(upload) is not { } output)
|
||||
return Outcome<RenderDto>.Fail(404, "not_found", "upload");
|
||||
if (upload.State == UploadState.Committed && await db.Renders.GetAsync(output.RenderId, cancellationToken) is { } done) return Dto.Render(done);
|
||||
if (upload.State != UploadState.Receiving) return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
if (!upload.IsComplete)
|
||||
return Outcome<RenderDto>.Fail(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
|
||||
if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Committing, cancellationToken: cancellationToken))
|
||||
return Outcome<RenderDto>.Fail(409, "upload_state");
|
||||
|
||||
if (await uploads.StageVerifiedAsync(upload, cancellationToken) is not { } staged) return Outcome<RenderDto>.Fail(422, "hash_mismatch");
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken);
|
||||
var result = new RenderResultRequest(output.FileName, output.Size, output.Sha256, output.PresetName, output.Codec, output.Width, output.Height, output.Fps,
|
||||
output.DurationSeconds);
|
||||
var render = sequence is null ? null : await renders.CommitAsync(sequence, staged, result, output.ProducedBy ?? caller.ClientName ?? caller.User.Username,
|
||||
output.RenderId, cancellationToken);
|
||||
if (render is null)
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
|
||||
store.Delete(upload.Id);
|
||||
return Outcome<RenderDto>.Fail(409, "upload_state", "sequence");
|
||||
}
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, cancellationToken: CancellationToken.None);
|
||||
store.Delete(upload.Id);
|
||||
if (await db.Sequences.GetAsync(sequenceId, CancellationToken.None) is { } updated)
|
||||
events.Publish(new SequenceChangedEvent(updated.Id, "renders", updated.FramesVersion, updated.SettingsVersion));
|
||||
return Dto.Render(render);
|
||||
}
|
||||
|
||||
private static RenderUploadRequest? Read(Upload upload)
|
||||
{
|
||||
if (upload.RenderJson is not { } json) return null;
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest) is { RenderId: var id } request && id != Guid.Empty ? request : null;
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static StartUploadResponse Started(Upload upload) =>
|
||||
new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// The archive this server serves (<see cref="ServerOptions.ArchivePath"/>) and its database row, created at first
|
||||
/// start. The admin panel can change its name, templates and proxy policy at runtime.
|
||||
/// </summary>
|
||||
public sealed class ServerArchive(Archive archive)
|
||||
{
|
||||
private volatile Archive _current = archive;
|
||||
|
||||
public Archive Current
|
||||
{
|
||||
get => _current;
|
||||
set => _current = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serves <paramref name="value"/> unless <see cref="Current"/> is no longer <paramref name="expected"/>, the archive
|
||||
/// it was read from: an edit an administrator saved meanwhile is never undone. False when it was not replaced.
|
||||
/// </summary>
|
||||
public bool TryReplace(Archive expected, Archive value) => ReferenceEquals(Interlocked.CompareExchange(ref _current, value, expected), expected);
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Current"/> once it and the index row hold the settings another writer sharing the archive (a desktop)
|
||||
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the polling and the admin
|
||||
/// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read.
|
||||
/// </summary>
|
||||
public async Task<Archive> RefreshAsync(ArchiveService archives, ChronosDatabase db, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(archives);
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
var current = Current;
|
||||
// Only a change the refresh registered is served, and never over an edit an administrator saved since the read above.
|
||||
if (await archives.RefreshSettingsAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } settings && !settings.IsRegisteredIn(current)
|
||||
&& await db.Archives.GetAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } row)
|
||||
TryReplace(current, row);
|
||||
return Current;
|
||||
}
|
||||
|
||||
public Guid Id => _current.Id;
|
||||
|
||||
public string Root => _current.RootPath;
|
||||
|
||||
/// <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.
|
||||
/// </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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Proxies the server asks for (BRIEF §2.3, §8.5): it decodes with managed decoders only, so the frames whose originals
|
||||
/// it cannot decode (HEIF) get their proxies from a Windows client or render node, made as the archive's proxy policy
|
||||
/// says. Manifests (sync and render nodes) list every frame with its flags and whether its proxy is wanted.
|
||||
/// </summary>
|
||||
public static class ServerProxies
|
||||
{
|
||||
private const int Page = 1000;
|
||||
|
||||
/// <summary>The server takes this format's pixels from proxies made elsewhere (its decoders are managed only, BRIEF §4.2).</summary>
|
||||
public static bool CannotDecode(ImageFileFormat format) => ArchiveImages.ServerNeedsProxy(format);
|
||||
|
||||
/// <summary>How proxies of the archive are made; null when it makes none (or its manifest cannot be read now).</summary>
|
||||
public static ProxySpec? Spec(Archive archive)
|
||||
{
|
||||
try
|
||||
{
|
||||
var policy = ManifestStore.ReadArchive(new ArchivePaths(archive.RootPath).ManifestPath).ProxyPolicy;
|
||||
return policy.LongEdge == ProxyPolicy.Disabled ? null : new ProxySpec(policy.LongEdge, policy.Quality);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the proxy of <paramref name="frame"/>, one the server cannot decode, is in <paramref name="folder"/>: the
|
||||
/// frame's own (<see cref="ArchiveImages.IsProxyOf"/>: one left at its index by a frame renumbered since is another
|
||||
/// photo's) and as large as <paramref name="spec"/> asks (null: the archive makes none, or its manifest cannot be read
|
||||
/// now, so the size is not judged).
|
||||
/// </summary>
|
||||
public static bool HasProxy(SequencePaths folder, Frame frame, ProxySpec? spec) =>
|
||||
ArchiveImages.IsProxyOf(folder.Proxy(frame.Index), frame.CapturedAt, frame.Width, frame.Height,
|
||||
spec is null ? null : new ProxyPolicy { LongEdge = spec.LongEdge, Quality = spec.Quality });
|
||||
|
||||
/// <summary>
|
||||
/// Every frame of <paramref name="sequence"/> in index order, as a manifest lists it. A frame the server cannot decode
|
||||
/// has its proxy when its own is there (<see cref="HasProxy"/>), whatever the sequence's built status says (frames
|
||||
/// added or renumbered since keep it until the next proxy pass), and wants one otherwise (unless it is missing or
|
||||
/// damaged, or <paramref name="spec"/> is null); any other frame has one when the server built them all.
|
||||
/// </summary>
|
||||
public static async Task<List<ManifestFrame>> FramesAsync(ChronosRepositories db, Archive archive, Sequence sequence, ProxySpec? spec,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var proxies = sequence.Status.HasFlag(SequenceStatus.ProxiesBuilt);
|
||||
var thumbs = sequence.Status.HasFlag(SequenceStatus.ThumbsBuilt);
|
||||
var folder = new ArchivePaths(archive.RootPath).Sequence(sequence.Folder);
|
||||
var frames = new List<ManifestFrame>(sequence.FrameCount);
|
||||
var after = -1;
|
||||
while (true)
|
||||
{
|
||||
var batch = await db.Frames.ListBySequenceAsync(sequence.Id, after, Page, cancellationToken);
|
||||
foreach (var f in batch)
|
||||
{
|
||||
var elsewhere = CannotDecode(f.Format);
|
||||
var has = elsewhere ? HasProxy(folder, f, spec) : proxies;
|
||||
var wanted = spec is not null && elsewhere && !has && (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0;
|
||||
frames.Add(new ManifestFrame(f.Id, f.Index, f.FileName, f.Size, f.Sha256 ?? string.Empty, has, thumbs, (long)f.Flags, wanted));
|
||||
}
|
||||
if (batch.Count < Page) return frames;
|
||||
after = batch[^1].Index;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Upload housekeeping (BRIEF §14.4): at start, uploads a crash left half-committed are settled; then every half hour
|
||||
/// abandoned uploads expire, orphaned partial and staging files are removed, old upload records and dead tokens purged.
|
||||
/// </summary>
|
||||
public sealed class UploadMaintenance(ChronosDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
|
||||
ILogger<UploadMaintenance> logger)
|
||||
: BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
|
||||
private static readonly TimeSpan FinishedRetention = TimeSpan.FromDays(90);
|
||||
private static readonly TimeSpan StagingRetention = TimeSpan.FromDays(1);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
await RecoverAsync(stoppingToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Upload recovery failed");
|
||||
}
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await SweepAsync(stoppingToken);
|
||||
await Task.Delay(Interval, time, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "Upload cleanup failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Uploads left committing by a crash: committed when an intact frame stands for their content as at the start of an
|
||||
/// upload (<see cref="UploadRules.StandIn"/>), otherwise back to receiving (the partial file is intact, so the client
|
||||
/// simply completes again and the ingest files or repairs it).
|
||||
/// </summary>
|
||||
public async Task RecoverAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var upload in await db.Uploads.ListByStateAsync(UploadState.Committing, cancellationToken))
|
||||
{
|
||||
var frame = upload.JobId is null ? await StandInAsync(upload, cancellationToken) : null;
|
||||
if (frame is not null)
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Committed, frame.Id, cancellationToken);
|
||||
store.Delete(upload.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: cancellationToken);
|
||||
}
|
||||
logger.LogInformation("Recovered interrupted upload {Upload} ({File})", upload.Id, upload.FileName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The intact frame that settles an interrupted commit, or null when the client must complete it again.</summary>
|
||||
private async Task<Frame?> StandInAsync(Upload upload, CancellationToken cancellationToken)
|
||||
{
|
||||
var copies = await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken);
|
||||
if (copies.Count == 0) return null;
|
||||
var target = await UploadRules.TargetAsync(db, archive.Id, upload.SequenceId, upload.SessionKey, upload.UserId, cancellationToken);
|
||||
return UploadRules.StandIn(archive.Root, copies, target);
|
||||
}
|
||||
|
||||
public async Task SweepAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = time.GetUtcNow();
|
||||
var abandonedBefore = now - TimeSpan.FromHours(options.UploadRetentionHours);
|
||||
var expired = 0;
|
||||
foreach (var upload in await db.Uploads.ListStaleAsync(abandonedBefore, cancellationToken))
|
||||
{
|
||||
if (!await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Receiving, UploadState.Cancelled, cancellationToken: cancellationToken)) continue;
|
||||
store.Delete(upload.Id);
|
||||
expired++;
|
||||
}
|
||||
|
||||
var active = new HashSet<Guid>();
|
||||
foreach (var state in new[] { UploadState.Receiving, UploadState.Committing })
|
||||
active.UnionWith((await db.Uploads.ListByStateAsync(state, cancellationToken)).Select(u => u.Id));
|
||||
foreach (var (id, _) in store.List().ToList())
|
||||
{
|
||||
if (!active.Contains(id)) store.Delete(id);
|
||||
}
|
||||
if (Directory.Exists(options.StagingPath))
|
||||
{
|
||||
// Only this server's staging files (named by upload id) are touched; clients may share the archive.
|
||||
foreach (var file in new DirectoryInfo(options.StagingPath).EnumerateFiles())
|
||||
{
|
||||
if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(file.Name), "N", out var id) && !active.Contains(id)
|
||||
&& file.LastWriteTimeUtc < now.UtcDateTime - StagingRetention)
|
||||
UploadStore.TryDelete(file.FullName);
|
||||
}
|
||||
}
|
||||
|
||||
await db.Uploads.PurgeFinishedAsync(now - FinishedRetention, cancellationToken);
|
||||
await db.Tokens.PurgeAsync(now, cancellationToken);
|
||||
if (expired > 0) logger.LogInformation("Expired {Count} abandoned upload(s)", expired);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>Validation shared by frame and render uploads.</summary>
|
||||
public static class UploadRules
|
||||
{
|
||||
/// <summary>A plain file name (no folders, no characters Windows or Linux refuse), or null.</summary>
|
||||
public static string? SafeFileName(string? name)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(name)) return null;
|
||||
var trimmed = name.Trim();
|
||||
if (trimmed.Length > 255 || trimmed is "." or ".." || trimmed.EndsWith('.')) return null;
|
||||
foreach (var c in trimmed)
|
||||
{
|
||||
if (char.IsControl(c) || c is '/' or '\\' or '<' or '>' or ':' or '"' or '|' or '?' or '*') return null;
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/// <summary>64 hexadecimal characters.</summary>
|
||||
public static bool IsSha256(string? value) => value is { Length: 64 } && value.All(char.IsAsciiHexDigit);
|
||||
|
||||
/// <summary>Indices of the chunks set in a received-chunk bitmap.</summary>
|
||||
public static List<int> ReceivedChunks(Chronos.Data.Repositories.Upload upload)
|
||||
{
|
||||
var received = new List<int>(upload.ReceivedCount);
|
||||
for (var i = 0; i < upload.ChunkCount; i++)
|
||||
{
|
||||
if (upload.HasChunk(i)) received.Add(i);
|
||||
}
|
||||
return received;
|
||||
}
|
||||
|
||||
/// <summary>The frame's original is in the archive with its recorded size.</summary>
|
||||
public static bool IsOnDisk(string archiveRoot, Frame frame) =>
|
||||
ArchivePathGuard.ExistingFile(archiveRoot, frame.RelativePath) is { } file && file.Length == frame.Size;
|
||||
|
||||
/// <summary>
|
||||
/// Not flagged missing or corrupt, and <see cref="IsOnDisk"/>: the copy holds its content, so it may stand for an upload
|
||||
/// of the same content; a damaged one is repaired by uploading the content again.
|
||||
/// </summary>
|
||||
public static bool IsIntact(string archiveRoot, Frame frame) =>
|
||||
(frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0 && IsOnDisk(archiveRoot, frame);
|
||||
|
||||
/// <summary>
|
||||
/// The frame that stands for an upload of content the archive already has (<paramref name="copies"/>): an intact copy,
|
||||
/// the one in the upload's <paramref name="target"/> sequence first. Null when there is none, or when the target holds
|
||||
/// the content only in damaged copies: the upload's bytes repair them, whatever other sequences hold.
|
||||
/// </summary>
|
||||
public static Frame? StandIn(string archiveRoot, IReadOnlyList<Frame> copies, Guid? target)
|
||||
{
|
||||
var intact = copies.Where(f => IsIntact(archiveRoot, f)).ToList();
|
||||
if (copies.Any(f => f.SequenceId == target) && !intact.Any(f => f.SequenceId == target)) return null;
|
||||
return intact.FirstOrDefault(f => f.SequenceId == target) ?? intact.FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence an upload files into: its own, or the one its session key names (the user's own key without one);
|
||||
/// null while that sequence does not exist yet.
|
||||
/// </summary>
|
||||
public static async Task<Guid?> TargetAsync(ChronosDatabase db, Guid archiveId, Guid? sequenceId, string? sessionKey, Guid userId,
|
||||
CancellationToken cancellationToken) =>
|
||||
sequenceId ?? await db.Sequences.FindBySessionKeyAsync(archiveId, SessionKeyOf(sessionKey, userId), cancellationToken).ConfigureAwait(false);
|
||||
|
||||
/// <summary>The session key an upload without a sequence is grouped by: the client's, or one per user.</summary>
|
||||
public static string SessionKeyOf(string? sessionKey, Guid userId) => sessionKey ?? "user-" + userId.ToString("N");
|
||||
|
||||
/// <summary>Free bytes on the volume holding <paramref name="path"/>, or null when the platform cannot tell.</summary>
|
||||
public static long? FreeBytes(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
return new DriveInfo(Path.GetFullPath(path)).AvailableFreeSpace;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ArgumentException or UnauthorizedAccessException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Globalization;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Repositories;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Server.Api;
|
||||
using Chronos.Server.Configuration;
|
||||
using Chronos.Server.Events;
|
||||
using Chronos.Server.Jobs;
|
||||
using Chronos.Server.Security;
|
||||
using UploadState = Chronos.Data.Repositories.UploadState;
|
||||
using UploadStateDto = Chronos.Protocol.UploadState;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256 held by an
|
||||
/// intact frame, resume an unfinished upload, quota and disk checks), idempotent chunks, and completion that stages the
|
||||
/// file on the archive volume, verifies its hash and hands it to <see cref="IArchiveIngest"/>, which repairs a missing or
|
||||
/// damaged frame of that content (no quota is charged for a repair: the archive already counts those bytes).
|
||||
/// </summary>
|
||||
public sealed class UploadService(
|
||||
ChronosDatabase db,
|
||||
ServerOptions options,
|
||||
ServerArchive archive,
|
||||
UploadStore store,
|
||||
IArchiveIngest ingest,
|
||||
SequenceJobs sequenceJobs,
|
||||
EventHub events,
|
||||
IHostApplicationLifetime lifetime,
|
||||
TimeProvider time,
|
||||
ILogger<UploadService> logger)
|
||||
{
|
||||
/// <summary>Space kept free on the upload volume beyond the announced size.</summary>
|
||||
private const long DiskReserve = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>Card events one account may publish per minute: progress once a second leaves room for every start and end.</summary>
|
||||
private const int CardEventsPerMinute = 120;
|
||||
|
||||
private static readonly TimeSpan CardProgressInterval = TimeSpan.FromSeconds(1);
|
||||
private static readonly TimeSpan CardEventWindow = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly ConcurrentDictionary<Guid, int> _chunksInFlight = new();
|
||||
private readonly ConcurrentDictionary<Guid, CardEvents> _cardEvents = new();
|
||||
|
||||
public async Task<Outcome<StartUploadResponse>> StartAsync(Caller caller, StartUploadRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (UploadRules.SafeFileName(request.FileName) is not { } fileName) return Fail<StartUploadResponse>(400, "invalid_file_name");
|
||||
if (!UploadRules.IsSha256(request.Sha256)) return Fail<StartUploadResponse>(400, "invalid_hash");
|
||||
if (request.Size <= 0) return Fail<StartUploadResponse>(400, "bad_request", "size");
|
||||
if (request.Size > options.MaxUploadBytes) return Fail<StartUploadResponse>(413, "too_large", options.MaxUploadBytes.ToString(CultureInfo.InvariantCulture));
|
||||
if (request.SessionKey is { Length: > 200 }) return Fail<StartUploadResponse>(400, "bad_request", "sessionKey");
|
||||
if (request.SequenceId is { } requested && await db.Sequences.GetAsync(requested, cancellationToken) is null)
|
||||
return Fail<StartUploadResponse>(404, "not_found", "sequence");
|
||||
|
||||
var sha = request.Sha256.ToLowerInvariant();
|
||||
var sessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim();
|
||||
var copies = await db.Frames.FindBySha256Async(sha, cancellationToken);
|
||||
var target = copies.Count == 0 ? null : await UploadRules.TargetAsync(db, archive.Id, request.SequenceId, sessionKey, caller.Id, cancellationToken);
|
||||
// Only a copy that is still whole stands for the upload: a client may delete its file on this answer.
|
||||
if (UploadRules.StandIn(archive.Root, copies, target) is { } known)
|
||||
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, known.Id);
|
||||
|
||||
var resumable = await db.Uploads.FindReceivingAsync(caller.Id, sha, cancellationToken);
|
||||
if (resumable is not null && resumable.Size == request.Size && resumable.SequenceId == request.SequenceId && store.Exists(resumable.Id))
|
||||
return Started(resumable);
|
||||
|
||||
// A repair puts back bytes the archive already counts: no quota for it.
|
||||
if (caller.User.QuotaBytes > 0 && !copies.Any(f => f.SequenceId == target))
|
||||
{
|
||||
var pending = await db.Uploads.PendingBytesAsync(caller.Id, cancellationToken);
|
||||
if (caller.User.UsedBytes + pending + request.Size > caller.User.QuotaBytes)
|
||||
return Fail<StartUploadResponse>(403, "quota_exceeded", caller.User.QuotaBytes.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
if (UploadRules.FreeBytes(options.UploadsPath) is { } free && free < request.Size + DiskReserve)
|
||||
return Fail<StartUploadResponse>(507, "insufficient_storage");
|
||||
|
||||
var now = time.GetUtcNow();
|
||||
var upload = await db.Uploads.CreateAsync(new Upload
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
UserId = caller.Id,
|
||||
SequenceId = request.SequenceId,
|
||||
FileName = fileName,
|
||||
Size = request.Size,
|
||||
Sha256 = sha,
|
||||
CapturedAt = request.CapturedAt,
|
||||
ChunkSize = options.ChunkSizeBytes,
|
||||
State = UploadState.Receiving,
|
||||
Created = now,
|
||||
UpdatedAt = now,
|
||||
SessionKey = sessionKey,
|
||||
}, cancellationToken);
|
||||
store.Create(upload.Id, upload.Size);
|
||||
return Started(upload);
|
||||
}
|
||||
|
||||
/// <summary>Stores chunk <paramref name="index"/> of an upload the caller owns; repeating a received chunk changes nothing.</summary>
|
||||
public async Task<Outcome<ChunkReceived>> ReceiveChunkAsync(Caller caller, Guid id, int index, HttpRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var upload = await db.Uploads.GetAsync(id, cancellationToken);
|
||||
// A body left unread by an answer below is drained after it: one of a chunk's size must not count as too large, or
|
||||
// Kestrel would close the connection while the client still sends it and the client would never see the answer. The
|
||||
// upload keeps the chunk size it started with: a smaller setting since a restart must not refuse its chunks (413).
|
||||
if (request.HttpContext.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false, MaxRequestBodySize: { } current } limit)
|
||||
limit.MaxRequestBodySize = Math.Max(current, Math.Max(upload?.ChunkSize ?? 0, options.ChunkSizeBytes));
|
||||
if (upload is null || upload.UserId != caller.Id) return Fail<ChunkReceived>(404, "not_found", "upload");
|
||||
if (upload.State != UploadState.Receiving) return Fail<ChunkReceived>(409, "upload_state");
|
||||
if (index < 0 || index >= upload.ChunkCount) return Fail<ChunkReceived>(400, "chunk_out_of_range");
|
||||
var expected = Math.Min(upload.ChunkSize, upload.Size - (long)index * upload.ChunkSize);
|
||||
if (request.ContentLength is { } announced && announced != expected) return Fail<ChunkReceived>(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
|
||||
if (upload.HasChunk(index)) return new ChunkReceived(index, UploadRules.ReceivedChunks(upload));
|
||||
|
||||
if (_chunksInFlight.AddOrUpdate(caller.Id, 1, (_, n) => n + 1) > options.ConcurrentChunksPerUser)
|
||||
{
|
||||
Release(caller.Id);
|
||||
return Fail<ChunkReceived>(429, "too_many_uploads");
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!await store.WriteChunkAsync(id, (long)index * upload.ChunkSize, request.Body, expected, cancellationToken))
|
||||
return Fail<ChunkReceived>(400, "chunk_size", expected.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Release(caller.Id);
|
||||
}
|
||||
var updated = await db.Uploads.MarkChunkReceivedAsync(id, index, cancellationToken);
|
||||
return updated is null ? Fail<ChunkReceived>(404, "not_found", "upload") : new ChunkReceived(index, UploadRules.ReceivedChunks(updated));
|
||||
}
|
||||
|
||||
public async Task<Outcome<UploadStateDto>> GetStateAsync(Caller caller, Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var upload = await db.Uploads.GetAsync(id, cancellationToken);
|
||||
if (upload is null || upload.UserId != caller.Id) return Fail<UploadStateDto>(404, "not_found", "upload");
|
||||
return new UploadStateDto(upload.Id, upload.FileName, upload.Size, upload.Sha256, upload.ChunkSize, UploadRules.ReceivedChunks(upload),
|
||||
upload.State.ToString().ToLowerInvariant());
|
||||
}
|
||||
|
||||
/// <summary>Abandons an upload that is still receiving and deletes its partial file.</summary>
|
||||
public async Task<Outcome<bool>> CancelAsync(Caller caller, Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
var upload = await db.Uploads.GetAsync(id, cancellationToken);
|
||||
if (upload is null || upload.UserId != caller.Id) return Fail<bool>(404, "not_found", "upload");
|
||||
if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Cancelled, cancellationToken: cancellationToken))
|
||||
return Fail<bool>(409, "upload_state");
|
||||
store.Delete(id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies and commits a frame upload. Completing an already committed upload answers its frame again, so a client
|
||||
/// may retry a completion whose response it lost. Runs to the end even if the client disconnects.
|
||||
/// </summary>
|
||||
public async Task<Outcome<CompleteUploadResponse>> CompleteAsync(Caller caller, Guid id)
|
||||
{
|
||||
var stopping = lifetime.ApplicationStopping;
|
||||
var upload = await db.Uploads.GetAsync(id, stopping);
|
||||
if (upload is null || upload.UserId != caller.Id) return Fail<CompleteUploadResponse>(404, "not_found", "upload");
|
||||
if (upload.JobId is not null || upload.RenderJson is not null) return Fail<CompleteUploadResponse>(409, "wrong_upload_kind");
|
||||
if (upload is { State: UploadState.Committed, FrameId: { } committed } && await db.Frames.GetAsync(committed, stopping) is { } done)
|
||||
return new CompleteUploadResponse(done.Id, done.SequenceId, done.Index);
|
||||
if (upload.State != UploadState.Receiving) return Fail<CompleteUploadResponse>(409, "upload_state");
|
||||
if (!upload.IsComplete)
|
||||
return Fail<CompleteUploadResponse>(409, "incomplete", (upload.ChunkCount - upload.ReceivedCount).ToString(CultureInfo.InvariantCulture));
|
||||
if (!await db.Uploads.TryTransitionAsync(id, UploadState.Receiving, UploadState.Committing, cancellationToken: stopping))
|
||||
return Fail<CompleteUploadResponse>(409, "upload_state");
|
||||
|
||||
var user = await db.Users.GetAsync(caller.Id, stopping);
|
||||
if (user is { QuotaBytes: > 0 } && user.UsedBytes + upload.Size > user.QuotaBytes && !await HeldByTargetAsync(upload, stopping))
|
||||
{
|
||||
await FailAsync(upload);
|
||||
return Fail<CompleteUploadResponse>(403, "quota_exceeded", user.QuotaBytes.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
var staged = await StageVerifiedAsync(upload, stopping);
|
||||
if (staged is null) return Fail<CompleteUploadResponse>(422, "hash_mismatch");
|
||||
|
||||
IngestResult result;
|
||||
try
|
||||
{
|
||||
result = await ingest.CommitAsync(new IngestRequest(
|
||||
archive.Id,
|
||||
upload.SequenceId,
|
||||
NewSequenceTitle: null,
|
||||
upload.SequenceId is null ? UploadRules.SessionKeyOf(upload.SessionKey, caller.Id) : null,
|
||||
staged,
|
||||
upload.FileName,
|
||||
upload.Size,
|
||||
upload.Sha256,
|
||||
upload.CapturedAt,
|
||||
caller.Id), stopping);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// The part file is intact: the client may complete again.
|
||||
logger.LogError(ex, "Archive ingest of upload {Upload} ({File}) failed", id, upload.FileName);
|
||||
UploadStore.TryDelete(staged);
|
||||
await db.Uploads.TryTransitionAsync(id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None);
|
||||
return Fail<CompleteUploadResponse>(503, "commit_failed");
|
||||
}
|
||||
|
||||
await db.Uploads.TryTransitionAsync(id, UploadState.Committing, UploadState.Committed, result.FrameId, CancellationToken.None);
|
||||
store.Delete(id);
|
||||
if (File.Exists(staged)) UploadStore.TryDelete(staged);
|
||||
if (!result.Duplicate && !result.Repaired) await db.Users.AddUsedBytesAsync(caller.Id, upload.Size, CancellationToken.None);
|
||||
if (await db.Sequences.GetAsync(result.SequenceId, CancellationToken.None) is { } sequence)
|
||||
{
|
||||
await sequenceJobs.FramesAddedAsync(sequence, CancellationToken.None);
|
||||
events.Publish(new SequenceChangedEvent(sequence.Id, "frames", sequence.FramesVersion, sequence.SettingsVersion));
|
||||
}
|
||||
return new CompleteUploadResponse(result.FrameId, result.SequenceId, result.Index);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells every connected client about a card import (BRIEF §14.3 <c>cardEvent</c>), so one account cannot crowd their
|
||||
/// event queues: its progress goes out at most once a second (a report sooner is dropped, the next one replaces it as
|
||||
/// on the client), and at most 120 of its events a minute (429 beyond). False when the report was dropped.
|
||||
/// </summary>
|
||||
public Outcome<bool> PublishCard(Caller caller, CardEvent card)
|
||||
{
|
||||
var now = time.GetUtcNow();
|
||||
var sent = _cardEvents.GetOrAdd(caller.Id, _ => new CardEvents());
|
||||
lock (sent.Gate)
|
||||
{
|
||||
var progress = card.State == CardImportStates.Progress;
|
||||
if (progress && now - sent.LastProgress < CardProgressInterval) return false;
|
||||
while (sent.Recent.Count > 0 && now - sent.Recent.Peek() >= CardEventWindow) sent.Recent.Dequeue();
|
||||
if (sent.Recent.Count >= CardEventsPerMinute)
|
||||
{
|
||||
var wait = Math.Max(1, (int)Math.Ceiling((CardEventWindow - (now - sent.Recent.Peek())).TotalSeconds));
|
||||
return Fail<bool>(429, "rate_limited", wait.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
sent.Recent.Enqueue(now);
|
||||
if (progress) sent.LastProgress = now;
|
||||
}
|
||||
events.Publish(card);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Copies a fully received upload to the archive staging folder and checks its SHA-256. On a mismatch the upload
|
||||
/// fails, its files are deleted and null is returned; the client starts over.
|
||||
/// </summary>
|
||||
public async Task<string?> StageVerifiedAsync(Upload upload, CancellationToken cancellationToken)
|
||||
{
|
||||
var staged = Path.Combine(options.StagingPath, upload.Id.ToString("N") + Path.GetExtension(upload.FileName).ToLowerInvariant());
|
||||
string hash;
|
||||
try
|
||||
{
|
||||
hash = await store.StageAsync(upload.Id, staged, cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
UploadStore.TryDelete(staged);
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Receiving, cancellationToken: CancellationToken.None);
|
||||
throw;
|
||||
}
|
||||
if (hash == upload.Sha256) return staged;
|
||||
logger.LogWarning("Upload {Upload} ({File}) arrived damaged: SHA-256 {Actual} instead of {Expected}", upload.Id, upload.FileName, hash, upload.Sha256);
|
||||
UploadStore.TryDelete(staged);
|
||||
await FailAsync(upload);
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task FailAsync(Upload upload)
|
||||
{
|
||||
await db.Uploads.TryTransitionAsync(upload.Id, UploadState.Committing, UploadState.Failed, cancellationToken: CancellationToken.None);
|
||||
store.Delete(upload.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence the upload files into holds its content already: filing it adds no bytes (an intact copy makes it a
|
||||
/// duplicate, a damaged one is repaired with it).
|
||||
/// </summary>
|
||||
private async Task<bool> HeldByTargetAsync(Upload upload, CancellationToken cancellationToken)
|
||||
{
|
||||
var copies = await db.Frames.FindBySha256Async(upload.Sha256, cancellationToken);
|
||||
if (copies.Count == 0) return false;
|
||||
var target = await UploadRules.TargetAsync(db, archive.Id, upload.SequenceId, upload.SessionKey, upload.UserId, cancellationToken);
|
||||
return copies.Any(f => f.SequenceId == target);
|
||||
}
|
||||
|
||||
private StartUploadResponse Started(Upload upload) =>
|
||||
new(upload.Id, upload.ChunkSize, UploadRules.ReceivedChunks(upload), AlreadyExists: false, FrameId: null);
|
||||
|
||||
private void Release(Guid userId)
|
||||
{
|
||||
if (_chunksInFlight.AddOrUpdate(userId, 0, (_, n) => n - 1) <= 0) _chunksInFlight.TryRemove(new KeyValuePair<Guid, int>(userId, 0));
|
||||
}
|
||||
|
||||
private static Outcome<T> Fail<T>(int status, string code, string? details = null) => Outcome<T>.Fail(status, code, details);
|
||||
|
||||
/// <summary>The card events one account published lately.</summary>
|
||||
private sealed class CardEvents
|
||||
{
|
||||
public Lock Gate { get; } = new();
|
||||
public Queue<DateTimeOffset> Recent { get; } = new();
|
||||
public DateTimeOffset LastProgress { get; set; } = DateTimeOffset.MinValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
using System.Buffers;
|
||||
using System.Security.Cryptography;
|
||||
using Chronos.Server.Configuration;
|
||||
|
||||
namespace Chronos.Server.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// Files behind resumable uploads (BRIEF §14.4): <c>/data/uploads/{id}.part</c> receives chunks at their offsets in any
|
||||
/// order; at completion it is copied, hashing on the way, to a staging file on the archive volume.
|
||||
/// </summary>
|
||||
public sealed class UploadStore(ServerOptions options)
|
||||
{
|
||||
private const string Extension = ".part";
|
||||
|
||||
public string PartPath(Guid id) => Path.Combine(options.UploadsPath, id.ToString("N") + Extension);
|
||||
|
||||
public bool Exists(Guid id) => File.Exists(PartPath(id));
|
||||
|
||||
/// <summary>Creates the part file at its final size, so chunks can land at their offsets.</summary>
|
||||
public void Create(Guid id, long size)
|
||||
{
|
||||
Directory.CreateDirectory(options.UploadsPath);
|
||||
using var file = new FileStream(PartPath(id), FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
|
||||
file.SetLength(size);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes exactly <paramref name="length"/> bytes of <paramref name="body"/> at <paramref name="offset"/> and flushes
|
||||
/// them to disk; false when the body is shorter or longer (nothing is marked received then).
|
||||
/// </summary>
|
||||
public async Task<bool> WriteChunkAsync(Guid id, long offset, Stream body, long length, CancellationToken cancellationToken)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(1 << 16);
|
||||
try
|
||||
{
|
||||
await using var file = new FileStream(PartPath(id), FileMode.Open, FileAccess.Write, FileShare.ReadWrite, 1 << 16, FileOptions.Asynchronous);
|
||||
file.Position = offset;
|
||||
long total = 0;
|
||||
int read;
|
||||
while ((read = await body.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
total += read;
|
||||
if (total > length) return false;
|
||||
await file.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
if (total != length) return false;
|
||||
await file.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
file.Flush(flushToDisk: true);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Copies the assembled upload to <paramref name="stagingPath"/> (synced to disk) and returns its lower-case hex SHA-256.</summary>
|
||||
public async Task<string> StageAsync(Guid id, string stagingPath, CancellationToken cancellationToken)
|
||||
{
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(stagingPath)!);
|
||||
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(1 << 20);
|
||||
try
|
||||
{
|
||||
await using var source = new FileStream(PartPath(id), FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||
await using var target = new FileStream(stagingPath, FileMode.Create, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous);
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
hash.AppendData(buffer, 0, read);
|
||||
await target.WriteAsync(buffer.AsMemory(0, read), cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await target.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||
target.Flush(flushToDisk: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
return Convert.ToHexStringLower(hash.GetHashAndReset());
|
||||
}
|
||||
|
||||
public void Delete(Guid id) => TryDelete(PartPath(id));
|
||||
|
||||
/// <summary>Every part file with its last write time (cleanup of uploads the database no longer knows).</summary>
|
||||
public IEnumerable<(Guid Id, DateTime LastWriteUtc)> List()
|
||||
{
|
||||
if (!Directory.Exists(options.UploadsPath)) yield break;
|
||||
foreach (var path in Directory.EnumerateFiles(options.UploadsPath, "*" + Extension))
|
||||
{
|
||||
if (Guid.TryParseExact(Path.GetFileNameWithoutExtension(path), "N", out var id)) yield return (id, File.GetLastWriteTimeUtc(path));
|
||||
}
|
||||
}
|
||||
|
||||
public static void TryDelete(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Retried by the next cleanup pass.
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user