using System.Globalization;
using Febe.Core.Abstractions;
using Febe.Core.Collection.Diagnostics;
using Febe.Core.Domain;
using Febe.Core.Storage;
namespace Febe.Core.Engine;
///
/// 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:
///
/// 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);
///
///
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; }
/// The Governor: for recipes, for the download queue.
public Governor Governor { get; }
/// Current engine and caution settings.
public EngineSettings Settings { get; private set; }
///
/// 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.
///
public CollectionDiagnostics? Diagnostics { get; set; }
///
/// 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.
///
/// The database.
/// Time source (virtual in tests and simulation).
/// Random source (seeded in tests and simulation).
/// Tuning; when null.
/// True while Alberto uses the browser.
/// Whether the browser holds an Instagram session; null when unknown.
/// Cancellation.
public static async Task CreateAsync(
IFebeStorage storage,
IClock clock,
IRandomSource random,
EngineOptions? options = null,
Func? userIsDriving = null,
Func? isConnected = null,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(random);
options ??= EngineOptions.Default;
var runtime = new EngineRuntime(userIsDriving, isConnected);
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);
}
///
/// Validates and stores new engine settings (mockup 07) and applies them at once. Throws
/// with Italian messages when a value is outside the limits of spec §7.5.
///
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);
}
///
/// 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 .
///
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);
}
}