Ricerca dei profili con suggerimenti e foto (#37)
verifica / controlli (push) Successful in 20s
verifica / prove (push) Failing after 19m40s
verifica / installatore (push) Skipped
verifica / immagine (push) Skipped

«Aggiungi account» ha una sola casella: mentre Alberto scrive compaiono
subito i suggerimenti locali, poi i profili di Instagram con la foto, come
chiesto in #37. Il browser di Febe scrive nella casella «Cerca» di Instagram
con tasti veri da una mappa chiusa (mai Invio, Tab o Esc), controlla prima
il fuoco, legge la risposta della pagina e non clicca mai un risultato.

La ricerca ha una categoria propria nel Governatore, con tetti larghi che
non consumano quelli della raccolta, e si dà il turno con il motore
sull'unica pagina; a fine sessione la pagina torna comunque al riposo. Le
foto passano dal CDN con un permesso ciascuna e restano solo in memoria.

Le risposte di Alberto del 15 novembre (controllo del fuoco, turni, evento
requestWillBeSent, niente foto dei seguiti per ora) sono in §6.1 e in
docs/decisioni.md. Su Instagram vero la ricerca parte quando i bersagli
search-open e search-box saranno raccolti dal vivo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-15 16:30:03 +01:00
1 parent 5e417c666d
commit 9941a2fa1f
98 files changed
+8021 -229

No files matched your search

+7
View File
@@ -24,6 +24,13 @@ public enum ActionKind
/// <summary>One page of the list of profiles Alberto follows.</summary>
FollowingListPage,
/// <summary>
/// One step of the profile search toward the site: opening Instagram for the search, opening its «Cerca» panel or
/// focusing its box, or one burst of typing (issue #37). Outside sessions, with its own wide budget that does not
/// consume the collection budgets.
/// </summary>
ProfileSearch,
/// <summary>Bytes downloaded from the CDN (daily byte budget).</summary>
DataDownload,
}
@@ -5,6 +5,7 @@ using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Privacy;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Collection.Search;
using Febe.Core.Domain;
using Febe.Core.Engine;
@@ -265,6 +266,17 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
b.Queued[key] = (current.Saves + 1, current.Files + Math.Max(0, files), current.Skipped + Math.Max(0, skipped));
});
/// <summary>Fates of a photo of a search result: downloaded, refused by the CDN or the budget, skipped.</summary>
public static readonly IReadOnlySet<string> SearchPhotoOutcomes = new HashSet<string>(StringComparer.Ordinal) { "scaricata", "rifiutata", "saltata" };
/// <summary>One step of the profile search ended (issue #37): only its outcome, never the text or the profiles.</summary>
public void SearchStepEnded(SearchOutcome outcome) =>
Record(null, (b, _) => Bump(b.SearchSteps, outcome));
/// <summary>A photo of a search result was downloaded, refused or skipped.</summary>
public void SearchPhotoSettled(string outcome) =>
Record(null, (b, _) => Bump(b.SearchPhotos, SearchPhotoOutcomes.Contains(outcome) ? outcome : Other));
/// <summary>The Governor refused an action (its event <c>Denied</c>).</summary>
public void PermitDenied(long? session, ActionKind kind, DenialReason reason) =>
Record(session, (b, _) => Bump(b.Denials, (kind, reason)));
@@ -1104,6 +1116,10 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
public long DownloadedBytes { get; set; }
public Dictionary<SearchOutcome, int> SearchSteps { get; } = [];
public Dictionary<string, int> SearchPhotos { get; } = new(StringComparer.Ordinal);
public OverflowCounter Overflow { get; } = new();
public void Touch(DateTimeOffset now)
@@ -1181,6 +1197,8 @@ public sealed partial class CollectionDiagnostics : IResponseObserver, IDisposab
FilesQueued = [.. Queued.Select(q => new QueuedFiles(q.Key.Kind, q.Key.Outcome, q.Value.Saves, q.Value.Files, q.Value.Skipped)).OrderBy(q => q.Kind).ThenBy(q => q.Outcome, StringComparer.Ordinal)],
Downloads = [.. Downloads.Select(d => new DownloadGroup(d.Key.Kind, d.Key.Step, d.Value.Count, d.Value.Bytes) { Cause = d.Key.Cause }).OrderBy(d => d.Kind).ThenBy(d => d.Step).ThenBy(d => d.Cause, StringComparer.Ordinal)],
DownloadedBytes = DownloadedBytes,
SearchSteps = [.. SearchSteps.Select(s => new SearchStepCount(s.Key, s.Value)).OrderBy(s => s.Outcome)],
SearchPhotos = [.. SearchPhotos.Select(s => new SearchPhotoCount(s.Key, s.Value)).OrderBy(s => s.Outcome, StringComparer.Ordinal)],
Overflow = new TraceOverflow
{
Pages = Overflow.Pages,
@@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using Febe.Core.Collection.Search;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Recipes;
@@ -69,6 +70,12 @@ public sealed record SessionTrace
/// <summary>Bytes of the files downloaded (what crossed the network), when the queue said.</summary>
public long DownloadedBytes { get; init; }
/// <summary>Steps of the profile search on the site (issue #37), by how they ended: never a typed text or a name.</summary>
public IReadOnlyList<SearchStepCount> SearchSteps { get; init; } = [];
/// <summary>Photos of search results, by what happened to them («scaricata», «rifiutata», «saltata»).</summary>
public IReadOnlyList<SearchPhotoCount> SearchPhotos { get; init; } = [];
/// <summary>Items not kept because a list was full: counted, never dropped silently.</summary>
public TraceOverflow Overflow { get; init; } = new();
}
@@ -130,6 +137,12 @@ public sealed record SignalLine(DateTimeOffset At, SignalLevel Level, string Cod
public sealed record DenialCount(ActionKind Action, DenialReason Reason, int Count);
/// <summary>Search steps that ended the same way (a name of the closed list <see cref="SearchOutcome"/>).</summary>
public sealed record SearchStepCount(SearchOutcome Outcome, int Count);
/// <summary>Photos of search results with the same fate.</summary>
public sealed record SearchPhotoCount(string Outcome, int Count);
/// <summary>Saves of contents read by the recipes: how many, and how many files they put in the download queue.</summary>
/// <param name="Outcome">A <see cref="SaveOutcome"/> name, or «Completed» for a «Post singolo» completion.</param>
public sealed record QueuedFiles(EntryKind Kind, string Outcome, int Saves, int Files, int Skipped);
+15 -1
View File
@@ -29,6 +29,11 @@ public enum HostKind
/// <param name="ResourceType">Browser resource type (Document, XHR, Fetch, Image, ...), when known.</param>
/// <param name="IsMainFrameDocument">True for the document of the main frame (a page load).</param>
/// <param name="At">When the response was seen.</param>
/// <param name="RequestOrder">
/// Order in which the page started the request among the site's requests (from 1, <c>Network.requestWillBeSent</c>);
/// 0 when unknown. The profile search (issue #37) tells answers to texts typed before the last key from the answer to
/// the text in the box with it.
/// </param>
public sealed record ResponseDescriptor(
string RequestId,
HostKind HostKind,
@@ -39,7 +44,8 @@ public sealed record ResponseDescriptor(
string MimeType,
string? ResourceType,
bool IsMainFrameDocument,
DateTimeOffset At);
DateTimeOffset At,
long RequestOrder = 0);
/// <summary>A main-frame navigation: a new document, or a route change inside a single-page site.</summary>
/// <param name="HostKind">Site, CDN or other.</param>
@@ -92,6 +98,14 @@ public interface IResponseObserver
void OnLoadingFinished(string requestId, long encodedBytes)
{
}
/// <summary>
/// The page started a request to the site: <paramref name="order"/> is its <see cref="ResponseDescriptor.RequestOrder"/>.
/// Nothing else of the request is passed (no address, no body).
/// </summary>
void OnRequestStarted(long order)
{
}
}
/// <summary>Why the body of a response did not reach the consumers (closed list: a report may show it).</summary>
@@ -160,4 +160,30 @@ public sealed record ReadResult
/// <summary>For unrecognized responses: the key structure, without any value (spec §6.4).</summary>
public string? KeyStructure { get; init; }
/// <summary>
/// The answer of the site's search box (issue #37), when this response is one. Its profiles are not in
/// <see cref="Profiles"/>, so a search answer never looks like a page of the followed list or a profile check.
/// </summary>
public SearchAnswer? Search { get; init; }
}
/// <summary>The profiles a search box answer gave, in their order (issue #37). Never printed with names.</summary>
public sealed record SearchAnswer(IReadOnlyList<SearchProfile> Hits)
{
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Hits = {Hits.Count}");
return true;
}
}
/// <summary>One profile of a search answer. Private and followed are never in the answer: they stay null.</summary>
public sealed record SearchProfile(int Position, ProfileInfo Profile, bool? IsVerified)
{
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Position = {Position}, HasPicture = {Profile.Picture is not null}, IsVerified = {IsVerified}");
return true;
}
}
@@ -150,6 +150,40 @@ public sealed record PageKeys
public VocabularyKeys Cursor { get; init; } = VocabularyKeys.None;
}
/// <summary>
/// Keys of the answer of the site's own search box (issue #37). The search carries its own profile keys, so a site
/// whose other concepts use other keys can still serve the search in its own shape. Only profiles are read: hashtags
/// and places are ignored.
/// </summary>
public sealed record SearchKeys
{
/// <summary>The key of the search answer: found anywhere in the tree, its value holds <see cref="Items"/>.</summary>
public VocabularyKeys Root { get; init; } = VocabularyKeys.None;
/// <summary>The list of profile results under the root.</summary>
public VocabularyKeys Items { get; init; } = VocabularyKeys.None;
/// <summary>Order of an item in the list (array order when missing).</summary>
public VocabularyKeys Position { get; init; } = VocabularyKeys.None;
/// <summary>The profile node of an item.</summary>
public VocabularyKeys Profile { get; init; } = VocabularyKeys.None;
public VocabularyKeys Id { get; init; } = VocabularyKeys.None;
public VocabularyKeys Username { get; init; } = VocabularyKeys.None;
public VocabularyKeys DisplayName { get; init; } = VocabularyKeys.None;
/// <summary>The profile picture: the first key present wins (the small one is enough for a suggestion).</summary>
public VocabularyKeys Picture { get; init; } = VocabularyKeys.None;
public VocabularyKeys Verified { get; init; } = VocabularyKeys.None;
/// <summary>True when the reader can recognize a search answer.</summary>
public bool IsSet => Root.IsSet && Items.IsSet && Id.IsSet && Username.IsSet;
}
/// <summary>Whether the vocabulary is confirmed on real samples or still a hypothesis (spec §6.4, rule 10).</summary>
public enum VocabularyStatus
{
@@ -185,6 +219,12 @@ public sealed record ReaderVocabulary
public PageKeys Page { get; init; } = new();
/// <summary>
/// The answer of the site's search box (issue #37). Not among <see cref="MissingConcepts"/>: the collection does not
/// depend on it, and without it the search on the site is «da configurare».
/// </summary>
public SearchKeys Search { get; init; } = new();
/// <summary>The key under which the response describes the connected account (H10).</summary>
public VocabularyKeys Viewer { get; init; } = VocabularyKeys.None;
@@ -295,6 +335,7 @@ public sealed record ReaderVocabulary
var p = file.Profile ?? new ProfileDto();
var h = file.Highlight ?? new HighlightDto();
var g = file.Page ?? new PageDto();
var s = file.Search ?? new SearchDto();
return new ReaderVocabulary
{
Site = file.Site.Trim(),
@@ -330,6 +371,18 @@ public sealed record ReaderVocabulary
},
Highlight = new HighlightKeys { Id = K(h.Id), Title = K(h.Title), Owner = K(h.Owner), Items = K(h.Items), Cover = K(h.Cover) },
Page = new PageKeys { HasMore = K(g.HasMore), Cursor = K(g.Cursor) },
Search = new SearchKeys
{
Root = K(s.Root),
Items = K(s.Items),
Position = K(s.Position),
Profile = K(s.Profile),
Id = K(s.Id),
Username = K(s.Username),
DisplayName = K(s.DisplayName),
Picture = K(s.Picture),
Verified = K(s.Verified),
},
Viewer = K(file.Viewer),
Relevance = [.. (file.Relevance?.Keys ?? []).Where(k => !string.IsNullOrWhiteSpace(k)).Select(k => k.Trim()).Distinct(StringComparer.Ordinal)],
};
@@ -354,6 +407,8 @@ internal sealed class VocabularyFile
public PageDto? Page { get; set; }
public SearchDto? Search { get; set; }
public List<string>? Viewer { get; set; }
public RelevanceDto? Relevance { get; set; }
@@ -453,6 +508,29 @@ internal sealed class PageDto
public List<string>? Cursor { get; set; }
}
internal sealed class SearchDto
{
public string? Note { get; set; }
public List<string>? Root { get; set; }
public List<string>? Items { get; set; }
public List<string>? Position { get; set; }
public List<string>? Profile { get; set; }
public List<string>? Id { get; set; }
public List<string>? Username { get; set; }
public List<string>? DisplayName { get; set; }
public List<string>? Picture { get; set; }
public List<string>? Verified { get; set; }
}
[JsonSourceGenerationOptions(
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
@@ -44,6 +44,22 @@ public sealed class ShapeReader
var profiles = walk.Profiles.Values.ToList();
var viewer = profiles.FirstOrDefault(p => p.IsViewer);
if (walk.Search is not null)
{
// A search answer, even with no profile in it: never an empty page and never an unknown shape (issue #37).
return new ReadResult
{
Shape = ReadShape.Recognized,
Search = walk.Search,
Contents = walk.Contents,
Profiles = profiles,
Highlights = walk.Highlights,
Page = walk.Page,
Viewer = viewer,
ViewerId = viewer?.Id ?? walk.ViewerId,
};
}
if (walk.Contents.Count > 0 || walk.Highlights.Count > 0 || profiles.Count > 0)
{
return new ReadResult
@@ -173,6 +189,13 @@ public sealed class ShapeReader
foreach (var property in node.EnumerateObject())
{
if (IsSearchRoot(property, out var items))
{
// The search answer: read with its own keys, and its subtree is not walked for generic profiles.
walk.Search ??= ReadSearch(items);
continue;
}
if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
{
Visit(property.Value, walk, inherited, highlightId, depth + 1);
@@ -180,6 +203,60 @@ public sealed class ShapeReader
}
}
/// <summary>A member named like the search root, whose value holds the list of results (issue #37).</summary>
private bool IsSearchRoot(JsonProperty property, out JsonElement items)
{
items = default;
var search = _v.Search;
return search.IsSet
&& property.Value.ValueKind == JsonValueKind.Object
&& search.Root.Paths.Contains(property.Name, StringComparer.Ordinal)
&& search.Items.TryGet(property.Value, out items)
&& items.ValueKind == JsonValueKind.Array;
}
/// <summary>The profiles of a search answer in their order; hashtags and places are never read.</summary>
private SearchAnswer ReadSearch(JsonElement items)
{
var search = _v.Search;
var hits = new List<SearchProfile>();
var index = 0;
foreach (var item in items.EnumerateArray())
{
var order = index++;
if (item.ValueKind != JsonValueKind.Object)
{
continue;
}
var node = search.Profile.TryGet(item, out var inner) && inner.ValueKind == JsonValueKind.Object ? inner : item;
var id = AsText(Get(search.Id, node));
var username = AsText(Get(search.Username, node));
if (id is null || string.IsNullOrWhiteSpace(username))
{
continue;
}
FileVersion? picture = null;
if (search.Picture.TryGet(node, out var pictureNode))
{
picture = ReadVersions(pictureNode).MaxBy(x => x.Version.Area)?.Version;
}
var profile = new ProfileInfo
{
Id = id,
Username = username.Trim(),
DisplayName = AsText(Get(search.DisplayName, node)),
Picture = picture,
};
var position = AsInt(Get(search.Position, item)) ?? order;
hits.Add(new SearchProfile(position, profile, search.Verified.TryGet(node, out var verified) ? AsBool(verified) : null));
}
return new SearchAnswer([.. hits.OrderBy(h => h.Position)]);
}
private bool IsContent(JsonElement node) =>
_v.Content.Id.Has(node) && _v.Content.TakenAt.Has(node)
&& (_v.Content.Images.Has(node) || _v.Content.Videos.Has(node) || _v.Content.Children.Has(node));
@@ -544,6 +621,9 @@ public sealed class ShapeReader
/// <summary>Identifier of the connected account when the answer gives no more than that.</summary>
public string? ViewerId { get; set; }
/// <summary>The search box answer, when the response holds one (issue #37).</summary>
public SearchAnswer? Search { get; set; }
/// <summary>Merges what different parts of a response say about the same profile.</summary>
public void AddProfile(ProfileInfo profile)
{
@@ -11,6 +11,12 @@ namespace Febe.Core.Collection.Recipes;
/// <param name="Result">What the reader recognized, detached from the body.</param>
public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, ReadResult Result);
/// <summary>
/// Where the search answers stood at one moment (issue #37): the last search answer that arrived and the last request
/// the page started. Pass it to <see cref="CaptureCollector.SearchSince"/>.
/// </summary>
public readonly record struct SearchAnswerMark(long Arrival, long Request);
/// <summary>
/// Bridge between the response tap and the recipes (spec §6.2, §6.4): every JSON body the site sends is read by the
/// <see cref="ShapeReader"/> as it arrives, and the recipes wait for what they expect after a gesture. Bodies are
@@ -23,13 +29,18 @@ public sealed record CapturedRead(long Sequence, ResponseDescriptor Response, Re
public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
{
private const int MaxKept = 2000;
private const int MaxSearchKept = 50;
private readonly ShapeReader _reader;
private readonly IClock _clock;
private readonly Lock _gate = new();
private readonly List<CapturedRead> _reads = [];
private readonly List<CapturedRead> _searchReads = [];
private readonly Dictionary<string, DateTimeOffset> _pending = new(StringComparer.Ordinal);
private long _sequence;
private long _searchSequence;
private long _lastRequestOrder;
private DateTimeOffset? _lastArrivalAt;
private string? _viewerId;
public CaptureCollector(ShapeReader reader, IClock clock)
@@ -82,6 +93,46 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
}
}
/// <summary>
/// Where the search box answers stand now (issue #37): pass it to <see cref="SearchSince"/>. Search answers have
/// their own buffer, so recipe windows (<see cref="Mark"/>, <see cref="Since"/>) never see them. Taken right before
/// a key, it separates the requests the page started for the texts before that key from the ones after it.
/// </summary>
public SearchAnswerMark SearchMark()
{
lock (_gate)
{
return new SearchAnswerMark(_searchSequence, _lastRequestOrder);
}
}
/// <summary>
/// Search box answers to requests the page started after <paramref name="mark"/>, oldest request first. An answer
/// whose request order is unknown counts by its arrival instead.
/// </summary>
public IReadOnlyList<CapturedRead> SearchSince(SearchAnswerMark mark)
{
lock (_gate)
{
return [.. _searchReads
.Where(r => r.Response.RequestOrder > 0 ? r.Response.RequestOrder > mark.Request : r.Sequence > mark.Arrival)
.OrderBy(r => r.Response.RequestOrder)
.ThenBy(r => r.Sequence)];
}
}
/// <summary>When the body of the last response of the site was read (any kind, unrelated ones included).</summary>
public DateTimeOffset? LastArrivalAt
{
get
{
lock (_gate)
{
return _lastArrivalAt;
}
}
}
/// <summary>Data responses whose body has not been read yet.</summary>
public int Pending
{
@@ -178,14 +229,31 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
var result = _reader.Read(body);
Observe(response, result, body);
if (result.ViewerId is { } viewerId)
lock (_gate)
{
lock (_gate)
_lastArrivalAt = _clock.Now;
if (result.ViewerId is { } viewerId)
{
_viewerId = viewerId;
}
}
if (result.Search is not null)
{
// A search box answer goes to its own buffer: it never stops, fills or judges a recipe (issue #37).
lock (_gate)
{
var found = new CapturedRead(++_searchSequence, response, result);
_searchReads.Add(found);
if (_searchReads.Count > MaxSearchKept)
{
_searchReads.RemoveRange(0, _searchReads.Count - MaxSearchKept);
}
return found;
}
}
if (result.Shape == ReadShape.Unrelated)
{
// Not about contents (promotions, logging): neither data nor an empty page, and not «something new
@@ -241,6 +309,17 @@ public sealed class CaptureCollector : IResponseConsumer, IResponseObserver
}
}
void IResponseObserver.OnRequestStarted(long order)
{
lock (_gate)
{
if (order > _lastRequestOrder)
{
_lastRequestOrder = order;
}
}
}
void IResponseObserver.OnBodyDropped(string requestId)
{
lock (_gate)
@@ -0,0 +1,54 @@
using System.Text;
namespace Febe.Core.Collection.Recipes;
/// <summary>
/// What the focus check of the site's search box says (issue #37). Never the text: only whether the box is on the
/// page, whether the focus is in it, how many characters it holds and whether the caret is at the end.
/// </summary>
/// <param name="BoxFound">The search box is on the page and visible.</param>
/// <param name="Focused">The focus is in the box.</param>
/// <param name="Length">Characters in the box, only when the focus is in it (null otherwise).</param>
/// <param name="CaretAtEnd">The caret is at the end of the text, with nothing selected.</param>
public sealed record SearchFocus(bool BoxFound, bool Focused, int? Length, bool CaretAtEnd)
{
/// <summary>No box on the page.</summary>
public static SearchFocus None { get; } = new(false, false, null, false);
/// <summary>The box has the focus and the caret is at the end: keys go where Febe wants them.</summary>
public bool Ready => BoxFound && Focused && Length is not null && CaretAtEnd;
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"BoxFound = {BoxFound}, Focused = {Focused}, Length = {Length}, CaretAtEnd = {CaretAtEnd}");
return true;
}
}
/// <summary>
/// Typing into the site's own search box (issue #37), with <c>Input.dispatchKeyEvent</c> only: letters, digits,
/// «.», «_» and spaces, Backspace and End, never Enter, Tab or Escape. Separate from <see cref="IPageDriver"/>, which
/// the recipes use: only the profile search types.
/// </summary>
public interface ISearchInput
{
/// <summary>The read-only focus check of the search box.</summary>
Task<SearchFocus> FocusAsync(CancellationToken ct);
/// <summary>Presses End: the caret goes to the end of the text.</summary>
Task EndKeyAsync(CancellationToken ct);
/// <summary>
/// Presses Backspace <paramref name="count"/> times at a human rhythm; <paramref name="beforeKey"/> runs right
/// before every key (the search notes where the page's requests stand).
/// </summary>
Task EraseAsync(int count, Action? beforeKey, CancellationToken ct);
/// <summary>
/// Types the characters <paramref name="next"/> gives, one at a time at a human rhythm, until it returns null.
/// <paramref name="next"/> receives how many characters were typed so far, and may run its own checks (it is
/// awaited before every key). Returns how many characters were typed. A character outside the closed key map stops
/// the burst with <see cref="ArgumentException"/> before its key is sent.
/// </summary>
Task<int> TypeAsync(Func<int, CancellationToken, ValueTask<char?>> next, CancellationToken ct);
}
+13 -2
View File
@@ -78,10 +78,20 @@ internal sealed class RecipeRun : IDisposable
}
}
/// <summary>Asks the Governor for a counted action; stops in order when refused or when the session is over.</summary>
public async Task PermitAsync(ActionKind kind, long? accountId)
/// <summary>
/// Asks the Governor for a counted action; stops in order when refused or when the session is over. With
/// <paramref name="opensPage"/> (the next step opens a page), this is a turn point of the page (issue #37): when the
/// profile search waits, it gets the page for one step first, and the checks run again after it.
/// </summary>
public async Task PermitAsync(ActionKind kind, long? accountId, bool opensPage = false)
{
ThrowIfSignal();
if (opensPage && Env.PageTurns is { } turns && turns.EngineTurn is { } turn && await turns.YieldAsync(turn, Ct).ConfigureAwait(false))
{
// The page may have changed meanwhile: what follows opens a page anyway, but the state is looked at again.
ThrowIfSignal();
}
if (Env.Clock.Now > Session.PlannedEnd)
{
throw Stop(RecipeStatus.Denied, "La sessione è finita: la ricetta riprenderà alla prossima.");
@@ -104,6 +114,7 @@ internal sealed class RecipeRun : IDisposable
try
{
load = await Env.Driver.OpenAsync(path, Ct).ConfigureAwait(false);
Env.PageTurns?.NoteOpened(PageUser.Engine);
}
catch
{
@@ -47,7 +47,7 @@ public sealed partial class RecipeRunner
throw RecipeRun.Stop(RecipeStatus.Denied, $"{account.Username} è «Solo archivio»: non si contatta.");
}
await run.PermitAsync(ActionKind.SinglePost, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.SinglePost, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Post, Values(("code", entry.Code))).ConfigureAwait(false);
bool Matches(Readers.ContentItem c) => c.Id == entry.InstagramId || (c.Code is not null && c.Code == entry.Code);
@@ -94,7 +94,7 @@ public sealed partial class RecipeRunner
}
var maxPages = Math.Max(1, run.Request.MaxPages ?? Env.Options.FollowingPagesPerRun);
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.FollowingListPage, mine.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(
byPage ? SitePages.FollowingFrom : SitePages.Following,
@@ -251,7 +251,7 @@ public sealed partial class RecipeRunner
if (Env.SiteMap.HasPage(walk.ResumePage))
{
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", stored.Cursor))).ConfigureAwait(false);
start = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
@@ -359,7 +359,7 @@ public sealed partial class RecipeRunner
if (target is not null && Env.SiteMap.HasPage(walk.ResumePage))
{
// Resume where the last run stopped: the page of the site that starts after the stored point.
await run.PermitAsync(ActionKind.BackfillPage, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.BackfillPage, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(walk.ResumePage, Values(("username", account.Username), ("cursor", target.Cursor))).ConfigureAwait(false);
reads = await WaitAndSettleAsync(run, mark, r => IsWalkPage(r, account, walk)).ConfigureAwait(false);
@@ -738,7 +738,7 @@ public sealed partial class RecipeRunner
private async Task<(Account Account, IReadOnlyList<CapturedRead> Reads)> OpenProfileAsync(RecipeRun run, Account account, bool waitForGrid = false)
{
var parameters = Values(("username", account.Username));
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
if (Env.SiteMap.IsTargetConfigured(SiteTargets.ProfileNotFound)
@@ -14,7 +14,7 @@ public sealed partial class RecipeRunner
/// </summary>
private async Task<RecipeStatus> FollowingSweepAsync(RecipeRun run)
{
await run.PermitAsync(ActionKind.Home, null).ConfigureAwait(false);
await run.PermitAsync(ActionKind.Home, null, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Home).ConfigureAwait(false);
@@ -45,13 +45,15 @@ public sealed partial class RecipeRunner
}
var parameters = Values(("username", account.Username));
var fromBar = Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
// After a search step the home page may be covered by the site's search panel: the profile is opened instead.
var fromBar = Env.PageTurns?.SearchTouchedPage != true
&& Env.SiteMap.IsTargetConfigured(SiteTargets.HomeStory)
&& Env.SiteMap.Match(SitePages.Home, await Env.Driver.CurrentPathAsync(run.Ct).ConfigureAwait(false)) is not null
&& (await run.FindAsync(SiteTargets.HomeStory, parameters).ConfigureAwait(false)).Found;
if (!fromBar)
{
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
var reads = await run.WaitForDataAsync(mark, r => ProfileIn(r, account) is not null).ConfigureAwait(false);
@@ -135,7 +137,7 @@ public sealed partial class RecipeRunner
var highlightId = ShapeReader.HighlightId(requested);
await EnsureStoryBudgetAsync(run, account).ConfigureAwait(false);
var parameters = Values(("username", account.Username));
await run.PermitAsync(ActionKind.ProfileOpen, account.Id).ConfigureAwait(false);
await run.PermitAsync(ActionKind.ProfileOpen, account.Id, opensPage: true).ConfigureAwait(false);
var mark = Env.Capture.Mark();
await run.OpenAsync(SitePages.Profile, parameters).ConfigureAwait(false);
@@ -44,6 +44,12 @@ public sealed record RecipeEnvironment
/// <summary>The recorder of the diagnostic report (issue #39). Null: nothing is recorded.</summary>
public CollectionDiagnostics? Diagnostics { get; init; }
/// <summary>
/// The turns of the page shared with the profile search (issue #37): recipes give the page to the search before an
/// action that opens a page, when the search waits. Null: no search, no turn points.
/// </summary>
public PageTurns? PageTurns { get; init; }
}
/// <summary>
@@ -0,0 +1,94 @@
namespace Febe.Core.Collection.Search;
/// <summary>
/// Times and bounds of the profile search (issue #37). Waits marked «× ritmo» are multiplied by the gesture pace of the
/// caution profile; every value is an option so that the tests can shorten them.
/// </summary>
public sealed record ProfileSearchOptions
{
public static ProfileSearchOptions Default { get; } = new();
/// <summary>How long the wanted text must stay still before Febe types it (× ritmo).</summary>
public TimeSpan EngineDebounce { get; init; } = TimeSpan.FromMilliseconds(350);
/// <summary>After a step, how long the search keeps the page waiting for the next letter (× ritmo).</summary>
public TimeSpan HoldWindow { get; init; } = TimeSpan.FromSeconds(2);
/// <summary>Longest the search keeps the page in one go, however Alberto keeps typing.</summary>
public TimeSpan MaxHold { get; init; } = TimeSpan.FromSeconds(20);
/// <summary>Least wait after the last key before an answer is taken (covers the site's own debounce, × ritmo).</summary>
public TimeSpan MinAnswerWait { get; init; } = TimeSpan.FromMilliseconds(700);
/// <summary>No data response for this long: the page is quiet (× ritmo).</summary>
public TimeSpan Quiet { get; init; } = TimeSpan.FromMilliseconds(600);
/// <summary>Longest wait for the answer after the last key.</summary>
public TimeSpan AnswerTimeout { get; init; } = TimeSpan.FromSeconds(8);
/// <summary>Longest wait for the page to be quiet before the page goes back to the engine.</summary>
public TimeSpan ReleaseSettle { get; init; } = TimeSpan.FromSeconds(2);
/// <summary>Longest one step may take (above the load timeout of a page plus the waits).</summary>
public TimeSpan StepGuard { get; init; } = TimeSpan.FromSeconds(60);
/// <summary>After the dialog closes, how long before the page goes to rest.</summary>
public TimeSpan EndGrace { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>With the dialog open and nothing typed for this long, the page goes to rest.</summary>
public TimeSpan IdleRest { get; init; } = TimeSpan.FromMinutes(3);
/// <summary>After the dialog closes, results and cached answers are forgotten after this long.</summary>
public TimeSpan DropHitsAfter { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Keys of one burst under one permit of the Governor.</summary>
public int KeysPerPermit { get; init; } = 40;
/// <summary>A focus check every this many keys.</summary>
public int FocusCheckEvery { get; init; } = 4;
/// <summary>How often the waits look at the page and the answers.</summary>
public TimeSpan Poll { get; init; } = TimeSpan.FromMilliseconds(100);
/// <summary>Wait after the «Cerca» button before clicking the box (× ritmo).</summary>
public TimeSpan PanelWaitMin { get; init; } = TimeSpan.FromMilliseconds(400);
/// <summary>Upper bound of <see cref="PanelWaitMin"/>.</summary>
public TimeSpan PanelWaitMax { get; init; } = TimeSpan.FromMilliseconds(1000);
/// <summary>Texts whose answer Febe remembers (no new search on the site for them).</summary>
public int CachedTexts { get; init; } = 40;
/// <summary>How long a remembered answer holds.</summary>
public TimeSpan CachedAnswerLifetime { get; init; } = TimeSpan.FromMinutes(5);
/// <summary>Photos fetched for each answer (the first results).</summary>
public int PhotosPerAnswer { get; init; } = 8;
/// <summary>Photos kept in memory.</summary>
public int MaxPhotos { get; init; } = 400;
/// <summary>Bytes of photos kept in memory.</summary>
public long MaxPhotoBytes { get; init; } = 8L * 1024 * 1024;
/// <summary>A photo older than this is forgotten.</summary>
public TimeSpan PhotoLifetime { get; init; } = TimeSpan.FromDays(3);
/// <summary>Long side of the photos kept (pixels).</summary>
public int PhotoLongSide { get; init; } = 160;
/// <summary>Largest photo file Febe downloads.</summary>
public long PhotoMaxDownload { get; init; } = 512 * 1024;
/// <summary>Photos downloaded at the same time.</summary>
public int PhotoConcurrency { get; init; } = 2;
/// <summary>A signed photo address waiting in the queue is dropped after this long.</summary>
public TimeSpan PhotoAddressLifetime { get; init; } = TimeSpan.FromMinutes(10);
/// <summary>Small pause between two photos of the same worker (bounds).</summary>
public TimeSpan PhotoPauseMin { get; init; } = TimeSpan.FromMilliseconds(150);
/// <summary>Upper bound of <see cref="PhotoPauseMin"/>.</summary>
public TimeSpan PhotoPauseMax { get; init; } = TimeSpan.FromMilliseconds(600);
}
@@ -0,0 +1,637 @@
using System.Text;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Engine;
using Febe.Core.Pacing;
namespace Febe.Core.Collection.Search;
/// <summary>
/// How one search step ended. <paramref name="Typed"/> is the text the answer belongs to (what Febe typed), never
/// printed; <paramref name="Denial"/> is the Governor's refusal when there was one.
/// </summary>
public sealed record SearchStepResult(SearchOutcome Outcome, string Typed, string? Message, SearchAnswer? Answer = null, Permit? Denial = null)
{
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Outcome = {Outcome}, TypedLength = {Typed.Length}, Hits = {Answer?.Hits.Count}, Denial = {Denial?.Reason}");
return true;
}
}
/// <summary>The browser half of the profile search (issue #37): one step on the site's own search box.</summary>
public interface IProfileSearchRunner
{
/// <summary>Why the search cannot run on this site (missing targets or reader), in Italian; null when it can.</summary>
string? NotConfiguredReason { get; }
/// <summary>
/// Types the wanted text into the site's search box and reads the answer. <paramref name="wanted"/> gives the
/// current wanted text (already normalized and typable), or null when it is not wanted any more: the step stops
/// between two keys. Every gesture follows a permit of the Governor.
/// </summary>
Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct);
/// <summary>Waits, briefly, for the page to be quiet before it goes back to the engine.</summary>
Task SettleAsync(CancellationToken ct);
/// <summary>The rest page (spec §6.1), unless the breaker says to leave the page as it is.</summary>
Task RestAsync(CancellationToken ct);
/// <summary>A multiplier of the waits (mood × ritmo).</summary>
double WaitMultiplier { get; }
}
/// <summary>
/// One search step on the site (issue #37, design §1.5.3): be on the site (home, under a permit), focus the box
/// (open the panel, click the box, End), type in bursts (one permit each) with the closed key map, then take the
/// answer to the request the page started last after the last key. It never clicks a result and never presses Enter.
/// </summary>
/// <remarks>
/// The answers have no echo of the text (cleaned sample 000002): while Febe types, the page may ask for the texts
/// before the last key, and their answers may arrive after the right one. So Febe notes where the page's requests
/// stand right before every key it sends (<see cref="CaptureCollector.SearchMark"/>), and only an answer to a request
/// started after the last key belongs to the text in the box. A page that answers a text again from its own memory
/// sends no request: the answer Febe read for that text on the same page is used.
/// </remarks>
public sealed class ProfileSearchRunner : IProfileSearchRunner
{
private readonly IPageDriver _driver;
private readonly ISearchInput _input;
private readonly CaptureCollector _capture;
private readonly SiteMap _siteMap;
private readonly IGovernor _governor;
private readonly IStopSignals _signals;
private readonly ICircuitBreaker _breaker;
private readonly IClock _clock;
private readonly IRandomSource _random;
private readonly PageTurns _turns;
private readonly ProfileSearchOptions _options;
private readonly Func<bool> _userIsDriving;
private readonly CollectionDiagnostics? _diagnostics;
/// <summary>Most answers remembered for one page (see <see cref="_pageAnswers"/>).</summary>
private const int MaxPageAnswers = 40;
/// <summary>What Febe typed into the box on the page of <see cref="_typedGeneration"/> (its own record; never logged).</summary>
private string _typed = string.Empty;
/// <summary>The page (<see cref="PageTurns.Generation"/>) that <see cref="_typed"/>, <see cref="_keyMark"/> and <see cref="_pageAnswers"/> belong to.</summary>
private long _typedGeneration = -1;
/// <summary>Where the page's requests stood right before the last key Febe sent on this page.</summary>
private SearchAnswerMark? _keyMark;
/// <summary>The answers read on this page, by text: the page answers a text again from its memory, without a request.</summary>
private readonly Dictionary<string, SearchAnswer> _pageAnswers = new(StringComparer.Ordinal);
public ProfileSearchRunner(
IPageDriver driver,
ISearchInput input,
CaptureCollector capture,
SiteMap siteMap,
IGovernor governor,
IStopSignals signals,
ICircuitBreaker breaker,
IClock clock,
IRandomSource random,
PageTurns turns,
ProfileSearchOptions? options = null,
Func<bool>? userIsDriving = null,
CollectionDiagnostics? diagnostics = null)
{
_driver = driver ?? throw new ArgumentNullException(nameof(driver));
_input = input ?? throw new ArgumentNullException(nameof(input));
_capture = capture ?? throw new ArgumentNullException(nameof(capture));
_siteMap = siteMap ?? throw new ArgumentNullException(nameof(siteMap));
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
_signals = signals ?? throw new ArgumentNullException(nameof(signals));
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_random = random ?? throw new ArgumentNullException(nameof(random));
_turns = turns ?? throw new ArgumentNullException(nameof(turns));
_options = options ?? ProfileSearchOptions.Default;
_userIsDriving = userIsDriving ?? (() => false);
_diagnostics = diagnostics;
}
public double WaitMultiplier => _driver.WaitMultiplier;
public string? NotConfiguredReason
{
get
{
if (!_siteMap.HasPage(SitePages.Home) || !_siteMap.IsTargetConfigured(SiteTargets.SearchOpen) || !_siteMap.IsTargetConfigured(SiteTargets.SearchBox))
{
return "Febe non sa ancora dove sta «Cerca» su questo sito: per ora vedi solo i profili che segui.";
}
return _capture.Reader.Vocabulary.Search.IsSet
? null
: "Febe non sa ancora leggere le risposte della ricerca di questo sito: per ora vedi solo i profili che segui.";
}
}
public async Task<SearchStepResult> SearchAsync(Func<string?> wanted, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(wanted);
if (wanted() is not { } first)
{
return new SearchStepResult(SearchOutcome.Interrupted, string.Empty, null);
}
if (NotConfiguredReason is { } reason)
{
return new SearchStepResult(SearchOutcome.NotConfigured, first, reason);
}
if (Stop(first) is { } stop)
{
return stop;
}
// 1. Be on the site: outside a session the page is the rest page.
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
{
var home = await OpenHomeAsync(first, ct).ConfigureAwait(false);
if (home is not null)
{
return home;
}
}
else if (_turns.Generation != _typedGeneration)
{
// A page was opened since (by the engine, between two steps): Febe's record of the box no longer holds.
ForgetPage();
}
// 2. Focus the box.
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
if (!focus.Ready)
{
var focused = await FocusBoxAsync(first, focus, ct).ConfigureAwait(false);
if (focused.Result is not null)
{
return focused.Result;
}
focus = focused.Focus;
}
// 3. Bursts of keys, then the answer.
var passes = 0;
while (true)
{
var text = wanted();
if (text is null)
{
return new SearchStepResult(SearchOutcome.Interrupted, _typed, null);
}
if (Stop(text) is { } stopped)
{
return stopped;
}
if (focus.Length != _typed.Length)
{
// The site restored a text, or Alberto typed in the box: Febe's record is reset and the box erased.
if (++passes > 3)
{
return new SearchStepResult(SearchOutcome.FocusLost, text, "Febe non riesce a scrivere nella casella «Cerca»: riprova fra poco.");
}
var unknown = focus.Length ?? 0;
var cleared = await BurstAsync(text, unknown, wanted, ct).ConfigureAwait(false);
if (cleared.Result is not null)
{
return cleared.Result;
}
focus = cleared.Focus;
continue;
}
if (!string.Equals(_typed, text, StringComparison.Ordinal))
{
var prefix = CommonPrefix(_typed, text);
var burst = await BurstAsync(text, _typed.Length - prefix, wanted, ct).ConfigureAwait(false);
if (burst.Result is not null)
{
return burst.Result;
}
focus = burst.Focus;
continue;
}
// The box holds the wanted text: read the answer.
var answer = await ReadAnswerAsync(text, wanted, ct).ConfigureAwait(false);
if (answer is not null)
{
return answer;
}
// The text changed before any answer came: next burst.
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
if (!focus.Ready)
{
return new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: riprova.");
}
}
}
public Task SettleAsync(CancellationToken ct) =>
_capture.SettleAsync(Scaled(_options.Quiet), _options.ReleaseSettle, _options.Poll, ct);
public async Task RestAsync(CancellationToken ct)
{
ForgetPage();
if (_breaker.State.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected)
{
// Left as it is, so that Alberto sees what happened (spec §7.6).
return;
}
await _driver.RestAsync(ct).ConfigureAwait(false);
}
private async Task<SearchStepResult?> OpenHomeAsync(string text, CancellationToken ct)
{
if (_userIsDriving())
{
return NotPossible(text);
}
if (await _driver.HasSessionCookieAsync(ct).ConfigureAwait(false) is false)
{
// The same stop path as the recipes: a missing session cookie is a disconnection (§7.6).
_signals.ObserveSessionCookie(false);
return new SearchStepResult(SearchOutcome.NotConnected, text, "Instagram ha chiuso la sessione di Febe: riconnetti il browser per cercare.");
}
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
{
return Denied(text, denied);
}
if (_userIsDriving())
{
return NotPossible(text);
}
PageLoad load;
try
{
load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
}
catch
{
_diagnostics?.PageOpened(null, SitePages.Home, ok: false);
throw;
}
_turns.NoteOpened(PageUser.Search);
ForgetPage();
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
if (!load.Succeeded)
{
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
}
if (Stop(text) is { } stop)
{
return stop;
}
if (!await _driver.IsOnSiteAsync(ct).ConfigureAwait(false))
{
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "Instagram ha portato il browser fuori dal sito: la ricerca si ferma.");
}
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
return Stop(text);
}
private async Task<(SearchStepResult? Result, SearchFocus Focus)> FocusBoxAsync(string text, SearchFocus focus, CancellationToken ct)
{
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
{
return (Denied(text, denied), focus);
}
if (!focus.BoxFound)
{
var open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
if (!open.Found && open.Status != TargetCheckStatus.NotConfigured)
{
// One recovery: the page may be a viewer or a list left by a recipe.
if (_userIsDriving())
{
return (NotPossible(text), focus);
}
if (await PermitAsync(ct).ConfigureAwait(false) is { } again)
{
return (Denied(text, again), focus);
}
if (await OpenHomeAfterPermitAsync(text, ct).ConfigureAwait(false) is { } failed)
{
return (failed, focus);
}
open = await ClickAsync(SiteTargets.SearchOpen, ct).ConfigureAwait(false);
}
if (!open.Found)
{
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova «Cerca» sulla pagina di Instagram."), focus);
}
_turns.NoteSearchUsedPage();
await _driver.WaitAsync(Scaled(_random.Between(_options.PanelWaitMin, _options.PanelWaitMax)), ct).ConfigureAwait(false);
if (Stop(text) is { } stop)
{
return (stop, focus);
}
}
var box = await ClickAsync(SiteTargets.SearchBox, ct).ConfigureAwait(false);
if (!box.Found)
{
return (new SearchStepResult(SearchOutcome.TargetMissing, text, "Febe non trova la casella «Cerca» sulla pagina di Instagram."), focus);
}
_turns.NoteSearchUsedPage();
// The click may put the caret anywhere in a text already there.
await _input.EndKeyAsync(ct).ConfigureAwait(false);
focus = await _input.FocusAsync(ct).ConfigureAwait(false);
return focus.Ready
? (null, focus)
: (new SearchStepResult(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non ha preso il cursore: Febe non scrive."), focus);
}
private async Task<SearchStepResult?> OpenHomeAfterPermitAsync(string text, CancellationToken ct)
{
var load = await _driver.OpenAsync(_siteMap.BuildPath(SitePages.Home), ct).ConfigureAwait(false);
_turns.NoteOpened(PageUser.Search);
ForgetPage();
_diagnostics?.PageOpened(null, SitePages.Home, load.Succeeded);
if (!load.Succeeded)
{
return new SearchStepResult(SearchOutcome.PageNotLoaded, text, "La pagina di Instagram non si è caricata: la ricerca riprova al prossimo testo.");
}
await _driver.WaitAfterLoadAsync(ct).ConfigureAwait(false);
return Stop(text);
}
/// <summary>
/// One burst under one permit: <paramref name="erase"/> Backspaces, then the letters of the wanted text while it
/// keeps extending what is typed, at most <see cref="ProfileSearchOptions.KeysPerPermit"/> keys.
/// </summary>
private async Task<(SearchStepResult? Result, SearchFocus Focus)> BurstAsync(string text, int erase, Func<string?> wanted, CancellationToken ct)
{
if (await PermitAsync(ct).ConfigureAwait(false) is { } denied)
{
return (Denied(text, denied), SearchFocus.None);
}
// The permit may have waited (spacing, the gap from the engine): the focus is looked at again right before the
// first key of the burst (§6.3).
var before = await _input.FocusAsync(ct).ConfigureAwait(false);
if (!before.Ready)
{
return (FocusLost(text), before);
}
var keys = 0;
if (erase == 0 && before.Length != _typed.Length)
{
// The box changed meanwhile: the caller erases it first.
return (null, before);
}
if (erase > 0)
{
var count = Math.Min(erase, _options.KeysPerPermit);
await _input.EraseAsync(count, NoteKey, ct).ConfigureAwait(false);
keys += count;
var after = await _input.FocusAsync(ct).ConfigureAwait(false);
if (!after.Focused || after.Length is not { } length)
{
return (FocusLost(text), after);
}
if (length == before.Length)
{
return (KeysNotReceived(text), after);
}
if (before.Length == _typed.Length && length == _typed.Length - count)
{
_typed = _typed[..length];
}
else
{
// The box held a text Febe did not type: now it holds what is left of it, unknown.
_typed = length == 0 ? string.Empty : _typed;
if (length != 0)
{
return (null, after);
}
}
if (erase > count || keys >= _options.KeysPerPermit)
{
return (null, after);
}
}
var startLength = _typed.Length;
var lost = false;
var typed = await _input.TypeAsync(
async (index, token) =>
{
var current = wanted();
if (current is null || keys >= _options.KeysPerPermit || current.Length <= _typed.Length || !current.StartsWith(_typed, StringComparison.Ordinal))
{
// Not wanted any more, done, at the end of the burst, or an erase is needed: the burst ends.
return null;
}
if (index > 0 && index % _options.FocusCheckEvery == 0)
{
var check = await _input.FocusAsync(token).ConfigureAwait(false);
if (!check.Ready || check.Length != _typed.Length)
{
lost = true;
return null;
}
}
var c = current[_typed.Length];
NoteKey();
_typed += c;
keys++;
return c;
},
ct).ConfigureAwait(false);
var focus = await _input.FocusAsync(ct).ConfigureAwait(false);
if (typed > 0 && focus.Focused && focus.Length == startLength)
{
// Not one key reached the box (seen at the end or at a focus check in between).
_typed = _typed[..startLength];
return (KeysNotReceived(text), focus);
}
if (lost || !focus.Focused || focus.Length is null)
{
return (FocusLost(text), focus);
}
return (null, focus);
}
/// <summary>
/// The answer to the text in the box: an answer to a request the page started after the last key, or, when the
/// page sends no request for a text it already answered on this page, the answer Febe read then. Null when the text
/// changed before any answer came.
/// </summary>
private async Task<SearchStepResult?> ReadAnswerAsync(string text, Func<string?> wanted, CancellationToken ct)
{
var mark = _keyMark ?? _capture.SearchMark();
var start = _clock.Now;
var least = start + Scaled(_options.MinAnswerWait);
var deadline = start + _options.AnswerTimeout;
var quiet = Scaled(_options.Quiet);
while (true)
{
if (Stop(text) is { } stop)
{
return stop;
}
var answers = _capture.SearchSince(mark);
var now = _clock.Now;
var current = wanted();
if (!string.Equals(current, text, StringComparison.Ordinal))
{
// Alberto kept typing: an answer already here is for this text and is kept, otherwise the next burst
// starts at once.
return answers.Count > 0 ? Answered(text, answers) : null;
}
var settled = _capture.Pending == 0 && (_capture.LastArrivalAt is not { } last || now - last >= quiet);
if (answers.Count > 0 && (answers[^1].Response.RequestOrder > 0 || (now >= least && settled)))
{
// A request started after the last key is for this text: no need to wait more. Without the order of
// the requests (an older browser event stream), the page must be quiet first.
return Answered(text, answers);
}
if (answers.Count == 0 && now >= least && settled && _pageAnswers.TryGetValue(text, out var remembered))
{
// The page answered this text from its memory: no request, the results Febe read before on this page.
return Result(text, remembered);
}
if (now >= deadline)
{
return answers.Count > 0
? Answered(text, answers)
: _pageAnswers.TryGetValue(text, out var late)
? Result(text, late)
: new SearchStepResult(SearchOutcome.NoAnswer, text, "Instagram non ha mandato risultati per questo testo: scrivi un'altra lettera o riprova.");
}
await _clock.Delay(_options.Poll, ct).ConfigureAwait(false);
}
}
private SearchStepResult Answered(string text, IReadOnlyList<CapturedRead> answers)
{
// The answer to the request started last (SearchSince orders them): earlier ones may belong to a text the page
// asked for while Febe was still typing.
var answer = answers[^1].Result.Search!;
if (!_pageAnswers.ContainsKey(text) && _pageAnswers.Count >= MaxPageAnswers)
{
_pageAnswers.Clear();
}
_pageAnswers[text] = answer;
return Result(text, answer);
}
private static SearchStepResult Result(string text, SearchAnswer answer) =>
answer.Hits.Count == 0
? new SearchStepResult(SearchOutcome.Empty, text, "Nessun profilo trovato su Instagram.", answer)
: new SearchStepResult(SearchOutcome.Ready, text, null, answer);
/// <summary>Right before a key: from here on, the page's requests are for the text with this key.</summary>
private void NoteKey() => _keyMark = _capture.SearchMark();
/// <summary>A new page (opened, rested, or opened by the engine): nothing Febe knew of the box holds.</summary>
private void ForgetPage()
{
_typed = string.Empty;
_keyMark = null;
_pageAnswers.Clear();
_typedGeneration = _turns.Generation;
}
private async Task<TargetCheck> ClickAsync(string target, CancellationToken ct)
{
var check = await _driver.ClickAsync(target, null, ct).ConfigureAwait(false);
_diagnostics?.TargetClicked(null, target, check.Status);
return check;
}
/// <summary>A permit of the Governor for one search action; the refusal when denied.</summary>
private async Task<Permit?> PermitAsync(CancellationToken ct)
{
var permit = await _governor.RequestAsync(ActionKind.ProfileSearch, null, ct).ConfigureAwait(false);
return permit.Granted ? null : permit;
}
private SearchStepResult? Stop(string text)
{
var state = _breaker.State;
if (!state.AllowsSiteActions)
{
return new SearchStepResult(SearchOutcome.Stopped, text, Governor.BreakerMessage(state, _clock.Now, _clock.LocalZone));
}
return _userIsDriving() ? NotPossible(text) : null;
}
private static SearchStepResult Denied(string text, Permit permit) => new(SearchOutcome.Denied, text, permit.Message, Denial: permit);
private static SearchStepResult NotPossible(string text) =>
new(SearchOutcome.NotPossible, text, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
private static SearchStepResult FocusLost(string text) =>
new(SearchOutcome.FocusLost, text, "La casella «Cerca» di Instagram non è più attiva: Febe smette di scrivere.");
private static SearchStepResult KeysNotReceived(string text) =>
new(SearchOutcome.KeysNotReceived, text, "Il browser di Febe non riceve i tasti: la ricerca su Instagram non funziona su questo computer.");
private TimeSpan Scaled(TimeSpan value) => value * Math.Max(0.1, _driver.WaitMultiplier);
private static int CommonPrefix(string a, string b)
{
var n = Math.Min(a.Length, b.Length);
var i = 0;
while (i < n && a[i] == b[i])
{
i++;
}
return i;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,128 @@
using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace Febe.Core.Collection.Search;
/// <summary>What the profile search is doing for the wanted text (issue #37). The interface shows it in Italian.</summary>
public enum SearchState
{
/// <summary>Nothing wanted (empty box, dialog closed).</summary>
Idle,
/// <summary>The text is not one Febe types on the site (several names, too short, other characters): local suggestions only.</summary>
LocalOnly,
/// <summary>Waiting for the page: a collection step holds it, or the search spacing.</summary>
Waiting,
/// <summary>Febe is typing on the site or waiting for its answer.</summary>
Searching,
/// <summary>The site answered with profiles.</summary>
Ready,
/// <summary>The site answered with no profile.</summary>
Empty,
/// <summary>No answer of the site came for this text (it may have answered from its own memory).</summary>
NoAnswer,
/// <summary>Alberto is using Febe's browser: the search on the site waits.</summary>
NotPossible,
/// <summary>Outside the active window Febe does not open the site.</summary>
OutsideWindow,
/// <summary>The breaker is open (spec §7.6), or the search's own budget is used up.</summary>
Stopped,
/// <summary>The browser or the engine is not up.</summary>
Unavailable,
/// <summary>The map of the site lacks the search targets, or the readers lack the search answer (H11).</summary>
NotConfigured,
/// <summary>The text holds a character Febe never types (a control character).</summary>
Refused,
/// <summary>A step went wrong; the next text tries again.</summary>
Failed,
}
/// <summary>Closed list of how one search step ended: diagnostics count these names, never a text (issue #37).</summary>
public enum SearchOutcome
{
Ready,
Empty,
NoAnswer,
Cached,
Refused,
Stopped,
NotConfigured,
NotConnected,
OutsideWindow,
TargetMissing,
FocusLost,
KeysNotReceived,
PageNotLoaded,
BrowserNotResponding,
Interrupted,
NotPossible,
Denied,
}
/// <summary>
/// One profile the search found or knows. Never printed with its values: the record prints only counts and flags.
/// </summary>
/// <param name="Position">Order in the site's answer, from 0.</param>
/// <param name="InstagramId">The site's identifier of the profile.</param>
/// <param name="Username">User name, lowercase.</param>
/// <param name="DisplayName">Full name, when the site gives one.</param>
/// <param name="IsVerified">Verified mark, when the site says.</param>
/// <param name="PhotoKey">Key of the photo in Febe's memory cache (32 hex characters), when it is there.</param>
/// <param name="PhotoReady">True once the photo is in the cache.</param>
public sealed record SearchHit(int Position, string InstagramId, string Username, string? DisplayName, bool? IsVerified, string? PhotoKey, bool PhotoReady)
{
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Position = {Position}, HasDisplayName = {DisplayName is not null}, IsVerified = {IsVerified}, PhotoReady = {PhotoReady}");
return true;
}
}
/// <summary>
/// What the search shows now. <paramref name="Owner"/> is the random id of the window that wrote the text last;
/// <paramref name="Text"/> is the text Febe typed (or would type), as the interface labels results «per "testo"».
/// </summary>
public sealed record SearchView(long Version, string Owner, string Text, SearchState State, string? Message, IReadOnlyList<SearchHit> Hits, DateTimeOffset? RetryAfter)
{
public static SearchView Initial { get; } = new(0, string.Empty, string.Empty, SearchState.Idle, null, [], null);
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Version = {Version}, State = {State}, Hits = {Hits.Count}, TextLength = {Text.Length}");
return true;
}
}
/// <summary>
/// The profile search as the interface sees it (issue #37): one wanted text at a time (the last window that writes
/// wins), the latest view for polling, and the photos of the results from Febe's memory.
/// </summary>
public interface IProfileSearch
{
/// <summary>Sets the wanted text of window <paramref name="client"/> and returns at once.</summary>
SearchView Update(string client, string text);
/// <summary>The latest view.</summary>
SearchView Current { get; }
/// <summary>The dialog of window <paramref name="client"/> closed; ignored when another window wrote last.</summary>
void End(string client);
/// <summary>The last result seen with this user name (for adding it with its identifier), server side only.</summary>
SearchHit? Known(string username);
/// <summary>A photo of the memory cache by its key.</summary>
bool TryOpenPhoto(string key, [NotNullWhen(true)] out Stream? stream);
}
@@ -0,0 +1,184 @@
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using Febe.Core.Abstractions;
namespace Febe.Core.Collection.Search;
/// <summary>
/// The photos of the search results, in memory only (issue #37): no file on disk reveals whom Alberto searched for and
/// nothing survives a restart. Bounded by count and bytes (least recently used goes first), entries expire, and every
/// photo has a random key of 32 hex characters that says nothing about the profile.
/// </summary>
/// <remarks>Not the library: rule 11 (the library never deletes files by itself) is not touched.</remarks>
public sealed class SearchPhotoCache
{
private readonly Lock _gate = new();
private readonly IClock _clock;
private readonly ProfileSearchOptions _options;
private readonly Dictionary<string, LinkedListNode<Entry>> _byKey = new(StringComparer.Ordinal);
private readonly Dictionary<string, LinkedListNode<Entry>> _byProfile = new(StringComparer.Ordinal);
private readonly LinkedList<Entry> _lru = new();
private long _bytes;
public SearchPhotoCache(IClock clock, ProfileSearchOptions? options = null)
{
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_options = options ?? ProfileSearchOptions.Default;
}
/// <summary>Photos in memory.</summary>
public int Count
{
get
{
lock (_gate)
{
return _byKey.Count;
}
}
}
/// <summary>Bytes in memory.</summary>
public long Bytes
{
get
{
lock (_gate)
{
return _bytes;
}
}
}
/// <summary>A short hash of the file name of a photo address (the signature in the query is left out).</summary>
public static string FileHash(Uri address)
{
ArgumentNullException.ThrowIfNull(address);
var name = address.AbsolutePath;
var slash = name.LastIndexOf('/');
name = slash >= 0 ? name[(slash + 1)..] : name;
return Convert.ToHexStringLower(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(name)))[..16];
}
/// <summary>The key of the photo of this profile, when it is in memory (any picture).</summary>
public string? KeyOf(string instagramId)
{
ArgumentNullException.ThrowIfNull(instagramId);
lock (_gate)
{
DropExpiredLocked();
return _byProfile.TryGetValue(instagramId, out var node) ? node.Value.Key : null;
}
}
/// <summary>True when this very picture (same file name) of the profile is already in memory.</summary>
public bool Has(string instagramId, string fileHash)
{
lock (_gate)
{
DropExpiredLocked();
return _byProfile.TryGetValue(instagramId, out var node) && node.Value.FileHash == fileHash;
}
}
/// <summary>Keeps a photo (already a small JPEG); a new picture of the same profile replaces the old one.</summary>
/// <returns>The key of the photo.</returns>
public string Put(string instagramId, string fileHash, byte[] jpeg)
{
ArgumentNullException.ThrowIfNull(instagramId);
ArgumentNullException.ThrowIfNull(fileHash);
ArgumentNullException.ThrowIfNull(jpeg);
lock (_gate)
{
if (_byProfile.TryGetValue(instagramId, out var old))
{
RemoveLocked(old);
}
var key = Convert.ToHexStringLower(RandomNumberGenerator.GetBytes(16));
var node = _lru.AddFirst(new Entry(key, instagramId, fileHash, jpeg, _clock.Now));
_byKey[key] = node;
_byProfile[instagramId] = node;
_bytes += jpeg.Length;
while ((_byKey.Count > _options.MaxPhotos || _bytes > _options.MaxPhotoBytes) && _lru.Last is { } last && !ReferenceEquals(last, node))
{
RemoveLocked(last);
}
return key;
}
}
/// <summary>A photo by its key, as a read-only stream.</summary>
public bool TryOpen(string key, [NotNullWhen(true)] out Stream? stream)
{
stream = null;
if (string.IsNullOrEmpty(key))
{
return false;
}
lock (_gate)
{
DropExpiredLocked();
if (!_byKey.TryGetValue(key, out var node))
{
return false;
}
_lru.Remove(node);
_lru.AddFirst(node);
stream = new MemoryStream(node.Value.Jpeg, writable: false);
return true;
}
}
/// <summary>Forgets every photo (disconnection, «Scollega», the dialog forgotten).</summary>
public void Clear()
{
lock (_gate)
{
_byKey.Clear();
_byProfile.Clear();
_lru.Clear();
_bytes = 0;
}
}
private void DropExpiredLocked()
{
var limit = _clock.Now - _options.PhotoLifetime;
var node = _lru.Last;
while (node is not null)
{
var previous = node.Previous;
if (node.Value.At < limit)
{
RemoveLocked(node);
}
node = previous;
}
}
private void RemoveLocked(LinkedListNode<Entry> node)
{
_lru.Remove(node);
_byKey.Remove(node.Value.Key);
if (_byProfile.TryGetValue(node.Value.InstagramId, out var current) && ReferenceEquals(current, node))
{
_byProfile.Remove(node.Value.InstagramId);
}
_bytes -= node.Value.Jpeg.Length;
}
private sealed record Entry(string Key, string InstagramId, string FileHash, byte[] Jpeg, DateTimeOffset At)
{
private bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append($"Bytes = {Jpeg.Length}");
return true;
}
}
}
@@ -0,0 +1,290 @@
using Febe.Core.Abstractions;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Pacing;
namespace Febe.Core.Collection.Search;
/// <summary>A photo to fetch: the profile and its picture (the signed address stays in memory, never logged).</summary>
public sealed record SearchPhotoRequest(string InstagramId, Uri Address)
{
private bool PrintMembers(System.Text.StringBuilder builder)
{
builder.Append("Photo");
return true;
}
}
/// <summary>
/// Fetches the photos of the search results (issue #37, design §3) from the CDN through the browser's file fetcher,
/// two at a time with small random pauses, and keeps them small in <see cref="SearchPhotoCache"/>. Each photo asks the
/// Governor for a <see cref="ActionKind.DataDownload"/> permit and counts its bytes in the daily data budget; a CDN
/// status that is a stop signal (§7.6) goes to the signal detector, as the download queue does, and empties the queue.
/// It works only while the breaker allows site actions and the page is on the site.
/// </summary>
public sealed class SearchPhotoQueue : IAsyncDisposable
{
private readonly Lock _gate = new();
private readonly SearchPhotoCache _cache;
private readonly IFileFetcher _fetcher;
private readonly IGovernor _governor;
private readonly IDataBudget _budget;
private readonly ICircuitBreaker _breaker;
private readonly SignalDetector? _signals;
private readonly IClock _clock;
private readonly IRandomSource _random;
private readonly ProfileSearchOptions _options;
private readonly Func<bool> _onSite;
private readonly LinkedList<(SearchPhotoRequest Request, DateTimeOffset At)> _queue = new();
private readonly HashSet<string> _queued = new(StringComparer.Ordinal);
private readonly CancellationTokenSource _lifetime = new();
private readonly List<Task> _workers = [];
private int _running;
private long _generation;
public SearchPhotoQueue(
SearchPhotoCache cache,
IFileFetcher fetcher,
IGovernor governor,
IDataBudget budget,
ICircuitBreaker breaker,
IClock clock,
IRandomSource random,
ProfileSearchOptions? options = null,
SignalDetector? signals = null,
Func<bool>? onSite = null)
{
_cache = cache ?? throw new ArgumentNullException(nameof(cache));
_fetcher = fetcher ?? throw new ArgumentNullException(nameof(fetcher));
_governor = governor ?? throw new ArgumentNullException(nameof(governor));
_budget = budget ?? throw new ArgumentNullException(nameof(budget));
_breaker = breaker ?? throw new ArgumentNullException(nameof(breaker));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_random = random ?? throw new ArgumentNullException(nameof(random));
_options = options ?? ProfileSearchOptions.Default;
_signals = signals;
_onSite = onSite ?? (() => true);
}
/// <summary>A photo landed in the cache: the profile and the key.</summary>
public event Action<string, string>? PhotoReady;
/// <summary>What happened to a photo («scaricata», «rifiutata», «saltata»): for the diagnostic report.</summary>
public event Action<string>? Settled;
/// <summary>The recorder of the diagnostic report. Null: nothing is recorded.</summary>
public CollectionDiagnostics? Diagnostics { get; init; }
/// <summary>Photos waiting.</summary>
public int Waiting
{
get
{
lock (_gate)
{
return _queue.Count;
}
}
}
/// <summary>Adds the photos of an answer; those already in memory with the same file name are skipped.</summary>
public void Enqueue(IEnumerable<SearchPhotoRequest> photos)
{
ArgumentNullException.ThrowIfNull(photos);
var now = _clock.Now;
lock (_gate)
{
if (_lifetime.IsCancellationRequested)
{
return;
}
foreach (var photo in photos)
{
if (_cache.Has(photo.InstagramId, SearchPhotoCache.FileHash(photo.Address)) || !_queued.Add(photo.InstagramId))
{
continue;
}
_queue.AddLast((photo, now));
}
while (_running < _options.PhotoConcurrency && _queue.Count > _running)
{
_running++;
_workers.RemoveAll(t => t.IsCompleted);
_workers.Add(Task.Run(() => WorkAsync(_lifetime.Token)));
}
}
}
/// <summary>Drops every photo waiting (rest page, stop signal, «Scollega»); one being fetched is not kept.</summary>
public void Clear()
{
lock (_gate)
{
_queue.Clear();
_queued.Clear();
_generation++;
}
}
public async ValueTask DisposeAsync()
{
Task[] workers;
lock (_gate)
{
_queue.Clear();
_queued.Clear();
workers = [.. _workers];
}
await _lifetime.CancelAsync().ConfigureAwait(false);
try
{
await Task.WhenAll(workers).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Stopping.
}
_lifetime.Dispose();
}
private async Task WorkAsync(CancellationToken ct)
{
var counted = true;
try
{
while (!ct.IsCancellationRequested)
{
SearchPhotoRequest request;
long generation;
lock (_gate)
{
if (_queue.First is not { } first)
{
_running--;
counted = false;
return;
}
_queue.RemoveFirst();
request = first.Value.Request;
generation = _generation;
if (_clock.Now - first.Value.At > _options.PhotoAddressLifetime)
{
_queued.Remove(request.InstagramId);
Report("saltata");
continue;
}
}
try
{
await FetchAsync(request, generation, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
// An optional photo: the initials stay. Only the type would be worth noting, and it is not text.
Report("rifiutata");
}
finally
{
lock (_gate)
{
_queued.Remove(request.InstagramId);
}
}
await _clock.Delay(_random.Between(_options.PhotoPauseMin, _options.PhotoPauseMax), ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Stopping.
}
finally
{
if (counted)
{
lock (_gate)
{
_running = Math.Max(0, _running - 1);
}
}
}
}
private async Task FetchAsync(SearchPhotoRequest request, long generation, CancellationToken ct)
{
if (!_breaker.State.AllowsSiteActions || !_onSite())
{
Clear();
Report("saltata");
return;
}
var permit = await _governor.RequestAsync(ActionKind.DataDownload, null, ct).ConfigureAwait(false);
if (!permit.Granted)
{
// The daily data budget is used up: the initials stay.
Clear();
Report("saltata");
return;
}
using var buffer = new MemoryStream();
var result = await _fetcher.FetchAsync(request.Address, buffer, new FetchOptions(MaxBytes: _options.PhotoMaxDownload), ct).ConfigureAwait(false);
if (result.BudgetBytes > 0)
{
await _budget.RecordAsync(result.BudgetBytes, null, ct).ConfigureAwait(false);
}
if (!result.Succeeded)
{
if (result.HttpStatus is { } status && _signals?.ObserveDownload(request.Address, status) is not null)
{
// A stop signal of the CDN (e.g. 429): no more photos.
Clear();
}
Report("rifiutata");
return;
}
buffer.Position = 0;
var jpeg = ThumbnailStore.EncodeSmallJpeg(buffer, _options.PhotoLongSide);
if (jpeg is null)
{
Report("rifiutata");
return;
}
lock (_gate)
{
if (generation != _generation)
{
// Cleared meanwhile (rest page, stop): the photo is not kept.
Report("saltata");
return;
}
}
var key = _cache.Put(request.InstagramId, SearchPhotoCache.FileHash(request.Address), jpeg);
Report("scaricata");
PhotoReady?.Invoke(request.InstagramId, key);
}
private void Report(string outcome)
{
Diagnostics?.SearchPhotoSettled(outcome);
Settled?.Invoke(outcome);
}
}
@@ -0,0 +1,160 @@
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace Febe.Core.Collection.Search;
/// <summary>What the normalized text of the search box is good for.</summary>
public enum SearchQueryKind
{
/// <summary>Nothing to search.</summary>
Empty,
/// <summary>Febe may type it into the site's search box.</summary>
Typable,
/// <summary>Several names or addresses: they go to the list, Febe does not search them on the site.</summary>
SeveralNames,
/// <summary>A character Febe never types (a control character other than a line break).</summary>
Refused,
/// <summary>Too short, too long, or other characters: local suggestions only.</summary>
LocalOnly,
}
/// <summary>The search text after <see cref="SearchText.Normalize"/>. Never printed with the text.</summary>
/// <param name="Kind">What it is good for.</param>
/// <param name="Typed">The text Febe types (lowercase, no accents, single spaces); empty unless <see cref="SearchQueryKind.Typable"/>.</param>
/// <param name="Shown">The cleaned text, for the local suggestions and the label of the results.</param>
public sealed record SearchQuery(SearchQueryKind Kind, string Typed, string Shown)
{
private bool PrintMembers(StringBuilder builder)
{
builder.Append($"Kind = {Kind}, Length = {Typed.Length}");
return true;
}
}
/// <summary>
/// The rules of what the profile search may type (issue #37), decided here in Core and not in the interface: a line
/// break, a tab or any control character is never typed (so nothing can ever press Enter on the site); several names
/// stay local; a profile address becomes its user name; accents are removed; only letters, digits, «.», «_» and single
/// spaces are typed, from 2 to 40 characters.
/// </summary>
public static partial class SearchText
{
/// <summary>Longest text the interface may send (characters, before cleaning).</summary>
public const int MaxRawLength = 60;
/// <summary>Shortest text Febe types on the site.</summary>
public const int MinTyped = 2;
/// <summary>Longest text Febe types on the site.</summary>
public const int MaxTyped = 40;
/// <summary>First path segments of Instagram that are pages, not profiles.</summary>
private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
{
"p", "reel", "reels", "tv", "stories", "explore", "accounts", "direct", "about", "legal", "developer", "web", "challenge", "emails", "session",
};
public static SearchQuery Normalize(string? raw)
{
if (string.IsNullOrEmpty(raw))
{
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
}
// 1. Control characters: a line break means several names, any other is refused. Never typed.
foreach (var c in raw)
{
if (c is '\r' or '\n')
{
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, string.Empty);
}
if (char.IsControl(c) || char.GetUnicodeCategory(c) is UnicodeCategory.Format or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator)
{
return new SearchQuery(SearchQueryKind.Refused, string.Empty, string.Empty);
}
}
// 2. Trim and single spaces.
var text = Spaces().Replace(raw.Trim(), " ");
if (text.Length == 0)
{
return new SearchQuery(SearchQueryKind.Empty, string.Empty, string.Empty);
}
// 4. Several names: only an explicit separator or more than one profile address.
if (text.Contains(',', StringComparison.Ordinal) || text.Contains(';', StringComparison.Ordinal) || Addresses().Count(text) > 1)
{
return new SearchQuery(SearchQueryKind.SeveralNames, string.Empty, text);
}
// 3. A profile address becomes its user name; a leading @ goes.
if (text.Contains("instagram.com", StringComparison.OrdinalIgnoreCase))
{
if (ProfileName(text) is not { } name)
{
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, text);
}
text = name;
}
text = text.TrimStart('@').Trim();
// 5. Lowercase, letters with diacritics folded to their base letter.
var typed = Fold(text.ToLowerInvariant());
var shown = text;
// 6. Only the closed set of characters, 2 to 40 of them.
if (typed.Length < MinTyped || typed.Length > MaxTyped || !Typable().IsMatch(typed))
{
return new SearchQuery(SearchQueryKind.LocalOnly, string.Empty, shown);
}
return new SearchQuery(SearchQueryKind.Typable, typed, shown);
}
/// <summary>Lowercase text without diacritics, for comparing names (local suggestions use the same rule).</summary>
public static string Fold(string text)
{
ArgumentNullException.ThrowIfNull(text);
var decomposed = text.Normalize(NormalizationForm.FormD);
var builder = new StringBuilder(decomposed.Length);
foreach (var c in decomposed)
{
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
{
builder.Append(c);
}
}
return builder.ToString().Normalize(NormalizationForm.FormC);
}
private static string? ProfileName(string text)
{
var address = text.Contains("://", StringComparison.Ordinal) ? text : "https://" + text;
if (!Uri.TryCreate(address, UriKind.Absolute, out var uri)
|| !(uri.Host.Equals("instagram.com", StringComparison.OrdinalIgnoreCase) || uri.Host.EndsWith(".instagram.com", StringComparison.OrdinalIgnoreCase)))
{
return null;
}
var segments = uri.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries);
return segments.Length == 0 || Reserved.Contains(segments[0]) ? null : Uri.UnescapeDataString(segments[0]);
}
[GeneratedRegex(@"\s+", RegexOptions.CultureInvariant)]
private static partial Regex Spaces();
[GeneratedRegex("instagram\\.com/", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)]
private static partial Regex Addresses();
[GeneratedRegex("^[a-z0-9._]+( [a-z0-9._]+)*$", RegexOptions.CultureInvariant)]
private static partial Regex Typable();
}
+7 -1
View File
@@ -72,8 +72,14 @@ public static class SiteTargets
/// <summary>The command that closes the viewer.</summary>
public const string ViewerClose = "viewer-close";
/// <summary>The command that opens the site's search panel («Cerca» in the side column; issue #37).</summary>
public const string SearchOpen = "search-open";
/// <summary>The search box of that panel, where the profile search types (issue #37).</summary>
public const string SearchBox = "search-box";
public static IReadOnlyList<string> All { get; } =
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose];
[HomeStory, ProfileStoryRing, ProfileNotFound, ProfileTabPosts, ProfileTabReels, ProfileTabTagged, ProfileHighlight, ViewerNext, ViewerClose, SearchOpen, SearchBox];
}
/// <summary>
+3 -1
View File
@@ -22,6 +22,8 @@
"profile-tab-tagged": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Scheda dei post in cui l'account è taggato." },
"profile-highlight": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Una raccolta in evidenza ({id})." },
"viewer-next": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Zona o comando per andare alla storia successiva." },
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." }
"viewer-close": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Comando per chiudere il visualizzatore." },
"search-open": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "Il comando «Cerca» della colonna laterale, che apre il pannello di ricerca (ricerca dei profili, issue #37)." },
"search-box": { "role": "", "name": "", "href": "", "hypothesis": "H11", "note": "La casella del pannello «Cerca», dove la ricerca dei profili scrive. Mai cliccare un risultato." }
}
}
+3 -1
View File
@@ -22,6 +22,8 @@
"profile-tab-tagged": { "role": "tab", "name": "^taggati$" },
"profile-highlight": { "role": "link", "href": "/evidenza/{id}/" },
"viewer-next": { "role": "button", "name": "^storia successiva$" },
"viewer-close": { "role": "button", "name": "^chiudi$" }
"viewer-close": { "role": "button", "name": "^chiudi$" },
"search-open": { "role": "button", "name": "^cerca$", "note": "Il comando «Cerca» della colonna laterale: apre il pannello di ricerca." },
"search-box": { "role": "searchbox", "name": "^cerca$", "note": "La casella del pannello di ricerca, dove la ricerca dei profili scrive." }
}
}
@@ -48,6 +48,18 @@
"hasMore": ["has_next_page", "more_available"],
"cursor": ["end_cursor"]
},
"search": {
"note": "Risposta della casella di ricerca (PolarisSearchBoxRefetchableQuery, campione ricerca-profili): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
"items": ["users"],
"position": ["position"],
"profile": ["user"],
"id": ["pk", "id"],
"username": ["username"],
"displayName": ["full_name"],
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
"verified": ["is_verified"]
},
"relevance": {
"note": "Una risposta che non contiene nessuna di queste chiavi non parla di contenuti né di profili e si ignora: promozioni, registri, il segno «storia vista», le definizioni delle pagine. Senza questo elenco ognuna conterebbe come «formato non riconosciuto».",
"keys": ["image_versions2", "video_versions", "carousel_media", "taken_at", "username"]
+12
View File
@@ -44,5 +44,17 @@
"hasMore": ["altro"],
"cursor": ["dopo"]
},
"search": {
"note": "La casella di ricerca del sito di prova risponde nella forma del campione ripulito di Instagram (ricerca-profili, PolarisSearchBoxRefetchableQuery), eccezione voluta alla regola «formato nostro, chiavi italiane» (tools/Febe.SitoDiProva/LEGGIMI.md): xdt_api__v1__fbsearch__topsearch_connection con users[] { position, user }. Niente is_private né friendship_status: «Privato» e «Seguito» vengono solo dai dati di Febe. Hashtag e luoghi si ignorano. Non si leggono mai search_social_context (nomi di chi segui in comune), rank_token, ai_agent_owner_username, attribution_label_text. La foto piccola viene prima: basta per un suggerimento.",
"root": ["xdt_api__v1__fbsearch__topsearch_connection"],
"items": ["users"],
"position": ["position"],
"profile": ["user"],
"id": ["pk", "id"],
"username": ["username"],
"displayName": ["full_name"],
"picture": ["profile_pic_url", "hd_profile_pic_url_info"],
"verified": ["is_verified"]
},
"viewer": ["io"]
}
+3
View File
@@ -66,6 +66,7 @@ public sealed record CautionProfile
[ActionKind.BackfillPage] = new(20, 100),
[ActionKind.SinglePost] = new(10, 60),
[ActionKind.FollowingListPage] = new(15, 60),
[ActionKind.ProfileSearch] = new(240, 1200),
},
DataPerDayBytes = 4 * GB,
BackfillPostsPerAccountPerDay = 300,
@@ -90,6 +91,7 @@ public sealed record CautionProfile
[ActionKind.BackfillPage] = new(30, 180),
[ActionKind.SinglePost] = new(15, 100),
[ActionKind.FollowingListPage] = new(20, 90),
[ActionKind.ProfileSearch] = new(300, 1500),
},
DataPerDayBytes = 8 * GB,
BackfillPostsPerAccountPerDay = 500,
@@ -114,6 +116,7 @@ public sealed record CautionProfile
[ActionKind.BackfillPage] = new(45, 300),
[ActionKind.SinglePost] = new(20, 160),
[ActionKind.FollowingListPage] = new(30, 150),
[ActionKind.ProfileSearch] = new(360, 1800),
},
DataPerDayBytes = 16 * GB,
BackfillPostsPerAccountPerDay = 800,
+36 -12
View File
@@ -724,22 +724,34 @@ public sealed class EngineHost : IAsyncDisposable
// using the browser (spec §6.1, §7.6).
var breaker = s.Breaker.State;
var keepPage = breaker.Status is BreakerStatus.Challenge or BreakerStatus.Disconnected || s.Runtime.UserIsDriving;
if (!keepPage)
{
// This rest also serves a driving period that ended during the session.
Interlocked.Exchange(ref _restAfterDriving, 0);
try
// The rest takes the page turn (issue #37). When the profile search holds or waits for the page, the rest is
// left to it (PageTurns.RestOwed): it rests the page when it is done, no session running.
var turn = await s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
if (turn is not null)
{
await _runner.RestAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeFailed,
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
sessionId: record.Id,
ct: ct).ConfigureAwait(false);
await using (turn.ConfigureAwait(false))
{
try
{
await _runner.RestAsync(ct).ConfigureAwait(false);
s.PageTurns.NoteRested();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
await s.Events.WriteAsync(
EventSeverity.Warning,
EngineEventCodes.RecipeFailed,
$"Non sono riuscito a portare il browser sulla pagina vuota ({ex.GetType().Name}).",
sessionId: record.Id,
ct: ct).ConfigureAwait(false);
}
}
}
}
@@ -799,7 +811,19 @@ public sealed class EngineHost : IAsyncDisposable
try
{
await _runner.RestAsync(ct).ConfigureAwait(false);
// With the page turn (issue #37): a search step in progress is never cut by the rest. When the search holds
// or waits for the page, the rest is left to it.
var turn = await _s.PageTurns.TakeForRestAsync(ct).ConfigureAwait(false);
if (turn is null)
{
return;
}
await using (turn.ConfigureAwait(false))
{
await _runner.RestAsync(ct).ConfigureAwait(false);
_s.PageTurns.NoteRested();
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
+6
View File
@@ -27,6 +27,12 @@ public sealed record EngineOptions
/// <summary>Minimum distance between two counted actions at the «naturale» gesture pace (spec §7.2); scaled by the pace.</summary>
public TimeSpan MinimumSpacing { get; init; } = TimeSpan.FromSeconds(4);
/// <summary>
/// Minimum distance between two profile-search steps, and between a search step and an engine action in either
/// direction, at the «naturale» pace (issue #37); scaled by the pace. A pace, not a refusal.
/// </summary>
public TimeSpan SearchSpacing { get; init; } = TimeSpan.FromSeconds(1.2);
/// <summary>The first session starts 2–10 minutes after the program (spec §7.2).</summary>
public TimeSpan StartupDelayMin { get; init; } = TimeSpan.FromMinutes(2);
+3
View File
@@ -65,6 +65,9 @@ public sealed class EngineServices
/// <summary>Current engine and caution settings.</summary>
public EngineSettings Settings { get; private set; }
/// <summary>The turns of the one browser page, shared by the recipes and the profile search (issue #37).</summary>
public PageTurns PageTurns { get; } = new();
/// <summary>
/// The recorder of the diagnostic report (issue #39): told when sessions start and end, and why. Null: nothing is
/// recorded. Set by the composition before the engine starts.
+109 -8
View File
@@ -15,6 +15,9 @@ namespace Febe.Core.Engine;
/// <remarks>
/// <para>The minimum spacing is a pace, not a refusal: <see cref="RequestAsync"/> waits for it (on <see cref="IClock"/>)
/// and then grants; <see cref="EvaluateAsync"/> reports it as <see cref="DenialReason.MinimumSpacing"/>.</para>
/// <para>The profile search (<see cref="ActionKind.ProfileSearch"/>, issue #37) has its own branch: no session is needed,
/// it has its own gate, budget and spacing, and it keeps a short crossing gap from the engine's actions both ways; the
/// breaker, Alberto at the browser, the pause and the active window stop it as they stop the engine.</para>
/// <para>CDN downloads are not site actions: <see cref="ActionKind.DataDownload"/> only checks the daily byte budget, also
/// during a stop (spec §7.6: queued downloads may complete), and bytes are recorded with <see cref="RecordAsync"/>.</para>
/// </remarks>
@@ -30,6 +33,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
private readonly EngineOptions _options;
private readonly EngineEvents? _events;
private readonly SemaphoreSlim _gate = new(1, 1);
private readonly SemaphoreSlim _searchGate = new(1, 1);
private readonly Lock _noticeGate = new();
private readonly HashSet<(ActionKind, DateOnly)> _dailyNoticesSent = [];
@@ -60,6 +64,9 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
/// <summary>Minimum distance between two counted actions at the current gesture pace.</summary>
public TimeSpan MinimumSpacing => _options.MinimumSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
/// <summary>Distance between two search steps, and between a search step and an engine action, at the current pace.</summary>
public TimeSpan SearchSpacing => _options.SearchSpacing * GesturePaceFactors.For(_runtime.Profile.Pace);
/// <summary>Budgets in force at <paramref name="now"/>: profile, gradual start and halved budgets, strongest reduction.</summary>
public EffectiveBudgets GetEffectiveBudgets(DateTimeOffset now) =>
BudgetLimits.Compute(_runtime.Profile, _runtime.RampStart, _breaker.State.HalvedBudgetsUntil, now);
@@ -71,13 +78,17 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
return await EvaluateDataAsync(accountId, ct).ConfigureAwait(false);
}
await _gate.WaitAsync(ct).ConfigureAwait(false);
var search = kind == ActionKind.ProfileSearch;
var gate = search ? _searchGate : _gate;
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
while (true)
{
var now = _clock.Now;
var permit = await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
var permit = search
? await EvaluateSearchAsync(now, ct).ConfigureAwait(false)
: await EvaluateCoreAsync(kind, accountId, now, ct).ConfigureAwait(false);
if (permit.Reason == DenialReason.MinimumSpacing && permit.RetryAfter is { } retry)
{
// Spacing is a pace: wait for it, then look again (the state may have changed meanwhile).
@@ -92,7 +103,8 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
return permit;
}
var session = _runtime.CurrentSession;
// A search step belongs to no session and is not one of its actions (issue #37).
var session = search ? null : _runtime.CurrentSession;
await _storage.ActionLog.AppendAsync(
new ActionLogRecord { At = now, Category = kind, AccountId = accountId, SessionId = session?.SessionId },
ct).ConfigureAwait(false);
@@ -103,7 +115,7 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
}
finally
{
_gate.Release();
gate.Release();
}
}
@@ -111,10 +123,12 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
/// What <see cref="RequestAsync"/> would answer now, without recording or waiting (spacing is reported as a
/// refusal with its retry time). The scheduler uses it to skip work whose budget is exhausted.
/// </summary>
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) =>
kind == ActionKind.DataDownload
? EvaluateDataAsync(accountId, ct)
: EvaluateCoreAsync(kind, accountId, _clock.Now, ct);
public Task<Permit> EvaluateAsync(ActionKind kind, long? accountId, CancellationToken ct = default) => kind switch
{
ActionKind.DataDownload => EvaluateDataAsync(accountId, ct),
ActionKind.ProfileSearch => EvaluateSearchAsync(_clock.Now, ct),
_ => EvaluateCoreAsync(kind, accountId, _clock.Now, ct),
};
/// <summary>Budget checks only (no breaker, window, session or spacing): «is there room today for this?».</summary>
public async Task<Permit> EvaluateBudgetAsync(ActionKind kind, long? accountId, CancellationToken ct = default)
@@ -279,10 +293,97 @@ public sealed class Governor : IGovernor, IDataBudget, Febe.Core.Collection.Reci
previous + spacing);
}
// The crossing gap from the last profile-search step (issue #37), which does not move the spacing above.
var crossing = await CrossingGapAsync(ActionKind.ProfileSearch, kind, accountId, now, ct).ConfigureAwait(false);
if (crossing is not null)
{
return crossing;
}
return await CheckAccountAsync(kind, accountId, now, budgets, session, ct).ConfigureAwait(false)
?? Permit.Grant(kind, accountId);
}
/// <summary>
/// The rules of the profile search (issue #37), in order: breaker (every stop of spec §7.6 stops the search too),
/// Alberto at the browser, pause, active window, the search's own budgets (reductions apply), its own spacing, and
/// the crossing gap from the engine's last action. No session check and no account check.
/// </summary>
private async Task<Permit> EvaluateSearchAsync(DateTimeOffset now, CancellationToken ct)
{
const ActionKind kind = ActionKind.ProfileSearch;
var zone = _clock.LocalZone;
var breaker = _breaker.State;
if (!breaker.AllowsSiteActions)
{
return Permit.Deny(kind, null, DenialReason.BreakerOpen, BreakerMessage(breaker, now, zone), breaker.Until);
}
if (_runtime.UserIsDriving)
{
return Permit.Deny(kind, null, DenialReason.UserIsDriving, "Stai usando il browser di Febe: la ricerca su Instagram riprende quando hai finito.");
}
if (_runtime.IsPaused)
{
return Permit.Deny(kind, null, DenialReason.Paused, "Febe è in pausa: la ricerca su Instagram riprende quando premi «Riprendi».");
}
var window = await _planner.GetWindowAtAsync(now, ct).ConfigureAwait(false);
if (window is null)
{
var next = await _planner.GetNextWindowAsync(now, ct).ConfigureAwait(false);
var when = next is null ? "nei giorni attivi" : ItalianText.Around(next.Start, now, zone);
return Permit.Deny(
kind,
null,
DenialReason.OutsideActiveWindow,
$"Fuori dalla fascia oraria Febe non apre Instagram: per ora vedi solo i profili che segui. Riprende {when}.",
next?.Start);
}
var denial = await CheckCategoryBudgetsAsync(kind, null, now, GetEffectiveBudgets(now), ct).ConfigureAwait(false);
if (denial is not null)
{
return denial;
}
var spacing = SearchSpacing;
var lastSearch = await _storage.ActionLog.GetLastActionAtAsync(kind, ct).ConfigureAwait(false);
if (lastSearch is { } previous && now - previous < spacing)
{
return Permit.Deny(
kind,
null,
DenialReason.MinimumSpacing,
$"Troppo vicino al passo di ricerca precedente: fra due passi passano almeno {ItalianText.Decimal(spacing.TotalSeconds, 1)} secondi.",
previous + spacing);
}
return await CrossingGapAsync(null, kind, null, now, ct).ConfigureAwait(false) ?? Permit.Grant(kind, null);
}
/// <summary>
/// The short distance between a search step and an engine action, both ways: <paramref name="other"/> is
/// <see cref="ActionKind.ProfileSearch"/> for an engine request, and null (the engine's own actions) for a search.
/// </summary>
private async Task<Permit?> CrossingGapAsync(ActionKind? other, ActionKind kind, long? accountId, DateTimeOffset now, CancellationToken ct)
{
var last = await _storage.ActionLog.GetLastActionAtAsync(other, ct).ConfigureAwait(false);
var gap = SearchSpacing;
if (last is { } previous && now - previous < gap)
{
return Permit.Deny(
kind,
accountId,
DenialReason.MinimumSpacing,
$"Troppo vicino all'azione precedente: fra la ricerca e il motore passano almeno {ItalianText.Decimal(gap.TotalSeconds, 1)} secondi.",
previous + gap);
}
return null;
}
private async Task<Permit?> CheckBudgetsAsync(ActionKind kind, long? accountId, DateTimeOffset now, EffectiveBudgets budgets, CancellationToken ct) =>
await CheckCategoryBudgetsAsync(kind, accountId, now, budgets, ct).ConfigureAwait(false)
?? await CheckAccountAsync(kind, accountId, now, budgets, _runtime.CurrentSession, ct).ConfigureAwait(false);
+1
View File
@@ -192,6 +192,7 @@ public static class ItalianText
ActionKind.BackfillPage => "pagine di storico",
ActionKind.SinglePost => "post singoli",
ActionKind.FollowingListPage => "pagine dell'elenco dei seguiti",
ActionKind.ProfileSearch => "ricerche di profili",
ActionKind.DataDownload => "dati scaricati",
_ => kind.ToString(),
};
+370
View File
@@ -0,0 +1,370 @@
using System.Diagnostics;
namespace Febe.Core.Engine;
/// <summary>Who uses the one page of Febe's browser.</summary>
public enum PageUser
{
/// <summary>The engine: a recipe of a session.</summary>
Engine,
/// <summary>The profile search (issue #37).</summary>
Search,
}
/// <summary>
/// One page, two users (issue #37): the engine's recipes and the profile search take turns on Febe's single browser
/// page. A FIFO queue with one holder at a time; cancellable; no timers. The engine takes a turn at the start of each
/// recipe and gives it back before an action that opens a page when the search is waiting (<see cref="YieldAsync"/>);
/// the search takes it for one step (and keeps it while Alberto keeps typing, bounded by the search itself).
/// </summary>
/// <remarks>The session never stops for a search: the search only slides in between two engine actions.</remarks>
public sealed class PageTurns
{
private readonly Lock _gate = new();
private readonly LinkedList<Waiter> _queue = new();
private PageTurn? _holder;
private PageUser? _lastUser;
private bool _searchTouchedPage;
private bool _restOwed;
private long _generation;
private List<TaskCompletionSource>? _freeWaiters;
/// <summary>Raised after every rest of the page (the search's photo queue forgets its addresses).</summary>
public event Action? Rested;
/// <summary>Raised when the rest of the page is left to the search (<see cref="TakeForRestAsync"/>).</summary>
public event Action? RestLeftToSearch;
/// <summary>
/// Changes every time a page is opened or put to rest: what the search typed in the box holds only within one
/// generation (the engine may open pages between two search steps without the search seeing it).
/// </summary>
public long Generation
{
get
{
lock (_gate)
{
return _generation;
}
}
}
/// <summary>
/// The engine wanted to rest the page while the search held or waited for it (end of a session, Alberto let go
/// of the browser): the search rests it when it is done, no session running. Cleared by a rest, by a page the
/// engine opens (the next session rests it), or by <see cref="ForgetOwedRest"/>.
/// </summary>
public bool RestOwed
{
get
{
lock (_gate)
{
return _restOwed;
}
}
}
/// <summary>Who opened the page last (null before anyone did, or after a rest).</summary>
public PageUser? LastUser
{
get
{
lock (_gate)
{
return _lastUser;
}
}
}
/// <summary>True from a search step until the next page the engine opens: the page state of a recipe may be gone.</summary>
public bool SearchTouchedPage
{
get
{
lock (_gate)
{
return _searchTouchedPage;
}
}
}
/// <summary>Who holds the page now, if anyone.</summary>
public PageUser? Holder
{
get
{
lock (_gate)
{
return _holder?.User;
}
}
}
/// <summary>True while <paramref name="user"/> waits for a turn.</summary>
public bool IsWaiting(PageUser user)
{
lock (_gate)
{
return _queue.Any(w => w.Turn.User == user);
}
}
/// <summary>Waits for a turn of <paramref name="user"/>; dispose the result to give it back.</summary>
public async ValueTask<PageTurn> TakeAsync(PageUser user, CancellationToken ct)
{
var turn = new PageTurn(this, user);
await AcquireAsync(turn, ct).ConfigureAwait(false);
return turn;
}
/// <summary>
/// When the other user waits, gives the page to it and waits to have it back (FIFO, so right after the other's
/// step). Returns true when it yielded. Does nothing when <paramref name="turn"/> does not hold the page.
/// </summary>
public async ValueTask<bool> YieldAsync(PageTurn turn, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(turn);
var other = turn.User == PageUser.Engine ? PageUser.Search : PageUser.Engine;
lock (_gate)
{
if (!ReferenceEquals(_holder, turn) || !_queue.Any(w => w.Turn.User == other))
{
return false;
}
ReleaseLocked(turn);
}
await AcquireAsync(turn, ct).ConfigureAwait(false);
return true;
}
/// <summary>The engine's current turn, for the recipes' yield points; null when the engine holds none.</summary>
public PageTurn? EngineTurn
{
get
{
lock (_gate)
{
return _holder is { User: PageUser.Engine } turn ? turn : null;
}
}
}
/// <summary>
/// A turn for a navigation of the engine outside its recipes (the rest page, Alberto's login page): at once when
/// the page is free. When the search holds or waits for the page, returns null and records that the rest is left to
/// the search (<see cref="RestOwed"/>): it rests the page itself when it is done. Otherwise waits for the turn.
/// </summary>
public async ValueTask<PageTurn?> TakeForRestAsync(CancellationToken ct)
{
var turn = new PageTurn(this, PageUser.Engine);
bool leftToSearch;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
_holder = turn;
return turn;
}
leftToSearch = _holder?.User == PageUser.Search || _queue.Any(w => w.Turn.User == PageUser.Search);
if (leftToSearch)
{
_restOwed = true;
}
}
if (leftToSearch)
{
RestLeftToSearch?.Invoke();
return null;
}
await AcquireAsync(turn, ct).ConfigureAwait(false);
return turn;
}
/// <summary>The search will not rest the page after all (it stays as it is after a verification, no browser).</summary>
public void ForgetOwedRest()
{
lock (_gate)
{
_restOwed = false;
}
}
/// <summary>Completes when nobody holds the page and nobody waits.</summary>
public Task WhenFreeAsync(CancellationToken ct)
{
TaskCompletionSource tcs;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
return Task.CompletedTask;
}
tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
(_freeWaiters ??= []).Add(tcs);
}
return tcs.Task.WaitAsync(ct);
}
/// <summary>A page was opened by <paramref name="user"/>.</summary>
public void NoteOpened(PageUser user)
{
lock (_gate)
{
_lastUser = user;
_searchTouchedPage = user == PageUser.Search;
_generation++;
if (user == PageUser.Engine)
{
// A session is on the page again: its end rests it.
_restOwed = false;
}
}
}
/// <summary>The search used the page (typed, opened its panel): the engine's page state may be gone.</summary>
public void NoteSearchUsedPage()
{
lock (_gate)
{
_searchTouchedPage = true;
}
}
/// <summary>The page went to rest (spec §6.1).</summary>
public void NoteRested()
{
lock (_gate)
{
_lastUser = null;
_searchTouchedPage = false;
_restOwed = false;
_generation++;
}
Rested?.Invoke();
}
internal void Release(PageTurn turn)
{
lock (_gate)
{
if (ReferenceEquals(_holder, turn))
{
ReleaseLocked(turn);
}
}
}
private async ValueTask AcquireAsync(PageTurn turn, CancellationToken ct)
{
Waiter waiter;
lock (_gate)
{
if (_holder is null && _queue.Count == 0)
{
_holder = turn;
return;
}
waiter = new Waiter(turn, new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously));
waiter.Node = _queue.AddLast(waiter);
}
try
{
await waiter.Ready.Task.WaitAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
lock (_gate)
{
if (waiter.Node?.List is not null)
{
_queue.Remove(waiter.Node);
NotifyFreeLocked();
throw;
}
// Granted while being cancelled: give it back at once.
if (ReferenceEquals(_holder, turn))
{
ReleaseLocked(turn);
}
}
throw;
}
}
private void ReleaseLocked(PageTurn turn)
{
Debug.Assert(ReferenceEquals(_holder, turn), "Only the holder gives the page back.");
_holder = null;
if (_queue.First is { } first)
{
_queue.RemoveFirst();
first.Value.Node = null;
_holder = first.Value.Turn;
first.Value.Ready.TrySetResult();
return;
}
NotifyFreeLocked();
}
private void NotifyFreeLocked()
{
if (_holder is not null || _queue.Count > 0 || _freeWaiters is null)
{
return;
}
foreach (var waiter in _freeWaiters)
{
waiter.TrySetResult();
}
_freeWaiters = null;
}
private sealed class Waiter(PageTurn turn, TaskCompletionSource ready)
{
public PageTurn Turn { get; } = turn;
public TaskCompletionSource Ready { get; } = ready;
public LinkedListNode<Waiter>? Node { get; set; }
}
}
/// <summary>A turn on the page; disposing it gives the page back (to the next in the queue).</summary>
public sealed class PageTurn : IAsyncDisposable, IDisposable
{
private readonly PageTurns _owner;
internal PageTurn(PageTurns owner, PageUser user)
{
_owner = owner;
User = user;
}
public PageUser User { get; }
public void Dispose() => _owner.Release(this);
public ValueTask DisposeAsync()
{
_owner.Release(this);
return ValueTask.CompletedTask;
}
}
+29
View File
@@ -864,6 +864,35 @@ internal sealed class SessionComposer
}
}
// The page is shared with the profile search (issue #37): a recipe starts on its turn. While the search holds
// the page the activity says so; the checks below run again once the turn is ours.
var turns = _s.PageTurns;
var waitsForSearch = turns.Holder is PageUser.Search || turns.IsWaiting(PageUser.Search);
if (waitsForSearch)
{
_s.Runtime.Activity = "In attesa della ricerca dei profili";
_s.Events.Publish(EngineNotificationKind.ActivityChanged);
}
PageTurn turn;
try
{
turn = await turns.TakeAsync(PageUser.Engine, ct).ConfigureAwait(false);
}
finally
{
if (waitsForSearch)
{
_s.Runtime.Activity = null;
}
}
await using var heldTurn = turn;
if (waitsForSearch && Clock.Now >= state.Context.PlannedEnd && !request.Manual)
{
return null;
}
if (!_s.Breaker.State.AllowsSiteActions || _s.Runtime.IsPaused || _s.Runtime.UserIsDriving)
{
state.Stop = true;
+25
View File
@@ -117,6 +117,31 @@ public sealed class ThumbnailStore
return path;
}
/// <summary>
/// Re-encodes an image to a small JPEG in memory (issue #37, photos of the profile search: never on disk). Returns
/// null when the content is not a decodable image.
/// </summary>
public static byte[]? EncodeSmallJpeg(Stream source, int longSide)
{
ArgumentNullException.ThrowIfNull(source);
ArgumentOutOfRangeException.ThrowIfLessThan(longSide, 16);
using var decoded = ImageDecoding.DecodeUpright(source, longSide);
if (decoded is null)
{
return null;
}
using var small = Render(decoded, longSide);
using var pixmap = small.PeekPixels();
if (pixmap is null)
{
return null;
}
using var data = pixmap.Encode(new SKJpegEncoderOptions(JpegQuality));
return data?.ToArray();
}
private static SKBitmap Render(SKBitmap source, int longSide)
{
var scale = Math.Min(1.0, (double)longSide / Math.Max(source.Width, source.Height));
+4 -1
View File
@@ -60,7 +60,10 @@ public interface IActionLogStore
/// </summary>
Task<IReadOnlyDictionary<ActionKind, BudgetUsage>> GetUsageAsync(DateTimeOffset now, TimeZoneInfo zone, CancellationToken ct = default);
/// <summary>Time of the last action (of a category, or of any category except data downloads when null).</summary>
/// <summary>
/// Time of the last action of a category, or, when null, of the engine's own actions: neither data downloads nor
/// profile-search steps (issue #37), so a search never moves the engine's spacing or its last session end.
/// </summary>
Task<DateTimeOffset?> GetLastActionAtAsync(ActionKind? category = null, CancellationToken ct = default);
/// <summary>Actions in [from, to), oldest first.</summary>