fix(upload): repairs charge no quota and another sequence's copy no longer blocks them

A re-upload that repairs a missing or damaged frame is now reported as
IngestResult.Repaired and adds nothing to the uploader's used bytes; the
quota checks at start and completion skip uploads whose target sequence
already holds the content. The start shortcut and crash recovery share
one rule (UploadRules.StandIn): an intact copy stands for the upload, the
target sequence's own copy first, except when the target holds the
content only in damaged copies, which the upload's bytes then repair.
A sequence adopted at the archive root that holds frames is never given
a new folder when its root sidecar is missing.

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 10:53:49 +00:00
1 parent bb55e47b47
commit 886132b5bb
8 files changed
+150 -39

No files matched your search

+14 -5
View File
@@ -1,3 +1,4 @@
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Repositories;
using Titano.Server.Configuration;
@@ -45,16 +46,15 @@ public sealed class UploadMaintenance(TitanoDatabase db, ServerOptions options,
}
/// <summary>
/// Uploads left committing by a crash: committed when an intact frame with their hash exists, otherwise back to
/// receiving (the partial file is intact, so the client simply completes again and the ingest files or repairs it).
/// 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.FindIntactBySha256Async(upload.Sha256, cancellationToken)).FirstOrDefault(f => UploadRules.IsOnDisk(archive.Root, f))
: 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);
@@ -68,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();
+32 -5
View File
@@ -1,4 +1,5 @@
using Titano.Core.Model;
using Titano.Data;
namespace Titano.Server.Storage;
@@ -32,14 +33,40 @@ public static class UploadRules
return received;
}
/// <summary>
/// The frame's original is in the archive with its recorded size. Together with flags that say neither missing nor
/// corrupt (<c>FindIntactBySha256Async</c>), that is the copy an upload of the same content may stand for; a damaged
/// one is repaired by uploading the content again.
/// </summary>
/// <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)
{
+25 -13
View File
@@ -19,7 +19,7 @@ namespace Titano.Server.Storage;
/// 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.
/// 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,
@@ -45,23 +45,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 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.
var known = (await db.Frames.FindIntactBySha256Async(sha, cancellationToken)).Where(f => UploadRules.IsOnDisk(archive.Root, f)).ToList();
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);
}
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)
@@ -84,7 +84,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);
@@ -159,7 +159,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));
@@ -175,7 +175,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,
@@ -195,7 +195,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);
@@ -235,6 +235,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);