D1, seconda parte: «Cosa scaricare prima» anche per account, reel distinti e quota per chi aspetta
L'ordine dei tipi (storie, evidenza, post, reel, taggati) ora vale anche per il singolo account: nella scheda account → Impostazioni si sceglie «Come le impostazioni generali» o un ordine suo, con lo stesso elenco da trascinare (o Su/Giù da tastiera) di Limiti e comportamento, ora un modulo solo (download-order.js). Il motore pesa le visite con l'ordine dell'account, la coda dei file mette ogni file al posto del suo tipo nell'ordine del suo account, stabile dentro il tipo (scadenza, scoperta, elemento, posizione). Perché nessun tipo resti fermo per sempre quando il tetto dei dati finisce prima della coda, un posto su otto di ogni giro della coda va al file che aspetta da più tempo, di qualunque tipo. I reel non si inventano (regola 9): un post è reel se viene dalla scheda Reel o se la risposta ha product_type «clips», valore visto nei campioni ripuliti. Il segno si scrive da solo e non si toglie mai, così una copia vecchia non sposta di nuovo i file in coda. Migrazione 0002_ordine_scaricamento (account.download_order, entry.is_reel): prende il primo numero dopo quelle unite, E1 userà il successivo. Prove su motore (seme fisso), coda, lettori, ricette e API; dimostrazione con un account che ha l'ordine suo; guida e decisioni aggiornate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d6c0ef851d
commit
0547c747c5
40 files changed
+775
-158
No files matched your search
@@ -74,6 +74,15 @@ public sealed record DownloadOptions
|
||||
/// <summary>How many pending files are read from the database at a time.</summary>
|
||||
public int BatchSize { get; init; } = 200;
|
||||
|
||||
/// <summary>
|
||||
/// «Cosa scaricare prima» never starves the later kinds (spec §6.5, §7.2): one file in this many is the one that has
|
||||
/// waited longest, whatever its kind; the others follow the order. Every file in the queue becomes the longest
|
||||
/// waiting sooner or later (new files are always younger), so every kind gets at least this share of the downloads
|
||||
/// while it has files waiting, even when the daily data budget ends each day before the queue does. 0 or 1: the
|
||||
/// order alone.
|
||||
/// </summary>
|
||||
public int LongestWaitingShare { get; init; } = 8;
|
||||
|
||||
/// <summary>When idle, how long to wait before looking at the database again (a <see cref="DownloadQueue.Wake"/> ends it earlier).</summary>
|
||||
public TimeSpan IdlePoll { get; init; } = TimeSpan.FromMinutes(1);
|
||||
}
|
||||
@@ -242,12 +251,15 @@ public sealed class DownloadQueue
|
||||
var now = _clock.Now;
|
||||
var waiting = _retryAt.Count(r => r.Value > now);
|
||||
var window = (int)Math.Min(10_000L, (long)_options.BatchSize + attempted.Count + waiting);
|
||||
// «Cosa scaricare prima» (spec §6.5, §7.2), read at every batch so that a change counts from the next one.
|
||||
var order = await Febe.Core.Engine.DownloadOrder.LoadAsync(_storage.Settings, ct).ConfigureAwait(false);
|
||||
var batch = (await _storage.Media.ListPendingDownloadsAsync(window, order.EntryKinds(), ct).ConfigureAwait(false))
|
||||
.Where(p => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now))
|
||||
.Take(_options.BatchSize)
|
||||
.ToList();
|
||||
// «Cosa scaricare prima» (spec §6.5, §7.2), general and per account, read at every batch so that a change
|
||||
// counts from the next one; one file in LongestWaitingShare is the longest waiting, whatever its kind.
|
||||
var order = await DownloadOrder.LoadQueueOrderAsync(_storage, ct).ConfigureAwait(false);
|
||||
bool Ready(PendingDownload p) => p.Media.SourceUrl is not null && !attempted.ContainsKey(p.Media.Id) && IsDue(p.Media.Id, now);
|
||||
var ordered = (await _storage.Media.ListPendingDownloadsAsync(window, order, ct).ConfigureAwait(false)).Where(Ready).ToList();
|
||||
var longest = _options.LongestWaitingShare > 1 && ordered.Count > 0
|
||||
? (await _storage.Media.ListLongestWaitingDownloadsAsync(window, ct).ConfigureAwait(false)).Where(Ready).ToList()
|
||||
: [];
|
||||
var batch = ComposeBatch(ordered, longest, _options.BatchSize, _options.LongestWaitingShare);
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
break;
|
||||
@@ -271,6 +283,51 @@ public sealed class DownloadQueue
|
||||
return tally.ToReport();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A batch of at most <paramref name="size"/> files (spec §6.5, §7.2): in the order of «Cosa scaricare prima», except
|
||||
/// that every <paramref name="share"/>-th place goes to the file that has waited longest and is not in the batch yet,
|
||||
/// whatever its kind. A file is never taken twice; when one list runs out the other fills the places.
|
||||
/// </summary>
|
||||
/// <param name="ordered">The waiting files in the order of «Cosa scaricare prima».</param>
|
||||
/// <param name="longest">The same files, the longest waiting first.</param>
|
||||
/// <param name="size">Places in the batch.</param>
|
||||
/// <param name="share">One place in this many for the longest waiting; 0 or 1 for the order alone.</param>
|
||||
internal static List<PendingDownload> ComposeBatch(IReadOnlyList<PendingDownload> ordered, IReadOnlyList<PendingDownload> longest, int size, int share)
|
||||
{
|
||||
var batch = new List<PendingDownload>(Math.Max(0, Math.Min(size, ordered.Count + longest.Count)));
|
||||
var taken = new HashSet<long>();
|
||||
int nextOrdered = 0, nextLongest = 0;
|
||||
PendingDownload? Next(IReadOnlyList<PendingDownload> list, ref int index)
|
||||
{
|
||||
while (index < list.Count)
|
||||
{
|
||||
var candidate = list[index++];
|
||||
if (taken.Add(candidate.Media.Id))
|
||||
{
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
while (batch.Count < size)
|
||||
{
|
||||
var oldestTurn = share > 1 && batch.Count % share == share - 1;
|
||||
var next = oldestTurn
|
||||
? Next(longest, ref nextLongest) ?? Next(ordered, ref nextOrdered)
|
||||
: Next(ordered, ref nextOrdered) ?? Next(longest, ref nextLongest);
|
||||
if (next is null)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
batch.Add(next);
|
||||
}
|
||||
|
||||
return batch;
|
||||
}
|
||||
|
||||
private bool IsDue(long mediaId, DateTimeOffset now)
|
||||
{
|
||||
if (!_retryAt.TryGetValue(mediaId, out var at))
|
||||
|
||||
@@ -26,6 +26,7 @@ public static class ReadMapping
|
||||
AuthorInstagramId = foreignAuthor ? item.Owner?.Id : null,
|
||||
DiscoveredAt = now,
|
||||
ExpiresAt = kind == EntryKind.Story ? item.ExpiresAt ?? item.TakenAt.AddHours(24) : null,
|
||||
IsReel = kind == EntryKind.Post && item.IsReel,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -90,9 +90,12 @@ public sealed record ContentItem
|
||||
/// <summary>Order of appearance in the response, from 0.</summary>
|
||||
public int Order { get; init; }
|
||||
|
||||
/// <summary>The response marks it as a reel, or it was found in the Reel tab (spec §7.2, «Cosa scaricare prima»).</summary>
|
||||
public bool IsReel { get; init; }
|
||||
|
||||
private bool PrintMembers(StringBuilder builder)
|
||||
{
|
||||
builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, Files = {Files.Count}, IsComplete = {IsComplete}");
|
||||
builder.Append($"Id = {Id}, Code = {Code}, TakenAt = {TakenAt:O}, Owner = {Owner?.Username}, Pinned = {Pinned}, IsReel = {IsReel}, Files = {Files.Count}, IsComplete = {IsComplete}");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +87,12 @@ public sealed record ContentKeys
|
||||
|
||||
/// <summary>Video duration in seconds (on the node or on the video version).</summary>
|
||||
public VocabularyKeys Duration { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The type of the content as the site names it (a text): a post is a reel when it is one of <see cref="ReelTypes"/>.</summary>
|
||||
public VocabularyKeys ProductType { get; init; } = VocabularyKeys.None;
|
||||
|
||||
/// <summary>The values of <see cref="ProductType"/> that mean «reel» (spec §7.2, «Cosa scaricare prima»). Empty: never told.</summary>
|
||||
public IReadOnlyList<string> ReelTypes { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>Keys of one version of a file (one size of an image, one rendition of a video).</summary>
|
||||
@@ -356,6 +362,8 @@ public sealed record ReaderVocabulary
|
||||
Pinned = K(c.Pinned),
|
||||
ExpiresAt = K(c.ExpiresAt),
|
||||
Duration = K(c.Duration),
|
||||
ProductType = K(c.ProductType),
|
||||
ReelTypes = [.. (c.ReelTypes ?? []).Where(v => !string.IsNullOrWhiteSpace(v)).Select(v => v.Trim()).Distinct(StringComparer.Ordinal)],
|
||||
},
|
||||
Version = new VersionKeys { Url = K(v.Url), Width = K(v.Width), Height = K(v.Height), HasAudio = K(v.HasAudio) },
|
||||
Profile = new ProfileKeys
|
||||
@@ -448,6 +456,10 @@ internal sealed class ContentDto
|
||||
public List<string>? ExpiresAt { get; set; }
|
||||
|
||||
public List<string>? Duration { get; set; }
|
||||
|
||||
public List<string>? ProductType { get; set; }
|
||||
|
||||
public List<string>? ReelTypes { get; set; }
|
||||
}
|
||||
|
||||
internal sealed class VersionDto
|
||||
|
||||
@@ -335,6 +335,8 @@ public sealed class ShapeReader
|
||||
IsComplete = complete,
|
||||
HighlightId = highlightId,
|
||||
Order = walk.Contents.Count,
|
||||
IsReel = _v.Content.ReelTypes.Count > 0 && AsText(Get(_v.Content.ProductType, node)) is { } type
|
||||
&& _v.Content.ReelTypes.Contains(type, StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -158,6 +158,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
if (known is not null)
|
||||
{
|
||||
await RefreshFilesAsync(known, item, fromHighlight: false, ct).ConfigureAwait(false);
|
||||
known = await MarkReelAsync(known, item, ct).ConfigureAwait(false);
|
||||
return (new SaveResult(SaveOutcome.Known, known), 0, 0);
|
||||
}
|
||||
|
||||
@@ -175,6 +176,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
InstagramId = item.Id,
|
||||
Code = imported.Code ?? item.Code,
|
||||
Caption = imported.Caption ?? item.Caption,
|
||||
IsReel = imported.IsReel || (kind == EntryKind.Post && item.IsReel),
|
||||
};
|
||||
await storage.Entries.UpdateAsync(enriched, ct).ConfigureAwait(false);
|
||||
return (new SaveResult(SaveOutcome.Enriched, enriched), 0, 0);
|
||||
@@ -186,7 +188,7 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
var added = await storage.Entries.AddAsync(entry, media, ct).ConfigureAwait(false);
|
||||
if (!added.Created)
|
||||
{
|
||||
return (new SaveResult(SaveOutcome.Known, added.Stored.Entry), 0, 0);
|
||||
return (new SaveResult(SaveOutcome.Known, await MarkReelAsync(added.Stored.Entry, item, ct).ConfigureAwait(false)), 0, 0);
|
||||
}
|
||||
|
||||
if (!item.IsComplete && kind is EntryKind.Post or EntryKind.Tagged)
|
||||
@@ -197,6 +199,22 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
return (new SaveResult(SaveOutcome.Created, added.Stored.Entry), media.Count(m => m.State == MediaState.ToDownload), media.Count(m => m.State == MediaState.Skipped));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A known post that the content now marks as a reel (the Reel tab, or the response) becomes one, for the queue of
|
||||
/// the files (spec §7.2); a reel never goes back to a plain post. Returns the entry as stored.
|
||||
/// </summary>
|
||||
private async Task<Entry> MarkReelAsync(Entry known, ContentItem item, CancellationToken ct)
|
||||
{
|
||||
if (known.Kind != EntryKind.Post || known.IsReel || !item.IsReel || known.State == EntryState.Deleted)
|
||||
{
|
||||
return known;
|
||||
}
|
||||
|
||||
// Only the flag is written: the queue may be changing the state of the same entry at this moment.
|
||||
await storage.Entries.MarkReelAsync(known.Id, ct).ConfigureAwait(false);
|
||||
return known with { IsReel = true };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the profile picture when its address identity is new (code = first eight hex digits of SHA-256). A
|
||||
/// picture already known whose file expired or failed takes the fresh address just read: the identity is the path
|
||||
@@ -278,6 +296,8 @@ public sealed class CollectionWriter(IFebeStorage storage, IClock clock)
|
||||
await storage.Entries.UpdateAsync(latest with { Code = latest.Code ?? item.Code, Caption = latest.Caption ?? item.Caption }, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
await MarkReelAsync(entry, item, ct).ConfigureAwait(false);
|
||||
|
||||
return changed;
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,9 @@ public sealed partial class RecipeRunner
|
||||
|
||||
public bool IsGrid => TabTarget is null;
|
||||
|
||||
/// <summary>The Reel tab: every post it gives is a reel (<see cref="Entry.IsReel"/>).</summary>
|
||||
public bool MarksReels => TabTarget == SiteTargets.ProfileTabReels;
|
||||
|
||||
/// <summary>The grid and the reels come newest first (pinned posts aside); the order of tagged posts is not known.</summary>
|
||||
public bool IsChronological => Kind != EntryKind.Tagged;
|
||||
|
||||
@@ -566,7 +569,9 @@ public sealed partial class RecipeRunner
|
||||
}
|
||||
}
|
||||
|
||||
var saved = await Writer.SaveAsync(account, item, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
// What the Reel tab gives is a reel, whatever the response says (spec §7.2, «Cosa scaricare prima»).
|
||||
var content = walk.MarksReels && !item.IsReel ? item with { IsReel = true } : item;
|
||||
var saved = await Writer.SaveAsync(account, content, walk.Kind, run.Session.SessionId, run.Ct).ConfigureAwait(false);
|
||||
if (saved.Outcome == SaveOutcome.Created)
|
||||
{
|
||||
run.NewEntries++;
|
||||
|
||||
Reference in new issue
Block a user