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

@@ -33,9 +33,44 @@ public sealed record DownloadOptions
/// </summary>
public IReadOnlySet<int> ExpiredStatuses { get; init; } = new HashSet<int> { 403, 410 };
/// <summary>After this many failed attempts a file is «fallito».</summary>
/// <summary>
/// After this many failed attempts a file is «fallito». Every failure counts, expired addresses included: a file
/// whose renewed address is refused again does not send «Post singolo» to the site for ever.
/// </summary>
public int MaxAttempts { get; init; } = 5;
/// <summary>
/// How long a file waits before its next attempt after a failure that may pass (network error, 5xx, any status that
/// is not an expired address), by the number of failures it had before: 5 minutes, then 30 minutes, 2 hours and
/// 8 hours. Five attempts span about ten hours instead of a few passes.
/// </summary>
public IReadOnlyList<TimeSpan> RetryDelays { get; init; } =
[TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2), TimeSpan.FromHours(8)];
/// <summary>
/// Browser network errors (<c>netErrorName</c>) that mean «no connection at all»: the file is not to blame. No
/// attempt is counted, the pass ends and the queue waits <see cref="ConnectionPause"/>.
/// </summary>
public IReadOnlyList<string> ConnectionErrors { get; init; } =
[
"ERR_INTERNET_DISCONNECTED",
"ERR_NAME_NOT_RESOLVED",
"ERR_NAME_RESOLUTION_FAILED",
"ERR_NETWORK_CHANGED",
"ERR_ADDRESS_UNREACHABLE",
"ERR_NETWORK_IO_SUSPENDED",
"ERR_PROXY_CONNECTION_FAILED",
];
/// <summary>Wait after a connection error before the next pass.</summary>
public TimeSpan ConnectionPause { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>
/// Wait after a stop signal of the CDN (e.g. 429, spec §7.6) before the next pass: the first throttle stop of the
/// site lasts an hour too. The file that got it is not counted as a failure.
/// </summary>
public TimeSpan SignalPause { get; init; } = TimeSpan.FromHours(1);
/// <summary>How many pending files are read from the database at a time.</summary>
public int BatchSize { get; init; } = 200;
@@ -47,6 +82,9 @@ public sealed record DownloadOptions
public sealed record DownloadReport(int Stored, int Duplicates, int Skipped, int Expired, int Failed, int Retried, long Bytes, bool BudgetReached)
{
public int Total => Stored + Duplicates + Skipped + Expired + Failed + Retried;
/// <summary>Set when the queue stopped for a stop signal of the CDN or a connection error: no file is tried before then.</summary>
public DateTimeOffset? PausedUntil { get; init; }
}
/// <summary>
@@ -59,9 +97,11 @@ public sealed record DownloadReport(int Stored, int Duplicates, int Skipped, int
/// </summary>
/// <remarks>
/// It talks only to the CDN, never to the site, so it keeps working while the circuit breaker stops the site
/// (spec §7.6). The <c>HttpClient</c> fallback of §6.5 point 3 is deliberately not implemented: it stays behind
/// <see cref="IFileFetcher"/> until H7 says whether it is needed (decision in docs/decisioni.md).
/// Addresses are never logged.
/// (spec §7.6). A stop signal of the CDN itself (429) is reported through the <see cref="SignalDetector"/> — the page
/// never sees these responses — and the queue waits <see cref="DownloadOptions.SignalPause"/>. A failure that may pass
/// is retried later with a growing wait, kept in memory (a restart allows one early attempt). The <c>HttpClient</c>
/// fallback of §6.5 point 3 is deliberately not implemented: it stays behind <see cref="IFileFetcher"/> until H7 says
/// whether it is needed (decision in docs/decisioni.md). Addresses are never logged.
/// </remarks>
public sealed class DownloadQueue
{
@@ -72,11 +112,26 @@ public sealed class DownloadQueue
private readonly IClock _clock;
private readonly IRandomSource _random;
private readonly DownloadOptions _options;
private readonly SignalDetector? _signals;
private readonly CollectionWriter _writer;
private readonly SemaphoreSlim _wake = new(0, int.MaxValue);
private readonly SemaphoreSlim _wake = new(0, 1);
private readonly Lock _randomGate = new();
private readonly Lock _pauseGate = new();
private readonly ConcurrentDictionary<long, DateTimeOffset> _retryAt = new();
private DateTimeOffset? _pausedUntil;
public DownloadQueue(IFebeStorage storage, LibraryIngest ingest, IFileFetcher fetcher, IDataBudget budget, IClock clock, IRandomSource random, DownloadOptions options)
/// <param name="storage">Database.</param>
/// <param name="ingest">Puts the files into the library.</param>
/// <param name="fetcher">Downloads from the CDN.</param>
/// <param name="budget">Daily data budget.</param>
/// <param name="clock">Time.</param>
/// <param name="random">Pauses between files.</param>
/// <param name="options">Options.</param>
/// <param name="signals">
/// Stop signals (spec §7.6): statuses of the CDN that match a rule of <c>segnali.json</c> are reported to the
/// circuit breaker and stop the queue for a while. Null: downloads raise no signal.
/// </param>
public DownloadQueue(IFebeStorage storage, LibraryIngest ingest, IFileFetcher fetcher, IDataBudget budget, IClock clock, IRandomSource random, DownloadOptions options, SignalDetector? signals = null)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_ingest = ingest ?? throw new ArgumentNullException(nameof(ingest));
@@ -85,6 +140,7 @@ public sealed class DownloadQueue
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_random = random ?? throw new ArgumentNullException(nameof(random));
_options = options ?? throw new ArgumentNullException(nameof(options));
_signals = signals;
if (_options.MaxConcurrent is < 1 or > 2)
{
throw new ArgumentOutOfRangeException(nameof(options), "Al massimo due scaricamenti insieme (specifica §6.5).");
@@ -96,8 +152,33 @@ public sealed class DownloadQueue
/// <summary>Raised after each file, for the interface (no addresses).</summary>
public event EventHandler<DownloadProgress>? Progress;
/// <summary>New files are waiting: ends the idle wait of <see cref="RunAsync"/>.</summary>
public void Wake() => _wake.Release();
/// <summary>Until when the queue is stopped by a signal of the CDN or a connection error; null when it is not.</summary>
public DateTimeOffset? PausedUntil
{
get
{
lock (_pauseGate)
{
return _pausedUntil is { } until && until > _clock.Now ? until : null;
}
}
}
/// <summary>
/// New files are waiting: ends the idle wait of <see cref="RunAsync"/>. Many calls during a pass give one more
/// pass, not one each.
/// </summary>
public void Wake()
{
try
{
_wake.Release();
}
catch (SemaphoreFullException)
{
// A pass is already due.
}
}
/// <summary>Works until cancelled: a pass over the waiting files, then an idle wait.</summary>
public async Task RunAsync(CancellationToken ct)
@@ -105,6 +186,18 @@ public sealed class DownloadQueue
while (!ct.IsCancellationRequested)
{
var report = await RunOnceAsync(ct).ConfigureAwait(false);
if (report.PausedUntil is { } until)
{
// A stop of the CDN or a missing connection: nothing wakes the queue before its time.
var left = until - _clock.Now;
if (left > TimeSpan.Zero)
{
await _clock.Delay(left, ct).ConfigureAwait(false);
}
continue;
}
var wait = report.BudgetReached ? TimeSpan.FromMinutes(30) : _options.IdlePoll;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
var woken = _wake.WaitAsync(linked.Token);
@@ -123,18 +216,33 @@ public sealed class DownloadQueue
}
}
/// <summary>One pass: downloads what is waiting until nothing is left or the data budget is reached.</summary>
/// <summary>
/// One pass: downloads what is waiting and due, until nothing is left, the data budget is reached, or the CDN or
/// the connection says to stop.
/// </summary>
public async Task<DownloadReport> RunOnceAsync(CancellationToken ct)
{
Directory.CreateDirectory(_options.StagingFolder);
var tally = new Tally();
if (PausedUntil is { } paused)
{
tally.Pause(paused);
return tally.ToReport();
}
Directory.CreateDirectory(_options.StagingFolder);
var attempted = new ConcurrentDictionary<long, bool>();
var accounts = new ConcurrentDictionary<long, Account?>();
var singlePostQueued = new ConcurrentDictionary<long, bool>();
while (!ct.IsCancellationRequested && !tally.BudgetReached)
while (!ct.IsCancellationRequested && !tally.Stopped)
{
var batch = (await _storage.Media.ListPendingDownloadsAsync(_options.BatchSize, ct).ConfigureAwait(false))
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id))
// Files tried in this pass, or waiting for their next attempt, stay at the head of the queue order: the
// window grows past them, so that they never hide the files behind.
var now = _clock.Now;
var waiting = _retryAt.Count(r => r.Value > now);
var window = (int)Math.Min(10_000L, (long)_options.BatchSize + attempted.Count + waiting);
var batch = (await _storage.Media.ListPendingDownloadsAsync(window, ct).ConfigureAwait(false))
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now))
.Take(_options.BatchSize)
.ToList();
if (batch.Count == 0)
{
@@ -145,7 +253,7 @@ public sealed class DownloadQueue
var workers = Enumerable.Range(0, _options.MaxConcurrent).Select(_ => Task.Run(
async () =>
{
while (!tally.BudgetReached && queue.TryDequeue(out var pending))
while (!tally.Stopped && queue.TryDequeue(out var pending))
{
attempted[pending.Media.Id] = true;
await ProcessAsync(pending, tally, accounts, singlePostQueued, ct).ConfigureAwait(false);
@@ -159,6 +267,22 @@ public sealed class DownloadQueue
return tally.ToReport();
}
private bool IsDue(long mediaId, DateTimeOffset now)
{
if (!_retryAt.TryGetValue(mediaId, out var at))
{
return true;
}
if (at > now)
{
return false;
}
_retryAt.TryRemove(mediaId, out _);
return true;
}
private TimeSpan DrawPause()
{
lock (_randomGate)
@@ -167,18 +291,35 @@ public sealed class DownloadQueue
}
}
private void PauseUntil(DateTimeOffset until, Tally tally)
{
lock (_pauseGate)
{
if (_pausedUntil is not { } current || current < until)
{
_pausedUntil = until;
}
}
tally.Pause(until);
}
private async Task ProcessAsync(PendingDownload pending, Tally tally, ConcurrentDictionary<long, Account?> accounts, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
{
var media = pending.Media;
if (!accounts.TryGetValue(pending.AccountId, out var account))
{
account = await _storage.Accounts.GetAsync(pending.AccountId, ct).ConfigureAwait(false);
accounts[pending.AccountId] = account;
}
var entry = await _storage.Entries.GetAsync(media.EntryId, ct).ConfigureAwait(false);
if (account is null || entry is null)
// The batch is a snapshot that takes minutes to go through: Alberto may have deleted the entry since, or a
// recipe may have given the file a fresh address.
var entry = await _storage.Entries.GetAsync(pending.Media.EntryId, ct).ConfigureAwait(false);
var media = await _storage.Media.GetAsync(pending.Media.Id, ct).ConfigureAwait(false);
if (account is null || entry is null || entry.State == EntryState.Deleted
|| media is null || media.State != MediaState.ToDownload || media.SourceUrl is null)
{
_retryAt.TryRemove(pending.Media.Id, out _);
return;
}
@@ -205,6 +346,7 @@ public sealed class DownloadQueue
var maxBytes = media.Kind == MediaKind.Video ? account.Limits.MaxVideoBytes : null;
var temp = Path.Combine(_options.StagingFolder, $"{SafeFileWriter.TempPrefix}{Guid.NewGuid():N}{SafeFileWriter.TempSuffix}");
using var reservation = SafeFileWriter.ReserveTemporaryFile(temp);
try
{
FetchResult result;
@@ -213,10 +355,16 @@ public sealed class DownloadQueue
result = await _fetcher.FetchAsync(address, file, new FetchOptions(maxBytes), ct).ConfigureAwait(false);
}
if (result.Bytes > 0)
// What crossed the network counts, also when less was written (a file over the limit is loaded whole).
if (result.BudgetBytes > 0)
{
await _budget.RecordAsync(result.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(result.Bytes);
await _budget.RecordAsync(result.BudgetBytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(result.BudgetBytes);
}
if (result.Outcome == FetchOutcome.HttpError && result.HttpStatus is { } signalled && StopSignal(address, signalled, tally))
{
return; // the CDN asked to stop: not the file's fault, no attempt counted
}
switch (result.Outcome)
@@ -227,6 +375,7 @@ public sealed class DownloadQueue
case FetchOutcome.TooLarge:
var limit = maxBytes is { } m ? ItalianText.Number(Math.Max(1, m / (1024 * 1024))) : "?";
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, $"Video oltre il limite di {limit} MB impostato per l'account.", _clock.Now, ct).ConfigureAwait(false);
_retryAt.TryRemove(media.Id, out _);
tally.Add(ref tally.Skipped);
Report(media, entry, DownloadStep.Skipped);
return;
@@ -235,28 +384,27 @@ public sealed class DownloadQueue
return;
case FetchOutcome.HostNotAllowed:
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "L'indirizzo non è del CDN: non si scarica (specifica §6.5).", _clock.Now, ct).ConfigureAwait(false);
_retryAt.TryRemove(media.Id, out _);
tally.Add(ref tally.Failed);
Report(media, entry, DownloadStep.Failed);
return;
case FetchOutcome.NetworkError when IsConnectionError(result.Error):
// No connection at all (router restarting, cable out): every file would fail the same way.
PauseUntil(_clock.Now + _options.ConnectionPause, tally);
return;
default:
var error = result.HttpStatus is { } code
? $"Il CDN ha risposto {code.ToString(CultureInfo.InvariantCulture)}."
: $"Errore di rete durante lo scaricamento ({result.Error ?? "senza dettagli"}).";
if (media.Attempts + 1 >= _options.MaxAttempts)
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Failed);
Report(media, entry, DownloadStep.Failed);
}
else
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, error, _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Retried);
}
await RetryLaterAsync(entry, media, error, tally, ct).ConfigureAwait(false);
return;
}
}
catch (EntryDeletedException)
{
// Deleted while it was downloading: Alberto's choice wins, nothing entered the library.
_retryAt.TryRemove(media.Id, out _);
}
catch (FileTooLargeException)
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
@@ -264,9 +412,8 @@ public sealed class DownloadQueue
}
catch (IOException ex)
{
// Disk full or similar: the file waits for the next pass (nothing was written under the final name).
await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, $"Scrittura non riuscita: {ex.GetType().Name}.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
tally.Add(ref tally.Retried);
// Disk full or similar: the file waits for a later pass (nothing was written under the final name).
await RetryLaterAsync(entry, media, $"Scrittura non riuscita: {ex.GetType().Name}.", tally, CancellationToken.None).ConfigureAwait(false);
}
finally
{
@@ -274,6 +421,49 @@ public sealed class DownloadQueue
}
}
/// <summary>
/// A status of the CDN that is a stop signal (segnali.json, e.g. 429): reported to the circuit breaker, the pass
/// ends and the queue waits. Returns false when the status is not a signal.
/// </summary>
private bool StopSignal(Uri address, int status, Tally tally)
{
if (_signals?.ObserveDownload(address, status) is null)
{
return false;
}
PauseUntil(_clock.Now + _options.SignalPause, tally);
return true;
}
private bool IsConnectionError(string? error) =>
error is not null && _options.ConnectionErrors.Any(e => error.Contains(e, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// A failure that may pass: the file waits for a later attempt, a little longer each time; after
/// <see cref="DownloadOptions.MaxAttempts"/> failures it is «fallito».
/// </summary>
private async Task RetryLaterAsync(Entry entry, Media media, string error, Tally tally, CancellationToken ct)
{
if (media.Attempts + 1 >= _options.MaxAttempts)
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, error, _clock.Now, ct).ConfigureAwait(false);
_retryAt.TryRemove(media.Id, out _);
tally.Add(ref tally.Failed);
Report(media, entry, DownloadStep.Failed);
return;
}
await _storage.Media.MarkFailedAsync(media.Id, MediaState.ToDownload, error, _clock.Now, ct).ConfigureAwait(false);
var delays = _options.RetryDelays;
if (delays.Count > 0)
{
_retryAt[media.Id] = _clock.Now + delays[Math.Clamp(media.Attempts, 0, delays.Count - 1)];
}
tally.Add(ref tally.Retried);
}
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct)
{
MemoryStream? cover = null;
@@ -283,10 +473,15 @@ public sealed class DownloadQueue
{
var buffer = new MemoryStream();
var fetched = await _fetcher.FetchAsync(coverAddress, buffer, new FetchOptions(8L * 1024 * 1024), ct).ConfigureAwait(false);
if (fetched.Bytes > 0)
if (fetched.BudgetBytes > 0)
{
await _budget.RecordAsync(fetched.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(fetched.Bytes);
await _budget.RecordAsync(fetched.BudgetBytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(fetched.BudgetBytes);
}
if (fetched.Outcome == FetchOutcome.HttpError && fetched.HttpStatus is { } status)
{
StopSignal(coverAddress, status, tally); // the video itself is already here: it is kept
}
if (fetched.Succeeded)
@@ -315,6 +510,7 @@ public sealed class DownloadQueue
ct).ConfigureAwait(false);
}
_retryAt.TryRemove(media.Id, out _);
if (saved.Outcome == MediaSaveOutcome.Stored)
{
tally.Add(ref tally.Stored);
@@ -369,14 +565,32 @@ public sealed class DownloadQueue
}
}
/// <summary>An expired address: back to wait and «Post singolo» queued; stories cannot be recovered (§6.5 point 5).</summary>
/// <summary>
/// An expired address (§6.5 point 5): a post file goes back to wait and «Post singolo» is queued; highlight items
/// and profile pictures wait for the next reading that gives them a fresh address; stories cannot be recovered.
/// A file whose renewed address is refused again and again ends «fallito» after
/// <see cref="DownloadOptions.MaxAttempts"/> failures, instead of sending «Post singolo» to the site for ever.
/// </summary>
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
{
_retryAt.TryRemove(media.Id, out _);
if (entry.Kind != EntryKind.Story && media.Attempts + 1 >= _options.MaxAttempts)
{
var attempts = ItalianText.Number(media.Attempts + 1);
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, $"Indirizzo rifiutato anche dopo il rinnovo ({attempts} tentativi): il file resta «fallito».", _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Failed);
Report(media, entry, DownloadStep.Failed);
return;
}
if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture)
{
var why = entry.Kind == EntryKind.Story
? "Indirizzo scaduto: per le storie non c'è recupero dopo la scadenza."
: "Indirizzo scaduto: si rinnova alla prossima lettura del profilo.";
var why = entry.Kind switch
{
EntryKind.Story => "Indirizzo scaduto: per le storie non c'è recupero dopo la scadenza.",
EntryKind.Highlight => "Indirizzo scaduto: si rinnova alla prossima apertura della raccolta.",
_ => "Indirizzo scaduto: si rinnova al prossimo controllo del profilo.",
};
await _storage.Media.MarkFailedAsync(media.Id, entry.Kind == EntryKind.Story ? MediaState.Failed : MediaState.Expired, why, _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Expired);
Report(media, entry, DownloadStep.Expired);
@@ -457,8 +671,11 @@ public sealed class DownloadQueue
public int Expired;
public int Failed;
public int Retried;
private readonly Lock _gate = new();
private long _bytes;
private volatile bool _budgetReached;
private volatile bool _paused;
private DateTimeOffset? _pausedUntil;
public bool BudgetReached
{
@@ -466,12 +683,33 @@ public sealed class DownloadQueue
set => _budgetReached = value;
}
/// <summary>The pass must end: budget reached, or a signal of the CDN, or no connection.</summary>
public bool Stopped => _budgetReached || _paused;
public void Pause(DateTimeOffset until)
{
lock (_gate)
{
if (_pausedUntil is not { } current || current < until)
{
_pausedUntil = until;
}
}
_paused = true;
}
public void Add(ref int counter) => Interlocked.Increment(ref counter);
public void AddBytes(long bytes) => Interlocked.Add(ref _bytes, bytes);
public DownloadReport ToReport() =>
new(Stored, Duplicates, Skipped, Expired, Failed, Retried, Interlocked.Read(ref _bytes), BudgetReached);
public DownloadReport ToReport()
{
lock (_gate)
{
return new(Stored, Duplicates, Skipped, Expired, Failed, Retried, Interlocked.Read(ref _bytes), BudgetReached) { PausedUntil = _pausedUntil };
}
}
}
}