using System.Collections.Concurrent;
namespace Febe.SitoDiProva;
/// The stop cases the site can play (spec §14.2), switched by the tests through /_controllo.
public enum StopMode
{
/// Everything works.
Normal,
/// Data requests get HTTP 429 (Rallentamento).
TooManyRequests,
/// Pages are redirected to /verifica; data requests get 403 and the page moves there (Verifica).
Challenge,
/// The session cookie is removed and pages move to /sessione-scaduta (Disconnessione).
SessionEnded,
/// Data requests return empty pages.
EmptyPages,
/// Data requests return a shape no reader knows (the site «changed»).
UnknownFormat,
}
///
/// What the site answers to the next request of the site client (/api/…, issue #36) instead of the data: the stop
/// cases of spec §7.6 and the renewals the client must keep. The shapes not known from samples are generic (H16).
///
public enum DirectReply
{
/// The data, after the checks of a real site.
Normal,
/// 429 with a short JSON and Retry-After: 60 (Rallentamento).
TooManyRequests,
/// 302 to the login page /accesso/ (H16-generic).
RedirectToLogin,
/// 302 to the challenge page /verifica (H16-generic).
RedirectToChallenge,
/// 200 with an HTML document where JSON is expected (H16-generic).
HtmlInsteadOfJson,
/// 200 with a JSON that has none of the expected root fields (H16-generic).
MissingRootField,
/// The data, with a Set-Cookie that renews the session cookie (new value, the old one stops working).
RenewSessionCookie,
/// The data, with a Set-Cookie that deletes the session cookie (the session ends).
DeleteSessionCookie,
/// The data, with a new x-ig-set-www-claim.
SetClaim,
}
/// Switches and counters of the test site. Thread-safe.
public sealed class SiteControl
{
private readonly Lock _gate = new();
private readonly ConcurrentQueue _dataRequests = new();
private readonly ConcurrentQueue _directRequests = new();
private readonly ConcurrentQueue _directReplies = new();
private readonly HashSet _sessions = new(StringComparer.Ordinal) { InitialSession };
private DirectReply _directAlways = DirectReply.Normal;
private int _directInFlight;
private int _maxDirectInFlight;
private int _loginVisits;
private int _challengeVisits;
private int _renewals;
private int _logins;
private int _claims;
private StopMode _mode = StopMode.Normal;
private int _armAfter;
/// How long a photo story stays on screen before the viewer moves on by itself.
public TimeSpan StoryDuration { get; set; } = TimeSpan.FromSeconds(5);
/// Validity of the CDN addresses handed out from now on.
public TimeSpan AddressLifetime { get; set; } = TimeSpan.FromHours(6);
/// The CDN answers 429 to every file (Rallentamento from the CDN, spec §7.6).
public bool CdnTooManyRequests { get; set; }
/// Number of CDN requests answered with 429.
public int CdnThrottled => _cdnThrottled;
/// Paths with query of every data request, in arrival order (for the tests).
public IReadOnlyList DataRequests => [.. _dataRequests];
/// Number of files served by the CDN.
public int CdnFilesServed => _cdnFiles;
/// Number of CDN requests refused because the address had expired.
public int CdnExpired => _cdnExpired;
private int _cdnFiles;
private int _cdnExpired;
private int _cdnThrottled;
private int _recentSearchWrites;
/// Extra wait before every answer of the search box (slow answers).
public TimeSpan SearchDelay { get; set; }
///
/// The search box answers shorter texts later than longer ones, so an earlier prefix arrives last (answers out of
/// order, as on a slow network).
///
public bool SearchDisorder { get; set; }
/// The page sends no request for a text it already searched, as a page with its own memory does.
public bool SearchMemory { get; set; }
///
/// Number of «ricerche recenti» the page wrote: clicking a result or pressing Enter in the search box writes one,
/// as Instagram registers a search. Febe must never cause one.
///
public int RecentSearchWrites => _recentSearchWrites;
///
/// A session already open when the site starts and after , as one opened before the test: the
/// tests that build a saved session without the browser use it. The pages never hand it out: a visit without a live
/// session gets a new value ().
///
public const string InitialSession = "attiva";
/// Method, path and query of every request of the site client (/api/…), in arrival order.
public IReadOnlyList DirectRequests => [.. _directRequests];
/// The most requests of the site client the site was answering at the same time.
public int MaxDirectInFlight => Volatile.Read(ref _maxDirectInFlight);
/// Extra wait before every answer to the site client (slow answers).
public TimeSpan DirectDelay { get; set; }
/// Requests of the login page /accesso… (a redirect followed would land there).
public int LoginPageVisits => Volatile.Read(ref _loginVisits);
/// Requests of the challenge page /verifica….
public int ChallengePageVisits => Volatile.Read(ref _challengeVisits);
/// The site client answers to the next request (or, with , to every one) with .
public void ReplyToDirect(DirectReply reply, bool always = false)
{
if (always)
{
lock (_gate)
{
_directAlways = reply;
}
_directReplies.Clear();
return;
}
_directReplies.Enqueue(reply);
}
/// True when is a session cookie the site handed out and did not end.
public bool IsSession(string? value)
{
lock (_gate)
{
return value is { Length: > 0 } && _sessions.Contains(value);
}
}
/// A new session, as a new login opens: its value works for the pages and for the site client.
internal string OpenSession()
{
var opened = "aperta-" + Interlocked.Increment(ref _logins).ToString(System.Globalization.CultureInfo.InvariantCulture);
lock (_gate)
{
_sessions.Add(opened);
}
return opened;
}
/// A new value of the session cookie in place of , which stops working.
internal string RenewSession(string old)
{
var renewed = "rinnovata-" + Interlocked.Increment(ref _renewals).ToString(System.Globalization.CultureInfo.InvariantCulture);
lock (_gate)
{
_sessions.Remove(old);
_sessions.Add(renewed);
}
return renewed;
}
/// Ends the session .
internal void EndSession(string value)
{
lock (_gate)
{
_sessions.Remove(value);
}
}
/// A new claim value.
internal string NextClaim() => "claim-prova-" + Interlocked.Increment(ref _claims).ToString(System.Globalization.CultureInfo.InvariantCulture);
///
/// Records a request of the site client and returns the reply it gets and the mode of the site that applies to it:
/// a request of the site client counts as a data request for with afterDataRequests, as a
/// page's /dati/ does. Pair with .
///
internal (DirectReply Reply, StopMode Mode) OnDirectRequest(string methodPathAndQuery)
{
_directRequests.Enqueue(methodPathAndQuery);
var now = Interlocked.Increment(ref _directInFlight);
int max;
while (now > (max = Volatile.Read(ref _maxDirectInFlight)) && Interlocked.CompareExchange(ref _maxDirectInFlight, now, max) != max)
{
}
StopMode mode;
DirectReply always;
lock (_gate)
{
if (_armAfter > 0)
{
_armAfter--;
mode = StopMode.Normal;
}
else
{
mode = _mode;
}
always = _directAlways;
}
return (_directReplies.TryDequeue(out var next) ? next : always, mode);
}
internal void OnDirectFinished() => Interlocked.Decrement(ref _directInFlight);
/// Counts the visits of the login and challenge pages.
internal void OnPageVisit(string path)
{
if (path.StartsWith("/accesso", StringComparison.Ordinal))
{
Interlocked.Increment(ref _loginVisits);
}
else if (path.StartsWith("/verifica", StringComparison.Ordinal))
{
Interlocked.Increment(ref _challengeVisits);
}
}
public StopMode Mode
{
get
{
lock (_gate)
{
return _armAfter > 0 ? StopMode.Normal : _mode;
}
}
}
/// Sets a stop case; with it starts after that many more data requests.
public void Set(StopMode mode, int afterDataRequests = 0)
{
lock (_gate)
{
_mode = mode;
_armAfter = Math.Max(0, afterDataRequests);
}
}
/// Back to normal; counters cleared; default story duration and address lifetime.
public void Reset()
{
lock (_gate)
{
_mode = StopMode.Normal;
_armAfter = 0;
}
_dataRequests.Clear();
_directRequests.Clear();
_directReplies.Clear();
lock (_gate)
{
_directAlways = DirectReply.Normal;
_sessions.Clear();
_sessions.Add(InitialSession);
}
DirectDelay = TimeSpan.Zero;
Interlocked.Exchange(ref _maxDirectInFlight, 0);
Interlocked.Exchange(ref _loginVisits, 0);
Interlocked.Exchange(ref _challengeVisits, 0);
StoryDuration = TimeSpan.FromSeconds(5);
AddressLifetime = TimeSpan.FromHours(6);
CdnTooManyRequests = false;
SearchDelay = TimeSpan.Zero;
SearchDisorder = false;
SearchMemory = false;
Interlocked.Exchange(ref _recentSearchWrites, 0);
Interlocked.Exchange(ref _cdnFiles, 0);
Interlocked.Exchange(ref _cdnExpired, 0);
Interlocked.Exchange(ref _cdnThrottled, 0);
}
public void ClearRequests() => _dataRequests.Clear();
/// Records a data request and returns the mode that applies to it.
internal StopMode OnDataRequest(string pathAndQuery)
{
_dataRequests.Enqueue(pathAndQuery);
lock (_gate)
{
if (_armAfter > 0)
{
_armAfter--;
return StopMode.Normal;
}
return _mode;
}
}
internal void OnCdnServed() => Interlocked.Increment(ref _cdnFiles);
internal void OnRecentSearchWritten() => Interlocked.Increment(ref _recentSearchWrites);
internal void OnCdnExpired() => Interlocked.Increment(ref _cdnExpired);
internal void OnCdnThrottled() => Interlocked.Increment(ref _cdnThrottled);
}