Richiesta di Alberto (#59): decidere cosa scaricare prima, una Dashboard compatta come pagina iniziale da guardare mentre il motore lavora, e le miniature di ciò che è arrivato. - Dashboard (§7.9, §10.2): /dashboard è la pagina iniziale e la prima voce della barra; /, /attivita, «Ho finito» del browser, il riquadro di stato e il ritorno dopo l'accesso portano lì. In alto l'anteprima del browser sempre visibile, chiesta ogni secondo mentre il motore lavora (LiveBrowserPreview cattura al più un fotogramma al secondo), accanto cosa sta facendo e i quattro tetti; poi la striscia più bassa, la cronologia con le miniature e la coda ridotta alle prime righe con «Mostra tutta». Sotto i 1000 px una colonna sola. - Miniature della cronologia: /api/activity/arrived dà gli elementi che una ricetta ha salvato (account, inizio e fine della ricetta), chiesti solo quando la riga entra in vista, al più otto con «+N». Un clic apre un'anteprima leggera con foto o video senza audio, frecce fra i file della riga, Esc, «Apri nella Libreria» e «Apri l'account». - «Cosa scaricare prima» (§7.2, §6.5): ordine generale dei tipi in Impostazioni → Limiti e comportamento (trascinare, «Su» e «Giù», nota sulle storie che scadono), predefinito storie, evidenza, post, reel, taggati. Dopo il giro, il lavoro dovuto si estrae con il peso dell'account per il peso del tipo (16, 8, 4, 2, 1): pesa, non rende fisso. La coda dei file segue lo stesso ordine. - Prove: DownloadOrderTests (ordine, pesi, coda, motore con seme fisso: il primo tipo viene più spesso ma non sempre, il giro resta primo, un tipo senza lavoro non si visita), DashboardApiTests, una prova dell'interfaccia per / e /attivita. Non ancora fatto: ordine per account e segno del reel (serve una migrazione da concordare con E1), «Raggruppa i post» / «Tutte le foto», confronto con i mockup, revisione del resto della guida che nomina ancora Attività. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
790 lines
36 KiB
C#
790 lines
36 KiB
C#
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». 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;
|
|
|
|
/// <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>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>
|
|
/// 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). 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
|
|
{
|
|
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 SignalDetector? _signals;
|
|
private readonly CollectionWriter _writer;
|
|
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;
|
|
|
|
/// <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));
|
|
_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));
|
|
_signals = signals;
|
|
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>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)
|
|
{
|
|
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);
|
|
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 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)
|
|
{
|
|
// Lines a busy _febe.jsonl refused earlier: local work, written also while the CDN or the connection says to wait.
|
|
await _ingest.AppendPendingJournalAsync(ct).ConfigureAwait(false);
|
|
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.Stopped)
|
|
{
|
|
// 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);
|
|
// «Cosa scaricare prima» (spec §6.5, §7.2), read at every batch so that a change counts from the next one.
|
|
var order = await Febe.Core.Engine.DownloadOrder.LoadAsync(_storage.Settings, ct).ConfigureAwait(false);
|
|
var batch = (await _storage.Media.ListPendingDownloadsAsync(window, order.EntryKinds(), 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)
|
|
{
|
|
break;
|
|
}
|
|
|
|
var queue = new ConcurrentQueue<PendingDownload>(batch);
|
|
var workers = Enumerable.Range(0, _options.MaxConcurrent).Select(_ => Task.Run(
|
|
async () =>
|
|
{
|
|
while (!tally.Stopped && 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 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)
|
|
{
|
|
return _random.Between(_options.PauseMin, _options.PauseMax);
|
|
}
|
|
}
|
|
|
|
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)
|
|
{
|
|
await ProcessFileAsync(pending, tally, accounts, singlePostQueued, ct).ConfigureAwait(false);
|
|
|
|
// Whatever the outcome (stored, duplicate, skipped, failed), the entry may now be settled: its journal line is
|
|
// written once no file waits any more and at least one is in the library (spec §8.5). A deleted entry gets
|
|
// none (LibraryIngest.AppendJournalAsync): a «save» line after its «delete» line would bring it back.
|
|
await AppendJournalWhenSettledAsync(pending.Media.EntryId).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ProcessFileAsync(PendingDownload pending, Tally tally, ConcurrentDictionary<long, Account?> accounts, ConcurrentDictionary<long, bool> singlePostQueued, CancellationToken ct)
|
|
{
|
|
if (!accounts.TryGetValue(pending.AccountId, out var account))
|
|
{
|
|
account = await _storage.Accounts.GetAsync(pending.AccountId, ct).ConfigureAwait(false);
|
|
accounts[pending.AccountId] = account;
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
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);
|
|
Report(media, entry, DownloadStep.Failed, cause: DownloadCauses.BadAddress);
|
|
return;
|
|
}
|
|
|
|
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;
|
|
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);
|
|
}
|
|
|
|
// 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.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)
|
|
{
|
|
case FetchOutcome.Completed:
|
|
await IngestAsync(account, entry, media, temp, maxBytes, result.BudgetBytes, 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);
|
|
_retryAt.TryRemove(media.Id, out _);
|
|
tally.Add(ref tally.Skipped);
|
|
Report(media, entry, DownloadStep.Skipped, result.BudgetBytes);
|
|
return;
|
|
case FetchOutcome.HttpError when result.HttpStatus is { } status && _options.ExpiredStatuses.Contains(status):
|
|
await ExpiredAsync(entry, media, tally, singlePostQueued, result.BudgetBytes, 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);
|
|
_retryAt.TryRemove(media.Id, out _);
|
|
tally.Add(ref tally.Failed);
|
|
Report(media, entry, DownloadStep.Failed, result.BudgetBytes, DownloadCauses.HostNotAllowed);
|
|
return;
|
|
case FetchOutcome.NetworkError when IsConnectionError(result.Error):
|
|
// No connection at all (router restarting, cable out): every file would fail the same way. Not the
|
|
// file's fault (no attempt counted), but the report says why it is still waiting.
|
|
PauseUntil(_clock.Now + _options.ConnectionPause, tally);
|
|
Report(media, entry, DownloadStep.Retried, result.BudgetBytes, DownloadCauses.Connection);
|
|
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"}).";
|
|
await RetryLaterAsync(entry, media, error, tally, result.BudgetBytes, ct, DownloadCauses.Of(result.HttpStatus)).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);
|
|
tally.Add(ref tally.Skipped);
|
|
Report(media, entry, DownloadStep.Skipped);
|
|
}
|
|
catch (IOException ex)
|
|
{
|
|
// 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, null, CancellationToken.None, DownloadCauses.Write).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
TryDelete(temp);
|
|
}
|
|
}
|
|
|
|
/// <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, long? bytes, CancellationToken ct, string? cause = null)
|
|
{
|
|
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, bytes, cause);
|
|
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);
|
|
Report(media, entry, DownloadStep.Retried, bytes, cause);
|
|
}
|
|
|
|
private async Task IngestAsync(Account account, Entry entry, Media media, string temp, long? maxBytes, long fileBytes, Tally tally, CancellationToken ct)
|
|
{
|
|
var bytes = fileBytes;
|
|
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.BudgetBytes > 0)
|
|
{
|
|
await _budget.RecordAsync(fetched.BudgetBytes, account.Id, CancellationToken.None).ConfigureAwait(false);
|
|
tally.AddBytes(fetched.BudgetBytes);
|
|
bytes += 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)
|
|
{
|
|
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);
|
|
}
|
|
|
|
_retryAt.TryRemove(media.Id, out _);
|
|
if (saved.Outcome == MediaSaveOutcome.Stored)
|
|
{
|
|
tally.Add(ref tally.Stored);
|
|
Report(media, entry, DownloadStep.Stored, bytes);
|
|
}
|
|
else
|
|
{
|
|
await IdenticalAsync(entry, media, saved.Identical!, ct).ConfigureAwait(false);
|
|
tally.Add(ref tally.Duplicates);
|
|
Report(media, entry, DownloadStep.Duplicate, bytes);
|
|
}
|
|
}
|
|
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 (§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, long? bytes, 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, bytes, DownloadCauses.RefusedAfterRenewal);
|
|
return;
|
|
}
|
|
|
|
if (entry.Kind is EntryKind.Story or EntryKind.Highlight or EntryKind.ProfilePicture)
|
|
{
|
|
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, bytes);
|
|
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, bytes);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Appends the journal line of an entry once settled. A journal that cannot be written now (a sync client holding
|
|
/// <c>_febe.jsonl</c>, a share that dropped) never turns a stored file back into one to download: the line waits
|
|
/// in <see cref="LibraryIngest.TryAppendJournalAsync"/> and is written by a later pass.
|
|
/// </summary>
|
|
private async Task AppendJournalWhenSettledAsync(long entryId)
|
|
{
|
|
var files = await _storage.Media.ListByEntryAsync(entryId, CancellationToken.None).ConfigureAwait(false);
|
|
if (files.Any(f => EntryStateRules.IsPresent(f.State)) && files.All(f => f.State is not (MediaState.ToDownload or MediaState.Expired)))
|
|
{
|
|
await _ingest.TryAppendJournalAsync(entryId, CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
private void Report(Media media, Entry entry, DownloadStep step, long? bytes = null, string? cause = null) =>
|
|
Progress?.Invoke(this, new DownloadProgress(media.Id, entry.Id, entry.AccountId, entry.Kind, step, bytes) { Cause = cause });
|
|
|
|
/// <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 readonly Lock _gate = new();
|
|
private long _bytes;
|
|
private volatile bool _budgetReached;
|
|
private volatile bool _paused;
|
|
private DateTimeOffset? _pausedUntil;
|
|
|
|
public bool BudgetReached
|
|
{
|
|
get => _budgetReached;
|
|
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()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return new(Stored, Duplicates, Skipped, Expired, Failed, Retried, Interlocked.Read(ref _bytes), BudgetReached) { PausedUntil = _pausedUntil };
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>How a file of the queue ended.</summary>
|
|
public enum DownloadStep
|
|
{
|
|
Stored,
|
|
Duplicate,
|
|
Skipped,
|
|
Expired,
|
|
Failed,
|
|
|
|
/// <summary>Not settled: the file waits for a later attempt (a failure that may pass).</summary>
|
|
Retried,
|
|
}
|
|
|
|
/// <summary>Progress of the queue for the interface: identifiers only, never addresses.</summary>
|
|
/// <param name="Bytes">What crossed the network for this file (its cover included), when known.</param>
|
|
public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step, long? Bytes = null)
|
|
{
|
|
/// <summary>Why the file failed or waits for another attempt (<see cref="DownloadCauses"/>); null when it did not.</summary>
|
|
public string? Cause { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// Why a file failed or waits for another attempt, for the diagnostic report (issue #39): a closed list of codes,
|
|
/// never an address or the text of an error.
|
|
/// </summary>
|
|
public static class DownloadCauses
|
|
{
|
|
/// <summary>A network error that is not a missing connection (the connection pauses the queue instead).</summary>
|
|
public const string Network = "rete";
|
|
|
|
/// <summary>No connection at all: the queue pauses, the file waits without an attempt counted.</summary>
|
|
public const string Connection = "connessione";
|
|
|
|
/// <summary>The file could not be written (disk full or similar).</summary>
|
|
public const string Write = "scrittura";
|
|
|
|
/// <summary>The address of the file is not valid.</summary>
|
|
public const string BadAddress = "indirizzo-non-valido";
|
|
|
|
/// <summary>The address is not of the CDN (spec §6.5).</summary>
|
|
public const string HostNotAllowed = "host-non-ammesso";
|
|
|
|
/// <summary>The renewed address was refused again, too many times.</summary>
|
|
public const string RefusedAfterRenewal = "rifiutato-dopo-rinnovo";
|
|
|
|
/// <summary>«http-404», «http-503»...: the status the CDN answered; <see cref="Network"/> without one.</summary>
|
|
public static string Of(int? httpStatus) =>
|
|
httpStatus is >= 100 and < 600 ? "http-" + httpStatus.Value.ToString(CultureInfo.InvariantCulture) : Network;
|
|
}
|