Raccolta (M0/M2): sito di prova completo, lettori per forma, ricette su browser vero, coda degli scaricamenti, sonda con ripulitura e verifica; documenti delle ipotesi e delle prove dal vivo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 17:32:35 +00:00
1 parent e2c987873b
commit 4fc5a6c0d4
74 files changed
+12689 -13

No files matched your search

@@ -0,0 +1,214 @@
using System.Text.Json;
using Febe.Browser.Cdp;
using Febe.Browser.Gestures;
using Febe.Browser.Hosting;
using Febe.Browser.Targets;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Pacing;
namespace Febe.Browser.Recipes;
/// <summary>Options of <see cref="BrowserPageDriver"/>.</summary>
public sealed record BrowserDriverOptions
{
/// <summary>Address of the site the recipes visit, without a trailing slash (e.g. the local test site).</summary>
public required string SiteBaseUrl { get; init; }
/// <summary>The «Ritmo dei gesti» slider.</summary>
public GesturePace Pace { get; init; } = GesturePace.Natural;
/// <summary>Gesture timings («naturale» by default).</summary>
public GestureSettings Gestures { get; init; } = GestureSettings.Natural;
/// <summary>How long a page may take to load and paint.</summary>
public TimeSpan LoadTimeout { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>Where the session cookie is checked (existence only). Null: not checked.</summary>
public SessionCookieOptions? SessionCookie { get; init; }
/// <summary>True while Alberto uses the browser: gestures are not performed.</summary>
public Func<bool>? UserIsDriving { get; init; }
}
/// <summary>
/// The page driver of the recipes over the browser layer (spec §6.1, §6.3, §7.7): navigation with <c>Page.navigate</c>,
/// read-only state with <c>Runtime.evaluate</c>, targets found with the target map and clicked with human gestures
/// through <c>Input</c>, wheel bursts, and the rest page. It never opens an address outside the site.
/// </summary>
public sealed class BrowserPageDriver : IPageDriver
{
/// <summary>Read-only: the page has loaded and painted (input before the first paint is ignored by Chromium).</summary>
private const string ReadyExpression =
"document.readyState === 'complete' && performance.getEntriesByType('paint').length > 0";
private readonly ICdpSession _cdp;
private readonly HostClassifier _hosts;
private readonly IClock _clock;
private readonly IRandomSource _random;
private readonly BrowserDriverOptions _options;
private readonly TargetResolver _resolver;
private HumanGestures _gestures;
private TargetActions _actions;
public BrowserPageDriver(ICdpSession cdp, TargetMap map, HostClassifier hosts, IClock clock, IRandomSource random, BrowserDriverOptions options)
{
_cdp = cdp ?? throw new ArgumentNullException(nameof(cdp));
_hosts = hosts ?? throw new ArgumentNullException(nameof(hosts));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
_random = random ?? throw new ArgumentNullException(nameof(random));
_options = options ?? throw new ArgumentNullException(nameof(options));
if (_hosts.Classify(options.SiteBaseUrl) != HostKind.Site)
{
throw new ArgumentException("L'indirizzo di base non è un indirizzo del sito.", nameof(options));
}
_resolver = new TargetResolver(cdp, map ?? throw new ArgumentNullException(nameof(map)));
(_gestures, _actions) = CreateGestures(1.0);
}
public double WaitMultiplier => _gestures.Multiplier;
public HumanGestures Gestures => _gestures;
public void BeginSession(double mood) => (_gestures, _actions) = CreateGestures(mood);
public async Task<PageLoad> OpenAsync(string path, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrEmpty(path);
if (!path.StartsWith('/') || path.StartsWith("//", StringComparison.Ordinal))
{
throw new ArgumentException("Le ricette aprono solo percorsi del sito.", nameof(path));
}
var url = _options.SiteBaseUrl.TrimEnd('/') + path;
if (_hosts.Classify(url) != HostKind.Site)
{
return new PageLoad(false, string.Empty, "indirizzo fuori dal sito");
}
var result = await _cdp.NavigateAsync(url, ct).ConfigureAwait(false);
if (!result.Succeeded)
{
return new PageLoad(false, string.Empty, result.ErrorText);
}
var deadline = _clock.Now + _options.LoadTimeout;
while (true)
{
try
{
var ready = await _cdp.EvaluateAsync(ReadyExpression, ct).ConfigureAwait(false);
if (ready.ValueKind == JsonValueKind.True)
{
break;
}
}
catch (Exception ex) when (ex is CdpCommandException or CdpEvaluationException)
{
// The document is being replaced: poll again.
}
if (_clock.Now >= deadline)
{
return new PageLoad(false, await CurrentPathAsync(ct).ConfigureAwait(false), "la pagina non ha finito di caricare");
}
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
return new PageLoad(true, await CurrentPathAsync(ct).ConfigureAwait(false), null);
}
public async Task<string> CurrentPathAsync(CancellationToken ct)
{
for (var attempt = 0; ; attempt++)
{
try
{
var value = await _cdp.EvaluateAsync("location.pathname", ct).ConfigureAwait(false);
return value.ValueKind == JsonValueKind.String ? value.GetString() ?? string.Empty : string.Empty;
}
catch (Exception ex) when (attempt < 3 && ex is CdpCommandException or CdpEvaluationException)
{
await _clock.Delay(TimeSpan.FromMilliseconds(100), ct).ConfigureAwait(false);
}
}
}
public async Task<bool> IsOnSiteAsync(CancellationToken ct)
{
var href = await _cdp.GetMainFrameUrlAsync(ct).ConfigureAwait(false);
return _hosts.Classify(href) == HostKind.Site;
}
public async Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
{
if (!_resolver.Map.Contains(target))
{
return new TargetCheck(target, TargetCheckStatus.NotConfigured, 0, $"Bersaglio «{target}» assente dalla mappa.");
}
var lookup = await _resolver.ResolveAsync(target, parameters, ct).ConfigureAwait(false);
return ToCheck(lookup, clicked: false);
}
public async Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct)
{
if (!_resolver.Map.Contains(target))
{
return new TargetCheck(target, TargetCheckStatus.NotConfigured, 0, $"Bersaglio «{target}» assente dalla mappa.");
}
// A person scrolls back as far as needed (e.g. to the stories bar after the sweep went down the feed).
var result = await _actions.ClickAsync(target, parameters, maxScrollBursts: 24, ct: ct).ConfigureAwait(false);
return ToCheck(result.Lookup, result.Clicked);
}
public async Task ScrollBurstAsync(CancellationToken ct)
{
await _gestures.ScrollBurstAsync(1, ct).ConfigureAwait(false);
if (_random.Chance(_gestures.Settings.ScrollBackProbability))
{
await _gestures.WaitAsync(new Interval(150, 600), ct).ConfigureAwait(false);
await _gestures.ScrollBackAsync(1, ct).ConfigureAwait(false);
}
await _gestures.PauseAfterBurstAsync(ct).ConfigureAwait(false);
}
public Task WaitAfterLoadAsync(CancellationToken ct) => _gestures.WaitAfterLoadAsync(ct);
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => _clock.Delay(duration, ct);
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => _gestures.MaybeDistractionAsync(ct);
public async Task<bool?> HasSessionCookieAsync(CancellationToken ct) =>
_options.SessionCookie is { } cookie ? await SessionCookieProbe.HasSessionCookieAsync(_cdp, cookie, ct).ConfigureAwait(false) : null;
public Task RestAsync(CancellationToken ct) => _cdp.RestAsync(ct);
private (HumanGestures, TargetActions) CreateGestures(double mood)
{
var gestures = new HumanGestures(_cdp, _clock, _random, mood, _options.Pace, _options.UserIsDriving, _options.Gestures);
return (gestures, new TargetActions(_resolver, gestures));
}
private static TargetCheck ToCheck(TargetLookup lookup, bool clicked)
{
var status = lookup.Status switch
{
TargetStatus.Found => clicked ? TargetCheckStatus.Clicked : TargetCheckStatus.Found,
TargetStatus.NotFound => TargetCheckStatus.NotFound,
TargetStatus.NotVisible => TargetCheckStatus.NotVisible,
TargetStatus.IndexOutOfRange => TargetCheckStatus.NotFound,
TargetStatus.OutOfView => TargetCheckStatus.OutOfView,
TargetStatus.Obstructed => TargetCheckStatus.Obstructed,
TargetStatus.NotConfigured => TargetCheckStatus.NotConfigured,
_ => TargetCheckStatus.NotFound,
};
return new TargetCheck(lookup.Id, status, lookup.Matches, lookup.Message);
}
}
@@ -0,0 +1,185 @@
using Febe.Browser.Capture;
using Febe.Browser.Diagnostics;
using Febe.Browser.Download;
using Febe.Browser.Hosting;
using Febe.Browser.Targets;
using Febe.Core.Abstractions;
using Febe.Core.Collection;
using Febe.Core.Collection.Downloads;
using Febe.Core.Collection.Readers;
using Febe.Core.Collection.Recipes;
using Febe.Core.Domain;
using Febe.Core.Engine;
using Febe.Core.Library;
using Febe.Core.Storage;
namespace Febe.Browser.Recipes;
/// <summary>The site the pipeline works on: its name (configuration files), address, hosts and session cookie.</summary>
/// <param name="Name">«instagram» or «prova»: selects <c>bersagli.{Name}.json</c> and <c>lettori.{Name}.json</c>.</param>
/// <param name="BaseUrl">Address the recipes open pages under.</param>
/// <param name="Hosts">Site and CDN hosts.</param>
/// <param name="SessionCookie">Where the session cookie is checked (existence only).</param>
public sealed record CollectionSite(string Name, string BaseUrl, HostClassifier Hosts, SessionCookieOptions SessionCookie)
{
/// <summary>
/// Instagram. Its target map and reader vocabulary are still skeletons until M0: every recipe refuses to run and
/// says why, without touching the site.
/// </summary>
public static CollectionSite Instagram { get; } = new("instagram", "https://www.instagram.com", HostClassifier.Instagram, SessionCookieOptions.Instagram);
/// <summary>The local test site (tools/Febe.SitoDiProva) on «127.0.0.1:port», with its CDN on another host.</summary>
public static CollectionSite TestSite(string siteHost, string cdnHost) =>
new("prova", $"http://{siteHost}", new HostClassifier([siteHost], [cdnHost]), new SessionCookieOptions("sessione_prova", $"http://{siteHost}/"));
/// <summary>The stop-signal rules of the site.</summary>
public string SignalsFile => Name == "prova" ? "segnali.prova.json" : "segnali.json";
}
/// <summary>What <see cref="CollectionPipeline.StartAsync"/> needs.</summary>
public sealed record CollectionPipelineOptions
{
public required ICdpSession Cdp { get; init; }
public required CollectionSite Site { get; init; }
public required IFebeStorage Storage { get; init; }
public required LibraryIngest Ingest { get; init; }
public required IGovernor Governor { get; init; }
/// <summary>Remaining budgets for the «at least ten stories» check; usually the Governor itself.</summary>
public IBudgetView? Budget { get; init; }
public required IDataBudget DataBudget { get; init; }
/// <summary>The circuit breaker: signals are reported to it, and recipes stop when it opens.</summary>
public required ICircuitBreaker Breaker { get; init; }
public required IClock Clock { get; init; }
public required IRandomSource Random { get; init; }
/// <summary>Temporary folder for downloads (under Dati).</summary>
public required string StagingFolder { get; init; }
/// <summary>
/// Folder with editable copies of the configuration (Dati, spec §8.2): <c>segnali.json</c>, <c>bersagli.*.json</c>,
/// <c>lettori.*.json</c>. Files missing there come from the copies embedded in Febe.Core.
/// </summary>
public string? ConfigFolder { get; init; }
public GesturePace Pace { get; init; } = GesturePace.Natural;
public RecipeOptions Recipes { get; init; } = new();
/// <summary>True while Alberto uses the browser: gestures are not performed.</summary>
public Func<bool>? UserIsDriving { get; init; }
public IBrowserLog? Log { get; init; }
}
/// <summary>
/// The collection pipeline put together (spec §6): response tap, stop signals, readers, page driver, recipe runner and
/// download queue, all on one browser page. Disposing it stops listening to the page.
/// </summary>
public sealed class CollectionPipeline : IAsyncDisposable
{
private readonly List<IDisposable> _subscriptions = [];
private CollectionPipeline(ResponseTap tap, SignalDetector signals, CaptureCollector capture, BrowserPageDriver driver, RecipeRunner runner, DownloadQueue downloads, SiteMap siteMap, TargetMap targets)
{
Tap = tap;
Signals = signals;
Capture = capture;
Driver = driver;
Runner = runner;
Downloads = downloads;
SiteMap = siteMap;
Targets = targets;
}
public ResponseTap Tap { get; }
public SignalDetector Signals { get; }
public CaptureCollector Capture { get; }
public BrowserPageDriver Driver { get; }
/// <summary>The <see cref="IRecipeRunner"/> of the engine.</summary>
public RecipeRunner Runner { get; }
public DownloadQueue Downloads { get; }
public SiteMap SiteMap { get; }
public TargetMap Targets { get; }
public ReaderVocabulary Vocabulary => Capture.Reader.Vocabulary;
public static async Task<CollectionPipeline> StartAsync(CollectionPipelineOptions options, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(options);
string? Override(string file) => options.ConfigFolder is { } folder ? Path.Combine(folder, file) : null;
var site = options.Site;
var siteMap = SiteMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json");
var targets = TargetMap.LoadOrEmbedded(Override($"bersagli.{site.Name}.json"), $"bersagli.{site.Name}.json");
var vocabulary = ReaderVocabulary.LoadOrEmbedded(Override($"lettori.{site.Name}.json"), $"lettori.{site.Name}.json");
var rulesFile = Override(site.SignalsFile);
var rules = rulesFile is not null && File.Exists(rulesFile) ? SignalRules.Load(rulesFile) : SignalRules.LoadEmbedded(site.SignalsFile);
var tap = new ResponseTap(options.Cdp, site.Hosts, options.Clock, options.Log);
var signals = new SignalDetector(rules, options.Breaker, options.Clock);
var capture = new CaptureCollector(new ShapeReader(vocabulary), options.Clock);
var driver = new BrowserPageDriver(options.Cdp, targets, site.Hosts, options.Clock, options.Random, new BrowserDriverOptions
{
SiteBaseUrl = site.BaseUrl,
Pace = options.Pace,
SessionCookie = site.SessionCookie,
UserIsDriving = options.UserIsDriving,
});
var runner = new RecipeRunner(new RecipeEnvironment
{
Driver = driver,
Capture = capture,
Governor = options.Governor,
Budget = options.Budget ?? options.Governor as IBudgetView,
Signals = signals,
Storage = options.Storage,
SiteMap = siteMap,
Clock = options.Clock,
Random = options.Random,
DataBudget = options.DataBudget,
Breaker = options.Breaker,
Options = options.Recipes,
});
var downloads = new DownloadQueue(
options.Storage,
options.Ingest,
new BrowserFileFetcher(options.Cdp, site.Hosts, options.Log),
options.DataBudget,
options.Clock,
options.Random,
new DownloadOptions { StagingFolder = options.StagingFolder });
var pipeline = new CollectionPipeline(tap, signals, capture, driver, runner, downloads, siteMap, targets);
pipeline._subscriptions.Add(tap.AddObserver(signals));
pipeline._subscriptions.Add(tap.AddConsumer(signals));
pipeline._subscriptions.Add(tap.AddObserver(capture));
pipeline._subscriptions.Add(tap.AddConsumer(capture));
await tap.StartAsync(ct).ConfigureAwait(false);
return pipeline;
}
public async ValueTask DisposeAsync()
{
foreach (var subscription in _subscriptions)
{
subscription.Dispose();
}
await Tap.DisposeAsync().ConfigureAwait(false);
}
}
+24 -3
View File
@@ -15,7 +15,14 @@ namespace Febe.Browser.Targets;
/// <param name="HrefPattern">Link shape on the path, e.g. «/{username}/», «/stories/**»: {name} or * is one segment, ** the rest.</param>
/// <param name="Index">Which of the visible matches, in document order (0 = first, -1 = last).</param>
/// <param name="Hypothesis">Hypothesis of spec §6.6 the target depends on (e.g. «H11»), when not yet confirmed.</param>
public sealed record TargetSpec(string Id, IReadOnlyList<string> Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis);
public sealed record TargetSpec(string Id, IReadOnlyList<string> Roles, string? NamePattern, string? HrefPattern, int Index, string? Hypothesis)
{
/// <summary>
/// False for a placeholder of a skeleton map (role, name and href written but empty, e.g. the first
/// <c>bersagli.instagram.json</c>): looking it up gives <see cref="TargetStatus.NotConfigured"/> without touching the page.
/// </summary>
public bool IsConfigured => Roles.Count > 0 || NamePattern is not null || HrefPattern is not null;
}
/// <summary>
/// The target map of one site (<c>bersagli.instagram.json</c>, <c>bersagli.prova.json</c>), editable without
@@ -62,6 +69,14 @@ public sealed partial class TargetMap
public static TargetMap Load(string path) => Parse(File.ReadAllText(path), path);
/// <summary>A map shipped with Febe.Core (<c>bersagli.prova.json</c>, <c>bersagli.instagram.json</c>).</summary>
public static TargetMap LoadEmbedded(string fileName) =>
Parse(Febe.Core.Collection.SiteMap.ReadEmbeddedText(fileName), fileName);
/// <summary>Loads <paramref name="path"/> when it exists, otherwise the embedded file with the same name.</summary>
public static TargetMap LoadOrEmbedded(string? path, string embeddedName) =>
!string.IsNullOrEmpty(path) && File.Exists(path) ? Load(path) : LoadEmbedded(embeddedName);
public static TargetMap Parse(string json, string? source = null)
{
var name = source ?? "bersagli";
@@ -92,9 +107,12 @@ public sealed partial class TargetMap
var roles = (dto.Role ?? string.Empty).Split('|', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(r => r.ToLowerInvariant())
.ToArray();
if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href))
// A skeleton entry writes the three keys empty on purpose (still to be filled from the M0 samples);
// an entry that names none of them is a mistake.
var placeholder = dto.Role is not null && dto.Name is not null && dto.Href is not null;
if (roles.Length == 0 && string.IsNullOrWhiteSpace(dto.Name) && string.IsNullOrWhiteSpace(dto.Href) && !placeholder)
{
throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href».");
throw new InvalidDataException($"{where}: serve almeno uno fra «role», «name» e «href» (vuoti tutti e tre per una voce ancora da compilare).");
}
if (!string.IsNullOrWhiteSpace(dto.Name))
@@ -196,6 +214,9 @@ internal sealed class TargetMapFile
public string? Note { get; set; }
/// <summary>Page addresses: read by <c>Febe.Core.Collection.SiteMap</c>, accepted and ignored here.</summary>
public Dictionary<string, JsonElement>? Pages { get; set; }
public Dictionary<string, TargetDto>? Targets { get; set; }
}
+16 -1
View File
@@ -25,6 +25,9 @@ public enum TargetStatus
/// <summary>Something covers the element (e.g. a dialog): clicking would hit something else.</summary>
Obstructed,
/// <summary>The map has the entry but it is still empty (skeleton to be filled from the M0 samples, H11).</summary>
NotConfigured,
}
/// <summary>One element matched by a target, as measured by the page.</summary>
@@ -48,6 +51,7 @@ public sealed record TargetLookup(string Id, TargetStatus Status, TargetElement?
TargetStatus.IndexOutOfRange => $"Bersaglio «{Id}»: trovati {Matches} elementi visibili, meno di quanti ne chiede la mappa.",
TargetStatus.OutOfView => $"Bersaglio «{Id}» fuori dalla parte visibile della pagina.",
TargetStatus.Obstructed => $"Bersaglio «{Id}» coperto da un altro elemento.",
TargetStatus.NotConfigured => $"Bersaglio «{Id}» ancora vuoto nella mappa: va compilato con i campioni della sonda (H11).",
_ => $"Bersaglio «{Id}»: esito sconosciuto.",
};
}
@@ -188,6 +192,11 @@ public sealed class TargetResolver
public async Task<TargetLookup> ResolveAsync(string id, IReadOnlyDictionary<string, string>? parameters = null, CancellationToken ct = default)
{
var spec = _map.Get(id);
if (!spec.IsConfigured)
{
return new TargetLookup(id, TargetStatus.NotConfigured, null, 0, 0, 0);
}
var (all, width, height) = await MeasureAsync(spec, parameters, ct).ConfigureAwait(false);
var visible = all.Where(e => e.Visible).ToList();
if (all.Count == 0)
@@ -209,7 +218,13 @@ public sealed class TargetResolver
/// <summary>Every element matching <paramref name="id"/>, visible or not, in document order (at most 200).</summary>
public async Task<IReadOnlyList<TargetElement>> FindAllAsync(string id, IReadOnlyDictionary<string, string>? parameters = null, CancellationToken ct = default)
{
var (all, _, _) = await MeasureAsync(_map.Get(id), parameters, ct).ConfigureAwait(false);
var spec = _map.Get(id);
if (!spec.IsConfigured)
{
return [];
}
var (all, _, _) = await MeasureAsync(spec, parameters, ct).ConfigureAwait(false);
return all;
}