Raccolta: 429 del CDN come rallentamento, attese crescenti e recupero dei falliti, storico e seguiti senza pagina di ripresa, lacuna sotto la prima pagina, eliminazioni durante lo scaricamento (regole-3, cdn-429, dl-1, post-loop, walk-1, check-1, scroll-1, reader-1, h9-1, ring-1, library-2, dedup-1, tmp-1, budget-1, regole-4, kind-1, vocab-1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-14 00:23:03 +00:00
1 parent 78c92eb2a4
commit b16e3a837d
28 files changed
+2619 -200

No files matched your search

+165 -34
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
@@ -50,6 +51,28 @@ public sealed class ContentChangedException : IOException
}
}
/// <summary>
/// The entry or the file record went away (Alberto deleted it) while the content was on its way: nothing was kept in
/// the library and no journal line was written.
/// </summary>
public sealed class EntryDeletedException : IOException
{
public EntryDeletedException()
: base("L'elemento è stato eliminato mentre il file si salvava: il file non entra in libreria.")
{
}
public EntryDeletedException(string message)
: base(message)
{
}
public EntryDeletedException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public enum MediaSaveOutcome
{
/// <summary>The file is in the library and its record is updated.</summary>
@@ -87,6 +110,14 @@ public sealed class LibraryIngest(
bool setFileTimeToPublication = true,
SafeFileWriter? writer = null)
{
/// <summary>
/// One gate per account folder, for every writer of the process: the §9.5 check «identical to a file of the
/// account?» and the record of the new file happen as one step, so two downloads (or a download and an import)
/// with the same bytes cannot both enter the library.
/// </summary>
private static readonly ConcurrentDictionary<string, SemaphoreSlim> AccountGates =
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength);
private volatile LibraryNaming _naming = naming;
private volatile bool _setFileTimeToPublication = setFileTimeToPublication;
@@ -129,6 +160,9 @@ public sealed class LibraryIngest(
/// The content exceeded <see cref="MediaContent.MaxBytes"/>: nothing was written; the caller marks the file
/// <see cref="MediaState.Skipped"/> with <see cref="IMediaStore.MarkFailedAsync"/>.
/// </exception>
/// <exception cref="EntryDeletedException">
/// The entry or the file record was deleted while the content was on its way: nothing was kept, no journal line.
/// </exception>
/// <exception cref="IOException">Writing failed (disk full, connection cut): nothing was written under the final name.</exception>
public async Task<MediaSaveResult> SaveMediaAsync(
Account account,
@@ -156,41 +190,75 @@ public sealed class LibraryIngest(
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle), zone);
var directory = provisional.Contains('/', StringComparison.Ordinal) ? provisional[..provisional.LastIndexOf('/')] : string.Empty;
MediaLocation? identical = null;
var saved = await _writer.SaveAsync(
content.Content,
folder,
directory,
async (digest, token) =>
{
if (content.ExpectedSha256 is { } expected && !string.Equals(expected, digest.Sha256, StringComparison.OrdinalIgnoreCase))
{
throw new ContentChangedException("Il contenuto letto è diverso da quello atteso: il file non viene salvato.");
}
var same = await storage.Media.FindBySha256Async(digest.Sha256, token).ConfigureAwait(false);
identical = same.FirstOrDefault(s => s.Entry.AccountId == account.Id && s.Media.Id != media.Id && EntryStateRules.IsPresent(s.Media.State));
if (identical is not null)
{
return null;
}
return content.FixedRelativePath is not null
? provisional
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone);
},
new SafeWriteOptions
{
LastWriteTime = _setFileTimeToPublication ? entry.PublishedAt : null,
MaxBytes = content.MaxBytes,
},
ct).ConfigureAwait(false);
if (saved is null)
// The content is written and hashed outside the gate; from the §9.5 check to the record of the file the account
// is held, so that the check sees every file of the account already decided.
var gate = AccountGates.GetOrAdd(Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)), _ => new SemaphoreSlim(1, 1));
SemaphoreSlim? held = null;
try
{
return new MediaSaveResult(MediaSaveOutcome.IdenticalInAccount, null, identical, []);
}
MediaLocation? identical = null;
var gone = false;
var saved = await _writer.SaveAsync(
content.Content,
folder,
directory,
async (digest, token) =>
{
if (content.ExpectedSha256 is { } expected && !string.Equals(expected, digest.Sha256, StringComparison.OrdinalIgnoreCase))
{
throw new ContentChangedException("Il contenuto letto è diverso da quello atteso: il file non viene salvato.");
}
await gate.WaitAsync(token).ConfigureAwait(false);
held = gate;
// Alberto may have deleted the entry while the content was on its way (a download takes minutes in
// the queue): its choice wins, the content does not enter the library.
if (await IsGoneAsync(entry.Id, media.Id, token).ConfigureAwait(false))
{
gone = true;
return null;
}
var same = await storage.Media.FindBySha256Async(digest.Sha256, token).ConfigureAwait(false);
identical = same.FirstOrDefault(s => s.Entry.AccountId == account.Id && s.Media.Id != media.Id && EntryStateRules.IsPresent(s.Media.State));
if (identical is not null)
{
return null;
}
return content.FixedRelativePath is not null
? provisional
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone);
},
new SafeWriteOptions
{
LastWriteTime = _setFileTimeToPublication ? entry.PublishedAt : null,
MaxBytes = content.MaxBytes,
},
ct).ConfigureAwait(false);
if (gone)
{
throw new EntryDeletedException();
}
if (saved is null)
{
return new MediaSaveResult(MediaSaveOutcome.IdenticalInAccount, null, identical, []);
}
return await RecordAsync(account, entry, media, content, saved).ConfigureAwait(false);
}
finally
{
held?.Release();
}
}
/// <summary>The file is on disk under its final name: hashes, thumbnail, record, probable duplicates.</summary>
private async Task<MediaSaveResult> RecordAsync(Account account, Entry entry, Media media, MediaContent content, SavedFile saved)
{
ulong? hash = null;
int? width = media.Width, height = media.Height;
var hasThumbnail = false;
@@ -215,7 +283,23 @@ public sealed class LibraryIngest(
var stored = new StoredFile(saved.RelativePath, saved.Bytes, saved.Sha256, hash, width, height, media.Duration, hasThumbnail);
var state = entry.Provenance == Provenance.Imported ? MediaState.Imported : MediaState.Downloaded;
var now = clock.Now;
await storage.Media.MarkStoredAsync(media.Id, stored, state, now, CancellationToken.None).ConfigureAwait(false);
bool recorded;
try
{
recorded = await storage.Media.MarkStoredAsync(media.Id, stored, state, now, CancellationToken.None).ConfigureAwait(false);
}
catch (KeyNotFoundException)
{
recorded = false; // «Eliminalo e lascia che torni»: the record itself is gone
}
if (!recorded)
{
// Deleted between the check and the record: the file just written belongs to nothing. It is this
// operation's own file, never one of the library: it goes, as Alberto's deletion asked.
await DiscardAsync(saved, hasThumbnail).ConfigureAwait(false);
throw new EntryDeletedException();
}
var pairs = new List<DuplicatePair>();
if (hash is { } h && hashIndex is not null)
@@ -249,6 +333,11 @@ public sealed class LibraryIngest(
{
var stored = await storage.Entries.GetWithMediaAsync(entryId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
if (stored.Entry.State == EntryState.Deleted)
{
return; // a «save» line after the «delete» line would bring the entry back with a rebuild
}
var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Account {stored.Entry.AccountId} non trovato.");
var highlights = await storage.Highlights.ListForEntryAsync(entryId, ct).ConfigureAwait(false);
@@ -261,6 +350,48 @@ public sealed class LibraryIngest(
ct).ConfigureAwait(false);
}
/// <summary>True when the entry or the file record no longer wants content: removed, or «eliminato».</summary>
private async Task<bool> IsGoneAsync(long entryId, long mediaId, CancellationToken ct)
{
var current = await storage.Entries.GetAsync(entryId, ct).ConfigureAwait(false);
if (current is null || current.State == EntryState.Deleted)
{
return true;
}
var file = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
return file is null || file.State == MediaState.Deleted;
}
/// <summary>Removes a file this operation has just written and that no record took, with its thumbnail when unused.</summary>
private async Task DiscardAsync(SavedFile saved, bool hasThumbnail)
{
try
{
File.Delete(saved.FullPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: the file stays without a record, and without a journal line it never brings the entry back.
}
if (hasThumbnail && thumbnails is not null)
{
var users = await storage.Media.FindBySha256Async(saved.Sha256, CancellationToken.None).ConfigureAwait(false);
if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State)))
{
try
{
thumbnails.Delete(saved.Sha256);
}
catch (IOException)
{
// A thumbnail left behind costs a few kilobytes.
}
}
}
}
private bool TryThumbnail(string key, Func<Stream> open, bool owned)
{
if (thumbnails is null)
+31 -2
View File
@@ -1,4 +1,5 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
@@ -71,6 +72,23 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
/// <summary>Serializes «is the name free? then rename» across all writers of the process.</summary>
private static readonly Lock MoveGate = new();
/// <summary>Temporary files this process is writing now: the clean-up of a previous run never touches them.</summary>
private static readonly ConcurrentDictionary<string, byte> LiveTemporaryFiles =
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
/// <summary>
/// Marks a temporary file this process is about to write: <see cref="CleanupTemporaryFiles"/> leaves it alone
/// until the returned handle is disposed. The clean-up of an interrupted run can still be going through a large
/// library while the first downloads of this run are written (on Linux a deleted open file would be lost).
/// </summary>
public static IDisposable ReserveTemporaryFile(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var key = Path.GetFullPath(path);
LiveTemporaryFiles[key] = 0;
return new TemporaryFileReservation(key);
}
/// <summary>Writes <paramref name="source"/> to <paramref name="relativePath"/> inside <paramref name="rootFolder"/>.</summary>
public Task<SavedFile> SaveAsync(Stream source, string rootFolder, string relativePath, SafeWriteOptions? options = null, CancellationToken ct = default)
{
@@ -120,6 +138,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
using var reservation = ReserveTemporaryFile(tempPath);
try
{
@@ -156,8 +175,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
}
/// <summary>
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>).
/// Returns how many were removed.
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>), except
/// those this process is writing (<see cref="ReserveTemporaryFile"/>). Returns how many were removed.
/// </summary>
public static int CleanupTemporaryFiles(string folder, bool recursive = true)
{
@@ -173,6 +192,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
new EnumerationOptions { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = 0 });
foreach (var file in files)
{
if (LiveTemporaryFiles.ContainsKey(Path.GetFullPath(file)))
{
continue; // being written by this process right now
}
if (TryDelete(file))
{
removed++;
@@ -272,6 +296,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
throw new IOException($"Nessun nome libero per {desiredRelativePath} dopo {MaxNameAttempts} tentativi.");
}
private sealed class TemporaryFileReservation(string key) : IDisposable
{
public void Dispose() => LiveTemporaryFiles.TryRemove(key, out _);
}
private static bool TryDelete(string path)
{
try