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:
28 files changed
+2619
-200
No files matched your search
@@ -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",
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user