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; /// Options of the download queue (spec §6.5). public sealed record DownloadOptions { /// /// 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). /// public required string StagingFolder { get; init; } /// At most two downloads at the same time (spec §6.5 point 6). public int MaxConcurrent { get; init; } = 2; /// Small random pause after each file. public TimeSpan PauseMin { get; init; } = TimeSpan.FromMilliseconds(400); public TimeSpan PauseMax { get; init; } = TimeSpan.FromSeconds(3); /// /// 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. /// public IReadOnlySet ExpiredStatuses { get; init; } = new HashSet { 403, 410 }; /// /// 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. /// public int MaxAttempts { get; init; } = 5; /// /// 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. /// public IReadOnlyList RetryDelays { get; init; } = [TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30), TimeSpan.FromHours(2), TimeSpan.FromHours(8)]; /// /// Browser network errors (netErrorName) that mean «no connection at all»: the file is not to blame. No /// attempt is counted, the pass ends and the queue waits . /// public IReadOnlyList 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", ]; /// Wait after a connection error before the next pass. public TimeSpan ConnectionPause { get; init; } = TimeSpan.FromMinutes(5); /// /// 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. /// public TimeSpan SignalPause { get; init; } = TimeSpan.FromHours(1); /// How many pending files are read from the database at a time. public int BatchSize { get; init; } = 200; /// When idle, how long to wait before looking at the database again (a ends it earlier). public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1); } /// What one pass of the queue did. 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; /// Set when the queue stopped for a stop signal of the CDN or a connection error: no file is tried before then. public DateTimeOffset? PausedUntil { get; init; } } /// /// 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 /// (the browser, Network.loadNetworkResource) into a temporary file and then into the library through /// (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. /// /// /// 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 — the page /// never sees these responses — and the queue waits . A failure that may pass /// is retried later with a growing wait, kept in memory (a restart allows one early attempt). The HttpClient /// fallback of §6.5 point 3 is deliberately not implemented: it stays behind until H7 says /// whether it is needed (decision in docs/decisioni.md). Addresses are never logged. /// 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 _retryAt = new(); private DateTimeOffset? _pausedUntil; /// Database. /// Puts the files into the library. /// Downloads from the CDN. /// Daily data budget. /// Time. /// Pauses between files. /// Options. /// /// Stop signals (spec §7.6): statuses of the CDN that match a rule of segnali.json are reported to the /// circuit breaker and stop the queue for a while. Null: downloads raise no signal. /// 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); } /// Raised after each file, for the interface (no addresses). public event EventHandler? Progress; /// Until when the queue is stopped by a signal of the CDN or a connection error; null when it is not. public DateTimeOffset? PausedUntil { get { lock (_pauseGate) { return _pausedUntil is { } until && until > _clock.Now ? until : null; } } } /// /// New files are waiting: ends the idle wait of . Many calls during a pass give one more /// pass, not one each. /// public void Wake() { try { _wake.Release(); } catch (SemaphoreFullException) { // A pass is already due. } } /// Works until cancelled: a pass over the waiting files, then an idle wait. 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(); } } /// /// 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. /// public async Task 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(); var accounts = new ConcurrentDictionary(); var singlePostQueued = new ConcurrentDictionary(); 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(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 accounts, ConcurrentDictionary 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 accounts, ConcurrentDictionary 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); } } /// /// 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. /// 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)); /// /// A failure that may pass: the file waits for a later attempt, a little longer each time; after /// failures it is «fallito». /// 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); } } } /// /// §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. /// 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); } } /// /// 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 /// failures, instead of sending «Post singolo» to the site for ever. /// private async Task ExpiredAsync(Entry entry, Media media, Tally tally, ConcurrentDictionary 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); } /// /// Appends the journal line of an entry once settled. A journal that cannot be written now (a sync client holding /// _febe.jsonl, a share that dropped) never turns a stored file back into one to download: the line waits /// in and is written by a later pass. /// 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 }); /// The extension from the content (magic numbers), else from the kind of file. private static string Extension(string path, Media media) { Span 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; } /// The pass must end: budget reached, or a signal of the CDN, or no connection. 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 }; } } } } /// How a file of the queue ended. public enum DownloadStep { Stored, Duplicate, Skipped, Expired, Failed, /// Not settled: the file waits for a later attempt (a failure that may pass). Retried, } /// Progress of the queue for the interface: identifiers only, never addresses. /// What crossed the network for this file (its cover included), when known. public sealed record DownloadProgress(long MediaId, long EntryId, long AccountId, EntryKind Kind, DownloadStep Step, long? Bytes = null) { /// Why the file failed or waits for another attempt (); null when it did not. public string? Cause { get; init; } } /// /// 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. /// public static class DownloadCauses { /// A network error that is not a missing connection (the connection pauses the queue instead). public const string Network = "rete"; /// No connection at all: the queue pauses, the file waits without an attempt counted. public const string Connection = "connessione"; /// The file could not be written (disk full or similar). public const string Write = "scrittura"; /// The address of the file is not valid. public const string BadAddress = "indirizzo-non-valido"; /// The address is not of the CDN (spec §6.5). public const string HostNotAllowed = "host-non-ammesso"; /// The renewed address was refused again, too many times. public const string RefusedAfterRenewal = "rifiutato-dopo-rinnovo"; /// «http-404», «http-503»...: the status the CDN answered; without one. public static string Of(int? httpStatus) => httpStatus is >= 100 and < 600 ? "http-" + httpStatus.Value.ToString(CultureInfo.InvariantCulture) : Network; }