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;
///
/// How one search step ended. is the text the answer belongs to (what Febe typed), never
/// printed; is the Governor's refusal when there was one.
///
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;
}
}
/// The browser half of the profile search (issue #37): one step on the site's own search box.
public interface IProfileSearchRunner
{
/// Why the search cannot run on this site (missing targets or reader), in Italian; null when it can.
string? NotConfiguredReason { get; }
///
/// Types the wanted text into the site's search box and reads the answer. 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.
///
Task SearchAsync(Func wanted, CancellationToken ct);
/// Waits, briefly, for the page to be quiet before it goes back to the engine.
Task SettleAsync(CancellationToken ct);
/// The rest page (spec §6.1), unless the breaker says to leave the page as it is.
Task RestAsync(CancellationToken ct);
/// A multiplier of the waits (mood × ritmo).
double WaitMultiplier { get; }
}
///
/// 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.
///
///
/// 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 (), 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.
///
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 _userIsDriving;
private readonly CollectionDiagnostics? _diagnostics;
/// Most answers remembered for one page (see ).
private const int MaxPageAnswers = 40;
/// What Febe typed into the box on the page of (its own record; never logged).
private string _typed = string.Empty;
/// The page () that , and belong to.
private long _typedGeneration = -1;
/// Where the page's requests stood right before the last key Febe sent on this page.
private SearchAnswerMark? _keyMark;
/// The answers read on this page, by text: the page answers a text again from its memory, without a request.
private readonly Dictionary _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? 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 SearchAsync(Func 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 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 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);
}
///
/// One burst under one permit: Backspaces, then the letters of the wanted text while it
/// keeps extending what is typed, at most keys.
///
private async Task<(SearchStepResult? Result, SearchFocus Focus)> BurstAsync(string text, int erase, Func 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);
}
///
/// 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.
///
private async Task ReadAnswerAsync(string text, Func 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 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);
/// Right before a key: from here on, the page's requests are for the text with this key.
private void NoteKey() => _keyMark = _capture.SearchMark();
/// A new page (opened, rested, or opened by the engine): nothing Febe knew of the box holds.
private void ForgetPage()
{
_typed = string.Empty;
_keyMark = null;
_pageAnswers.Clear();
_typedGeneration = _turns.Generation;
}
private async Task ClickAsync(string target, CancellationToken ct)
{
var check = await _driver.ClickAsync(target, null, ct).ConfigureAwait(false);
_diagnostics?.TargetClicked(null, target, check.Status);
return check;
}
/// A permit of the Governor for one search action; the refusal when denied.
private async Task 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;
}
}