Files
Febe/src/Febe.Core/Engine/EngineServices.cs
T
Alby96andClaude Opus 5.5 883ea4683c Sessione salvata: copia alla chiusura della finestra e alla fine della guida, «Serve «Ho finito»», scelta per la copia incompleta e stato in Collegamento (#36, S4b)
Risposte 1, 5, 6, 9 e 10 di Alberto a S4. I valori __spin_r, __spin_b e __spin_t si copiano dalla pagina come gli altri (su Instagram da SiteData, ipotesi H23, operazioni ancora non configurate; nel sito di prova dal modulo GiroProva). La sessione si copia anche quando si chiude la finestra del browser su Windows e quando il permesso di guida finisce, sempre prima che la pagina torni al motore e con le garanzie di «Ho finito». Con «richieste» «Collegato» vuole una sessione salvata leggibile, altrimenti lo stato è «Serve «Ho finito»» e il motore aspetta. Nuova impostazione sessione.copia-incompleta (sostituisci, predefinita, o tieni-completa) e riquadro della sessione salvata nella pagina Collegamento, con soli conteggi e nomi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 11:41:35 +01:00

161 lines
6.8 KiB
C#

using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
/// <summary>
/// The parts of the engine that recipes and the interface need before the engine host exists: runtime state,
/// timeline, day planner, circuit breaker and Governor. Built in two steps because the real recipe runner needs the
/// Governor and the breaker, and the host needs the recipe runner:
/// <code>
/// var services = await EngineServices.CreateAsync(storage, clock, random);
/// var runner = new SomeRecipeRunner(services.Governor, services.Breaker, ...);
/// await using var engine = new EngineHost(services, runner);
/// await engine.StartAsync(ct);
/// </code>
/// </summary>
public sealed class EngineServices
{
private EngineServices(
IFebeStorage storage,
IClock clock,
IRandomSource random,
EngineOptions options,
EngineRuntime runtime,
EngineEvents events,
DayPlanner planner,
CircuitBreaker breaker,
Governor governor,
EngineSettings settings)
{
Storage = storage;
Clock = clock;
Random = random;
Options = options;
Runtime = runtime;
Events = events;
Planner = planner;
Breaker = breaker;
Governor = governor;
Settings = settings;
}
public IFebeStorage Storage { get; }
public IClock Clock { get; }
public IRandomSource Random { get; }
public EngineOptions Options { get; }
public EngineRuntime Runtime { get; }
public EngineEvents Events { get; }
public DayPlanner Planner { get; }
public CircuitBreaker Breaker { get; }
/// <summary>The Governor: <see cref="IGovernor"/> for recipes, <see cref="IDataBudget"/> for the download queue.</summary>
public Governor Governor { get; }
/// <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.
/// </summary>
public CollectionDiagnostics? Diagnostics { get; set; }
/// <summary>
/// Loads settings, pause flag, gradual-start origin and breaker state from the database. When the gradual start has
/// no origin yet (first run after the first connection) it starts now.
/// </summary>
/// <param name="storage">The database.</param>
/// <param name="clock">Time source (virtual in tests and simulation).</param>
/// <param name="random">Random source (seeded in tests and simulation).</param>
/// <param name="options">Tuning; <see cref="EngineOptions.Default"/> when null.</param>
/// <param name="userIsDriving">True while Alberto uses the browser.</param>
/// <param name="isConnected">Whether the browser holds an Instagram session; null when unknown.</param>
/// <param name="ct">Cancellation.</param>
/// <param name="sessionCopyMissing">True when the session is in the browser but its saved copy is missing (S4b).</param>
public static async Task<EngineServices> CreateAsync(
IFebeStorage storage,
IClock clock,
IRandomSource random,
EngineOptions? options = null,
Func<bool>? userIsDriving = null,
Func<bool>? isConnected = null,
CancellationToken ct = default,
Func<bool>? sessionCopyMissing = null)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(random);
options ??= EngineOptions.Default;
var runtime = new EngineRuntime(userIsDriving, isConnected, sessionCopyMissing);
var settings = await EngineSettingsStore.LoadAsync(storage.Settings, ct).ConfigureAwait(false);
runtime.Profile = settings.EffectiveProfile;
runtime.IsPaused = await storage.Settings.GetBoolAsync(EngineSettingKeys.Paused, false, ct).ConfigureAwait(false);
var rampStart = await storage.Settings.GetInt64Async(EngineSettingKeys.RampStart, ct).ConfigureAwait(false);
if (rampStart is null)
{
rampStart = clock.Now.ToUnixTimeMilliseconds();
await storage.Settings.SetInt64Async(EngineSettingKeys.RampStart, rampStart, ct).ConfigureAwait(false);
}
runtime.RampStart = DateTimeOffset.FromUnixTimeMilliseconds(rampStart.Value);
var events = new EngineEvents(storage.Events, clock);
var planner = new DayPlanner(storage.Settings, random, () => runtime.Profile, clock.LocalZone);
// Draws (or loads) the seed of the daily windows now, so that later readers never consume randomness.
await planner.GetNextWindowAsync(clock.Now, ct).ConfigureAwait(false);
var breaker = await CircuitBreaker.LoadAsync(storage, clock, runtime, events, ct).ConfigureAwait(false);
var governor = new Governor(storage, breaker, runtime, planner, clock, options, events);
return new EngineServices(storage, clock, random, options, runtime, events, planner, breaker, governor, settings);
}
/// <summary>
/// Validates and stores new engine settings (mockup 07) and applies them at once. Throws
/// <see cref="ArgumentException"/> with Italian messages when a value is outside the limits of spec §7.5.
/// </summary>
public async Task ApplySettingsAsync(EngineSettings settings, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(settings);
await EngineSettingsStore.SaveAsync(Storage.Settings, settings, ct).ConfigureAwait(false);
Settings = settings;
Runtime.Profile = settings.EffectiveProfile;
await Events.WriteAsync(
EventSeverity.Info,
EngineEventCodes.SettingsChanged,
$"Impostazioni del motore cambiate: profilo «{ItalianText.Profile(settings.ProfileKind)}».",
ct: ct).ConfigureAwait(false);
Events.Publish(EngineNotificationKind.StateChanged);
}
/// <summary>
/// The first connection to Instagram (spec §7.2): the gradual start begins now. Later connections do not restart it;
/// the resume after a verification or a disconnection does, through <see cref="CircuitBreaker.ResumeAsync"/>.
/// </summary>
public async Task NotifyFirstConnectionAsync(CancellationToken ct = default)
{
var now = Clock.Now;
Runtime.RampStart = now;
await Storage.Settings.SetAsync(
EngineSettingKeys.RampStart,
now.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture),
ct).ConfigureAwait(false);
}
}