Merge branch 'fix/ingest-upload': uploads into API-made sequences, damaged frames repaired, positions follow inserts, cardEvent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:44:09 +00:00
commit 3b1b743fcd
29 files changed
+1546 -80

No files matched your search

+4 -3
View File
@@ -42,15 +42,16 @@ public static class SequenceEndpoints
sequences.MapGet("/{id:guid}/analysis/report", ReportAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
// Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads.
// Renders made on a client, sent on request (BRIEF §14.5) by the sync of an editor's copy; chunks go through /uploads.
// Edit, not Upload: render outputs count against no quota, so an upload-only account cannot add them.
sequences.MapPost("/{id:guid}/renders", async (HttpContext c, Caller caller, Guid id, RenderUploadRequest request, RenderUploads uploads) =>
(await uploads.StartAsync(caller, id, request, c.RequestAborted)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.StartUploadResponse,
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Upload | Permissions.Edit);
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created))).Requires(Permissions.Edit);
sequences.MapPost("/{id:guid}/renders/{uploadId:guid}/complete", async (HttpContext c, Caller caller, Guid id, Guid uploadId, RenderUploads uploads,
IHostApplicationLifetime lifetime) =>
// The commit runs to the end even if the client disconnects meanwhile.
(await uploads.CompleteAsync(caller, id, uploadId, lifetime.ApplicationStopping)).ToResult(c, r => Results.Json(r, ProtocolJson.Default.RenderDto)))
.Requires(Permissions.Upload | Permissions.Edit);
.Requires(Permissions.Edit);
}
private static async Task<IResult> ListAsync(HttpContext context, TitanoDatabase db, ServerArchive archive, int? year, string? camera, string? status,
+26 -6
View File
@@ -1,7 +1,5 @@
using Microsoft.AspNetCore.Http.Features;
using Titano.Core.Model;
using Titano.Protocol;
using Titano.Server.Configuration;
using Titano.Server.Security;
using Titano.Server.Storage;
@@ -9,10 +7,13 @@ namespace Titano.Server.Api;
/// <summary>
/// <c>/api/v1/uploads</c> (BRIEF §14.4). Chunk, state and cancel calls also serve render nodes uploading their output,
/// which start and complete through the node endpoints.
/// which start and complete through the node endpoints. <c>POST /uploads/cards</c> takes the reports of a card import a
/// client streams through these uploads and tells every connected client (BRIEF §14.3 <c>cardEvent</c>).
/// </summary>
public static class UploadEndpoints
{
private const int MaxCardName = 200;
public static void Map(RouteGroupBuilder api)
{
var uploads = api.MapGroup("/uploads").Requires(Permissions.Upload | Permissions.RenderNode);
@@ -25,6 +26,7 @@ public static class UploadEndpoints
uploads.MapPost("/{id:guid}/complete", async (HttpContext context, Caller caller, Guid id, UploadService service) =>
(await service.CompleteAsync(caller, id)).ToResult(context, r => Results.Json(r, ProtocolJson.Default.CompleteUploadResponse)))
.Requires(Permissions.Upload);
uploads.MapPost("/cards", ReportCard).Requires(Permissions.Upload);
}
private static async Task<IResult> StartAsync(HttpContext context, Caller caller, StartUploadRequest request, UploadService service)
@@ -34,10 +36,28 @@ public static class UploadEndpoints
statusCode: r.AlreadyExists ? StatusCodes.Status200OK : StatusCodes.Status201Created));
}
private static async Task<IResult> ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service, ServerOptions options)
/// <summary>
/// A card import's start, progress or end, published as a <see cref="CardEvent"/> naming who imports it; 204, also for
/// progress dropped because it came within a second of the last (<see cref="UploadService.PublishCard"/>).
/// </summary>
private static IResult ReportCard(HttpContext context, Caller caller, CardImportReport report, UploadService service)
{
if (report.ImportId == Guid.Empty) return ApiErrors.BadRequest(context, "bad_request", "importId");
var card = report.Card?.Trim();
if (string.IsNullOrEmpty(card) || card.Length > MaxCardName || card.Any(char.IsControl)) return ApiErrors.BadRequest(context, "bad_request", "card");
if (!CardImportStates.IsKnown(report.State)) return ApiErrors.BadRequest(context, "bad_request", "state");
if (report.Total < 0 || report.Done < 0 || report.Done > report.Total || report.Failed < 0 || report.Failed > report.Total)
return ApiErrors.BadRequest(context, "bad_request", "done");
return service.PublishCard(caller, new CardEvent(report.ImportId, card, report.State, report.Done, report.Total, report.Failed, caller.User.Username,
caller.ClientName)).ToResult(context, _ => Results.NoContent());
}
/// <summary>
/// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit. The service
/// raises it to the chunk size of this upload (fixed when it started) before it reads the body.
/// </summary>
private static async Task<IResult> ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service)
{
// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit.
if (context.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = options.ChunkSizeBytes;
var outcome = await service.ReceiveChunkAsync(caller, id, index, context.Request, context.RequestAborted);
return outcome.ToResult(context, r => Results.Json(r, ProtocolJson.Default.ChunkReceived));
}
+16 -4
View File
@@ -1,3 +1,4 @@
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
using Titano.Server.Configuration;
@@ -8,7 +9,8 @@ namespace Titano.Server.Storage;
/// 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(TitanoDatabase db, ServerOptions options, UploadStore store, TimeProvider time, ILogger<UploadMaintenance> logger)
public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options, ServerArchive archive, UploadStore store, TimeProvider time,
ILogger<UploadMaintenance> logger)
: BackgroundService
{
private static readonly TimeSpan Interval = TimeSpan.FromMinutes(30);
@@ -44,14 +46,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
/// <summary>
/// Uploads left committing by a crash: committed when the frame with their hash exists, otherwise back to receiving
/// (the partial file is intact, so the client simply completes again).
/// 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 db.Frames.FindBySha256Async(upload.Sha256, cancellationToken)).FirstOrDefault() : null;
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);
@@ -65,6 +68,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
}
/// <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();
+37
View File
@@ -1,3 +1,6 @@
using Titano.Core.Model;
using Titano.Data;
namespace Titano.Server.Storage;
/// <summary>Validation shared by frame and render uploads.</summary>
@@ -30,6 +33,40 @@ public static class UploadRules
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(TitanoDatabase 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)
{
+73 -15
View File
@@ -1,5 +1,6 @@
using System.Collections.Concurrent;
using System.Globalization;
using Microsoft.AspNetCore.Http.Features;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
@@ -15,9 +16,10 @@ using UploadStateDto = Titano.Protocol.UploadState;
namespace Titano.Server.Storage;
/// <summary>
/// Chunked, resumable, hash-verified frame uploads (BRIEF §14.4): start (short-circuit on a known SHA-256, 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"/>.
/// 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(
TitanoDatabase db,
@@ -34,7 +36,14 @@ public sealed class UploadService(
/// <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)
{
@@ -43,22 +52,23 @@ public sealed class UploadService(
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 { } target && await db.Sequences.GetAsync(target, cancellationToken) is null)
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 known = await db.Frames.FindBySha256Async(sha, cancellationToken);
if (known.Count > 0)
{
var frame = known.FirstOrDefault(f => f.SequenceId == request.SequenceId) ?? known[0];
return new StartUploadResponse(null, options.ChunkSizeBytes, [], AlreadyExists: true, frame.Id);
}
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);
if (caller.User.QuotaBytes > 0)
// 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)
@@ -81,7 +91,7 @@ public sealed class UploadService(
State = UploadState.Receiving,
Created = now,
UpdatedAt = now,
SessionKey = string.IsNullOrWhiteSpace(request.SessionKey) ? null : request.SessionKey.Trim(),
SessionKey = sessionKey,
}, cancellationToken);
store.Create(upload.Id, upload.Size);
return Started(upload);
@@ -97,6 +107,8 @@ public sealed class UploadService(
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));
// 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 } limit) limit.MaxRequestBodySize = upload.ChunkSize;
if (_chunksInFlight.AddOrUpdate(caller.Id, 1, (_, n) => n + 1) > options.ConcurrentChunksPerUser)
{
@@ -154,7 +166,7 @@ public sealed class UploadService(
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)
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));
@@ -170,7 +182,7 @@ public sealed class UploadService(
archive.Id,
upload.SequenceId,
NewSequenceTitle: null,
upload.SequenceId is null ? upload.SessionKey ?? "user-" + caller.Id.ToString("N") : null,
upload.SequenceId is null ? UploadRules.SessionKeyOf(upload.SessionKey, caller.Id) : null,
staged,
upload.FileName,
upload.Size,
@@ -190,7 +202,7 @@ public sealed class UploadService(
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) await db.Users.AddUsedBytesAsync(caller.Id, upload.Size, CancellationToken.None);
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);
@@ -199,6 +211,32 @@ public sealed class UploadService(
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.
@@ -230,6 +268,18 @@ public sealed class UploadService(
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);
@@ -239,4 +289,12 @@ public sealed class UploadService(
}
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;
}
}