Ricette fatte di richieste, un permesso per richiesta (#36, S3)
Otto ricette (controllo del profilo, storico, taggati, reel, storie di un account, raccolta in evidenza, post singolo, elenco dei seguiti) hanno una strada per richieste dirette accanto a quella con il browser. Ci vanno solo se ogni ruolo che servono è un'operazione configurata di richieste.<sito>.json: con Instagram nessuna lo è e Febe non costruisce il client del sito, quindi il comportamento con Instagram non cambia fino a S4. Ogni richiesta prende il suo permesso dal Governatore nella categoria di ciò che chiede (la prima pagina dei post conta come profilo); i segnali delle risposte vanno all'interruttore e fermano la ricetta prima di ogni altra richiesta. Se manca un valore o la pagina successiva, la ricetta torna alle pagine per quella volta e il motore controlla tutti e due i tetti. I tetti non cambiano: il dimezzamento delle storie viste è tolto perché toccava anche il browser e i «Su misura» salvati, e resta una domanda per Alberto prima di S4. Il simulatore ha --raccolta pagine|richieste con il costo delle operazioni separate di Instagram: sei simulazioni di 30 giorni senza superamenti. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4dcbd0b096
commit
63acae4e73
46 files changed
+3724
-136
No files matched your search
@@ -0,0 +1,176 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Febe.Core.Abstractions;
|
||||
using Febe.Core.Collection;
|
||||
using Febe.Core.Collection.Diagnostics;
|
||||
using Febe.Core.Collection.Readers;
|
||||
using Febe.Core.Collection.Recipes;
|
||||
using Febe.Core.Collection.Requests;
|
||||
using Febe.Core.Domain;
|
||||
using Febe.Core.Engine;
|
||||
using Febe.Data;
|
||||
using Febe.Tests.Support;
|
||||
using RecordingBreaker = Febe.Tests.Browser.TestSupport.RecordingBreaker;
|
||||
using VirtualClock = Febe.Tests.Browser.TestSupport.VirtualClock;
|
||||
|
||||
namespace Febe.Tests.Collection.Support;
|
||||
|
||||
/// <summary>
|
||||
/// A page that must never be touched: the recipes by requests do not use it (issue #36, S3). Every call is counted
|
||||
/// and fails.
|
||||
/// </summary>
|
||||
public sealed class NoPageDriver : IPageDriver
|
||||
{
|
||||
private int _touched;
|
||||
|
||||
/// <summary>Calls received (each one failed).</summary>
|
||||
public int Touched => Volatile.Read(ref _touched);
|
||||
|
||||
public double WaitMultiplier => 1.0;
|
||||
|
||||
/// <summary>Counted, not failed: it comes before the run, where a failure would not be the run's.</summary>
|
||||
public void BeginSession(double mood) => Interlocked.Increment(ref _touched);
|
||||
|
||||
public Task<PageLoad> OpenAsync(string path, CancellationToken ct) => Touch<PageLoad>();
|
||||
|
||||
public Task<string> CurrentPathAsync(CancellationToken ct) => Touch<string>();
|
||||
|
||||
public Task<bool> IsOnSiteAsync(CancellationToken ct) => Touch<bool>();
|
||||
|
||||
public Task<TargetCheck> FindAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
|
||||
|
||||
public Task<TargetCheck> ClickAsync(string target, IReadOnlyDictionary<string, string>? parameters, CancellationToken ct) => Touch<TargetCheck>();
|
||||
|
||||
public Task ScrollBurstAsync(CancellationToken ct) => Touch<bool>();
|
||||
|
||||
public Task WaitAfterLoadAsync(CancellationToken ct) => Touch<bool>();
|
||||
|
||||
public Task WaitAsync(TimeSpan duration, CancellationToken ct) => Touch<bool>();
|
||||
|
||||
public Task<bool> MaybeDistractionAsync(CancellationToken ct) => Touch<bool>();
|
||||
|
||||
public Task<bool?> HasSessionCookieAsync(CancellationToken ct) => Touch<bool?>();
|
||||
|
||||
public Task RestAsync(CancellationToken ct) => Touch<bool>();
|
||||
|
||||
private void Touch()
|
||||
{
|
||||
Interlocked.Increment(ref _touched);
|
||||
throw new InvalidOperationException("La pagina è stata toccata da una ricetta per richieste.");
|
||||
}
|
||||
|
||||
private Task<T> Touch<T>()
|
||||
{
|
||||
Touch();
|
||||
return Task.FromResult<T>(default!);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The recipes by requests without a browser (issue #36, S3): the runner of the test site's readers and map, with a
|
||||
/// site client (<see cref="ScriptedRequester"/> by default) and a page that must never be touched.
|
||||
/// </summary>
|
||||
internal sealed class RequestBed : IAsyncDisposable
|
||||
{
|
||||
private readonly ConcurrentQueue<string> _warnings = new();
|
||||
|
||||
private RequestBed(TempFolder temp, FebeDatabase db, VirtualClock clock, NoPageDriver page, ISiteRequester requester, PermissiveGovernor governor, RecordingBreaker breaker, RecipeRunner runner, TestSession session)
|
||||
{
|
||||
Temp = temp;
|
||||
Db = db;
|
||||
Clock = clock;
|
||||
Page = page;
|
||||
Requester = requester;
|
||||
Governor = governor;
|
||||
Breaker = breaker;
|
||||
Runner = runner;
|
||||
Session = session;
|
||||
}
|
||||
|
||||
public TempFolder Temp { get; }
|
||||
|
||||
public FebeDatabase Db { get; }
|
||||
|
||||
public VirtualClock Clock { get; }
|
||||
|
||||
public NoPageDriver Page { get; }
|
||||
|
||||
public ISiteRequester Requester { get; }
|
||||
|
||||
/// <summary>The scripted site client (null when the bed runs on another one).</summary>
|
||||
public ScriptedRequester? Scripted => Requester as ScriptedRequester;
|
||||
|
||||
public PermissiveGovernor Governor { get; }
|
||||
|
||||
public RecordingBreaker Breaker { get; }
|
||||
|
||||
public RecipeRunner Runner { get; }
|
||||
|
||||
public TestSession Session { get; }
|
||||
|
||||
public IReadOnlyList<string> Warnings => [.. _warnings];
|
||||
|
||||
/// <param name="map">The map of the site; the test site's by default (every recipe could also go by the pages).</param>
|
||||
/// <param name="catalog">The catalog; the test site's by default.</param>
|
||||
/// <param name="requester">The site client; a <see cref="ScriptedRequester"/> on the cleaned samples by default.</param>
|
||||
/// <param name="diagnostics">The recorder of the diagnostic report, when the test reads it.</param>
|
||||
/// <param name="requests">False: no site client at all (every recipe by the page).</param>
|
||||
public static async Task<RequestBed> CreateAsync(SiteMap? map = null, RequestCatalog? catalog = null, ISiteRequester? requester = null, CollectionDiagnostics? diagnostics = null, bool requests = true, VirtualClock? clock = null)
|
||||
{
|
||||
var temp = new TempFolder("ricette-richieste");
|
||||
var db = await TestDatabase.OpenAsync(temp);
|
||||
clock ??= new VirtualClock(new DateTimeOffset(2026, 10, 13, 16, 0, 0, TimeSpan.Zero));
|
||||
catalog ??= RequestCatalog.LoadTestSite();
|
||||
requester ??= new ScriptedRequester(catalog) { SessionCookie = "sessione_prova" };
|
||||
var capture = new CaptureCollector(new ShapeReader(ReaderVocabulary.LoadTestSite()), clock) { Diagnostics = diagnostics };
|
||||
var page = new NoPageDriver();
|
||||
var breaker = new RecordingBreaker();
|
||||
var governor = new PermissiveGovernor();
|
||||
RequestBed? bed = null;
|
||||
var runner = new RecipeRunner(new RecipeEnvironment
|
||||
{
|
||||
Driver = page,
|
||||
Capture = capture,
|
||||
Governor = governor,
|
||||
Budget = governor,
|
||||
Signals = new SignalDetector(SignalRules.LoadTestSite(), breaker, clock),
|
||||
Storage = db,
|
||||
SiteMap = map ?? SiteMap.LoadTestSite(),
|
||||
Clock = clock,
|
||||
Random = new SeededRandom(7),
|
||||
Breaker = breaker,
|
||||
Diagnostics = diagnostics,
|
||||
Requests = requests
|
||||
? new SiteRequestEnvironment(requester, catalog, new SiteAnswerSignals(SignalRules.LoadTestSite(), "sessione_prova"), Warn: m => bed?._warnings.Enqueue(m))
|
||||
: null,
|
||||
});
|
||||
var session = new TestSession((await db.Sessions.StartAsync(clock.Now)).Id);
|
||||
bed = new RequestBed(temp, db, clock, page, requester, governor, breaker, runner, session);
|
||||
return bed;
|
||||
}
|
||||
|
||||
/// <summary>The account of the samples: «numero» 5555 (marta.prova on the site, a fake name in the samples).</summary>
|
||||
public Task<Account> AddSampleAccountAsync(Func<Account, Account>? change = null) => AddAccountAsync("5555", "ndkwq.shzgd", change);
|
||||
|
||||
public Task<Account> AddAccountAsync(string? instagramId, string username, Func<Account, Account>? change = null, bool isMine = false)
|
||||
{
|
||||
var account = Account.Create(username, StartingPoint.EverythingAndKeepUpdated, Clock.Now, TestZones.Rome, isMine: isMine) with
|
||||
{
|
||||
InstagramId = instagramId,
|
||||
IsFollowed = !isMine,
|
||||
};
|
||||
return Db.Accounts.AddAsync(change is null ? account : change(account));
|
||||
}
|
||||
|
||||
public Task<RecipeOutcome> RunAsync(RecipeKind kind, long? accountId = null, long? entryId = null, string? highlightId = null, int? maxPages = null, bool manual = false) =>
|
||||
Runner.RunAsync(new RecipeRequest(kind, accountId, entryId, highlightId, maxPages, manual), Session, CancellationToken.None);
|
||||
|
||||
public async Task<IReadOnlyList<string>> EventCodesAsync() =>
|
||||
[.. (await Db.Events.ListAsync(new Febe.Core.Storage.EventQuery())).Select(e => e.Code)];
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
(Requester as IDisposable)?.Dispose();
|
||||
await Db.DisposeAsync();
|
||||
Temp.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,33 @@ public enum ScriptedReply
|
||||
|
||||
/// <summary>The sample, with the session cookie deleted by the site.</summary>
|
||||
SessionCookieDeleted,
|
||||
|
||||
/// <summary>A 404 with the JSON of the test site («non-trovato»): the resource is not there (H19).</summary>
|
||||
NotFoundJson,
|
||||
|
||||
/// <summary>A 500 with JSON: an error of the site.</summary>
|
||||
ServerError500,
|
||||
|
||||
/// <summary>A 503 with JSON: the site is not available.</summary>
|
||||
ServerError503,
|
||||
|
||||
/// <summary>No answer in time (<see cref="SiteUnreachableReason.Timeout"/>).</summary>
|
||||
Timeout,
|
||||
|
||||
/// <summary>No connection (<see cref="SiteUnreachableReason.Unreachable"/>).</summary>
|
||||
Unreachable,
|
||||
|
||||
/// <summary>An answer larger than allowed (<see cref="SiteUnreachableReason.TooLarge"/>).</summary>
|
||||
TooLarge,
|
||||
|
||||
/// <summary>A body that cannot be decoded (<see cref="SiteUnreachableReason.Broken"/>).</summary>
|
||||
Broken,
|
||||
|
||||
/// <summary>
|
||||
/// A 200 with JSON that no reader recognizes (the body of the sample «forma-sconosciuta»), said to have the expected
|
||||
/// fields: what a site that changed its format inside the same fields would send.
|
||||
/// </summary>
|
||||
UnknownShape,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -140,6 +167,23 @@ public sealed class ScriptedRequester : ISiteRequester
|
||||
return new SiteAnswer(operation, 302, "text/html", ReadOnlyMemory<byte>.Empty, redirectTo: ChallengeLocation);
|
||||
case ScriptedReply.HtmlInsteadOfJson:
|
||||
return new SiteAnswer(operation, 200, "text/html; charset=utf-8", Encoding.UTF8.GetBytes("<!DOCTYPE html><html><head><title>Pagina</title></head><body></body></html>"));
|
||||
case ScriptedReply.NotFoundJson:
|
||||
return new SiteAnswer(operation, 404, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"non-trovato\"}"), rootFieldsPresent: false);
|
||||
case ScriptedReply.ServerError500 or ScriptedReply.ServerError503:
|
||||
return new SiteAnswer(operation, reply == ScriptedReply.ServerError500 ? 500 : 503, "application/json", Encoding.UTF8.GetBytes("{\"errore\":\"interno\"}"), rootFieldsPresent: false);
|
||||
case ScriptedReply.Timeout or ScriptedReply.Unreachable or ScriptedReply.TooLarge or ScriptedReply.Broken:
|
||||
var reason = reply switch
|
||||
{
|
||||
ScriptedReply.Timeout => SiteUnreachableReason.Timeout,
|
||||
ScriptedReply.TooLarge => SiteUnreachableReason.TooLarge,
|
||||
ScriptedReply.Broken => SiteUnreachableReason.Broken,
|
||||
_ => SiteUnreachableReason.Unreachable,
|
||||
};
|
||||
throw new SiteUnreachableException($"«{operation.Name}» ({operation.PathShape}): nessuna risposta (prova).", reason);
|
||||
case ScriptedReply.UnknownShape:
|
||||
var unknown = Directory.EnumerateFiles(_samples, "*-forma-sconosciuta.json").Single();
|
||||
var corpo = JsonNode.Parse(File.ReadAllText(unknown))!["corpo"]!;
|
||||
return new SiteAnswer(operation, 200, "application/json", Encoding.UTF8.GetBytes(corpo.ToJsonString()), rootFieldsPresent: true);
|
||||
}
|
||||
|
||||
var (mime, body) = Sample(operation);
|
||||
|
||||
Reference in new issue
Block a user