using Febe.Core.Collection.Downloads; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; using Febe.Tests.Engine.Support; using Febe.Tests.Support; namespace Febe.Tests.Engine; /// /// «Cosa scaricare prima» (spec §7.2, §6.5, tappa D1): the order of the kinds, its weight on the visits after the Giro dei /// seguiti (on the virtual clock, with a fixed seed) and on the queue of the files. /// [TestClass] public sealed class DownloadOrderTests { private static readonly DateTimeOffset Morning = EngineTestBed.Local(2026, 10, 14, 6, 0); [TestMethod] public void TheDefaultOrderIsStoriesHighlightsPostsReelsTagged() { Assert.AreEqual("storie,evidenza,post,reel,taggati", DownloadOrder.Default.ToString()); Assert.IsTrue(DownloadOrder.Parse(null).IsDefault); Assert.IsTrue(DownloadOrder.Parse(" ").IsDefault); Assert.AreEqual(16, DownloadOrder.Default.Weight(DownloadKind.Stories)); Assert.AreEqual(8, DownloadOrder.Default.Weight(DownloadKind.Highlights)); Assert.AreEqual(4, DownloadOrder.Default.Weight(DownloadKind.Posts)); Assert.AreEqual(2, DownloadOrder.Default.Weight(DownloadKind.Reels)); Assert.AreEqual(1, DownloadOrder.Default.Weight(DownloadKind.Tagged)); } [TestMethod] [DataRow("taggati,post", "taggati,post,storie,evidenza,reel")] [DataRow("POST, post ,qualcosa,reel", "post,reel,storie,evidenza,taggati")] [DataRow("reel,taggati,post,evidenza,storie", "reel,taggati,post,evidenza,storie")] public void AnyStoredTextGivesTheFiveKindsOnce(string stored, string expected) { var order = DownloadOrder.Parse(stored); Assert.AreEqual(expected, order.ToString()); Assert.HasCount(5, order.Kinds); Assert.AreEqual(order.ToString(), DownloadOrder.Parse(order.ToString()).ToString()); } [TestMethod] public void EveryTaskAndEntryKindHasItsPlace() { Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingSweep), "il giro resta primo, nessun tipo lo pesa"); Assert.IsNull(DownloadOrder.KindOf(EngineTaskKind.FollowingList)); Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EngineTaskKind.AccountStories)); Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EngineTaskKind.HighlightCheck)); Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.ProfileCheck)); Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EngineTaskKind.Backfill)); Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EngineTaskKind.ReelsCheck)); Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EngineTaskKind.TaggedCheck)); Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.ProfilePicture), "le foto del profilo vanno con i post"); Assert.AreEqual(DownloadKind.Posts, DownloadOrder.KindOf(EntryKind.Post)); Assert.AreEqual(DownloadKind.Reels, DownloadOrder.KindOf(EntryKind.Post, isReel: true), "un post che Febe sa essere un reel conta come reel"); Assert.AreEqual(DownloadKind.Tagged, DownloadOrder.KindOf(EntryKind.Tagged, isReel: true), "un taggato resta un taggato"); Assert.AreEqual(DownloadKind.Stories, DownloadOrder.KindOf(EntryKind.Story)); Assert.AreEqual(DownloadKind.Highlights, DownloadOrder.KindOf(EntryKind.Highlight)); } [TestMethod] public void AnAccountWithoutAnOrderOfItsOwnFollowsTheGeneralOne() { var general = DownloadOrder.Parse("post,storie"); var account = Make.Account("marta.demo"); Assert.AreSame(general, DownloadOrder.For(account, general), "«Come le impostazioni generali»"); Assert.AreSame(general, DownloadOrder.For(account with { DownloadOrder = " " }, general)); Assert.AreSame(general, DownloadOrder.For(null, general)); Assert.AreEqual("taggati,reel,storie,evidenza,post", DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).ToString(), "«Un ordine suo»"); Assert.AreEqual(16, DownloadOrder.For(account with { DownloadOrder = "taggati,reel" }, general).Weight(DownloadKind.Tagged)); } [TestMethod] public async Task TheQueueOfTheFilesFollowsTheOrder() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo(1), Make.Photo(2)]); await db.Entries.AddAsync(Make.Entry(a.Id, "storia", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(2) }, [Make.Video()]); await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged), [Make.Photo()]); var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); CollectionAssert.AreEqual(new[] { EntryKind.Story, EntryKind.Post, EntryKind.Post, EntryKind.Tagged }, standard.Select(p => p.Kind).ToArray()); var tagged = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("taggati,post,storie"))); CollectionAssert.AreEqual(new[] { EntryKind.Tagged, EntryKind.Post, EntryKind.Post, EntryKind.Story }, tagged.Select(p => p.Kind).ToArray()); Assert.AreEqual(1, tagged[1].Media.Position, "dentro un tipo l'ordine di sempre"); Assert.AreEqual(2, tagged[2].Media.Position); } [TestMethod] public async Task AReelGoesInTheQueueAsAReelAndStaysOne() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var a = await db.Accounts.AddAsync(Make.Account("marta.demo")); var post = (await db.Entries.AddAsync(Make.Entry(a.Id, "post", Make.T0), [Make.Photo()])).Stored.Entry; var reel = (await db.Entries.AddAsync(Make.Entry(a.Id, "reel", Make.T0) with { IsReel = true }, [Make.Video()])).Stored.Entry; var tagged = (await db.Entries.AddAsync(Make.Entry(a.Id, "taggato", Make.T0, EntryKind.Tagged) with { IsReel = true }, [Make.Video()])).Stored.Entry; Assert.IsTrue(reel.IsReel); Assert.IsTrue((await db.Entries.GetAsync(reel.Id))!.IsReel, "il segno del reel resta nel database (migrazione 0002)"); Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel, "solo un post può essere un reel"); var reelsFirst = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Parse("reel,taggati,post"))); CollectionAssert.AreEqual(new[] { reel.Id, tagged.Id, post.Id }, reelsFirst.Select(p => p.Media.EntryId).ToArray()); Assert.IsTrue(reelsFirst[0].IsReel); var standard = await db.Media.ListPendingDownloadsAsync(10, Everywhere(DownloadOrder.Default)); CollectionAssert.AreEqual(new[] { post.Id, reel.Id, tagged.Id }, standard.Select(p => p.Media.EntryId).ToArray(), "post, poi reel, poi taggati"); // A known post marked as a reel later becomes one; a full update with a stale copy never clears the mark. await db.Entries.MarkReelAsync(post.Id); Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel); await db.Entries.UpdateAsync(post with { Caption = "didascalia" }); Assert.IsTrue((await db.Entries.GetAsync(post.Id))!.IsReel, "un reel non torna un post"); await db.Entries.MarkReelAsync(tagged.Id); Assert.IsFalse((await db.Entries.GetAsync(tagged.Id))!.IsReel); } [TestMethod] public async Task EachAccountHasItsOwnOrderInTheQueue() { using var temp = new TempFolder(); await using var db = await TestDatabase.OpenAsync(temp); var general = await db.Accounts.AddAsync(Make.Account("marta.demo")); var own = await db.Accounts.AddAsync(Make.Account("luca.demo") with { DownloadOrder = "taggati,post" }); var other = await db.Accounts.AddAsync(Make.Account("pina.demo") with { DownloadOrder = "taggati,post" }); var same = await db.Accounts.AddAsync(Make.Account("anna.demo") with { DownloadOrder = DownloadOrder.Default.ToString() }); Assert.AreEqual("taggati,post", (await db.Accounts.GetAsync(own.Id))!.DownloadOrder); Assert.IsNull((await db.Accounts.GetAsync(general.Id))!.DownloadOrder); var story = (await db.Entries.AddAsync(Make.Entry(general.Id, "s", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; var post = (await db.Entries.AddAsync(Make.Entry(general.Id, "p", Make.T0), [Make.Photo()])).Stored.Entry; var ownPost = (await db.Entries.AddAsync(Make.Entry(own.Id, "q", Make.T0), [Make.Photo()])).Stored.Entry; var ownTagged = (await db.Entries.AddAsync(Make.Entry(own.Id, "g", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; var ownStory = (await db.Entries.AddAsync(Make.Entry(own.Id, "t", Make.T0, EntryKind.Story) with { ExpiresAt = Make.T0.AddHours(3) }, [Make.Photo()])).Stored.Entry; var otherTagged = (await db.Entries.AddAsync(Make.Entry(other.Id, "h", Make.T0, EntryKind.Tagged), [Make.Photo()])).Stored.Entry; var order = await DownloadOrder.LoadQueueOrderAsync(db); Assert.HasCount(2, order.Accounts, "an own order equal to the general one changes nothing in the queue"); Assert.IsFalse(order.Accounts.ContainsKey(same.Id)); // Positions: the story of the general account 0, the tagged of the two accounts with their own order 0, their // post 1, their story 2, the post of the general account 2. Within a position: expiring first, then discovery. var queue = await db.Media.ListPendingDownloadsAsync(20, order); CollectionAssert.AreEqual( new[] { story.Id, ownTagged.Id, otherTagged.Id, ownPost.Id, ownStory.Id, post.Id }, queue.Select(p => p.Media.EntryId).ToArray()); } [TestMethod] public void TheLongestWaitingFileHasItsShareOfTheBatch() { // Ten stories that keep coming and one tagged post that has waited the longest. var stories = Enumerable.Range(1, 10).Select(i => Pending(i, EntryKind.Story)).ToList(); var tagged = Pending(100, EntryKind.Tagged); var ordered = stories.Append(tagged).ToList(); var longest = new[] { tagged }.Concat(stories).ToList(); var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 4); CollectionAssert.AreEqual(new long[] { 1, 2, 3, 100, 4, 5, 6, 7 }, batch.Select(p => p.Media.Id).ToArray(), "un posto su quattro va a chi aspetta da più tempo"); var orderOnly = DownloadQueue.ComposeBatch(ordered, longest, 11, 0); Assert.AreEqual(100, orderOnly[^1].Media.Id, "senza la quota il taggato viene per ultimo"); var all = DownloadQueue.ComposeBatch(ordered, longest, 50, 4); Assert.HasCount(11, all, "nessun file due volte, e tutti quando c'è posto"); Assert.AreEqual(11, all.Select(p => p.Media.Id).Distinct().Count()); Assert.IsEmpty(DownloadQueue.ComposeBatch([], [], 8, 4)); CollectionAssert.AreEqual(new long[] { 100 }, DownloadQueue.ComposeBatch([], [tagged], 8, 4).Select(p => p.Media.Id).ToArray()); } [TestMethod] public void NoKindWaitsForEverEvenWhenTheFirstKindNeverEnds() { // Every round (a day with its data budget) brings 6 new stories and downloads only 4 files: with the order // alone the tagged posts would wait for ever; with one place in four for the longest waiting they all arrive. var waiting = Enumerable.Range(1, 5).Select(i => Pending(1000 + i, EntryKind.Tagged, discovered: i)).ToList(); var next = 1L; var rounds = 0; while (waiting.Any(p => p.Kind == EntryKind.Tagged) && rounds++ < 100) { for (var i = 0; i < 6; i++) { waiting.Add(Pending(next, EntryKind.Story, discovered: 100 + next)); next++; } var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Story ? 0 : 4).ThenBy(p => p.Media.EntryId).ToList(); var longest = waiting.OrderBy(p => p.Media.EntryId).ToList(); foreach (var done in DownloadQueue.ComposeBatch(ordered, longest, 4, 4)) { waiting.Remove(done); } } Assert.IsLessThanOrEqualTo(20, rounds, $"i taggati sono arrivati in {rounds} giri"); } [TestMethod] public void TheReservedPlaceGoesToTheOldestFileOfTheQueueNotToEachKindInTurn() { // A new account: 40 posts of the backfill found first, then 5 tagged posts, and 7 new posts every round. The // share is not a minimum per kind: while older posts wait, their kind takes the reserved place too, and the // tagged posts come only once that backlog is done. What holds is that no file waits for ever. var waiting = Enumerable.Range(1, 40).Select(i => Pending(i, EntryKind.Post)).ToList(); waiting.AddRange(Enumerable.Range(100, 5).Select(i => Pending(i, EntryKind.Tagged))); var next = 1000L; var taggedByRound = new List(); while (waiting.Any(p => p.Kind == EntryKind.Tagged) && taggedByRound.Count < 100) { for (var i = 0; i < 7; i++) { waiting.Add(Pending(next++, EntryKind.Post)); } var ordered = waiting.OrderBy(p => p.Kind == EntryKind.Post ? 0 : 1).ThenBy(p => p.Media.EntryId).ToList(); var longest = waiting.OrderBy(p => p.Media.EntryId).ToList(); var batch = DownloadQueue.ComposeBatch(ordered, longest, 8, 8); var oldest = longest.First(p => !batch.Take(7).Contains(p)); Assert.AreSame(oldest, batch[7], "il posto riservato va al file che aspetta da più tempo, di qualunque tipo"); taggedByRound.Add(batch.Count(p => p.Kind == EntryKind.Tagged)); foreach (var done in batch) { waiting.Remove(done); } } CollectionAssert.AreEqual(new[] { 0, 0, 0, 0, 0 }, taggedByRound.Take(5).ToArray(), "finché i post più vecchi aspettano, i taggati non hanno un posto loro"); Assert.AreEqual(5, taggedByRound.Sum(), "poi arrivano tutti"); Assert.HasCount(10, taggedByRound, "uno per giro, nel posto riservato"); } [TestMethod] public async Task TheOrderWeighsTheVisitsAfterTheSweepWithoutMakingThemFixed() { var standard = await FirstVisitsAsync(null); var postsFirst = await FirstVisitsAsync("post,storie"); Assert.IsGreaterThan(10, postsFirst.Sessions, "abbastanza sessioni con le due cose da fare"); Assert.IsGreaterThan(standard.PostsFirst + 0.2, postsFirst.PostsFirst, $"post per primi: {postsFirst.PostsFirst:P0} contro {standard.PostsFirst:P0}"); Assert.IsLessThan(1.0, postsFirst.PostsFirst, "l'ordine pesa ma non diventa fisso"); Assert.IsGreaterThan(0.0, standard.PostsFirst, "anche con le storie in cima i post vengono talvolta prima"); Assert.IsGreaterThan(0.75, postsFirst.SweepFirst, "il giro resta di norma il primo"); Assert.AreEqual(standard.SweepFirst, postsFirst.SweepFirst, 0.15, "la composizione delle sessioni non cambia"); } [TestMethod] public async Task TheOwnOrderOfAnAccountWeighsItsVisitsAsTheGeneralOneDoes() { // The accounts of the posts put «post» first in an order of their own, the general order stays the default. var standard = await FirstVisitsAsync(null); var own = await FirstVisitsAsync(null, postsOwnOrder: "post,storie"); Assert.IsGreaterThan(10, own.Sessions); Assert.IsGreaterThan(standard.PostsFirst + 0.1, own.PostsFirst, $"post per primi: {own.PostsFirst:P0} contro {standard.PostsFirst:P0}"); Assert.IsLessThan(1.0, own.PostsFirst, "l'ordine pesa ma non diventa fisso"); Assert.AreEqual(standard.SweepFirst, own.SweepFirst, 0.15, "il giro resta primo, la composizione non cambia"); } [TestMethod] public async Task AKindWithNothingDueIsNotVisited() { await using var bed = await EngineTestBed.CreateAsync(Morning); await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, "evidenza,taggati,reel,post,storie"); await bed.AddAccountAsync("seguito.demo", followed: true); for (var i = 0; i < 4; i++) { await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos); } var runner = new ScriptedRunner(bed.Governor, bed.Clock); bed.Start(runner); await bed.RunUntilAsync(Morning.AddDays(2)); Assert.IsFalse(runner.Runs.Any(r => r.Request.Kind == RecipeKind.Highlight), "nessuna raccolta in evidenza da controllare"); Assert.IsTrue(runner.Runs.Any(r => r.Request.Kind == RecipeKind.ProfileCheck), "il resto del lavoro va avanti"); } private static DownloadQueueOrder Everywhere(DownloadOrder order) => DownloadQueueOrder.Everywhere(order.Kinds); /// A file waiting in the queue; orders the longest waiting (here: the entry key). private static PendingDownload Pending(long id, EntryKind kind, long? discovered = null) => new(Make.Photo() with { Id = id, EntryId = discovered ?? id }, 1, kind, Make.T0, null); /// /// Three days of the engine with accounts that want only their stories and accounts that want only their posts: in /// how many sessions with both, the first of them after the sweep was a profile check. /// private static async Task<(double PostsFirst, double SweepFirst, int Sessions)> FirstVisitsAsync(string? order, string? postsOwnOrder = null) { await using var bed = await EngineTestBed.CreateAsync(Morning, seed: 11); if (order is not null) { await bed.Db.Settings.SetAsync(DownloadOrder.SettingKey, order); } await bed.AddAccountAsync("seguito.demo", followed: true); for (var i = 0; i < 6; i++) { await bed.AddAccountAsync($"storie{i}.demo", followed: false, Frequency.High, types: ContentTypes.Stories); var posts = await bed.AddAccountAsync($"post{i}.demo", followed: false, Frequency.High, types: ContentTypes.PostPhotos); if (postsOwnOrder is not null) { await bed.Db.Accounts.UpdateAsync(posts with { DownloadOrder = postsOwnOrder }); } } var runner = new ScriptedRunner(bed.Governor, bed.Clock); bed.Start(runner); await bed.RunUntilAsync(Morning.AddDays(3)); var sessions = runner.Runs.GroupBy(r => r.SessionId).ToList(); var sweepFirst = sessions.Count(g => g.First().Request.Kind == RecipeKind.FollowingSweep) / (double)sessions.Count; var both = sessions .Select(g => g.Where(r => r.Request.Kind is RecipeKind.AccountStories or RecipeKind.ProfileCheck).ToList()) .Where(v => v.Any(r => r.Request.Kind == RecipeKind.AccountStories) && v.Any(r => r.Request.Kind == RecipeKind.ProfileCheck)) .ToList(); var postsFirst = both.Count == 0 ? 0 : both.Count(v => v[0].Request.Kind == RecipeKind.ProfileCheck) / (double)both.Count; return (postsFirst, sweepFirst, both.Count); } }