Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

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-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

@@ -0,0 +1,489 @@
using System.Collections.Concurrent;
using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Pacing;
using Febe.Core.Storage;
namespace Febe.Core.Collection.Downloads;
/// <summary>Options of the download queue (spec §6.5).</summary>
public sealed record DownloadOptions
{
/// <summary>
/// Folder for the temporary copy of a file while it downloads (under Dati, never the library). A partial download
/// never leaves a file with its final name (spec §6.5 point 4).
/// </summary>
public required string StagingFolder { get; init; }
/// <summary>At most two downloads at the same time (spec §6.5 point 6).</summary>
public int MaxConcurrent { get; init; } = 2;
/// <summary>Small random pause after each file.</summary>
public TimeSpan PauseMin { get; init; } = TimeSpan.FromMilliseconds(400);
public TimeSpan PauseMax { get; init; } = TimeSpan.FromSeconds(3);
/// <summary>
/// HTTP statuses that mean «the signed address expired». 403 and 410 for the test site; for the real CDN they are
/// a hypothesis to confirm with H7 in M0.
/// </summary>
public IReadOnlySet<int> ExpiredStatuses { get; init; } = new HashSet<int> { 403, 410 };
/// <summary>After this many failed attempts a file is «fallito».</summary>
public int MaxAttempts { get; init; } = 5;
/// <summary>How many pending files are read from the database at a time.</summary>
public int BatchSize { get; init; } = 200;
/// <summary>When idle, how long to wait before looking at the database again (a <see cref="DownloadQueue.Wake"/> ends it earlier).</summary>
public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1);
}
/// <summary>What one pass of the queue did.</summary>
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>
/// The download queue (spec §6.5): files waiting in the database, stories first (they expire), at most two at the
/// same time with small random pauses, inside the daily data budget. Each file goes through <see cref="IFileFetcher"/>
/// (the browser, <c>Network.loadNetworkResource</c>) into a temporary file and then into the library through
/// <see cref="LibraryIngest"/> (final name, SHA-256, duplicates of §9.5). The account's settings apply: video size
/// limit and «video delle storie» (skipped files become «saltato»). An expired address sends the file back to wait
/// and queues «Post singolo» — never for stories, which cannot be recovered.
/// </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.
/// </remarks>
public sealed class DownloadQueue
{
private readonly IFebeStorage _storage;
private readonly LibraryIngest _ingest;
private readonly IFileFetcher _fetcher;
private readonly IDataBudget _budget;
private readonly IClock _clock;
private readonly IRandomSource _random;
private readonly DownloadOptions _options;
private readonly CollectionWriter _writer;
private readonly SemaphoreSlim _wake = new(0, int.MaxValue);
private readonly Lock _randomGate = new();
public DownloadQueue(IFebeStorage storage, LibraryIngest ingest, IFileFetcher fetcher, IDataBudget budget, IClock clock, IRandomSource random, DownloadOptions options)
{
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
_ingest = ingest ?? throw new ArgumentNullException(nameof(ingest));
_fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher));
_budget = budget ?? throw new ArgumentNullException(nameof(budget));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_random = random ?? throw new ArgumentNullException(nameof(random));
_options = options ?? throw new ArgumentNullException(nameof(options));
if (_options.MaxConcurrent is < 1 or > 2)
{
throw new ArgumentOutOfRangeException(nameof(options), "Al massimo due scaricamenti insieme (specifica §6.5).");
}
_writer = new CollectionWriter(storage, clock);
}
/// <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>Works until cancelled: a pass over the waiting files, then an idle wait.</summary>
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var report = await RunOnceAsync(ct).ConfigureAwait(false);
var wait = report.BudgetReached ? TimeSpan.FromMinutes(30) : _options.IdlePoll;
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
var woken = _wake.WaitAsync(linked.Token);
var slept = _clock.Delay(wait, linked.Token);
await Task.WhenAny(woken, slept).ConfigureAwait(false);
await linked.CancelAsync().ConfigureAwait(false);
try
{
await Task.WhenAll(woken, slept).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
ct.ThrowIfCancellationRequested();
}
}
/// <summary>One pass: downloads what is waiting until nothing is left or the data budget is reached.</summary>
public async Task<DownloadReport> RunOnceAsync(CancellationToken ct)
{
Directory.CreateDirectory(_options.StagingFolder);
var tally = new Tally();
var attempted = new ConcurrentDictionary<long, bool>();
var accounts = new ConcurrentDictionary<long, Account?>();
var singlePostQueued = new ConcurrentDictionary<long, bool>();
while (!ct.IsCancellationRequested && !tally.BudgetReached)
{
var batch = (await _storage.Media.ListPendingDownloadsAsync(_options.BatchSize, ct).ConfigureAwait(false))
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id))
.ToList();
if (batch.Count == 0)
{
break;
}
var queue = new ConcurrentQueue<PendingDownload>(batch);
var workers = Enumerable.Range(0, _options.MaxConcurrent).Select(_ => Task.Run(
async () =>
{
while (!tally.BudgetReached && queue.TryDequeue(out var pending))
{
attempted[pending.Media.Id] = true;
await ProcessAsync(pending, tally, accounts, singlePostQueued, ct).ConfigureAwait(false);
await _clock.Delay(DrawPause(), ct).ConfigureAwait(false);
}
},
ct)).ToList();
await Task.WhenAll(workers).ConfigureAwait(false);
}
return tally.ToReport();
}
private TimeSpan DrawPause()
{
lock (_randomGate)
{
return _random.Between(_options.PauseMin, _options.PauseMax);
}
}
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)
{
return;
}
if (CollectionWriter.SkipReason(account, entry.Kind, media.Kind) is { } reason)
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, reason, _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Skipped);
Report(media, entry, DownloadStep.Skipped);
return;
}
if (await _budget.RemainingTodayAsync(ct).ConfigureAwait(false) <= 0)
{
tally.BudgetReached = true;
return;
}
if (!Uri.TryCreate(media.SourceUrl, UriKind.Absolute, out var address))
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Failed, "Indirizzo del file non valido.", _clock.Now, ct).ConfigureAwait(false);
tally.Add(ref tally.Failed);
return;
}
var maxBytes = media.Kind == MediaKind.Video ? account.Limits.MaxVideoBytes : null;
var temp = Path.Combine(_options.StagingFolder, $"{SafeFileWriter.TempPrefix}{Guid.NewGuid():N}{SafeFileWriter.TempSuffix}");
try
{
FetchResult result;
await using (var file = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true))
{
result = await _fetcher.FetchAsync(address, file, new FetchOptions(maxBytes), ct).ConfigureAwait(false);
}
if (result.Bytes > 0)
{
await _budget.RecordAsync(result.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(result.Bytes);
}
switch (result.Outcome)
{
case FetchOutcome.Completed:
await IngestAsync(account, entry, media, temp, maxBytes, tally, ct).ConfigureAwait(false);
return;
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);
tally.Add(ref tally.Skipped);
Report(media, entry, DownloadStep.Skipped);
return;
case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status):
await ExpiredAsync(entry, media, tally, singlePostQueued, ct).ConfigureAwait(false);
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);
tally.Add(ref tally.Failed);
Report(media, entry, DownloadStep.Failed);
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);
}
return;
}
}
catch (FileTooLargeException)
{
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Video oltre il limite impostato per l'account.", _clock.Now, CancellationToken.None).ConfigureAwait(false);
tally.Add(ref tally.Skipped);
}
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);
}
finally
{
TryDelete(temp);
}
}
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, Tally tally, CancellationToken ct)
{
MemoryStream? cover = null;
try
{
if (media.Kind == MediaKind.Video && Uri.TryCreate(media.CoverUrl, UriKind.Absolute, out var coverAddress))
{
var buffer = new MemoryStream();
var fetched = await _fetcher.FetchAsync(coverAddress, buffer, new FetchOptions(8L * 1024 * 1024), ct).ConfigureAwait(false);
if (fetched.Bytes > 0)
{
await _budget.RecordAsync(fetched.Bytes, account.Id, CancellationToken.None).ConfigureAwait(false);
tally.AddBytes(fetched.Bytes);
}
if (fetched.Succeeded)
{
buffer.Position = 0;
cover = buffer;
}
else
{
await buffer.DisposeAsync().ConfigureAwait(false);
}
}
var highlightTitle = entry.Kind == EntryKind.Highlight
? (await _storage.Highlights.ListForEntryAsync(entry.Id, ct).ConfigureAwait(false)).OrderBy(h => h.Position).FirstOrDefault()?.Title
: null;
MediaSaveResult saved;
await using (var content = new FileStream(temp, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true))
{
saved = await _ingest.SaveMediaAsync(
account,
entry,
media,
new MediaContent { Content = content, Extension = Extension(temp, media), Cover = cover, MaxBytes = maxBytes },
highlightTitle,
ct).ConfigureAwait(false);
}
if (saved.Outcome == MediaSaveOutcome.Stored)
{
tally.Add(ref tally.Stored);
Report(media, entry, DownloadStep.Stored);
await AppendJournalWhenCompleteAsync(entry, ct).ConfigureAwait(false);
}
else
{
await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false);
tally.Add(ref tally.Duplicates);
Report(media, entry, DownloadStep.Duplicate);
}
}
finally
{
if (cover is not null)
{
await cover.DisposeAsync().ConfigureAwait(false);
}
}
}
/// <summary>
/// §9.5: the file just downloaded is identical to one already in the same account. The new file is discarded
/// before entering the library. When the existing file belongs to an imported entry without Instagram data, that
/// entry takes the data and the new record goes away; otherwise the new file is settled as «saltato» with a note.
/// </summary>
private async Task IdenticalAsync(Entry entry, Media media, MediaLocation existing, CancellationToken ct)
{
var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
if (existing.Entry.InstagramId is null && existing.Entry.Kind == entry.Kind && files.Count == 1)
{
await _storage.Entries.RemoveAsync(entry.Id, ct).ConfigureAwait(false);
await _storage.Entries.UpdateAsync(
existing.Entry with
{
InstagramId = entry.InstagramId,
Code = existing.Entry.Code ?? entry.Code,
Caption = existing.Entry.Caption ?? entry.Caption,
AuthorUsername = existing.Entry.AuthorUsername ?? entry.AuthorUsername,
AuthorInstagramId = existing.Entry.AuthorInstagramId ?? entry.AuthorInstagramId,
},
ct).ConfigureAwait(false);
await _writer.EventAsync("file-gia-in-libreria", "Un file appena scaricato era già in libreria fra quelli importati: non è stato copiato di nuovo, all'elemento esistente sono stati aggiunti i dati di Instagram.", EventSeverity.Info, entry.AccountId, null, ct).ConfigureAwait(false);
return;
}
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Skipped, "Identico a un file già presente nell'account: non copiato di nuovo.", _clock.Now, ct).ConfigureAwait(false);
if (existing.Entry.Caption is null && entry.Caption is not null && existing.Entry.Provenance == Provenance.Imported)
{
await _storage.Entries.UpdateAsync(existing.Entry with { Caption = entry.Caption }, ct).ConfigureAwait(false);
}
}
/// <summary>An expired address: back to wait and «Post singolo» queued; stories cannot be recovered (§6.5 point 5).</summary>
private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
{
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.";
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);
return;
}
await _storage.Media.MarkFailedAsync(media.Id, MediaState.Expired, "Indirizzo scaduto: lo rinnova «Post singolo».", _clock.Now, ct).ConfigureAwait(false);
if (singlePostQueued.TryAdd(entry.Id, true))
{
await _writer.QueueSinglePostAsync(entry, ct).ConfigureAwait(false);
}
tally.Add(ref tally.Expired);
Report(media, entry, DownloadStep.Expired);
}
private async Task AppendJournalWhenCompleteAsync(Entry entry, CancellationToken ct)
{
var files = await _storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
if (files.All(f => f.State is not (MediaState.ToDownload or MediaState.Expired)))
{
await _ingest.AppendJournalAsync(entry.Id, ct).ConfigureAwait(false);
}
}
private void Report(Media media, Entry entry, DownloadStep step) =>
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step));
/// <summary>The extension from the content (magic numbers), else from the kind of file.</summary>
private static string Extension(string path, Media media)
{
Span<byte> head = stackalloc byte[12];
using (var stream = File.OpenRead(path))
{
var read = stream.Read(head);
head = head[..read];
}
if (head.Length >= 3 && head[0] == 0xFF && head[1] == 0xD8 && head[2] == 0xFF)
{
return ".jpg";
}
if (head.Length >= 8 && head[0] == 0x89 && head[1] == (byte)'P' && head[2] == (byte)'N' && head[3] == (byte)'G')
{
return ".png";
}
if (head.Length >= 12 && head[..4].SequenceEqual("RIFF"u8) && head[8..12].SequenceEqual("WEBP"u8))
{
return ".webp";
}
if (head.Length >= 12 && head[4..8].SequenceEqual("ftyp"u8))
{
return head[8..12].SequenceEqual("heic"u8) || head[8..12].SequenceEqual("heix"u8) ? ".heic" : ".mp4";
}
return media.Kind == MediaKind.Video ? ".mp4" : ".jpg";
}
private static void TryDelete(string path)
{
try
{
File.Delete(path);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
}
}
private sealed class Tally
{
public int Stored;
public int Duplicates;
public int Skipped;
public int Expired;
public int Failed;
public int Retried;
private long _bytes;
private volatile bool _budgetReached;
public bool BudgetReached
{
get => _budgetReached;
set => _budgetReached = value;
}
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);
}
}
/// <summary>How a file of the queue ended.</summary>
public enum DownloadStep
{
Stored,
Duplicate,
Skipped,
Expired,
Failed,
}
/// <summary>Progress of the queue for the interface: identifiers only, never addresses.</summary>
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step);