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

@@ -99,6 +99,15 @@ public sealed class BrowserFileFetcher : IFileFetcher
return new FetchResult(FetchOutcome.NetworkError, 0, status, "Il browser non ha aperto il flusso dei dati.");
}
// The browser hands out the stream only once the whole resource has been loaded: a file over the limit has
// already crossed the network. When its length is declared, nothing is read and the real transfer is counted.
var declared = DeclaredLength(resource);
if (options?.MaxBytes is { } limit && declared > limit)
{
await CloseQuietlyAsync(handle).ConfigureAwait(false);
return new FetchResult(FetchOutcome.TooLarge, 0, status, "Il file supera la dimensione massima ammessa.") { TransferredBytes = declared };
}
long written = 0;
try
{
@@ -122,7 +131,10 @@ public sealed class BrowserFileFetcher : IFileFetcher
var allowed = (int)Math.Max(0, max - written);
await destination.WriteAsync(bytes.AsMemory(0, allowed), ct).ConfigureAwait(false);
written += allowed;
return new FetchResult(FetchOutcome.TooLarge, written, status, "Il file supera la dimensione massima ammessa.");
return new FetchResult(FetchOutcome.TooLarge, written, status, "Il file supera la dimensione massima ammessa.")
{
TransferredBytes = declared > written ? declared : null,
};
}
await destination.WriteAsync(bytes, ct).ConfigureAwait(false);
@@ -147,6 +159,27 @@ public sealed class BrowserFileFetcher : IFileFetcher
: new FetchResult(FetchOutcome.Completed, written, status, null);
}
/// <summary>The Content-Length the response declared (header names are case-insensitive), or null.</summary>
private static long? DeclaredLength(JsonElement resource)
{
if (!resource.TryGetProperty("headers", out var headers) || headers.ValueKind != JsonValueKind.Object)
{
return null;
}
foreach (var header in headers.EnumerateObject())
{
if (string.Equals(header.Name, "content-length", StringComparison.OrdinalIgnoreCase)
&& header.Value.ValueKind == JsonValueKind.String
&& long.TryParse(header.Value.GetString(), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var length))
{
return length;
}
}
return null;
}
private async Task CloseQuietlyAsync(string handle)
{
try
@@ -162,7 +162,8 @@ public sealed class CollectionPipeline : IAsyncDisposable
options.DataBudget,
options.Clock,
options.Random,
new DownloadOptions { StagingFolder = options.StagingFolder });
new DownloadOptions { StagingFolder = options.StagingFolder },
signals);
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets);
pipeline._subscriptions.Add(tap.AddObserver(signals));
@@ -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 };
}
}
}
}
+14 -1
View File
@@ -27,10 +27,23 @@ public enum FetchOutcome
public sealed record FetchResult(FetchOutcome Outcome, long Bytes, int? HttpStatus, string? Error)
{
public bool Succeeded => Outcome == FetchOutcome.Completed;
/// <summary>
/// Bytes that crossed the network when they are known to be more than <see cref="Bytes"/>: a file over the size
/// limit is loaded whole by the browser before the first byte can be read (its declared length), even though
/// only part of it, or nothing, is written. Null when it is <see cref="Bytes"/>.
/// </summary>
public long? TransferredBytes { get; init; }
/// <summary>What the daily data budget must count for this download: the larger of written and transferred.</summary>
public long BudgetBytes => Math.Max(Bytes, TransferredBytes ?? 0);
}
/// <summary>Options of a single download.</summary>
/// <param name="MaxBytes">Abort with <see cref="FetchOutcome.TooLarge"/> past this size; null for no limit.</param>
/// <param name="MaxBytes">
/// Abort with <see cref="FetchOutcome.TooLarge"/> past this size; null for no limit. Through the browser the limit
/// saves disk, not network: <c>Network.loadNetworkResource</c> loads the whole resource before handing out its stream.
/// </param>
/// <param name="Progress">Receives the number of bytes written so far.</param>
public sealed record FetchOptions(long? MaxBytes = null, IProgress<long>? Progress = null);
@@ -29,11 +29,14 @@ public static class ReadMapping
};
}
/// <summary>The files of a content item, positions from 1, with the addresses of the chosen versions.</summary>
/// <summary>
/// The files of a content item with the addresses of the chosen versions. Positions are the places the series
/// declares (from 1): a child that could not be read leaves its place free for «Post singolo» to fill.
/// </summary>
public static IReadOnlyList<Media> ToMedia(ContentItem item, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(item);
return [.. item.Files.Select((file, index) => ToMedia(file, index + 1, now))];
return [.. item.Files.Select((file, index) => ToMedia(file, file.Position ?? index + 1, now))];
}
public static Media ToMedia(ContentFile file, int position, DateTimeOffset now)
@@ -25,7 +25,15 @@ public sealed record FileVersion(string Url, int? Width, int? Height, bool? HasA
/// <param name="Best">Largest image, or best video version complete with audio.</param>
/// <param name="Cover">For videos: the largest cover image.</param>
/// <param name="Duration">Video duration, when given.</param>
public sealed record ContentFile(MediaKind Kind, string? InstagramId, FileVersion Best, FileVersion? Cover, TimeSpan? Duration);
public sealed record ContentFile(MediaKind Kind, string? InstagramId, FileVersion Best, FileVersion? Cover, TimeSpan? Duration)
{
/// <summary>
/// Place of the file in its series, from 1, counting the children the response declares even when one of them
/// cannot be read (no versions yet): a missing file leaves a gap instead of moving the following ones. Null for
/// a content with a single file.
/// </summary>
public int? Position { get; init; }
}
/// <summary>A profile as it appears in a response (author of content, profile page, list of followed profiles).</summary>
public sealed record ProfileInfo
@@ -206,6 +206,10 @@ public sealed record ReaderVocabulary
Need(Content.TakenAt, "content.takenAt");
Need(Content.Images, "content.images");
Need(Content.Videos, "content.videos");
// Without the author nothing tells whose a post is: the giro dei seguiti would save nothing and the profile
// recipes would skip every post, silently.
Need(Content.Owner, "content.owner");
Need(Version.Url, "version.url");
Need(Version.Width, "version.width");
Need(Version.Height, "version.height");
@@ -188,7 +188,7 @@ public sealed class ShapeReader
declaredChildren++;
if (child.ValueKind == JsonValueKind.Object && ReadFile(child) is { } file)
{
files.Add(file);
files.Add(file with { Position = declaredChildren });
}
}
}
@@ -36,6 +36,12 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
/// <summary>Tolerance for recognizing imported entries by publication time (spec §9.5: two seconds).</summary>
public static readonly TimeSpan ImportedTimeTolerance = TimeSpan.FromSeconds(2);
/// <summary>
/// A «fallito» file gets a fresh address from a new reading of its content only while it has failed fewer times
/// than this: a file broken for good does not cost a download at every check.
/// </summary>
public const int RevivalAttemptsLimit = 10;
public IFebeStorage Storage => storage;
/// <summary>
@@ -140,7 +146,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
var known = await storage.Entries.FindAsync(account.Id, kind, item.Id, ct).ConfigureAwait(false);
if (known is not null)
{
await RefreshExpiredAsync(known, item, ct).ConfigureAwait(false);
await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false);
return new SaveResult(SaveOutcome.Known, known);
}
@@ -180,7 +186,11 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
}
/// <summary>Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256).</summary>
/// <summary>
/// Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256). A
/// picture already known whose file expired or failed takes the fresh address just read: the identity is the path
/// of the address, which stays the same when only the signature changes.
/// </summary>
public async Task<SaveResult> SaveProfilePictureAsync(Account account, ProfileInfo profile, CancellationToken ct)
{
if (!Wants(account, EntryKind.ProfilePicture) || ReadMapping.ToProfilePicture(profile, account.Id, clock.Now) is not { } picture)
@@ -189,7 +199,21 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
}
var added = await storage.Entries.AddAsync(picture.Entry, [picture.Media], ct).ConfigureAwait(false);
return new SaveResult(added.Created ? SaveOutcome.Created : SaveOutcome.Known, added.Stored.Entry);
if (added.Created)
{
return new SaveResult(SaveOutcome.Created, added.Stored.Entry);
}
var known = added.Stored.Entry;
if (known.State != EntryState.Deleted && picture.Media.SourceUrl is { } url)
{
foreach (var file in (await storage.Media.ListByEntryAsync(known.Id, ct).ConfigureAwait(false)).Where(NeedsFreshAddress))
{
await storage.Media.UpdateSourceAsync(file.Id, url, null, clock.Now, ct).ConfigureAwait(false);
}
}
return new SaveResult(SaveOutcome.Known, known);
}
/// <summary>
@@ -203,9 +227,19 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
ArgumentNullException.ThrowIfNull(item);
var now = clock.Now;
var current = await storage.Media.ListByEntryAsync(entry.Id, ct).ConfigureAwait(false);
var positions = current.Select(m => m.Position).ToHashSet();
var received = ReadMapping.ToMedia(item, now).Select(m => ApplyPolicy(account, entry.Kind, m)).ToList();
var missing = received.Where(m => !positions.Contains(m.Position)).ToList();
// A file is the same file by its identifier first, by its place in the series only when there is none.
var taken = current.Select(m => m.Position).ToHashSet();
var free = Math.Max(taken.DefaultIfEmpty(0).Max(), received.Select(m => m.Position).DefaultIfEmpty(0).Max()) + 1;
var missing = new List<Media>();
foreach (var file in received.Where(r => Counterpart(current, r) is null))
{
// Its place is normally free (series keep the gaps of the files that were not readable); a place taken
// by another file (records written before) gives it the next free one, so that it is never lost.
missing.Add(taken.Add(file.Position) ? file : file with { Position = free++ });
}
var changed = 0;
if (missing.Count > 0)
{
@@ -217,7 +251,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
{
foreach (var file in current.Where(m => m.State is MediaState.Expired or MediaState.Failed || (m.State == MediaState.ToDownload && m.SourceUrl is null)))
{
if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh)
if (Counterpart(received, file) is { SourceUrl: { } url } fresh)
{
await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false);
changed++;
@@ -270,8 +304,10 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
/// <summary>
/// Puts an item shown in a collection into it. A story already saved with the same identifier is referenced, not
/// downloaded again (H9); otherwise the item becomes an entry of kind «evidenza». Returns the entry, or null when
/// the account does not want highlights.
/// downloaded again (H9); otherwise the item becomes an entry of kind «evidenza». An entry reused this way takes
/// the fresh addresses the viewer just gave for its files that expired or failed — a story whose file was never
/// saved included: the collection keeps for good what the story offered for a day. Returns the entry, or null
/// when the account does not want highlights.
/// </summary>
public async Task<(Entry? Entry, bool Created)> LinkHighlightItemAsync(Account account, Highlight highlight, ContentItem item, long? sessionId, CancellationToken ct)
{
@@ -284,6 +320,10 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
reuse = saved.Entry;
created = saved.Outcome == SaveOutcome.Created;
}
else
{
await RefreshFilesAsync(reuse, item, fromHighlight: true, ct).ConfigureAwait(false);
}
if (reuse is not null)
{
@@ -329,28 +369,66 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
? media with { State = MediaState.Skipped, SourceUrl = null, CoverUrl = null, LastError = reason }
: media;
private async Task RefreshExpiredAsync(Entry known, ContentItem item, CancellationToken ct)
/// <summary>
/// A known entry read again: its files that expired, or failed (fewer than <see cref="RevivalAttemptsLimit"/>
/// times), take the fresh addresses just received and wait for the queue again. A story only while it is still
/// on offer (before it expires), unless the address comes from a highlight collection, which keeps it.
/// </summary>
private async Task RefreshFilesAsync(Entry known, ContentItem item, bool fromHighlight, CancellationToken ct)
{
if (known.State is EntryState.Deleted)
{
return;
}
var files = await storage.Media.ListByEntryAsync(known.Id, ct).ConfigureAwait(false);
var expired = files.Where(f => f.State == MediaState.Expired).ToList();
if (expired.Count == 0)
var now = clock.Now;
if (known.Kind == EntryKind.Story && !fromHighlight && known.ExpiresAt is { } expires && expires <= now)
{
return;
}
var now = clock.Now;
var received = ReadMapping.ToMedia(item, now);
foreach (var file in expired)
var files = await storage.Media.ListByEntryAsync(known.Id, ct).ConfigureAwait(false);
var stale = files.Where(NeedsFreshAddress).ToList();
if (stale.Count == 0)
{
if (received.FirstOrDefault(r => r.Position == file.Position) is { SourceUrl: { } url } fresh)
return;
}
var received = ReadMapping.ToMedia(item, now);
foreach (var file in stale)
{
if (Counterpart(received, file) is { SourceUrl: { } url } fresh)
{
await storage.Media.UpdateSourceAsync(file.Id, url, fresh.CoverUrl, now, ct).ConfigureAwait(false);
}
}
}
private static bool NeedsFreshAddress(Media file) =>
file.State == MediaState.Expired || (file.State == MediaState.Failed && file.Attempts < RevivalAttemptsLimit);
/// <summary>
/// The file of <paramref name="files"/> that is <paramref name="wanted"/>: the same identifier when both have one,
/// otherwise the same place in the series (never a place held by a file with another identifier).
/// </summary>
private static Media? Counterpart(IEnumerable<Media> files, Media wanted)
{
var id = wanted.InstagramId?.Trim();
Media? byPosition = null;
foreach (var file in files)
{
var other = file.InstagramId?.Trim();
if (!string.IsNullOrEmpty(id) && string.Equals(other, id, StringComparison.Ordinal))
{
return file;
}
if (byPosition is null && file.Position == wanted.Position && (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(other)))
{
byPosition = file;
}
}
return byPosition;
}
}
@@ -30,6 +30,12 @@ public sealed record RecipeOptions
/// <summary>Pages of the following list per run when the request does not say.</summary>
public int FollowingPagesPerRun { get; init; } = 5;
/// <summary>
/// Controllo del profilo: pages of the grid read after the first one, at most, when posts are missing between the
/// first page and the known ones (each a counted page of history); the rest waits for the next check.
/// </summary>
public int GapPagesPerCheck { get; init; } = 3;
/// <summary>Stories are opened only when the budget allows at least this many (spec §6.3: ten).</summary>
public int MinStoryBudget { get; init; } = 10;
@@ -64,6 +64,9 @@ public sealed partial class RecipeRunner
/// <summary>
/// Elenco dei seguiti (spec §4.2, §6.3): reads the list of the profiles Alberto follows, one page per permit,
/// over as many sessions as needed; the progress is stored («Letti 96 profili, continuo alla prossima sessione»).
/// Without a resume page in the map (followingFrom is optional) the list is scrolled from the top back to where the
/// last run stopped — every page counted by the Governor, the profiles read again kept — and only the pages after
/// that count against the pages of the run: the progress is never thrown away.
/// <see cref="RecipeOutcome.BackfillFinished"/> is true when the end of the list was reached.
/// </summary>
private async Task<RecipeStatus> FollowingListAsync(RecipeRun run)
@@ -74,53 +77,79 @@ public sealed partial class RecipeRunner
var cursor = await settings.GetAsync(FollowingKeys.Cursor, run.Ct).ConfigureAwait(false);
var started = DateTimeOffset.TryParse(await settings.GetAsync(FollowingKeys.StartedAt, run.Ct).ConfigureAwait(false), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var s) ? s : (DateTimeOffset?)null;
var read = (int)(await settings.GetInt64Async(FollowingKeys.Read, run.Ct).ConfigureAwait(false) ?? 0);
var resume = cursor is not null && started is not null && Env.SiteMap.HasPage(SitePages.FollowingFrom);
if (!resume)
var stored = cursor is not null && started is not null ? cursor : null;
var byPage = stored is not null && Env.SiteMap.HasPage(SitePages.FollowingFrom);
var catchingUp = stored is not null && !byPage;
var readBefore = read;
if (stored is null)
{
cursor = null;
read = 0;
started = Env.Clock.Now;
}
else if (catchingUp)
{
read = 0; // the list is read again from the top: positions and the count start over
}
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(
resume ? SitePages.FollowingFrom : SitePages.Following,
resume ? Values(("username", mine.Username), ("cursor", cursor!)) : Values(("username", mine.Username))).ConfigureAwait(false);
byPage ? SitePages.FollowingFrom : SitePages.Following,
byPage ? Values(("username", mine.Username), ("cursor", stored!)) : Values(("username", mine.Username))).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(mark, r => r.Profiles.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Profiles.Count > 0, null))
{
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
var pages = 1;
var pages = catchingUp ? 0 : 1;
var finished = false;
while (true)
{
read += await SaveFollowingPageAsync(run, reads, mine, read).ConfigureAwait(false);
var page = LastPage(reads);
cursor = page?.Cursor ?? cursor;
if (catchingUp && ((page?.Cursor is { } c && string.Equals(c, stored, StringComparison.Ordinal)) || read >= readBefore))
{
catchingUp = false; // back where the last run stopped
}
if (!catchingUp)
{
cursor = page?.Cursor ?? cursor;
}
if (page?.HasMore == false)
{
finished = true;
break;
}
if (pages >= maxPages)
if (!catchingUp && pages >= maxPages)
{
break;
}
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
var counted = !catchingUp;
reads = await ScrollForPageAsync(run, r => r.Profiles.Count > 0).ConfigureAwait(false);
pages++;
if (counted)
{
pages++;
}
if (reads.Count == 0)
{
break;
}
}
if (catchingUp)
{
read = Math.Max(read, readBefore); // not back there yet: the stored point stays
}
if (finished)
{
var removed = await Env.Storage.Following.RemoveNotReadSinceAsync(started!.Value, run.Ct).ConfigureAwait(false);
@@ -8,24 +8,128 @@ namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>A walk through the pages of a profile tab (Storico on the grid, Taggati, Reel).</summary>
/// <summary>A walk through the pages of a profile tab (Storico on the grid, Taggati, Reel, the gap of the check).</summary>
private sealed record ProfileWalk(EntryKind Kind, string? TabTarget, string ResumePage, string SettingPrefix)
{
public static readonly ProfileWalk Posts = new(EntryKind.Post, null, SitePages.ProfileFrom, "raccolta.post");
public static readonly ProfileWalk Tagged = new(EntryKind.Tagged, SiteTargets.ProfileTabTagged, SitePages.TaggedFrom, "raccolta.taggati");
public static readonly ProfileWalk Reels = new(EntryKind.Post, SiteTargets.ProfileTabReels, SitePages.ReelsFrom, "raccolta.reel");
/// <summary>The posts missing below the first page of the grid, filled by the profile check (same pages as the grid).</summary>
public static readonly ProfileWalk Gap = new(EntryKind.Post, null, SitePages.ProfileFrom, "raccolta.lacuna");
public bool IsGrid => TabTarget is null;
public string CursorKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.cursore";
/// <summary>The grid and the reels come newest first (pinned posts aside); the order of tagged posts is not known.</summary>
public bool IsChronological => Kind != EntryKind.Tagged;
public string CompletedKey(long accountId) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.completo";
public string CursorKey(long accountId) => Key(accountId, "cursore");
public string CompletedKey(long accountId) => Key(accountId, "completo");
/// <summary>The last item read before the stored cursor («time|id»): with it the point is found again by scrolling.</summary>
public string MarkKey(long accountId) => Key(accountId, "segno");
/// <summary>Gap only: known posts newer than this time do not end the walk (an older gap is still open below them).</summary>
public string KnownBeforeKey(long accountId) => Key(accountId, "fino");
private string Key(long accountId, string part) => $"{SettingPrefix}.{accountId.ToString(CultureInfo.InvariantCulture)}.{part}";
}
/// <summary>
/// Where a walk stopped: the cursor the site gave after the last page read, and the last item of that page. Without
/// a resume page in the map the walk gets back there by scrolling (decision 76): new posts on top move the pages
/// and their cursors, the item stays where it is.
/// </summary>
private sealed record ResumePoint(string Cursor, string? LastId, DateTimeOffset? LastAt)
{
public static ResumePoint Parse(string cursor, string? mark)
{
var separator = mark?.IndexOf('|', StringComparison.Ordinal) ?? -1;
if (mark is null || separator <= 0)
{
return new ResumePoint(cursor, null, null);
}
var at = DateTimeOffset.TryParse(mark[..separator], CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : (DateTimeOffset?)null;
var id = mark[(separator + 1)..];
return new ResumePoint(cursor, id.Length > 0 ? id : null, at);
}
public static string? MarkOf(ContentItem? item) =>
item is null ? null : $"{item.TakenAt.UtcDateTime.ToString("O", CultureInfo.InvariantCulture)}|{item.Id}";
/// <summary>
/// True when the page of <paramref name="items"/> holds the stored point or comes after it: the same cursor,
/// the same last item, or (newest first) a regular post older than it.
/// </summary>
public bool IsReachedBy(PageInfo? page, IReadOnlyList<ContentItem> items, Func<ContentItem, bool> olderCounts) =>
(page?.Cursor is { } cursor && string.Equals(cursor, Cursor, StringComparison.Ordinal))
|| (LastId is { } id && items.Any(i => string.Equals(i.Id, id, StringComparison.Ordinal)))
|| (LastAt is { } at && items.Any(i => olderCounts(i) && i.TakenAt < at));
}
/// <summary>What stops a walk at known content: nothing, any known post, or only known posts older than a time.</summary>
private sealed record KnownStop(bool Enabled, DateTimeOffset? Before = null)
{
public static readonly KnownStop Never = new(false);
public static readonly KnownStop Any = new(true);
public bool Stops(ContentItem item) => Enabled && (Before is not { } before || item.TakenAt < before);
}
/// <summary>How a walk over the pages of a profile ended.</summary>
private enum WalkEnd
{
/// <summary>No more pages: the beginning of the profile.</summary>
EndOfList,
/// <summary>A history limit of the account (from a date, last N posts).</summary>
Limit,
/// <summary>Known content, where the walk was to stop at it.</summary>
Known,
/// <summary>The pages allowed to this run were read.</summary>
Pages,
/// <summary>No page came after the bursts (counted as an empty page).</summary>
NoData,
}
/// <summary>The rules of one walk over the pages of a profile, starting from the page on screen.</summary>
private sealed record WalkRules
{
/// <summary>A stored point to get back to by scrolling first: the pages before it are read and saved, not counted.</summary>
public ResumePoint? CatchUpTo { get; init; }
/// <summary>Pages of this run counted before the walk (a resume page, a tab).</summary>
public int PagesRead { get; init; }
public required int MaxPages { get; init; }
/// <summary>Known content that ends the walk, once past the stored point.</summary>
public required KnownStop Stop { get; init; }
/// <summary>«Lo storico non corre più veloce dei download» before each page.</summary>
public required bool CheckDownloads { get; init; }
/// <summary>Whether the backfill suspension is announced in the timeline («Storico sospeso»).</summary>
public bool AnnounceSuspension { get; init; } = true;
/// <summary>Stores the point after each page read past the stored one: its cursor and its last item.</summary>
public required Func<string, ContentItem?, Task> Store { get; init; }
/// <summary>Items already saved by the caller (they are not saved again).</summary>
public HashSet<string> Processed { get; init; } = new(StringComparer.Ordinal);
}
/// <summary>
/// Controllo del profilo (spec §6.3): opens the profile (1 counted action), reads its state, the first page of
/// posts and the list of highlight collections, keeps a copy of the profile picture when it changes, and stops at
/// known content. Pinned posts are recognized and skipped for the stop rule.
/// known content. Pinned posts are recognized and skipped for the stop rule. When the first page ends with posts
/// Febe did not have, more may be missing below it: the check goes on down the grid until known content
/// (<see cref="FillGapAsync"/>).
/// </summary>
private async Task<RecipeStatus> ProfileCheckAsync(RecipeRun run)
{
@@ -48,8 +152,13 @@ public sealed partial class RecipeRunner
run.NewEntries++;
}
var reachedKnown = false;
foreach (var item in Contents(reads, c => IsOwnedBy(c, account)))
// The whole first page is read (it is on screen already): known posts at its top do not hide new ones below
// them, e.g. when the giro dei seguiti saved only the newest. Pinned posts are known but stop nothing.
var walk = ProfileWalk.Posts;
var items = PageItems(reads, account, walk);
var sawKnown = false;
SaveOutcome? tail = null;
foreach (var item in items)
{
var saved = await Writer.SaveAsync(account, item, EntryKind.Post, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (saved.Outcome == SaveOutcome.Created)
@@ -57,35 +166,135 @@ public sealed partial class RecipeRunner
run.NewEntries++;
run.AccountsWithNewPosts.Add(account.Id);
}
else if (saved.Outcome == SaveOutcome.Known && !item.Pinned)
if (!IsPinned(item, items, walk))
{
reachedKnown = true; // pinned posts are known but do not stop the check
break;
tail = saved.Outcome;
sawKnown |= saved.Outcome == SaveOutcome.Known;
}
}
var page = LastPage(reads);
if (!reachedKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
if (!sawKnown && account.BackfillCompletedAt is null && account.BackfillCursor is null)
{
if (page?.HasMore == true && page.Cursor is { } cursor)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
await Env.Storage.Settings.SetAsync(walk.MarkKey(account.Id), ResumePoint.MarkOf(items.LastOrDefault()), run.Ct).ConfigureAwait(false);
}
else if (page?.HasMore == false)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
}
}
else if (CollectionWriter.Wants(account, EntryKind.Post) && (account.BackfillCursor is not null || account.BackfillCompletedAt is not null))
{
await FillGapAsync(run, account, reads, items, tailIsNew: tail == SaveOutcome.Created).ConfigureAwait(false);
}
await Env.Driver.MaybeDistractionAsync(run.Ct).ConfigureAwait(false);
return RecipeStatus.Completed;
}
/// <summary>
/// The second half of the profile check, once the backfill has started or ended: when the first page ends with
/// posts Febe did not have (Febe off for days, the account paused or unreachable), the posts between it and the
/// known ones would be fetched by nothing else. The check goes on down the grid, one counted page each and at most
/// <see cref="RecipeOptions.GapPagesPerCheck"/>, until it meets known posts; the rest waits for the next check from
/// the stored point. A refused permit, the end of the session or too many files waiting for download leave the
/// gap for later: the check itself is done.
/// </summary>
private async Task FillGapAsync(RecipeRun run, Account account, IReadOnlyList<CapturedRead> reads, IReadOnlyList<ContentItem> firstPage, bool tailIsNew)
{
var walk = ProfileWalk.Gap;
var settings = Env.Storage.Settings;
var keys = new[] { walk.CursorKey(account.Id), walk.MarkKey(account.Id), walk.KnownBeforeKey(account.Id) };
var storedCursor = await settings.GetAsync(keys[0], run.Ct).ConfigureAwait(false);
var stored = storedCursor is null ? null : ResumePoint.Parse(storedCursor, await settings.GetAsync(keys[1], run.Ct).ConfigureAwait(false));
var before = ParseTime(await settings.GetAsync(keys[2], run.Ct).ConfigureAwait(false));
async Task ClearAsync() => await settings.SetManyAsync(keys.ToDictionary(k => k, _ => (string?)null), run.Ct).ConfigureAwait(false);
if (LastPage(reads)?.HasMore == false)
{
if (stored is not null || before is not null)
{
await ClearAsync().ConfigureAwait(false); // the whole grid is on the first page, read just now
}
return;
}
// Known posts newer than the end of an older gap still open further down do not end the walk: one walk fills
// both. A stored point also stops only at posts older than its last item (those before it were saved by it).
var floor = Earliest(before, stored?.LastAt);
IReadOnlyList<CapturedRead> start = reads;
ResumePoint? catchUpTo = null;
var pages = 0;
if (!tailIsNew)
{
if (stored is null)
{
return;
}
if (Env.SiteMap.HasPage(walk.ResumePage))
{
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
start = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(start, r => r.Contents.Count > 0 || r.Page is not null, null))
{
return; // an empty page, counted: the gap stays for the next check
}
pages = 1;
}
else
{
catchUpTo = stored; // scroll down from the first page, on screen, back to the stored point
}
}
try
{
var (end, _, _) = await WalkPagesAsync(run, account, walk, start, new WalkRules
{
CatchUpTo = catchUpTo,
PagesRead = pages,
MaxPages = Math.Max(1, Env.Options.GapPagesPerCheck),
Stop = floor is { } f ? new KnownStop(true, f) : KnownStop.Any,
CheckDownloads = true,
AnnounceSuspension = false,
Processed = new HashSet<string>(firstPage.Select(i => i.Id), StringComparer.Ordinal),
Store = (cursor, last) => settings.SetManyAsync(
new Dictionary<string, string?>
{
[keys[0]] = cursor,
[keys[1]] = ResumePoint.MarkOf(last),
[keys[2]] = floor?.ToString("O", CultureInfo.InvariantCulture),
},
run.Ct),
}).ConfigureAwait(false);
if (end is WalkEnd.EndOfList or WalkEnd.Limit or WalkEnd.Known)
{
await ClearAsync().ConfigureAwait(false);
}
}
catch (RecipeStopException stop) when (stop.Status == RecipeStatus.Denied)
{
// No permit, the session is over, or too many files wait for download: the gap waits for the next check.
}
}
/// <summary>
/// Storico, Taggati and Reel (spec §6.3): one page per permit, resuming from the stored point and stopping at the
/// beginning of the profile. The backfill stops while the account has more than 60 files waiting for download or
/// the data budget is used up (the engine checks too, the recipe must stop as well). Once a tab has been walked to
/// the end, later runs only check its first page and stop at known content.
/// beginning of the profile. Without a resume page in the map (profileFrom, taggedFrom, reelsFrom are optional)
/// the walk scrolls from the top back to the stored point, each page counted by the Governor and saved on the
/// way, and only the pages after it count against the pages of the run (decision 76): never a silent restart. The
/// backfill stops while the account has more than 60 files waiting for download or the data budget is used up
/// (the engine checks too, the recipe must stop as well). Once a tab has been walked to the end, later runs only
/// check its first page and stop at known content.
/// </summary>
private async Task<RecipeStatus> WalkAsync(RecipeRun run, ProfileWalk walk)
{
@@ -121,6 +330,7 @@ public sealed partial class RecipeRunner
}
}
var target = cursor is null ? null : ResumePoint.Parse(cursor, await settings.GetAsync(walk.MarkKey(account.Id), run.Ct).ConfigureAwait(false));
if (!checkOnly)
{
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
@@ -130,12 +340,13 @@ public sealed partial class RecipeRunner
var parameters = Values(("username", account.Username));
IReadOnlyList<CapturedRead> reads;
var pages = 0;
if (cursor is not null && Env.SiteMap.HasPage(walk.ResumePage))
ResumePoint? catchUpTo = null;
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
{
// Resume where the last run stopped: the page of the site that starts after the stored point.
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", cursor))).ConfigureAwait(false);
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
reads = await run.WaitForDataAsync(mark, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (!run.Judge(reads, r => r.Contents.Count > 0 || r.Page is not null, Env.SiteMap.BuildPath(SitePages.Profile, parameters)))
{
@@ -159,54 +370,32 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Completed, EmptyPageMessage);
}
pages++;
if (target is null)
{
pages++;
}
}
catchUpTo = target;
}
var finished = false;
var processed = new HashSet<string>(StringComparer.Ordinal);
while (true)
var (end, caughtUp, catchUpPages) = await WalkPagesAsync(run, account, walk, reads, new WalkRules
{
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, reads, processed, stopAtKnown: checkOnly).ConfigureAwait(false);
var page = LastPage(reads);
if (reachedLimit || page?.HasMore == false)
{
finished = !checkOnly || page?.HasMore == false;
break;
}
CatchUpTo = catchUpTo,
PagesRead = pages,
MaxPages = maxPages,
Stop = checkOnly ? KnownStop.Any : KnownStop.Never,
CheckDownloads = !checkOnly,
Store = (next, last) => StoreWalkPointAsync(run, account, walk, next, last),
}).ConfigureAwait(false);
if (checkOnly && reachedKnown)
{
break;
}
cursor = page?.Cursor ?? cursor;
await StoreWalkCursorAsync(run, account, walk, cursor).ConfigureAwait(false);
if (pages >= maxPages)
{
break;
}
if (!checkOnly)
{
await EnsureBackfillAllowedAsync(run, account).ConfigureAwait(false);
}
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
pages++;
if (reads.Count == 0)
{
break; // nothing came in after the bursts (counted as an empty page)
}
}
if (finished)
if (end == WalkEnd.EndOfList || (end == WalkEnd.Limit && !checkOnly))
{
run.Finished = true;
if (walk.IsGrid)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, null, Env.Clock.Now, run.Ct).ConfigureAwait(false);
await settings.SetAsync(walk.MarkKey(account.Id), null, run.Ct).ConfigureAwait(false);
await Writer.EventAsync("storico-completato", $"Storico di {account.Username} completato.", EventSeverity.Success, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
else
@@ -215,27 +404,107 @@ public sealed partial class RecipeRunner
new Dictionary<string, string?>
{
[walk.CursorKey(account.Id)] = null,
[walk.MarkKey(account.Id)] = null,
[walk.CompletedKey(account.Id)] = Env.Clock.Now.ToString("O", CultureInfo.InvariantCulture),
},
run.Ct).ConfigureAwait(false);
}
}
else if (!caughtUp)
{
await Writer.EventAsync(
"ripresa-scorrendo",
$"«{Name(run.Request.Kind)}» di {account.Username}: {ItalianText.Number(catchUpPages + 1)} pagine lette scorrendo senza ritrovare ancora il punto in cui si era fermato. Il punto resta salvato: si riprende da lì alla prossima sessione.",
EventSeverity.Info,
account.Id,
run.Session.SessionId,
run.Ct).ConfigureAwait(false);
}
return RecipeStatus.Completed;
}
/// <summary>
/// Saves the new items of a walk page. Returns whether known content was met (only meaningful when
/// <paramref name="stopAtKnown"/>) and whether a history limit of the account was reached (from a date, last N posts).
/// Saves the pages of a walk, from the page on screen: first back to the stored point when there is one (pages
/// read and saved, not counted against <see cref="WalkRules.MaxPages"/>, no point stored before it is reached),
/// then one page per permit until the end of the profile, a history limit, known content (when the rules say so)
/// or the pages of the run. Returns how it ended, whether the stored point was reached, and the pages scrolled to
/// get back there.
/// </summary>
private async Task<(bool ReachedKnown, bool ReachedLimit)> SaveWalkPageAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList<CapturedRead> reads, HashSet<string> processed, bool stopAtKnown)
private async Task<(WalkEnd End, bool CaughtUp, int CatchUpPages)> WalkPagesAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList<CapturedRead> reads, WalkRules rules)
{
var items = Contents(reads, c => walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account))
.Where(c => processed.Add(c.Id))
.ToList();
foreach (var item in items)
var pending = rules.CatchUpTo;
var pages = rules.PagesRead;
var catchUp = 0;
while (true)
{
if (walk.Kind != EntryKind.Tagged && !item.Pinned)
var items = PageItems(reads, account, walk);
var page = LastPage(reads);
if (pending is not null && pending.IsReachedBy(page, items, i => walk.IsChronological && !IsPinned(i, items, walk)))
{
pending = null; // this page holds the stored point: from here on the walk goes on as usual
}
var (reachedKnown, reachedLimit) = await SaveWalkPageAsync(run, account, walk, items, rules.Processed, pending is null ? rules.Stop : KnownStop.Never).ConfigureAwait(false);
if (reachedLimit)
{
return (WalkEnd.Limit, pending is null, catchUp);
}
if (page?.HasMore == false)
{
return (WalkEnd.EndOfList, pending is null, catchUp);
}
if (reachedKnown)
{
return (WalkEnd.Known, true, catchUp);
}
if (pending is null && page?.Cursor is { } next)
{
await rules.Store(next, items.LastOrDefault()).ConfigureAwait(false);
}
if (pending is null && pages >= rules.MaxPages)
{
return (WalkEnd.Pages, true, catchUp);
}
if (rules.CheckDownloads)
{
await EnsureBackfillAllowedAsync(run, account, rules.AnnounceSuspension).ConfigureAwait(false);
}
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
var counted = pending is null;
reads = await ScrollForPageAsync(run, r => r.Contents.Count > 0 || r.Page is not null).ConfigureAwait(false);
if (counted)
{
pages++;
}
else
{
catchUp++;
}
if (reads.Count == 0)
{
return (WalkEnd.NoData, pending is null, catchUp); // nothing came in after the bursts (counted as an empty page)
}
}
}
/// <summary>
/// Saves the new items of a walk page. Returns whether known content that ends the walk was met and whether a
/// history limit of the account was reached (from a date, last N posts).
/// </summary>
private async Task<(bool ReachedKnown, bool ReachedLimit)> SaveWalkPageAsync(RecipeRun run, Account account, ProfileWalk walk, IReadOnlyList<ContentItem> page, HashSet<string> processed, KnownStop stop)
{
foreach (var item in page.Where(c => processed.Add(c.Id)).ToList())
{
var pinned = IsPinned(item, page, walk);
if (walk.Kind != EntryKind.Tagged && !pinned)
{
if (account.Limits.Depth == HistoryDepth.FromDate && account.Limits.FromDate is { } from && item.TakenAt < from)
{
@@ -256,7 +525,7 @@ public sealed partial class RecipeRunner
run.NewEntries++;
run.AccountsWithNewPosts.Add(account.Id);
}
else if (stopAtKnown && saved.Outcome == SaveOutcome.Known && !item.Pinned)
else if (saved.Outcome == SaveOutcome.Known && !pinned && stop.Stops(item))
{
return (true, false);
}
@@ -265,33 +534,48 @@ public sealed partial class RecipeRunner
return (false, false);
}
private async Task StoreWalkCursorAsync(RecipeRun run, Account account, ProfileWalk walk, string? cursor)
/// <summary>The stored point of a walk: its cursor, and its last item to find it again by scrolling.</summary>
private async Task StoreWalkPointAsync(RecipeRun run, Account account, ProfileWalk walk, string cursor, ContentItem? last)
{
if (cursor is null)
{
return;
}
if (walk.IsGrid)
{
await Env.Storage.Accounts.SetBackfillAsync(account.Id, cursor, null, run.Ct).ConfigureAwait(false);
await Env.Storage.Settings.SetAsync(walk.MarkKey(account.Id), ResumePoint.MarkOf(last), run.Ct).ConfigureAwait(false);
}
else
{
await Env.Storage.Settings.SetAsync(walk.CursorKey(account.Id), cursor, run.Ct).ConfigureAwait(false);
await Env.Storage.Settings.SetManyAsync(
new Dictionary<string, string?>
{
[walk.CursorKey(account.Id)] = cursor,
[walk.MarkKey(account.Id)] = ResumePoint.MarkOf(last),
},
run.Ct).ConfigureAwait(false);
}
}
/// <summary>The posts of a walk page: of the account (tagged: of others), never a story or a collection item.</summary>
private static IReadOnlyList<ContentItem> PageItems(IReadOnlyList<CapturedRead> reads, Account account, ProfileWalk walk) =>
Contents(reads, c => IsPostLike(c) && (walk.Kind == EntryKind.Tagged ? !IsOwnedBy(c, account) : IsOwnedBy(c, account)));
/// <summary>Pinned on top of the profile: the vocabulary says so, or (newest first) the order of the page does.</summary>
private bool IsPinned(ContentItem item, IReadOnlyList<ContentItem> page, ProfileWalk walk) =>
walk.IsChronological ? LooksPinned(item, page) : item.Pinned;
/// <summary>
/// «Lo storico non corre più veloce dei download» (spec §6.3): stops while the account has more than 60 files waiting
/// or the data budget is used up.
/// </summary>
private async Task EnsureBackfillAllowedAsync(RecipeRun run, Account account)
private async Task EnsureBackfillAllowedAsync(RecipeRun run, Account account, bool announce = true)
{
var pending = await Env.Storage.Media.CountPendingDownloadsAsync(account.Id, run.Ct).ConfigureAwait(false);
if (pending > Env.Options.MaxPendingDownloadsForBackfill)
{
await Writer.EventAsync("storico-sospeso", $"Storico di {account.Username} sospeso: {ItalianText.Number(pending)} file aspettano di essere scaricati.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
if (announce)
{
await Writer.EventAsync("storico-sospeso", $"Storico di {account.Username} sospeso: {ItalianText.Number(pending)} file aspettano di essere scaricati.", EventSeverity.Info, account.Id, run.Session.SessionId, run.Ct).ConfigureAwait(false);
}
throw RecipeRun.Stop(RecipeStatus.Denied, $"Storico sospeso: {ItalianText.Number(pending)} file di {account.Username} aspettano di essere scaricati (più di {Env.Options.MaxPendingDownloadsForBackfill}).");
}
@@ -350,30 +634,35 @@ public sealed partial class RecipeRunner
/// <summary>
/// Scrolls with bursts until a new page of data that satisfies <paramref name="expected"/> arrives, at most
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Returns the reads of that page (empty when none came).
/// <see cref="RecipeOptions.BurstsPerPage"/> bursts. Only the expected data ends the bursts: a response the page
/// fetches for something else (a background poll, a bare status) says nothing about the next page. When the
/// bursts are used up without it, the responses received are judged: an unknown shape is «formato non
/// riconosciuto», anything else an empty page. Returns the reads of that page (empty when none came).
/// </summary>
private async Task<IReadOnlyList<CapturedRead>> ScrollForPageAsync(RecipeRun run, Func<ReadResult, bool> expected)
{
var mark = Env.Capture.Mark();
var seen = mark;
for (var burst = 0; burst < Env.Options.BurstsPerPage; burst++)
{
await Env.Driver.ScrollBurstAsync(run.Ct).ConfigureAwait(false);
run.ThrowIfSignal();
if (Env.Capture.Pending > 0 || Env.Capture.Since(mark).Count > 0)
if (Env.Capture.Pending > 0 || Env.Capture.Mark() != seen)
{
await run.SettleAsync().ConfigureAwait(false);
seen = Env.Capture.Mark();
}
var reads = Env.Capture.Since(mark);
if (reads.Any(r => r.Result.Shape != ReadShape.Recognized || expected(r.Result)))
var page = reads.Where(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)).ToList();
if (page.Count > 0)
{
return run.Judge(reads, expected, null)
? reads.Where(r => r.Result.Shape == ReadShape.Recognized && expected(r.Result)).ToList()
: [];
run.Judge(reads, expected, null);
return page;
}
}
run.Judge([], expected, null);
run.Judge(Env.Capture.Since(mark), expected, null);
return [];
}
@@ -382,4 +671,10 @@ public sealed partial class RecipeRunner
private static PageInfo? LastPage(IEnumerable<CapturedRead> reads) =>
reads.Where(r => r.Result.Page is not null).Select(r => r.Result.Page).LastOrDefault();
private static DateTimeOffset? ParseTime(string? value) =>
DateTimeOffset.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var time) ? time : null;
private static DateTimeOffset? Earliest(DateTimeOffset? a, DateTimeOffset? b) =>
a is null ? b : b is null ? a : a < b ? a : b;
}
@@ -73,9 +73,9 @@ public sealed partial class RecipeRunner
var sawKnown = false;
foreach (var item in items)
{
if (item.Owner is null)
if (item.Owner is null || !IsPostLike(item))
{
continue;
continue; // stories received in advance with the bar are saved only when shown, by «Storie di un account»
}
var account = await Writer.ObserveProfileAsync(item.Owner, run.Session.SessionId, run.Ct).ConfigureAwait(false);
@@ -8,6 +8,9 @@ namespace Febe.Core.Collection.Recipes;
public sealed partial class RecipeRunner
{
/// <summary>A story stays on offer for a day (spec §4.3: «storie attive nelle 24 ore»).</summary>
private static readonly TimeSpan StoryLifetime = TimeSpan.FromHours(24);
/// <summary>
/// Storie di un account (spec §6.3): checks that the budget allows at least ten stories, opens the viewer from the
/// stories bar (when the home is on screen) or from the profile, watches the stories one by one with the timings of
@@ -53,8 +56,16 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.AccountUnreachable, $"{account.Username} è un profilo privato che non segui: non si tocca.");
}
if (!(await run.FindAsync(SiteTargets.ProfileStoryRing, parameters).ConfigureAwait(false)).Found)
var ring = await run.FindAsync(SiteTargets.ProfileStoryRing, parameters).ConfigureAwait(false);
if (!ring.Found)
{
// No ring means no active stories, unless the profile just read says there is one: then it is the map
// that no longer finds the ring (§7.7: the recipe stops and reports), not a quiet day.
if (profile.LatestStoryAt is { } latest && latest > Env.Clock.Now - StoryLifetime)
{
throw RecipeRun.Stop(RecipeStatus.TargetNotFound, $"{ring.Message} Il profilo di {account.Username} dice però che c'è una storia attiva: la mappa dei bersagli va controllata.");
}
await StoriesCheckedAsync(account, run).ConfigureAwait(false);
return RecipeStatus.Completed; // no active stories: nothing to open
}
@@ -287,6 +287,43 @@ public sealed partial class RecipeRunner : IRecipeRunner
private static bool IsOwnedBy(ContentItem item, Account account) =>
item.Owner is { } owner && (account.InstagramId is { } id ? owner.Id == id : string.Equals(owner.Username, account.Username, StringComparison.OrdinalIgnoreCase));
/// <summary>
/// A post, not a story (it expires) nor an item found inside a highlight collection. The reader recognizes all three
/// by the same shape; stories and collection items are saved only by the viewer recipes, and only when shown
/// (spec §6.3: «anche quando la pagina riceve in anticipo l'elenco completo»).
/// </summary>
private static bool IsPostLike(ContentItem item) => item.ExpiresAt is null && item.HighlightId is null;
/// <summary>
/// Pinned on top of a profile (spec §6.3: not «already known» for the stop rule, nor a limit of history). When the
/// vocabulary has no key for it, a post followed on its page by a newer one is out of the order of the grid,
/// newest first: that is what a pinned post looks like.
/// </summary>
private bool LooksPinned(ContentItem item, IReadOnlyList<ContentItem> page)
{
if (item.Pinned)
{
return true;
}
if (Env.Capture.Reader.Vocabulary.Content.Pinned.IsSet)
{
return false;
}
var index = -1;
for (var i = 0; i < page.Count; i++)
{
if (string.Equals(page[i].Id, item.Id, StringComparison.Ordinal))
{
index = i;
break;
}
}
return index >= 0 && page.Skip(index + 1).Any(later => later.TakenAt > item.TakenAt);
}
private static IReadOnlyDictionary<string, string> Values(params (string Key, string Value)[] pairs) =>
pairs.ToDictionary(p => p.Key, p => p.Value, StringComparer.Ordinal);
}
+31 -2
View File
@@ -48,6 +48,35 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
public Signal? ObserveResponse(ResponseDescriptor response)
{
ArgumentNullException.ThrowIfNull(response);
return MatchResponse(response, statusOnly: false) is { } rule ? Raise(rule.Level, rule.Code, response.Url) : null;
}
/// <summary>
/// The HTTP status of a file the download queue asked the CDN for (spec §6.5). The browser serves
/// <c>Network.loadNetworkResource</c> outside the page, so the page's network events never show these responses:
/// the queue reports them here, and the status rules for the CDN apply (e.g. 429, «vale per sito e CDN»).
/// Returns the level of the matching rule — also when the same signal was already reported within
/// <see cref="DedupeWindow"/>, so the caller stops every time — or null when no rule matches.
/// </summary>
/// <remarks>The incident keeps only scheme and host: the path of a CDN address identifies a file (spec §13.2).</remarks>
public SignalLevel? ObserveDownload(Uri address, int status)
{
ArgumentNullException.ThrowIfNull(address);
var sanitized = UrlSanitizer.Sanitize(address.AbsoluteUri);
var origin = $"{sanitized.Scheme}://{sanitized.Host}/";
var response = new ResponseDescriptor("download", HostKind.Cdn, origin, sanitized.Host, "/", status, string.Empty, "Other", false, _clock.Now);
if (MatchResponse(response, statusOnly: true) is not { } rule)
{
return null;
}
Raise(rule.Level, rule.Code, origin);
return rule.Level;
}
/// <summary>The first status or path rule for <paramref name="response"/>; path rules describe pages, not files.</summary>
private SignalRule? MatchResponse(ResponseDescriptor response, bool statusOnly)
{
var scope = response.IsMainFrameDocument ? SignalScope.Document : SignalScope.Subresource;
foreach (var rule in _rules.Rules)
{
@@ -57,9 +86,9 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
}
if ((rule.Statuses.Count > 0 && rule.Statuses.Contains(response.Status))
|| (rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|| (!statusOnly && rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
{
return Raise(rule.Level, rule.Code, response.Url);
return rule;
}
}
+165 -34
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using Febe.Core.Abstractions;
using Febe.Core.Domain;
using Febe.Core.Storage;
@@ -50,6 +51,28 @@ public sealed class ContentChangedException : IOException
}
}
/// <summary>
/// The entry or the file record went away (Alberto deleted it) while the content was on its way: nothing was kept in
/// the library and no journal line was written.
/// </summary>
public sealed class EntryDeletedException : IOException
{
public EntryDeletedException()
: base("L'elemento è stato eliminato mentre il file si salvava: il file non entra in libreria.")
{
}
public EntryDeletedException(string message)
: base(message)
{
}
public EntryDeletedException(string message, Exception innerException)
: base(message, innerException)
{
}
}
public enum MediaSaveOutcome
{
/// <summary>The file is in the library and its record is updated.</summary>
@@ -87,6 +110,14 @@ public sealed class LibraryIngest(
bool setFileTimeToPublication = true,
SafeFileWriter? writer = null)
{
/// <summary>
/// One gate per account folder, for every writer of the process: the §9.5 check «identical to a file of the
/// account?» and the record of the new file happen as one step, so two downloads (or a download and an import)
/// with the same bytes cannot both enter the library.
/// </summary>
private static readonly ConcurrentDictionary<string, SemaphoreSlim> AccountGates =
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
private readonly SafeFileWriter _writer = writer ?? new SafeFileWriter(layout.MaxPathLength);
private volatile LibraryNaming _naming = naming;
private volatile bool _setFileTimeToPublication = setFileTimeToPublication;
@@ -129,6 +160,9 @@ public sealed class LibraryIngest(
/// The content exceeded <see cref="MediaContent.MaxBytes"/>: nothing was written; the caller marks the file
/// <see cref="MediaState.Skipped"/> with <see cref="IMediaStore.MarkFailedAsync"/>.
/// </exception>
/// <exception cref="EntryDeletedException">
/// The entry or the file record was deleted while the content was on its way: nothing was kept, no journal line.
/// </exception>
/// <exception cref="IOException">Writing failed (disk full, connection cut): nothing was written under the final name.</exception>
public async Task<MediaSaveResult> SaveMediaAsync(
Account account,
@@ -156,41 +190,75 @@ public sealed class LibraryIngest(
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle), zone);
var directory = provisional.Contains('/', StringComparison.Ordinal) ? provisional[..provisional.LastIndexOf('/')] : string.Empty;
MediaLocation? identical = null;
var saved = await _writer.SaveAsync(
content.Content,
folder,
directory,
async (digest, token) =>
{
if (content.ExpectedSha256 is { } expected && !string.Equals(expected, digest.Sha256, StringComparison.OrdinalIgnoreCase))
{
throw new ContentChangedException("Il contenuto letto è diverso da quello atteso: il file non viene salvato.");
}
var same = await storage.Media.FindBySha256Async(digest.Sha256, token).ConfigureAwait(false);
identical = same.FirstOrDefault(s => s.Entry.AccountId == account.Id && s.Media.Id != media.Id && EntryStateRules.IsPresent(s.Media.State));
if (identical is not null)
{
return null;
}
return content.FixedRelativePath is not null
? provisional
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone);
},
new SafeWriteOptions
{
LastWriteTime = _setFileTimeToPublication ? entry.PublishedAt : null,
MaxBytes = content.MaxBytes,
},
ct).ConfigureAwait(false);
if (saved is null)
// The content is written and hashed outside the gate; from the §9.5 check to the record of the file the account
// is held, so that the check sees every file of the account already decided.
var gate = AccountGates.GetOrAdd(Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder)), _ => new SemaphoreSlim(1, 1));
SemaphoreSlim? held = null;
try
{
return new MediaSaveResult(MediaSaveOutcome.IdenticalInAccount, null, identical, []);
}
MediaLocation? identical = null;
var gone = false;
var saved = await _writer.SaveAsync(
content.Content,
folder,
directory,
async (digest, token) =>
{
if (content.ExpectedSha256 is { } expected && !string.Equals(expected, digest.Sha256, StringComparison.OrdinalIgnoreCase))
{
throw new ContentChangedException("Il contenuto letto è diverso da quello atteso: il file non viene salvato.");
}
await gate.WaitAsync(token).ConfigureAwait(false);
held = gate;
// Alberto may have deleted the entry while the content was on its way (a download takes minutes in
// the queue): its choice wins, the content does not enter the library.
if (await IsGoneAsync(entry.Id, media.Id, token).ConfigureAwait(false))
{
gone = true;
return null;
}
var same = await storage.Media.FindBySha256Async(digest.Sha256, token).ConfigureAwait(false);
identical = same.FirstOrDefault(s => s.Entry.AccountId == account.Id && s.Media.Id != media.Id && EntryStateRules.IsPresent(s.Media.State));
if (identical is not null)
{
return null;
}
return content.FixedRelativePath is not null
? provisional
: layout.RelativePathFor(folder, scheme, NamingValues.For(account.Username, entry, media.Position, content.Extension, highlightTitle, digest.Sha256), zone);
},
new SafeWriteOptions
{
LastWriteTime = _setFileTimeToPublication ? entry.PublishedAt : null,
MaxBytes = content.MaxBytes,
},
ct).ConfigureAwait(false);
if (gone)
{
throw new EntryDeletedException();
}
if (saved is null)
{
return new MediaSaveResult(MediaSaveOutcome.IdenticalInAccount, null, identical, []);
}
return await RecordAsync(account, entry, media, content, saved).ConfigureAwait(false);
}
finally
{
held?.Release();
}
}
/// <summary>The file is on disk under its final name: hashes, thumbnail, record, probable duplicates.</summary>
private async Task<MediaSaveResult> RecordAsync(Account account, Entry entry, Media media, MediaContent content, SavedFile saved)
{
ulong? hash = null;
int? width = media.Width, height = media.Height;
var hasThumbnail = false;
@@ -215,7 +283,23 @@ public sealed class LibraryIngest(
var stored = new StoredFile(saved.RelativePath, saved.Bytes, saved.Sha256, hash, width, height, media.Duration, hasThumbnail);
var state = entry.Provenance == Provenance.Imported ? MediaState.Imported : MediaState.Downloaded;
var now = clock.Now;
await storage.Media.MarkStoredAsync(media.Id, stored, state, now, CancellationToken.None).ConfigureAwait(false);
bool recorded;
try
{
recorded = await storage.Media.MarkStoredAsync(media.Id, stored, state, now, CancellationToken.None).ConfigureAwait(false);
}
catch (KeyNotFoundException)
{
recorded = false; // «Eliminalo e lascia che torni»: the record itself is gone
}
if (!recorded)
{
// Deleted between the check and the record: the file just written belongs to nothing. It is this
// operation's own file, never one of the library: it goes, as Alberto's deletion asked.
await DiscardAsync(saved, hasThumbnail).ConfigureAwait(false);
throw new EntryDeletedException();
}
var pairs = new List<DuplicatePair>();
if (hash is { } h && hashIndex is not null)
@@ -249,6 +333,11 @@ public sealed class LibraryIngest(
{
var stored = await storage.Entries.GetWithMediaAsync(entryId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Elemento {entryId} non trovato.");
if (stored.Entry.State == EntryState.Deleted)
{
return; // a «save» line after the «delete» line would bring the entry back with a rebuild
}
var account = await storage.Accounts.GetAsync(stored.Entry.AccountId, ct).ConfigureAwait(false)
?? throw new KeyNotFoundException($"Account {stored.Entry.AccountId} non trovato.");
var highlights = await storage.Highlights.ListForEntryAsync(entryId, ct).ConfigureAwait(false);
@@ -261,6 +350,48 @@ public sealed class LibraryIngest(
ct).ConfigureAwait(false);
}
/// <summary>True when the entry or the file record no longer wants content: removed, or «eliminato».</summary>
private async Task<bool> IsGoneAsync(long entryId, long mediaId, CancellationToken ct)
{
var current = await storage.Entries.GetAsync(entryId, ct).ConfigureAwait(false);
if (current is null || current.State == EntryState.Deleted)
{
return true;
}
var file = await storage.Media.GetAsync(mediaId, ct).ConfigureAwait(false);
return file is null || file.State == MediaState.Deleted;
}
/// <summary>Removes a file this operation has just written and that no record took, with its thumbnail when unused.</summary>
private async Task DiscardAsync(SavedFile saved, bool hasThumbnail)
{
try
{
File.Delete(saved.FullPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Best effort: the file stays without a record, and without a journal line it never brings the entry back.
}
if (hasThumbnail && thumbnails is not null)
{
var users = await storage.Media.FindBySha256Async(saved.Sha256, CancellationToken.None).ConfigureAwait(false);
if (!users.Any(u => EntryStateRules.IsPresent(u.Media.State)))
{
try
{
thumbnails.Delete(saved.Sha256);
}
catch (IOException)
{
// A thumbnail left behind costs a few kilobytes.
}
}
}
}
private bool TryThumbnail(string key, Func<Stream> open, bool owned)
{
if (thumbnails is null)
+31 -2
View File
@@ -1,4 +1,5 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
@@ -71,6 +72,23 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
/// <summary>Serializes «is the name free? then rename» across all writers of the process.</summary>
private static readonly Lock MoveGate = new();
/// <summary>Temporary files this process is writing now: the clean-up of a previous run never touches them.</summary>
private static readonly ConcurrentDictionary<string, byte> LiveTemporaryFiles =
new(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
/// <summary>
/// Marks a temporary file this process is about to write: <see cref="CleanupTemporaryFiles"/> leaves it alone
/// until the returned handle is disposed. The clean-up of an interrupted run can still be going through a large
/// library while the first downloads of this run are written (on Linux a deleted open file would be lost).
/// </summary>
public static IDisposable ReserveTemporaryFile(string path)
{
ArgumentException.ThrowIfNullOrWhiteSpace(path);
var key = Path.GetFullPath(path);
LiveTemporaryFiles[key] = 0;
return new TemporaryFileReservation(key);
}
/// <summary>Writes <paramref name="source"/> to <paramref name="relativePath"/> inside <paramref name="rootFolder"/>.</summary>
public Task<SavedFile> SaveAsync(Stream source, string rootFolder, string relativePath, SafeWriteOptions? options = null, CancellationToken ct = default)
{
@@ -120,6 +138,7 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
var tempFolder = string.IsNullOrEmpty(tempDirectory) ? root : LibraryLayout.FullPath(root, tempDirectory);
Directory.CreateDirectory(tempFolder);
var tempPath = Path.Combine(tempFolder, TempPrefix + Guid.NewGuid().ToString("N")[..12] + TempSuffix);
using var reservation = ReserveTemporaryFile(tempPath);
try
{
@@ -156,8 +175,8 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
}
/// <summary>
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>).
/// Returns how many were removed.
/// Removes temporary files left by an interrupted process (never library files: only <c>.febe-*.part</c>), except
/// those this process is writing (<see cref="ReserveTemporaryFile"/>). Returns how many were removed.
/// </summary>
public static int CleanupTemporaryFiles(string folder, bool recursive = true)
{
@@ -173,6 +192,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
new EnumerationOptions { RecurseSubdirectories = recursive, IgnoreInaccessible = true, AttributesToSkip = 0 });
foreach (var file in files)
{
if (LiveTemporaryFiles.ContainsKey(Path.GetFullPath(file)))
{
continue; // being written by this process right now
}
if (TryDelete(file))
{
removed++;
@@ -272,6 +296,11 @@ public sealed class SafeFileWriter(int maxPathLength = WindowsFileNames.MaxPathL
throw new IOException($"Nessun nome libero per {desiredRelativePath} dopo {MaxNameAttempts} tentativi.");
}
private sealed class TemporaryFileReservation(string key) : IDisposable
{
public void Dispose() => LiveTemporaryFiles.TryRemove(key, out _);
}
private static bool TryDelete(string path)
{
try
+6 -2
View File
@@ -33,8 +33,12 @@ public interface IMediaStore
/// <summary>Files waiting to be downloaded, for one account or overall («lo storico non corre più veloce dei download»).</summary>
Task<int> CountPendingDownloadsAsync(long? accountId = null, CancellationToken ct = default);
/// <summary>Records a file now on disk and recomputes the state of its entry, in one transaction.</summary>
Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// Records a file now on disk and recomputes the state of its entry, in one transaction. Returns false, changing
/// nothing, when the file or its entry is «eliminato» (Alberto deleted it while the content was on its way): the
/// caller removes the file it just wrote. Throws <see cref="KeyNotFoundException"/> when the file record is gone.
/// </summary>
Task<bool> MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default);
/// <summary>
/// Records a failed attempt: <paramref name="state"/> is Failed, Expired (address expired) or Skipped (a limit).
+13 -4
View File
@@ -119,7 +119,7 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
},
ct);
public Task MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default)
public Task<bool> MarkStoredAsync(long mediaId, StoredFile file, MediaState state, DateTimeOffset at, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(file);
if (!EntryStateRules.IsPresent(state))
@@ -127,15 +127,18 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
throw new ArgumentException("Un file salvato è «scaricato» o «importato».", nameof(state));
}
return db.WriteAsync(
return db.WriteAsync<bool>(
w =>
{
var entryId = EntryOf(w, mediaId);
w.Command("""
// A deletion «ricordando la scelta» wins over a file that arrives afterwards.
var rows = w.Command("""
UPDATE media SET state = @state, relative_path = @path, bytes = @bytes, sha256 = @sha, phash = @phash,
width = COALESCE(@w, width), height = COALESCE(@h, height), duration_ms = COALESCE(@d, duration_ms),
has_thumbnail = @thumb, downloaded_at = @at, last_error = NULL, source_url = NULL, cover_url = NULL
WHERE id = @id
WHERE id = @id AND state <> 'Deleted'
AND (SELECT e.state FROM entry e WHERE e.id = media.entry_id) <> 'Deleted'
""")
.With("@state", Sql.Enum(state))
.With("@path", file.RelativePath)
@@ -149,7 +152,13 @@ internal sealed class MediaStore(FebeDatabase db) : IMediaStore
.With("@at", Sql.Time(at))
.With("@id", mediaId)
.ExecuteNonQuery();
if (rows == 0)
{
return false;
}
RecomputeState(w, entryId, at);
return true;
},
ct);
}
@@ -0,0 +1,193 @@
using System.Text.Json.Nodes;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Data;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The collection writer: files of a series in their declared places, fresh addresses for files that expired or
/// failed (posts, stories still on offer, highlight items, profile pictures).
/// </summary>
[TestClass]
public sealed class CollectionWriterTests
{
private static readonly ShapeReader Reader = new(ReaderVocabulary.LoadTestSite());
private static readonly ScriptedAccount Marta = new("1001", "marta.prova");
[TestMethod]
public async Task ASeriesChildWithoutVersionsKeepsItsPlaceAndPostSingoloFillsIt()
{
await using var bed = await Bed.CreateAsync();
var partial = Item(new ScriptedPost("500", Make.T0.AddDays(-1)) { Children = [("c1", Url("c1")), ("c2", null), ("c3", Url("c3"))] });
Assert.IsFalse(partial.IsComplete);
CollectionAssert.AreEqual(new[] { 1, 3 }, ReadMapping.ToMedia(partial, Make.T0).Select(m => m.Position).ToArray(), "The unreadable second child leaves its place free.");
var saved = await bed.Writer.SaveAsync(bed.Account, partial, EntryKind.Post, null, CancellationToken.None);
Assert.AreEqual(SaveOutcome.Created, saved.Outcome);
Assert.IsTrue((await bed.Db.Tasks.ListPendingAsync(10)).Any(t => t.Kind == EngineTaskKind.SinglePost), "«Post singolo» completes it.");
var full = Item(new ScriptedPost("500", Make.T0.AddDays(-1)) { Children = [("c1", Url("c1", 2)), ("c2", Url("c2", 2)), ("c3", Url("c3", 2))] });
var changed = await bed.Writer.CompleteAsync(saved.Entry!, full, bed.Account, CancellationToken.None);
Assert.AreEqual(1, changed, "Only the missing child is added.");
var files = await bed.Db.Media.ListByEntryAsync(saved.Entry!.Id);
CollectionAssert.AreEqual(new[] { 1, 2, 3 }, files.Select(f => f.Position).ToArray());
CollectionAssert.AreEqual(new[] { "c1", "c2", "c3" }, files.Select(f => f.InstagramId).ToArray(), "Each child in its place, the third never twice.");
Assert.AreEqual(Url("c2", 2), files[1].SourceUrl);
Assert.AreEqual(Url("c3"), files[2].SourceUrl, "A file still waiting keeps its address.");
}
[TestMethod]
public async Task AFreshAddressGoesToTheFileWithTheSameIdentifierNotTheSamePlace()
{
await using var bed = await Bed.CreateAsync();
// Files recorded in consecutive places although the second child was missing (records written before).
var entry = await bed.Db.Entries.AddAsync(Make.Entry(bed.Account.Id, "600", Make.T0.AddDays(-2)),
[
Make.Photo(1, MediaState.Expired) with { InstagramId = "c1" },
Make.Photo(2, MediaState.Expired) with { InstagramId = "c3" },
]);
var fresh = Item(new ScriptedPost("600", Make.T0.AddDays(-2)) { Children = [("c1", Url("c1", 3)), ("c2", Url("c2", 3)), ("c3", Url("c3", 3))] });
Assert.AreEqual(SaveOutcome.Known, (await bed.Writer.SaveAsync(bed.Account, fresh, EntryKind.Post, null, CancellationToken.None)).Outcome);
var files = await bed.Db.Media.ListByEntryAsync(entry.Stored.Entry.Id);
Assert.AreEqual(Url("c1", 3), files[0].SourceUrl);
Assert.AreEqual(Url("c3", 3), files[1].SourceUrl, "The record of the third child takes the third child's address.");
Assert.IsTrue(files.All(f => f.State == MediaState.ToDownload));
var changed = await bed.Writer.CompleteAsync(entry.Stored.Entry, fresh, bed.Account, CancellationToken.None);
Assert.AreEqual(1, changed);
var completed = await bed.Db.Media.ListByEntryAsync(entry.Stored.Entry.Id);
CollectionAssert.AreEquivalent(new[] { "c1", "c2", "c3" }, completed.Select(f => f.InstagramId).ToArray(), "The second child is added in a free place, never lost.");
}
[TestMethod]
public async Task AFailedFileTakesTheFreshAddressOfANewReadingWhileItIsStillOnOffer()
{
await using var bed = await Bed.CreateAsync();
var post = await AddFailedAsync(bed, "p1", EntryKind.Post, attempts: 5);
var broken = await AddFailedAsync(bed, "p9", EntryKind.Post, attempts: CollectionWriter.RevivalAttemptsLimit);
var story = await AddFailedAsync(bed, "s2", EntryKind.Story, attempts: 1, expiresAt: Make.T0.AddHours(10));
var expired = await AddFailedAsync(bed, "s3", EntryKind.Story, attempts: 1, expiresAt: Make.T0.AddHours(-1));
foreach (var (id, kind) in new[] { ("p1", EntryKind.Post), ("p9", EntryKind.Post), ("s2", EntryKind.Story), ("s3", EntryKind.Story) })
{
var item = Item(new ScriptedPost(id, Make.T0.AddHours(-5)) { Url = Url(id, 4) });
Assert.AreEqual(SaveOutcome.Known, (await bed.Writer.SaveAsync(bed.Account, item, kind, null, CancellationToken.None)).Outcome);
}
var revived = (await bed.Db.Media.ListByEntryAsync(post)).Single();
Assert.AreEqual(MediaState.ToDownload, revived.State, "A network outage does not lose a post for good.");
Assert.AreEqual(Url("p1", 4), revived.SourceUrl);
Assert.AreEqual(MediaState.ToDownload, (await bed.Db.Media.ListByEntryAsync(story)).Single().State, "A story shown again before it expires.");
Assert.AreEqual(MediaState.Failed, (await bed.Db.Media.ListByEntryAsync(expired)).Single().State, "No recovery after the expiry (§6.5 point 5).");
Assert.AreEqual(MediaState.Failed, (await bed.Db.Media.ListByEntryAsync(broken)).Single().State, "A file broken for good is not tried at every check.");
}
[TestMethod]
public async Task AHighlightItemThatWasAFailedStoryGivesTheStoryItsFreshAddress()
{
await using var bed = await Bed.CreateAsync();
var story = await AddFailedAsync(bed, "s1", EntryKind.Story, attempts: 1, expiresAt: Make.T0.AddDays(-3));
var item = await bed.Db.Entries.AddAsync(Make.Entry(bed.Account.Id, "e2", Make.T0.AddDays(-20), EntryKind.Highlight), [Make.Photo(1, MediaState.Expired)]);
var highlight = await bed.Db.Highlights.UpsertAsync(new Highlight { AccountId = bed.Account.Id, InstagramId = "h1", Title = "Estate", DiscoveredAt = Make.T0 });
var shown = Reader.Read(new JsonObject
{
["raccolta"] = new JsonObject
{
["numero"] = "h1",
["titolo"] = "Estate",
["autore"] = ScriptedSite.Lite(Marta),
["contenuti"] = new JsonArray(
ScriptedSite.Post(Marta, new ScriptedPost("s1", Make.T0.AddDays(-4)) { Url = Url("s1", 5) }),
ScriptedSite.Post(Marta, new ScriptedPost("e2", Make.T0.AddDays(-20)) { Url = Url("e2", 5) })),
},
}.ToJsonString()).Contents;
var (linked, created) = await bed.Writer.LinkHighlightItemAsync(bed.Account, highlight, shown.Single(c => c.Id == "s1"), null, CancellationToken.None);
Assert.AreEqual(story, linked!.Id, "The story is referenced (H9), not downloaded as a new entry…");
Assert.IsFalse(created);
var storyFile = (await bed.Db.Media.ListByEntryAsync(story)).Single();
Assert.AreEqual(MediaState.ToDownload, storyFile.State, "…but its file, never saved, now comes from the collection.");
Assert.AreEqual(Url("s1", 5), storyFile.SourceUrl);
await bed.Writer.LinkHighlightItemAsync(bed.Account, highlight, shown.Single(c => c.Id == "e2"), null, CancellationToken.None);
var itemFile = (await bed.Db.Media.ListByEntryAsync(item.Stored.Entry.Id)).Single();
Assert.AreEqual(MediaState.ToDownload, itemFile.State, "An expired collection item is renewed when the collection is opened again.");
Assert.AreEqual(Url("e2", 5), itemFile.SourceUrl);
}
[TestMethod]
public async Task AKnownProfilePictureWhoseFileExpiredTakesTheFreshAddress()
{
await using var bed = await Bed.CreateAsync();
ProfileInfo Profile(string signature) => new()
{
Id = "1001",
Username = "marta.prova",
Picture = new FileVersion($"https://cdn.esempio/v/ritratto.jpg?firma={signature}", 320, 320, null),
};
var first = await bed.Writer.SaveProfilePictureAsync(bed.Account, Profile("uno"), CancellationToken.None);
Assert.AreEqual(SaveOutcome.Created, first.Outcome);
var file = (await bed.Db.Media.ListByEntryAsync(first.Entry!.Id)).Single();
await bed.Db.Media.MarkFailedAsync(file.Id, MediaState.Expired, "Indirizzo scaduto.", Make.T0);
var second = await bed.Writer.SaveProfilePictureAsync(bed.Account, Profile("due"), CancellationToken.None);
Assert.AreEqual(SaveOutcome.Known, second.Outcome, "Same picture, new signature.");
var renewed = (await bed.Db.Media.ListByEntryAsync(first.Entry.Id)).Single();
Assert.AreEqual(MediaState.ToDownload, renewed.State);
Assert.AreEqual("https://cdn.esempio/v/ritratto.jpg?firma=due", renewed.SourceUrl);
}
private static string Url(string id, int version = 1) => $"https://cdn.esempio/m/{id}-{version}.jpg?firma=x";
private static ContentItem Item(ScriptedPost post) =>
Reader.Read(new JsonObject { ["contenuto"] = ScriptedSite.Post(Marta, post) }.ToJsonString()).Contents.Single(c => c.Id == post.Id);
private static async Task<long> AddFailedAsync(Bed bed, string id, EntryKind kind, int attempts, DateTimeOffset? expiresAt = null)
{
var entry = Make.Entry(bed.Account.Id, id, Make.T0.AddHours(-5), kind) with { ExpiresAt = expiresAt };
var added = await bed.Db.Entries.AddAsync(entry, [Make.Photo(1, MediaState.Failed) with { Attempts = attempts, LastError = "Errore di rete." }]);
return added.Stored.Entry.Id;
}
private sealed class Bed : IAsyncDisposable
{
private Bed(TempFolder temp, FebeDatabase db, Account account)
{
Temp = temp;
Db = db;
Account = account;
Writer = new CollectionWriter(db, new ManualClock(Make.T0));
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public Account Account { get; }
public CollectionWriter Writer { get; }
public static async Task<Bed> CreateAsync()
{
var temp = new TempFolder("scrittore");
var db = await TestDatabase.OpenAsync(temp);
var account = await db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
return new Bed(temp, db, account);
}
public async ValueTask DisposeAsync()
{
await Db.DisposeAsync();
Temp.Dispose();
}
}
}
@@ -0,0 +1,473 @@
using System.Globalization;
using System.Text.Json.Nodes;
using Febe.Browser.Download;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Downloads;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
using Febe.Tests.Browser.TestSupport;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// The download queue (spec §6.5) without a browser: stop signals of the CDN, failures that may pass, addresses refused
/// again after their renewal, entries deleted while their files download, identical files downloaded together, the
/// clean-up of an interrupted run, and the data budget of files over the size limit.
/// </summary>
[TestClass]
public sealed class DownloadQueueTests
{
[TestMethod]
public async Task A429OfTheCdnIsAThrottleSignalThatStopsTheQueueWithoutCountingAnAttempt()
{
using var temp = new TempFolder("coda-429");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var files = new List<long>();
for (var i = 0; i < 3; i++)
{
files.Add(await AddAsync(library.Db, account, $"p{i}", EntryKind.Post, $"https://cdn.esempio/m/{i}.jpg?firma=segreta"));
}
var breaker = new RecordingBreaker();
var fetcher = ScriptedFetcher.Status(429);
var queue = Queue(library, temp, fetcher, new SignalDetector(SignalRules.LoadDefault(), breaker, library.Clock), new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 });
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, fetcher.Calls, "The pass ends at the first 429: the other files are not asked for.");
var signal = breaker.Signals.Single();
Assert.AreEqual(SignalLevel.Throttle, signal.Level);
Assert.AreEqual("http-429", signal.Code);
Assert.AreEqual("https://cdn.esempio/", signal.Url, "Only the host: the path of a CDN address identifies a file.");
Assert.IsNotNull(report.PausedUntil);
Assert.IsTrue(report.PausedUntil >= library.Clock.Now.AddMinutes(59), report.PausedUntil.ToString());
foreach (var id in files)
{
var media = (await library.Db.Media.ListByEntryAsync(id)).Single();
Assert.AreEqual(MediaState.ToDownload, media.State);
Assert.AreEqual(0, media.Attempts, "The CDN asked to slow down: not the file's fault.");
}
// Until the pause is over the queue asks the CDN for nothing, however often it is woken.
queue.Wake();
Assert.IsNotNull((await queue.RunOnceAsync(CancellationToken.None)).PausedUntil);
Assert.AreEqual(1, fetcher.Calls);
library.Clock.Now = report.PausedUntil!.Value.AddMinutes(1);
fetcher.Answer = ScriptedFetcher.PhotoByPath;
var after = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(3, after.Stored, after.ToString());
Assert.AreEqual(1, breaker.Signals.Count);
}
[TestMethod]
public void ADownloadStatusIsReportedOncePerWindowButAlwaysRecognized()
{
var clock = new VirtualClock();
var breaker = new RecordingBreaker();
var signals = new SignalDetector(SignalRules.LoadDefault(), breaker, clock);
var address = new Uri("https://cdn.esempio/v/t51/abc.jpg?oh=firma");
Assert.AreEqual(SignalLevel.Throttle, signals.ObserveDownload(address, 429));
Assert.AreEqual(SignalLevel.Throttle, signals.ObserveDownload(address, 429), "Still a throttle, to stop the caller.");
Assert.AreEqual(1, breaker.Signals.Count, "Reported once in the dedupe window.");
Assert.IsNull(signals.ObserveDownload(address, 404));
Assert.IsNull(signals.ObserveDownload(address, 500));
}
[TestMethod]
public async Task AFailureThatMayPassIsRetriedLaterAndLaterBeforeTheFileFails()
{
using var temp = new TempFolder("coda-attesa");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entry = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
var fetcher = ScriptedFetcher.Network("net::ERR_CONNECTION_RESET");
var queue = Queue(library, temp, fetcher);
var start = library.Clock.Now;
Assert.AreEqual(1, (await queue.RunOnceAsync(CancellationToken.None)).Retried);
Assert.AreEqual(0, (await queue.RunOnceAsync(CancellationToken.None)).Total, "Not again at the next pass: it waits.");
Assert.AreEqual(1, fetcher.Calls);
// One pass a minute, as when idle, until the file is settled.
var passes = 0;
while ((await library.Db.Media.ListByEntryAsync(entry)).Single().State == MediaState.ToDownload && passes++ < 2000)
{
library.Clock.Now = library.Clock.Now.AddMinutes(1);
await queue.RunOnceAsync(CancellationToken.None);
}
var media = (await library.Db.Media.ListByEntryAsync(entry)).Single();
Assert.AreEqual(MediaState.Failed, media.State);
Assert.AreEqual(5, fetcher.Calls, "Five attempts in all.");
Assert.IsTrue(library.Clock.Now - start >= TimeSpan.FromHours(10.5), $"Spread over {library.Clock.Now - start}, not over a few passes.");
}
[TestMethod]
public async Task WithoutAConnectionNoAttemptIsCountedAndThePassEnds()
{
using var temp = new TempFolder("coda-rete");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entries = new List<long>();
for (var i = 0; i < 3; i++)
{
entries.Add(await AddAsync(library.Db, account, $"p{i}", EntryKind.Story, $"https://cdn.esempio/m/{i}.jpg"));
}
var fetcher = ScriptedFetcher.Network("net::ERR_INTERNET_DISCONNECTED");
var queue = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 });
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, fetcher.Calls, "Every file would fail the same way: the pass ends.");
Assert.IsNotNull(report.PausedUntil);
foreach (var id in entries)
{
Assert.AreEqual(0, (await library.Db.Media.ListByEntryAsync(id)).Single().Attempts, "The router restarting is not the file's fault.");
}
library.Clock.Now = report.PausedUntil!.Value.AddSeconds(1);
fetcher.Answer = ScriptedFetcher.PhotoByPath;
Assert.AreEqual(3, (await queue.RunOnceAsync(CancellationToken.None)).Stored, "Back online: the stories are still there to download.");
}
[TestMethod]
[Timeout(30_000, CooperativeCancellation = true)]
public async Task ManyWakeCallsDuringAPassGiveOneMorePassNotOneEach()
{
using var temp = new TempFolder("coda-sveglia");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
// Every pass tries the file again (no wait between attempts here): the passes are the attempts.
var fetcher = ScriptedFetcher.Status(503);
var queue = new DownloadQueue(library.Db, library.Ingest, fetcher, new FakeDataBudget(), new IdleClock(), new SeededRandom(1),
new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), RetryDelays = [], MaxAttempts = 1000 });
for (var i = 0; i < 50; i++)
{
queue.Wake(); // e.g. one per «ricetta.*» event of a long session
}
using var stop = new CancellationTokenSource();
var running = queue.RunAsync(stop.Token);
await Task.Delay(TimeSpan.FromMilliseconds(500));
await stop.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => running);
Assert.AreEqual(2, fetcher.Calls, "The pass, then one more for all the calls: then it waits.");
}
[TestMethod]
public async Task FilesWaitingForTheirNextAttemptDoNotHideTheOthers()
{
using var temp = new TempFolder("coda-finestra");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
await AddAsync(library.Db, account, "a", EntryKind.Post, "https://cdn.esempio/m/a.jpg");
await AddAsync(library.Db, account, "b", EntryKind.Post, "https://cdn.esempio/m/b.jpg");
var good = await AddAsync(library.Db, account, "c", EntryKind.Post, "https://cdn.esempio/m/c.jpg");
var fetcher = new ScriptedFetcher((uri, destination, ct) => uri!.AbsolutePath.EndsWith("/c.jpg", StringComparison.Ordinal)
? ScriptedFetcher.Photo(31)(uri, destination, ct)
: Task.FromResult(new FetchResult(FetchOutcome.HttpError, 0, 503, "prova")));
var queue = Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), BatchSize = 2 });
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(2, report.Retried, report.ToString());
Assert.AreEqual(1, report.Stored, "The third file is reached in the same pass.");
Assert.AreEqual(MediaState.Downloaded, (await library.Db.Media.ListByEntryAsync(good)).Single().State);
}
[TestMethod]
public async Task AnAddressRefusedAgainAfterItsRenewalsEndsFailedWithoutAnotherSinglePost()
{
using var temp = new TempFolder("coda-rinnovo");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var renewed = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg", attempts: 4);
var fresh = await AddAsync(library.Db, account, "p2", EntryKind.Post, "https://cdn.esempio/m/2.jpg");
var queue = Queue(library, temp, ScriptedFetcher.Status(403));
var report = await queue.RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, report.Failed, report.ToString());
Assert.AreEqual(1, report.Expired);
var refused = (await library.Db.Media.ListByEntryAsync(renewed)).Single();
Assert.AreEqual(MediaState.Failed, refused.State);
StringAssert.Contains(refused.LastError, "rinnovo");
Assert.AreEqual(MediaState.Expired, (await library.Db.Media.ListByEntryAsync(fresh)).Single().State);
var tasks = (await library.Db.Tasks.ListPendingAsync(10)).Where(t => t.Kind == EngineTaskKind.SinglePost).ToList();
CollectionAssert.AreEqual(new[] { fresh.ToString(CultureInfo.InvariantCulture) }, tasks.Select(t => t.Payload).ToArray(), "«Post singolo» only for the first expiry.");
}
[TestMethod]
public async Task AnEntryDeletedWhileItsFileDownloadsStaysDeletedAndOutOfTheLibrary()
{
using var temp = new TempFolder("coda-eliminato");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entry = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index);
// Alberto deletes the entry («ricorda la scelta») while its file is on its way.
var fetcher = new ScriptedFetcher(async (uri, destination, ct) =>
{
await deletion.DeleteAsync(entry, DeletionMode.Remember, ct);
return await ScriptedFetcher.Photo(41)(uri, destination, ct);
});
var report = await Queue(library, temp, fetcher).RunOnceAsync(CancellationToken.None);
Assert.AreEqual(0, report.Stored, report.ToString());
Assert.AreEqual(EntryState.Deleted, (await library.Db.Entries.GetAsync(entry))!.State);
var media = (await library.Db.Media.ListByEntryAsync(entry)).Single();
Assert.AreEqual(MediaState.Deleted, media.State);
Assert.IsNull(media.RelativePath);
var folder = library.Layout.AccountFolder(account);
Assert.AreEqual(0, Directory.EnumerateFiles(folder, "*.jpg", SearchOption.AllDirectories).Count(), "Nothing entered the library.");
var lines = (await AccountJournal.ReadAsync(folder)).Lines;
Assert.AreEqual(JournalOps.Delete, lines[^1].Op, "No «save» line after the «delete» line: a rebuild keeps it deleted.");
Assert.AreEqual(0, lines.Count(l => l.Op == JournalOps.Save));
Assert.AreEqual(0, Directory.EnumerateFiles(temp.Combine("dati", "temporanei")).Count());
}
[TestMethod]
public async Task AnEntryRemovedWhileItsFileDownloadsLeavesNoOrphanAndTheQueueGoesOn()
{
using var temp = new TempFolder("coda-tolto");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entry = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
var other = await AddAsync(library.Db, account, "p2", EntryKind.Post, "https://cdn.esempio/m/2.jpg");
var deletion = new LibraryDeletion(library.Db, library.Layout, library.Journal, library.Clock, library.Thumbnails, library.Index);
var fetcher = new ScriptedFetcher(async (uri, destination, ct) =>
{
if (uri!.AbsolutePath.EndsWith("/1.jpg", StringComparison.Ordinal))
{
await deletion.DeleteAsync(entry, DeletionMode.AllowReturn, ct); // «Eliminalo e lascia che torni»
}
return await ScriptedFetcher.PhotoByPath(uri, destination, ct);
});
var report = await Queue(library, temp, fetcher, options: new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei"), MaxConcurrent = 1 }).RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, report.Stored, "The pass goes on with the next file.");
Assert.IsNull(await library.Db.Entries.GetAsync(entry));
Assert.AreEqual(MediaState.Downloaded, (await library.Db.Media.ListByEntryAsync(other)).Single().State);
Assert.AreEqual(1, Directory.EnumerateFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories).Count(), "No orphan file for the removed entry.");
}
[TestMethod]
public async Task AFileOfADeletedEntryIsNeverRecordedAsStored()
{
using var temp = new TempFolder("coda-registro");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entry = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
var media = (await library.Db.Media.ListByEntryAsync(entry)).Single();
await library.Db.Entries.MarkDeletedAsync(entry, library.Clock.Now);
var recorded = await library.Db.Media.MarkStoredAsync(media.Id, new StoredFile("post/2026/x_1.jpg", 10, Make.Sha(1)), MediaState.Downloaded, library.Clock.Now);
Assert.IsFalse(recorded);
var after = (await library.Db.Media.ListByEntryAsync(entry)).Single();
Assert.AreEqual(MediaState.Deleted, after.State);
Assert.IsNull(after.RelativePath);
Assert.AreEqual(EntryState.Deleted, (await library.Db.Entries.GetAsync(entry))!.State);
}
[TestMethod]
public async Task TwoIdenticalFilesDownloadedAtTheSameTimeEnterTheLibraryOnce()
{
using var temp = new TempFolder("coda-gemelli");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
await AddAsync(library.Db, account, "p2", EntryKind.Post, "https://cdn.esempio/m/2.jpg");
var bytes = TestFile.PhotoBytes(17, 900, 1100);
using var together = new Barrier(2);
var fetcher = new ScriptedFetcher(async (_, destination, ct) =>
{
await Task.Run(() => together.SignalAndWait(TimeSpan.FromSeconds(10), ct), ct);
await destination.WriteAsync(bytes, ct);
return new FetchResult(FetchOutcome.Completed, bytes.Length, 200, null);
});
var report = await Queue(library, temp, fetcher).RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, report.Stored, report.ToString());
Assert.AreEqual(1, report.Duplicates);
Assert.AreEqual(1, Directory.EnumerateFiles(library.Layout.AccountFolder(account), "*.jpg", SearchOption.AllDirectories).Count(), "§9.5: one copy of the same bytes per account.");
}
[TestMethod]
public async Task TheCleanupOfAnInterruptedRunLeavesTheFilesOnTheirWayAlone()
{
using var temp = new TempFolder("coda-pulizia");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var entry = await AddAsync(library.Db, account, "p1", EntryKind.Post, "https://cdn.esempio/m/1.jpg");
var staging = temp.Combine("dati", "temporanei");
Directory.CreateDirectory(staging);
var leftover = Path.Combine(staging, SafeFileWriter.TempPrefix + "vecchio" + SafeFileWriter.TempSuffix);
await File.WriteAllTextAsync(leftover, "lasciato da un arresto");
var removed = -1;
// The start-up clean-up runs while the first download is being written.
var bytes = TestFile.PhotoBytes(23, 640, 800);
var fetcher = new ScriptedFetcher(async (_, destination, ct) =>
{
await destination.WriteAsync(bytes.AsMemory(0, 1000), ct);
removed = SafeFileWriter.CleanupTemporaryFiles(staging, recursive: false);
await destination.WriteAsync(bytes.AsMemory(1000), ct);
return new FetchResult(FetchOutcome.Completed, bytes.Length, 200, null);
});
var report = await Queue(library, temp, fetcher).RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, removed, "Only the file of the previous run.");
Assert.IsFalse(File.Exists(leftover));
Assert.AreEqual(1, report.Stored, report.ToString());
Assert.AreEqual(MediaState.Downloaded, (await library.Db.Media.ListByEntryAsync(entry)).Single().State);
}
[TestMethod]
public async Task TheCleanupLeavesALibraryFileBeingWrittenAlone()
{
using var temp = new TempFolder("pulizia-libreria");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001"));
var added = await library.Db.Entries.AddAsync(Make.Entry(account.Id, "p1", Make.T0.AddDays(-1)), [Make.Photo()]);
var folder = library.Layout.AccountFolder(account);
var removed = -1;
var content = new InterceptingStream(TestFile.PhotoBytes(29, 640, 800), () => removed = SafeFileWriter.CleanupTemporaryFiles(folder));
var result = await library.Ingest.SaveMediaAsync(account, added.Stored.Entry, added.Stored.Media[0], new MediaContent { Content = content, Extension = ".jpg" });
Assert.AreEqual(0, removed, "The temporary file of the write in progress is not a leftover.");
Assert.AreEqual(MediaSaveOutcome.Stored, result.Outcome);
Assert.IsTrue(File.Exists(library.Layout.FullPath(account, result.File!.RelativePath)));
}
[TestMethod]
public async Task AFileOverTheLimitCountsWhatTheBrowserLoadedNotWhatWasWritten()
{
using var temp = new TempFolder("coda-limite");
await using var library = await TestLibrary.CreateAsync(temp);
var account = await library.Db.Accounts.AddAsync(Make.Account("marta.prova", "1001") with { Limits = new AccountLimits { MaxVideoBytes = 1000 } });
await library.Db.Entries.AddAsync(Make.Entry(account.Id, "v1", Make.T0), [Make.Video() with { SourceUrl = "https://cdn.esempio/m/v.mp4", SourceSeenAt = Make.T0 }]);
var budget = new FakeDataBudget();
var fetcher = new ScriptedFetcher((_, _, _) => Task.FromResult(new FetchResult(FetchOutcome.TooLarge, 0, 200, "troppo grande") { TransferredBytes = 600_000_000 }));
var report = await Queue(library, temp, fetcher, budget: budget).RunOnceAsync(CancellationToken.None);
Assert.AreEqual(1, report.Skipped);
Assert.AreEqual(600_000_000, budget.Used, "The daily data budget counts the real transfer.");
Assert.AreEqual(600_000_000, report.Bytes);
}
[TestMethod]
public async Task TheBrowserFetcherDoesNotReadAFileThatDeclaresMoreThanTheLimit()
{
var cdp = new FakeCdpSession(new VirtualClock());
cdp.Responder = (method, _) => method switch
{
"Page.getFrameTree" => new JsonObject { ["frameTree"] = new JsonObject { ["frame"] = new JsonObject { ["id"] = "F1" } } },
"Network.loadNetworkResource" => new JsonObject
{
["resource"] = new JsonObject
{
["success"] = true,
["httpStatusCode"] = 200,
["stream"] = "S1",
["headers"] = new JsonObject { ["Content-Type"] = "video/mp4", ["content-length"] = "600000" },
},
},
"IO.read" => new JsonObject { ["data"] = Convert.ToBase64String(new byte[10_000]), ["base64Encoded"] = true, ["eof"] = false },
_ => null,
};
var fetcher = new BrowserFileFetcher(cdp, new HostClassifier(["127.0.0.1:5000"], ["127.0.0.1:5001"]));
using var destination = new MemoryStream();
var result = await fetcher.FetchAsync(new Uri("http://127.0.0.1:5001/grande.mp4"), destination, new FetchOptions(MaxBytes: 100_000), CancellationToken.None);
Assert.AreEqual(FetchOutcome.TooLarge, result.Outcome);
Assert.AreEqual(0, destination.Length);
Assert.AreEqual(600_000, result.TransferredBytes);
Assert.AreEqual(600_000, result.BudgetBytes);
Assert.AreEqual(0, cdp.Sent.Count(c => c.Method == "IO.read"), "Nothing more to read: the browser already loaded it.");
Assert.AreEqual(1, cdp.Sent.Count(c => c.Method == "IO.close"));
}
private static DownloadQueue Queue(TestLibrary library, TempFolder temp, IFileFetcher fetcher, SignalDetector? signals = null, DownloadOptions? options = null, IDataBudget? budget = null) =>
new(library.Db, library.Ingest, fetcher, budget ?? new FakeDataBudget(), library.Clock, new SeededRandom(1), options ?? new DownloadOptions { StagingFolder = temp.Combine("dati", "temporanei") }, signals);
private static async Task<long> AddAsync(IFebeStorage db, Account account, string id, EntryKind kind, string url, int attempts = 0)
{
var entry = Make.Entry(account.Id, id, Make.T0.AddHours(-1)) with
{
Kind = kind,
ExpiresAt = kind == EntryKind.Story ? Make.T0.AddHours(20) : null,
};
var added = await db.Entries.AddAsync(entry, [Make.Photo() with { SourceUrl = url, SourceSeenAt = Make.T0, Attempts = attempts }]);
return added.Stored.Entry.Id;
}
/// <summary>A file fetcher answering from a function that can be changed between passes: no network.</summary>
private sealed class ScriptedFetcher(Func<Uri?, Stream, CancellationToken, Task<FetchResult>> answer) : IFileFetcher
{
private int _calls;
public Func<Uri?, Stream, CancellationToken, Task<FetchResult>> Answer { get; set; } = answer;
public int Calls => Volatile.Read(ref _calls);
public static ScriptedFetcher Status(int status) =>
new((_, _, _) => Task.FromResult(new FetchResult(FetchOutcome.HttpError, 0, status, $"Il server ha risposto {status}.")));
public static ScriptedFetcher Network(string error) =>
new((_, _, _) => Task.FromResult(new FetchResult(FetchOutcome.NetworkError, 0, null, error)));
/// <summary>A photo of scene <paramref name="scene"/>, written whole.</summary>
public static Func<Uri?, Stream, CancellationToken, Task<FetchResult>> Photo(int scene) => async (_, destination, ct) =>
{
var bytes = TestFile.PhotoBytes(scene, 320, 400);
await destination.WriteAsync(bytes, ct);
return new FetchResult(FetchOutcome.Completed, bytes.Length, 200, null);
};
/// <summary>A photo whose scene depends on the address: different files, different bytes.</summary>
public static Task<FetchResult> PhotoByPath(Uri? address, Stream destination, CancellationToken ct) =>
Photo(100 + (address?.AbsolutePath ?? string.Empty).Aggregate(0, (sum, c) => (sum * 31) + c) % 1000)(address, destination, ct);
public Task<FetchResult> FetchAsync(Uri address, Stream destination, FetchOptions? options, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
return Answer(address, destination, ct);
}
}
/// <summary>A clock whose short waits (pauses between files) pass at once and whose long ones (idle) never end.</summary>
private sealed class IdleClock : IClock
{
public DateTimeOffset Now => Make.T0;
public TimeZoneInfo LocalZone => TestZones.Rome;
public Task Delay(TimeSpan time, CancellationToken ct) =>
time < TimeSpan.FromSeconds(10) ? Task.CompletedTask : Task.Delay(Timeout.Infinite, ct);
}
/// <summary>A content stream that runs <paramref name="midway"/> once, half way through.</summary>
private sealed class InterceptingStream(byte[] bytes, Action midway) : MemoryStream(bytes)
{
private bool _done;
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var read = await base.ReadAsync(buffer[..Math.Min(buffer.Length, 4096)], cancellationToken);
if (!_done && Position > Length / 2)
{
_done = true;
midway();
}
return read;
}
}
}
@@ -0,0 +1,279 @@
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Tests.Collection.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Collection;
/// <summary>
/// Rules of the recipes the local test site cannot show, on a scripted site without a browser: maps without the
/// optional resume pages, posts missing below the first page, responses unrelated to the page, stories and collection
/// items received ahead of time, a vocabulary without «pinned», a story ring that is no longer found.
/// </summary>
[TestClass]
public sealed class RecipeRuleTests
{
[TestMethod]
public async Task WithoutTheResumePageTheBackfillScrollsBackToTheStoredPointInsteadOfStartingOver()
{
await using var bed = await ScriptedBed.CreateAsync(ScriptedBed.MapWithout(SitePages.ProfileFrom));
var luca = bed.Site.Add(new ScriptedAccount("2001", "luca.prova"));
luca.Posts.AddRange(ScriptedBed.Posts(0, 40, bed.Clock.Now.AddDays(-1)));
var account = await bed.AddAccountAsync(luca);
var first = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 1);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(24, (await bed.PostIdsAsync(account.Id)).Count);
Assert.AreEqual("c24", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor);
// Five new posts on top move every page: the stored point is found again all the same.
luca.PublishOnTop(ScriptedBed.Posts(0, 5, bed.Clock.Now, prefix: "n"));
var second = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 1);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.IsFalse(second.BackfillFinished);
var ids = await bed.PostIdsAsync(account.Id);
Assert.AreEqual(36, ids.Count, "One page past the stored point (and the five new ones met on the way), not the first two pages again.");
CollectionAssert.Contains(ids.ToList(), "p30");
Assert.AreEqual("c36", (await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCursor, "The stored point moves on, never back.");
Assert.IsFalse(bed.Site.Opened.Any(p => p.Contains('?', StringComparison.Ordinal)), "No resume page in the map: only scrolling.");
var third = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 1);
Assert.IsTrue(third.BackfillFinished, third.Message);
Assert.AreEqual(45, (await bed.PostIdsAsync(account.Id)).Count);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt);
}
[TestMethod]
public async Task WithCursorsThatChangeAtEveryLoadThePointIsFoundAgainByItsLastItem()
{
await using var bed = await ScriptedBed.CreateAsync(ScriptedBed.MapWithout(SitePages.ProfileFrom));
bed.Site.VolatileCursors = true;
var luca = bed.Site.Add(new ScriptedAccount("2001", "luca.prova"));
luca.Posts.AddRange(ScriptedBed.Posts(0, 40, bed.Clock.Now.AddDays(-1)));
var account = await bed.AddAccountAsync(luca);
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 1)).Status);
var second = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 1);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.AreEqual(36, (await bed.PostIdsAsync(account.Id)).Count, "Found again by the last item read, then one more page.");
Assert.AreEqual(3, bed.Governor.Granted(ActionKind.BackfillPage), "Every page scrolled is counted: 1 in the first run, 1 to get back and 1 more.");
}
[TestMethod]
public async Task WithoutTheResumePageTheFollowingListContinuesWhereItStopped()
{
await using var bed = await ScriptedBed.CreateAsync(ScriptedBed.MapWithout(SitePages.FollowingFrom));
await bed.Db.Accounts.AddAsync(Account.Create("alberto.prova", StartingPoint.EverythingAndKeepUpdated, bed.Clock.Now, TestZones.Rome, isMine: true) with { InstagramId = "1000" });
for (var i = 0; i < 28; i++)
{
bed.Site.Following.Add(new ScriptedAccount((3000 + i).ToString(System.Globalization.CultureInfo.InvariantCulture), $"seguito{i}.prova"));
}
var first = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 2);
Assert.AreEqual("Letti 20 profili, continuo alla prossima sessione", first.Message);
var second = await bed.RunAsync(RecipeKind.FollowingList, maxPages: 2);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.IsTrue(second.BackfillFinished, "Back to the 20th profile by scrolling, then the end of the list: " + second.Message);
Assert.AreEqual(28, await bed.Db.Following.CountAsync());
Assert.IsNull(await bed.Db.Settings.GetAsync(RecipeRunner.FollowingKeys.Cursor));
Assert.AreEqual(5, bed.Governor.Granted(ActionKind.FollowingListPage), "Every page of the list is counted, those read again included.");
}
[TestMethod]
public async Task TheProfileCheckFillsThePostsMissingBelowTheFirstPageOverMoreChecks()
{
await using var bed = await ScriptedBed.CreateAsync(options: new RecipeOptions { GapPagesPerCheck = 1 });
var marta = bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
marta.Posts.AddRange(ScriptedBed.Posts(0, 20, bed.Clock.Now.AddDays(-30), prefix: "o"));
var account = await bed.AddAccountAsync(marta);
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.IsTrue((await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5)).BackfillFinished);
Assert.AreEqual(20, (await bed.PostIdsAsync(account.Id)).Count);
// Febe was off for weeks: thirty posts appeared above the twenty it has.
marta.PublishOnTop(ScriptedBed.Posts(0, 30, bed.Clock.Now, prefix: "n"));
var first = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, first.Status, first.Message);
Assert.AreEqual(44, (await bed.PostIdsAsync(account.Id)).Count, "The first page and one more (the pages allowed to one check).");
var second = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
var ids = await bed.PostIdsAsync(account.Id);
Assert.AreEqual(50, ids.Count, "The next check goes on from the stored point down to the known posts.");
Assert.IsTrue(Enumerable.Range(0, 30).All(i => ids.Contains($"n{i}")));
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{account.Id}.cursore"), "The gap is closed.");
var third = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(0, third.NewEntries);
Assert.AreEqual(3, bed.Governor.Granted(ActionKind.BackfillPage), "One page for the backfill, one for each step of the gap.");
}
[TestMethod]
public async Task WithoutTheResumePageTheGapIsReachedAgainByScrolling()
{
await using var bed = await ScriptedBed.CreateAsync(ScriptedBed.MapWithout(SitePages.ProfileFrom), options: new RecipeOptions { GapPagesPerCheck = 1 });
var marta = bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
marta.Posts.AddRange(ScriptedBed.Posts(0, 10, bed.Clock.Now.AddDays(-30), prefix: "o"));
var account = await bed.AddAccountAsync(marta);
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.BackfillCompletedAt, "Ten posts: one page, the backfill is done.");
marta.PublishOnTop(ScriptedBed.Posts(0, 40, bed.Clock.Now, prefix: "n"));
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.AreEqual(34, (await bed.PostIdsAsync(account.Id)).Count);
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.AreEqual(46, (await bed.PostIdsAsync(account.Id)).Count, "Back to the stored point by scrolling, then one more page.");
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.AreEqual(50, (await bed.PostIdsAsync(account.Id)).Count, "All forty, down to the known posts.");
Assert.IsNull(await bed.Db.Settings.GetAsync($"raccolta.lacuna.{account.Id}.cursore"));
}
[TestMethod]
public async Task AResponseUnrelatedToThePageNeitherEndsTheWalkNorStopsTheRecipe()
{
await using var bed = await ScriptedBed.CreateAsync();
var luca = bed.Site.Add(new ScriptedAccount("2001", "luca.prova"));
luca.Posts.AddRange(ScriptedBed.Posts(0, 40, bed.Clock.Now.AddDays(-1)));
var nadia = bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
nadia.Posts.AddRange(ScriptedBed.Posts(0, 30, bed.Clock.Now.AddDays(-1), prefix: "q"));
// A bare status reply arrives before each next page.
bed.Site.NoiseBeforeEachPage = new JsonObject { ["stato"] = "ok" };
var account = await bed.AddAccountAsync(luca);
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
Assert.AreEqual(RecipeStatus.Completed, outcome.Status, outcome.Message);
Assert.IsTrue(outcome.BackfillFinished, "The walk went on to the end.");
Assert.AreEqual(40, (await bed.PostIdsAsync(account.Id)).Count);
Assert.AreEqual(0, bed.Breaker.Signals.Count, "No empty pages counted.");
// A response of a shape no reader knows (a poll with a nested object) is not the next page either.
bed.Site.NoiseBeforeEachPage = new JsonObject { ["aggiornamento"] = new JsonObject { ["conteggio"] = 3 } };
var other = await bed.AddAccountAsync(nadia);
var second = await bed.RunAsync(RecipeKind.Backfill, other.Id, maxPages: 5);
Assert.AreEqual(RecipeStatus.Completed, second.Status, second.Message);
Assert.AreEqual(30, (await bed.PostIdsAsync(other.Id)).Count);
Assert.IsFalse((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "formato-non-riconosciuto"));
}
[TestMethod]
public async Task OnlyAnUnknownShapeWithoutTheNextPageIsAnUnrecognizedFormat()
{
await using var bed = await ScriptedBed.CreateAsync(options: new RecipeOptions { BurstsPerPage = 3 });
var luca = bed.Site.Add(new ScriptedAccount("2001", "luca.prova"));
luca.Posts.AddRange(ScriptedBed.Posts(0, 40, bed.Clock.Now.AddDays(-1)));
var account = await bed.AddAccountAsync(luca);
// After the first page only a response of an unknown shape comes, never the next page.
bed.Site.NoiseBeforeEachPage = new JsonObject { ["aggiornamento"] = new JsonObject { ["conteggio"] = 3 } };
bed.Site.DropNextPages = true;
var outcome = await bed.RunAsync(RecipeKind.Backfill, account.Id, maxPages: 5);
Assert.AreEqual(RecipeStatus.UnrecognizedFormat, outcome.Status, outcome.Message);
Assert.AreEqual(3, bed.Site.Scrolls, "Every burst allowed was tried before judging.");
Assert.AreEqual(12, (await bed.PostIdsAsync(account.Id)).Count, "The first page is kept.");
}
[TestMethod]
public async Task StoriesAndCollectionItemsReceivedAheadAreNeverSavedAsPosts()
{
await using var bed = await ScriptedBed.CreateAsync();
var nadia = bed.Site.Add(new ScriptedAccount("2003", "nadia.prova"));
var account = await bed.AddAccountAsync(nadia);
var now = bed.Clock.Now;
var post = new ScriptedPost("post1", now.AddHours(-3)) { Url = "https://cdn.prova/m/post1.jpg" };
var story = new ScriptedPost("storia1", now.AddHours(-1)) { ExpiresAt = now.AddHours(23), Url = "https://cdn.prova/m/storia1.jpg" };
var item = new ScriptedPost("evid1", now.AddDays(-40)) { Url = "https://cdn.prova/m/evid1.jpg" };
// The home brings the bar with the first stories of the account and a collection with its items.
var bar = ScriptedSite.Profile(nadia, latestStoryAt: story.TakenAt);
bar["storie"] = new JsonArray(ScriptedSite.Post(nadia, story));
bed.Site.Home = new JsonObject
{
["io"] = ScriptedSite.Lite(bed.Site.Viewer),
["barra"] = new JsonArray(bar),
["raccolte"] = new JsonArray(new JsonObject
{
["numero"] = "h1",
["titolo"] = "Estate",
["autore"] = ScriptedSite.Lite(nadia),
["contenuti"] = new JsonArray(ScriptedSite.Post(nadia, item)),
}),
["contenuti"] = new JsonArray(ScriptedSite.Post(nadia, post)),
["pagina"] = new JsonObject { ["altro"] = false, ["dopo"] = null },
};
var sweep = await bed.RunAsync(RecipeKind.FollowingSweep);
Assert.AreEqual(RecipeStatus.Completed, sweep.Status, sweep.Message);
CollectionAssert.AreEqual(new[] { "post1" }, (await bed.PostIdsAsync(account.Id)).ToArray(), "Only the post: the story was not shown, the item is not a post.");
Assert.IsTrue(sweep.AccountsWithStories.Contains(account.Id), "The bar still flags the account for its stories.");
Assert.AreEqual(0, (await bed.Db.Entries.ListByAccountAsync(account.Id, new EntryListOptions { Kind = EntryKind.Story })).Count);
// The profile lists its collection with the items: the check keeps the grid only.
nadia.Posts.Add(post);
nadia.HighlightsWithItems.Add(("h1", "Estate", [item]));
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(RecipeStatus.Completed, check.Status, check.Message);
CollectionAssert.AreEqual(new[] { "post1" }, (await bed.PostIdsAsync(account.Id)).ToArray());
}
[TestMethod]
public void AConfirmedVocabularyWithoutTheAuthorOfAPostIsNotUsable()
{
var vocabulary = ScriptedBed.VocabularyWithout("owner");
Assert.IsFalse(vocabulary.IsUsable);
StringAssert.Contains(vocabulary.UnusableReason, "content.owner");
}
[TestMethod]
public async Task WithoutAPinnedKeyAnOldPostOnTopIsRecognizedByTheOrderOfTheGrid()
{
await using var bed = await ScriptedBed.CreateAsync(vocabulary: ScriptedBed.VocabularyWithout("pinned"));
var marta = bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { Followed = false });
var pinned = new ScriptedPost("fisso", bed.Clock.Now.AddDays(-400), Pinned: true) { Url = "https://cdn.prova/m/fisso.jpg" };
marta.Posts.Add(pinned);
marta.Posts.AddRange(ScriptedBed.Posts(0, 5, bed.Clock.Now.AddDays(-60), prefix: "o"));
var account = await bed.AddAccountAsync(marta);
Assert.AreEqual(RecipeStatus.Completed, (await bed.RunAsync(RecipeKind.ProfileCheck, account.Id)).Status);
Assert.AreEqual(6, (await bed.PostIdsAsync(account.Id)).Count);
// New posts below the pinned one, which is known and old: they are saved all the same.
marta.PublishOnTop(ScriptedBed.Posts(0, 4, bed.Clock.Now, prefix: "n"));
var check = await bed.RunAsync(RecipeKind.ProfileCheck, account.Id);
Assert.AreEqual(4, check.NewEntries, check.Message);
// «Da una data»: an old pinned post on top is not the limit of history.
var luca = bed.Site.Add(new ScriptedAccount("2001", "luca.prova"));
luca.Posts.Add(pinned with { Id = "fisso2" });
luca.Posts.AddRange(ScriptedBed.Posts(0, 30, bed.Clock.Now.AddDays(-1)));
var limited = await bed.AddAccountAsync(luca, a => a with { Limits = a.Limits with { Depth = HistoryDepth.FromDate, FromDate = bed.Clock.Now.AddDays(-30) } });
var walk = await bed.RunAsync(RecipeKind.Backfill, limited.Id, maxPages: 5);
Assert.AreEqual(RecipeStatus.Completed, walk.Status, walk.Message);
Assert.AreEqual(30, (await bed.PostIdsAsync(limited.Id)).Count(id => id.StartsWith('p')), "Every post of the last thirty days.");
}
[TestMethod]
public async Task ARingNotFoundWhileTheProfileSaysThereIsAStoryIsAMissingTarget()
{
await using var bed = await ScriptedBed.CreateAsync();
var marta = bed.Site.Add(new ScriptedAccount("2002", "marta.prova") { LatestStoryAt = bed.Clock.Now.AddHours(-2) });
var account = await bed.AddAccountAsync(marta);
bed.Site.Present.Remove(SiteTargets.ProfileStoryRing);
var outcome = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.TargetNotFound, outcome.Status, outcome.Message);
StringAssert.Contains(outcome.Message, "storia attiva");
Assert.IsNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt, "Not recorded as checked: the stories are still to be seen.");
Assert.IsTrue((await bed.Db.Events.ListAsync(new EventQuery())).Any(e => e.Code == "bersaglio-non-trovato"));
// A day later the story has expired: no ring is what the profile says too.
marta.LatestStoryAt = bed.Clock.Now.AddHours(-30);
var quiet = await bed.RunAsync(RecipeKind.AccountStories, account.Id);
Assert.AreEqual(RecipeStatus.Completed, quiet.Status, quiet.Message);
Assert.IsNotNull((await bed.Db.Accounts.GetAsync(account.Id))!.LastStoriesCheckAt);
}
}
@@ -235,6 +235,29 @@ public sealed class StopAndDownloadIntegrationTests
Assert.IsTrue(posts.All(p => p.State == EntryState.Downloaded));
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task A429OfTheCdnDuringDownloadsIsAThrottleSignalThroughTheRealBrowser()
{
await using var h = await CollectionHarness.CreateAsync(Chromium);
var nadia = await h.AddAccountAsync("nadia.prova");
Assert.AreEqual(RecipeStatus.Completed, (await h.RunAsync(RecipeKind.ProfileCheck, nadia.Id)).Status);
var pending = await h.Db.Media.CountPendingDownloadsAsync();
h.Site.Control.CdnTooManyRequests = true;
// Network.loadNetworkResource is served outside the page: only the queue can tell the breaker.
var report = await h.Downloads.RunOnceAsync(CancellationToken.None);
Assert.IsNotNull(report.PausedUntil, report.ToString());
Assert.AreEqual(0, report.Stored + report.Failed + report.Retried, report.ToString());
var signal = h.Breaker.Signals.Single();
Assert.AreEqual(SignalLevel.Throttle, signal.Level);
Assert.AreEqual("http-429", signal.Code);
Assert.IsTrue(h.Site.Control.CdnThrottled is >= 1 and <= 2, $"The pass ended at once ({h.Site.Control.CdnThrottled} requests): at most the two downloads already under way.");
Assert.AreEqual(pending, await h.Db.Media.CountPendingDownloadsAsync(), "Every file is still waiting…");
var media = await Task.WhenAll((await h.Db.Entries.ListByAccountAsync(nadia.Id)).Select(e => h.Db.Media.ListByEntryAsync(e.Id)));
Assert.IsTrue(media.SelectMany(m => m).All(m => m.Attempts == 0), "…and none lost an attempt.");
}
[TestMethod]
[Timeout(90_000, CooperativeCancellation = true)]
public async Task DownloadsGoOnWhileTheSiteIsStoppedByAVerification()
@@ -0,0 +1,469 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Data;
using Febe.Tests.Browser.TestSupport;
using Febe.Tests.Support;
namespace Febe.Tests.Collection.Support;
/// <summary>A post (or a story, or a collection item) of the scripted site.</summary>
/// <param name="Id">Identifier («numero»).</param>
/// <param name="TakenAt">Publication time.</param>
/// <param name="Pinned">Pinned on top of the grid.</param>
internal sealed record ScriptedPost(string Id, DateTimeOffset TakenAt, bool Pinned = false)
{
/// <summary>The files of a series by child identifier; a null address is a child without versions yet.</summary>
public IReadOnlyList<(string Id, string? Url)>? Children { get; init; }
/// <summary>For stories: when they stop being available («scade»).</summary>
public DateTimeOffset? ExpiresAt { get; init; }
public string Url { get; init; } = "https://cdn.prova/m/default.jpg";
}
/// <summary>An account of the scripted site; its grid is newest first, pinned posts on top.</summary>
internal sealed class ScriptedAccount(string id, string username)
{
public string Id { get; } = id;
public string Username { get; } = username;
public bool Followed { get; init; } = true;
public List<ScriptedPost> Posts { get; } = [];
/// <summary>Publication time of the latest active story («ultima_storia»), as the profile says.</summary>
public DateTimeOffset? LatestStoryAt { get; set; }
/// <summary>Highlight collections listed on the profile with their items (the test site lists them without).</summary>
public List<(string Id, string Title, IReadOnlyList<ScriptedPost> Items)> HighlightsWithItems { get; } = [];
/// <summary>Adds posts on top of the grid (below pinned ones), newest first in <paramref name="posts"/>.</summary>
public void PublishOnTop(IEnumerable<ScriptedPost> posts)
{
var pinned = Posts.Count(p => p.Pinned);
Posts.InsertRange(pinned, posts);
}
}
/// <summary>
/// A page driver over an in-memory site that speaks the format of tools/Febe.SitoDiProva (<c>lettori.prova.json</c>):
/// opening a page or scrolling hands the capture the JSON the page would receive, without a browser. For the recipe
/// rules the test site cannot show: a target map without resume pages, responses unrelated to the page arriving between
/// two pages, stories and collection items received ahead of time.
/// </summary>
internal sealed class ScriptedSite : IPageDriver
{
public const int GridPageSize = 12;
public const int FollowingPageSize = 10;
private readonly CaptureCollector _capture;
private readonly IClock _clock;
private readonly Lock _gate = new();
private Func<JsonObject?>? _next;
private bool _noiseDue;
private int _requests;
public ScriptedSite(CaptureCollector capture, IClock clock)
{
_capture = capture;
_clock = clock;
}
public ScriptedAccount Viewer { get; } = new("1000", "alberto.prova");
public Dictionary<string, ScriptedAccount> Accounts { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>The list of the profiles Alberto follows, in its order.</summary>
public List<ScriptedAccount> Following { get; } = [];
/// <summary>Body of the home; null: the connected account and nothing else.</summary>
public JsonObject? Home { get; set; }
/// <summary>A response unrelated to the page (a poll, an acknowledgement), arriving with the first burst after each page.</summary>
public JsonObject? NoiseBeforeEachPage { get; set; }
/// <summary>Targets the page shows: all but «profile-not-found», unless changed.</summary>
public HashSet<string> Present { get; } = [.. SiteTargets.All.Where(t => t != SiteTargets.ProfileNotFound)];
public List<string> Opened { get; } = [];
/// <summary>
/// Cursors that change at every page load (a site whose cursors are tokens of the moment): a stored point can be
/// found again only by the item read before it.
/// </summary>
public bool VolatileCursors { get; set; }
/// <summary>Scrolling brings no further page (only <see cref="NoiseBeforeEachPage"/>, if set).</summary>
public bool DropNextPages { get; set; }
public int Scrolls { get; private set; }
public string CurrentPath { get; private set; } = "about:blank";
public double WaitMultiplier => 1;
public ScriptedAccount Add(ScriptedAccount account)
{
Accounts[account.Username] = account;
return account;
}
public void BeginSession(double mood)
{
}
public Task<PageLoad> OpenAsync(string path, CancellationToken ct)
{
Opened.Add(path);
var query = path.IndexOf('?', StringComparison.Ordinal);
var route = query < 0 ? path : path[..query];
var cursor = query < 0 ? null : Uri.UnescapeDataString(path[(query + 1)..].Replace("dopo=", string.Empty, StringComparison.Ordinal));
CurrentPath = route;
var segments = route.Split('/', StringSplitOptions.RemoveEmptyEntries);
JsonObject? body = null;
lock (_gate)
{
_next = null;
if (segments.Length == 0)
{
body = Home ?? new JsonObject { ["io"] = Lite(Viewer) };
}
else if (segments is ["profilo", _, "seguiti"])
{
body = FollowingPage(Offset(cursor));
}
else if (segments is ["profilo", var username] && Accounts.TryGetValue(username, out var account))
{
body = ProfilePage(account, Offset(cursor));
}
else if (segments is ["post", var code])
{
var post = Accounts.Values.SelectMany(a => a.Posts.Select(p => (Account: a, Post: p))).FirstOrDefault(x => "S" + x.Post.Id == code);
body = post.Post is null ? null : new JsonObject { ["contenuto"] = Post(post.Account, post.Post) };
}
}
if (body is not null)
{
Deliver(body);
}
return Task.FromResult(new PageLoad(true, route, null));
}
public Task<string> CurrentPathAsync(CancellationToken ct) => Task.FromResult(CurrentPath);
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Task.FromResult(true);
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) =>
Task.FromResult(Present.Contains(target)
? new TargetCheck(target, TargetCheckStatus.Found, 1, "Trovato.")
: new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) =>
Task.FromResult(Present.Contains(target)
? new TargetCheck(target, TargetCheckStatus.Clicked, 1, "Cliccato.")
: new TargetCheck(target, TargetCheckStatus.NotFound, 0, $"Bersaglio «{target}» non trovato."));
public Task ScrollBurstAsync(CancellationToken ct)
{
JsonObject? body;
lock (_gate)
{
Scrolls++;
if (_noiseDue && NoiseBeforeEachPage is { } noise)
{
_noiseDue = false;
body = (JsonObject)noise.DeepClone();
}
else
{
var next = DropNextPages ? null : _next;
if (next is not null)
{
_next = null;
}
body = next?.Invoke(); // sets the page after it, when there is one
}
}
if (body is not null)
{
Deliver(body);
}
return Task.CompletedTask;
}
public Task WaitAfterLoadAsync(CancellationToken ct) => Task.CompletedTask;
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Task.CompletedTask;
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Task.FromResult(false);
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Task.FromResult<bool?>(true);
public Task RestAsync(CancellationToken ct)
{
CurrentPath = "about:blank";
return Task.CompletedTask;
}
public static string Cursor(int offset) => "c" + offset.ToString(CultureInfo.InvariantCulture);
public static JsonObject Post(ScriptedAccount owner, ScriptedPost post)
{
var node = new JsonObject
{
["numero"] = post.Id,
["sigla"] = "S" + post.Id,
["pubblicato"] = Date(post.TakenAt),
["fissato"] = post.Pinned,
["autore"] = Lite(owner),
};
if (post.ExpiresAt is { } expires)
{
node["scade"] = Date(expires);
}
if (post.Children is { } children)
{
node["parti"] = new JsonArray([.. children.Select(c =>
{
var part = new JsonObject { ["numero"] = c.Id };
if (c.Url is { } url)
{
part["foto"] = Versions(url);
}
return (JsonNode)part;
})]);
node["parti_totali"] = children.Count;
}
else
{
node["foto"] = Versions(post.Url);
}
return node;
}
public static JsonObject Lite(ScriptedAccount account) => new() { ["numero"] = account.Id, ["nome"] = account.Username };
public static JsonObject Profile(ScriptedAccount account, DateTimeOffset? latestStoryAt = null)
{
var node = new JsonObject
{
["numero"] = account.Id,
["nome"] = account.Username,
["riservato"] = false,
["seguito"] = account.Followed,
["pubblicazioni"] = account.Posts.Count,
};
if ((latestStoryAt ?? account.LatestStoryAt) is { } latest)
{
node["ultima_storia"] = Date(latest);
}
return node;
}
private static JsonArray Versions(string url) =>
[new JsonObject { ["indirizzo"] = url, ["larghezza"] = 1080, ["altezza"] = 1350 }];
private static string Date(DateTimeOffset at) => at.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
private static int Offset(string? cursor)
{
var digits = cursor is { Length: > 1 } && cursor[0] == 'c' ? cursor[1..].Split('.')[0] : null;
return int.TryParse(digits, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n) ? n : 0;
}
private JsonObject Page(int total, int offset, int size)
{
var more = offset + size < total;
var cursor = Cursor(offset + size) + (VolatileCursors ? "." + Opened.Count.ToString(CultureInfo.InvariantCulture) : string.Empty);
return new JsonObject { ["altro"] = more, ["dopo"] = more ? cursor : null };
}
private JsonObject ProfilePage(ScriptedAccount account, int offset)
{
var body = new JsonObject { ["profilo"] = Profile(account) };
if (offset == 0 && account.HighlightsWithItems.Count > 0)
{
body["raccolte"] = new JsonArray([.. account.HighlightsWithItems.Select(h => (JsonNode)new JsonObject
{
["numero"] = h.Id,
["titolo"] = h.Title,
["autore"] = Lite(account),
["contenuti"] = new JsonArray([.. h.Items.Select(i => (JsonNode)Post(account, i))]),
})]);
}
AddGrid(body, account, offset);
return body;
}
private void AddGrid(JsonObject body, ScriptedAccount account, int offset)
{
body["contenuti"] = new JsonArray([.. account.Posts.Skip(offset).Take(GridPageSize).Select(p => (JsonNode)Post(account, p))]);
body["pagina"] = Page(account.Posts.Count, offset, GridPageSize);
if (offset + GridPageSize < account.Posts.Count)
{
_next = () =>
{
var more = new JsonObject();
AddGrid(more, account, offset + GridPageSize);
return more;
};
_noiseDue = NoiseBeforeEachPage is not null;
}
}
private JsonObject FollowingPage(int offset)
{
var body = new JsonObject
{
["seguiti"] = new JsonArray([.. Following.Skip(offset).Take(FollowingPageSize).Select(a => (JsonNode)Profile(a))]),
["pagina"] = Page(Following.Count, offset, FollowingPageSize),
};
if (offset + FollowingPageSize < Following.Count)
{
_next = () => FollowingPage(offset + FollowingPageSize);
_noiseDue = NoiseBeforeEachPage is not null;
}
return body;
}
private void Deliver(JsonObject body)
{
var id = Interlocked.Increment(ref _requests).ToString(CultureInfo.InvariantCulture);
using var document = JsonDocument.Parse(body.ToJsonString());
_capture.Accept(new ResponseDescriptor("r" + id, HostKind.Site, "http://prova.local/dati", "prova.local", "/dati", 200, "application/json", "Fetch", false, _clock.Now), document.RootElement);
}
}
/// <summary>Everything a recipe test on the scripted site needs: database, clock, Governor, signals, runner.</summary>
internal sealed class ScriptedBed : IAsyncDisposable
{
private ScriptedBed(TempFolder temp, FebeDatabase db, VirtualClock clock, ScriptedSite site, RecipeRunner runner, TestSession session)
{
Temp = temp;
Db = db;
Clock = clock;
Site = site;
Runner = runner;
Session = session;
}
public TempFolder Temp { get; }
public FebeDatabase Db { get; }
public VirtualClock Clock { get; }
public ScriptedSite Site { get; }
public RecipeRunner Runner { get; }
public TestSession Session { get; }
public PermissiveGovernor Governor => (PermissiveGovernor)Runner.Env.Governor;
public RecordingBreaker Breaker => (RecordingBreaker)Runner.Env.Breaker!;
/// <summary>The pages of <c>bersagli.prova.json</c>, for maps that leave some of them out.</summary>
public static IReadOnlyDictionary<string, string?> TestSitePages { get; } = new Dictionary<string, string?>
{
[SitePages.Home] = "/",
[SitePages.Profile] = "/profilo/{username}/",
[SitePages.ProfileFrom] = "/profilo/{username}/?dopo={cursor}",
[SitePages.ReelsFrom] = "/profilo/{username}/reel/?dopo={cursor}",
[SitePages.TaggedFrom] = "/profilo/{username}/taggati/?dopo={cursor}",
[SitePages.Post] = "/post/{code}/",
[SitePages.Following] = "/profilo/{username}/seguiti/",
[SitePages.FollowingFrom] = "/profilo/{username}/seguiti/?dopo={cursor}",
[SitePages.StoryViewer] = "/storie/{username}/{id}/",
[SitePages.HighlightViewer] = "/evidenza/{highlight}/{id}/",
};
/// <summary>The test site map without some pages (the optional resume pages, for instance).</summary>
public static SiteMap MapWithout(params string[] pages) =>
new("prova", TestSitePages.Where(p => !pages.Contains(p.Key)).ToDictionary(p => p.Key, p => p.Value), SiteTargets.All, SiteTargets.All);
/// <summary>The test site vocabulary with a concept emptied (e.g. «pinned»: the site would not say it).</summary>
public static ReaderVocabulary VocabularyWithout(string concept)
{
var json = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "config", "lettori.prova.json"));
var node = JsonNode.Parse(json)!;
node["content"]![concept] = new JsonArray();
return ReaderVocabulary.Parse(node.ToJsonString(), "lettori.prova.json (prova)");
}
public static async Task<ScriptedBed> CreateAsync(SiteMap? map = null, ReaderVocabulary? vocabulary = null, RecipeOptions? options = null)
{
var temp = new TempFolder("ricette-finte");
var db = await TestDatabase.OpenAsync(temp);
var clock = new VirtualClock();
var capture = new CaptureCollector(new ShapeReader(vocabulary ?? ReaderVocabulary.LoadTestSite()), clock);
var site = new ScriptedSite(capture, clock);
var breaker = new RecordingBreaker();
var governor = new PermissiveGovernor();
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = site,
Capture = capture,
Governor = governor,
Budget = governor,
Signals = new SignalDetector(SignalRules.LoadTestSite(), breaker, clock),
Storage = db,
SiteMap = map ?? SiteMap.LoadTestSite(),
Clock = clock,
Random = new SeededRandom(7),
Breaker = breaker,
Options = options ?? new RecipeOptions(),
});
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
return new ScriptedBed(temp, db, clock, site, runner, session);
}
/// <summary>An account Febe keeps, for a scripted account.</summary>
public Task<Account> AddAccountAsync(ScriptedAccount scripted, Func<Account, Account>? change = null)
{
var account = Account.Create(scripted.Username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome) with
{
InstagramId = scripted.Id,
IsFollowed = scripted.Followed,
};
return Db.Accounts.AddAsync(change is null ? account : change(account));
}
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, int? maxPages = null) =>
Runner.RunAsync(new RecipeRequest(kind, accountId, MaxPages: maxPages), Session, CancellationToken.None);
public async Task<IReadOnlyList<string>> PostIdsAsync(long accountId) =>
[.. (await Db.Entries.ListByAccountAsync(accountId, new Core.Storage.EntryListOptions { Kind = EntryKind.Post, Limit = 1000 })).Select(e => e.InstagramId!)];
public async ValueTask DisposeAsync()
{
await Db.DisposeAsync();
Temp.Dispose();
}
/// <summary>Posts «p{from}»…«p{to-1}», one hour apart going back from <paramref name="newest"/>.</summary>
public static IEnumerable<ScriptedPost> Posts(int from, int to, DateTimeOffset newest, string prefix = "p") =>
Enumerable.Range(from, to - from).Select(i => new ScriptedPost(prefix + i.ToString(CultureInfo.InvariantCulture), newest.AddHours(-(i - from)))
{
Url = $"https://cdn.prova/m/{prefix}{i.ToString(CultureInfo.InvariantCulture)}.jpg",
});
}
+1
View File
@@ -107,6 +107,7 @@ Dentro il processo: `site.Control` (`SiteControl`). Da fuori: `/_controllo/...`
| `/_controllo/modo?valore=normale`, `/_controllo/reimposta` | tutto torna normale |
| `/_controllo/durata-storie?ms=` | quanto resta a schermo una storia prima che il visualizzatore vada avanti da solo |
| `/_controllo/scadenza-indirizzi?secondi=` | durata degli indirizzi firmati consegnati da quel momento |
| `/_controllo/cdn-troppe-richieste?valore=si\|no` | il CDN risponde 429 a ogni file (rallentamento chiesto dal CDN) |
| `/_controllo/rinomina?da=&a=` | un account cambia nome (stesso numero) |
| `/_controllo/ritratto?nome=` | nuova foto del profilo |
| `/_controllo/pubblica?nome=&tipo=foto\|video\|serie` | nuovo post in cima |
+11
View File
@@ -38,6 +38,12 @@ public sealed class SiteControl
/// <summary>Validity of the CDN addresses handed out from now on.</summary>
public TimeSpan AddressLifetime { get; set; } = TimeSpan.FromHours(6);
/// <summary>The CDN answers 429 to every file (Rallentamento from the CDN, spec §7.6).</summary>
public bool CdnTooManyRequests { get; set; }
/// <summary>Number of CDN requests answered with 429.</summary>
public int CdnThrottled => _cdnThrottled;
/// <summary>Paths with query of every data request, in arrival order (for the tests).</summary>
public IReadOnlyList<string> DataRequests => [.. _dataRequests];
@@ -49,6 +55,7 @@ public sealed class SiteControl
private int _cdnFiles;
private int _cdnExpired;
private int _cdnThrottled;
public StopMode Mode
{
@@ -83,8 +90,10 @@ public sealed class SiteControl
_dataRequests.Clear();
StoryDuration = TimeSpan.FromSeconds(5);
AddressLifetime = TimeSpan.FromHours(6);
CdnTooManyRequests = false;
Interlocked.Exchange(ref _cdnFiles, 0);
Interlocked.Exchange(ref _cdnExpired, 0);
Interlocked.Exchange(ref _cdnThrottled, 0);
}
public void ClearRequests() => _dataRequests.Clear();
@@ -108,4 +117,6 @@ public sealed class SiteControl
internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles);
internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired);
internal void OnCdnThrottled() => Interlocked.Increment(ref _cdnThrottled);
}
+12
View File
@@ -307,6 +307,15 @@ public sealed class TestSite : IAsyncDisposable
private async Task ServeCdnAsync(HttpContext context)
{
var path = context.Request.Path.Value ?? string.Empty;
if (Control.CdnTooManyRequests)
{
Control.OnCdnThrottled();
context.Response.StatusCode = 429;
context.Response.ContentType = "text/plain; charset=utf-8";
await context.Response.WriteAsync("Troppe richieste.").ConfigureAwait(false);
return;
}
var query = context.Request.Query;
var check = Signer.Check(path, query["scad"].ToString(), query["firma"].ToString(), _time.GetUtcNow());
if (check != CdnCheck.Valid)
@@ -368,6 +377,9 @@ public sealed class TestSite : IAsyncDisposable
case "durata-storie":
Control.StoryDuration = TimeSpan.FromMilliseconds(int.Parse(q["ms"].ToString(), CultureInfo.InvariantCulture));
break;
case "cdn-troppe-richieste":
Control.CdnTooManyRequests = q["valore"].ToString() is "si" or "sì" or "true";
break;
case "scadenza-indirizzi":
Control.AddressLifetime = TimeSpan.FromSeconds(int.Parse(q["secondi"].ToString(), CultureInfo.InvariantCulture));
break;