Unione delle correzioni della raccolta

This commit is contained in:
Claude committed 2026-10-14 01:39:42 +00:00
commit 7d208f6030
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
@@ -168,7 +168,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
@@ -57,6 +57,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;
var paths = !UserIsOnPage();
foreach (var rule in _rules.Rules)
@@ -67,9 +96,9 @@ public sealed class SignalDetector : IResponseObserver, IResponseConsumer, IStop
}
if ((rule.Statuses.Count > 0 && rule.Statuses.Contains(response.Status))
|| (paths && rule.Path is not null && SafeIsMatch(rule.Path, response.Path)))
|| (!statusOnly && paths && 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);
}