Files
Febe/src/Febe.Web/Api/EngineApi.cs
T
Alby96andClaude Opus 5.5 c69755db23 Sessione salvata: correzioni della revisione di S4b (#36)
Un errore imprevisto durante la copia senza «Ho finito» (database, disco) non trattiene più per sempre il permesso di guida: la copia scrive solo il tipo d'errore e la guida finisce lo stesso, così il motore non resta in «Stai usando il browser». Un «Ho finito» tardivo dopo una copia fatta lasciando il browser dice che la sessione era già stata copiata invece di chiedere un nuovo accesso. Il registro distingue la finestra chiusa da quella ridotta a icona troppo a lungo. /api/engine e gli eventi prendono «Serve «Ho finito»» dall'istantanea del motore (EngineSnapshot.SessionCopyMissing) senza chiedere al browser a ogni evento. La prova di WebView2 aspetta la riga del registro, non solo la sessione in memoria. Documenti: nove operazioni GraphQL con __spin_*, H23 descritta in prove-dal-vivo (parte E), guida aggiornata.

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

292 lines
13 KiB
C#

using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using Febe.Core.Abstractions;
using Febe.Core.Engine;
using Febe.Core.Storage;
using Febe.Web.Connection;
using Febe.Web.Engine;
using Febe.Web.Library;
using Febe.Web.Native;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace Febe.Web.Api;
/// <summary>The engine for the interface: snapshot, «Metti in pausa», «Riprendi», the browser, and the event stream.</summary>
public static class EngineApi
{
/// <summary>Idle time after which a comment line keeps the event stream open through proxies.</summary>
public static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(25);
/// <summary>The snapshot is pushed again at least this often, so «8 min fa» and «verso le» stay current.</summary>
public static readonly TimeSpan Refresh = TimeSpan.FromSeconds(60);
public static void Map(IEndpointRouteBuilder endpoints)
{
endpoints.MapGet("/api/engine", async (IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct) =>
ApiHttp.Json(await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false), FebeJsonContext.Default.EngineDto));
endpoints.MapPost("/api/engine/pause", async (IEngineControl control, CancellationToken ct) =>
{
await control.PauseAsync(ct).ConfigureAwait(false);
return ApiHttp.Message("Febe è in pausa: non apre nulla finché non premi «Riprendi».");
});
endpoints.MapPost("/api/engine/resume", async (IEngineControl control, CancellationToken ct) =>
{
var result = await control.ResumeAsync(ct).ConfigureAwait(false);
return ApiHttp.Json(new ResumeDto(result.Resumed, result.Message), FebeJsonContext.Default.ResumeDto);
});
// «Riattiva» a recipe suspended after three unknown formats (or targets not found) in a row.
endpoints.MapPost("/api/engine/recipes/{recipe}/resume", async (string recipe, IEngineControl control, CancellationToken ct) =>
{
if (!Enum.TryParse<RecipeKind>(recipe, ignoreCase: true, out var kind) || !Enum.IsDefined(kind))
{
throw new BadRequestException("Ricetta sconosciuta.");
}
var resumed = await control.ResumeRecipeAsync(kind, ct).ConfigureAwait(false);
return ApiHttp.Json(
new ResumeDto(resumed, resumed
? "Ricetta riattivata: riprende alla prossima sessione. Se il formato è ancora sconosciuto, si sospende di nuovo dopo tre volte."
: "Questa ricetta non era sospesa."),
FebeJsonContext.Default.ResumeDto);
});
// «Apri il browser» on Windows: the window of the browser comes to the front, on the start page when it was at rest
// and on the login page with { openLogin: true } (the red strip of a disconnection; issue #52).
endpoints.MapPost("/api/browser/show", async (HttpContext context, IBrowserWindow browser, IConnectionService connection, BrowserUseTracker tracker, IClock clock, CancellationToken ct) =>
{
if (!browser.IsSeparateWindow)
{
throw new BadRequestException("Qui il browser di Febe si usa dalla pagina Browser.");
}
var body = await ApiHttp.OptionalBodyAsync(context, FebeJsonContext.Default.BeginDrivingRequest, new BeginDrivingRequest(false)).ConfigureAwait(false);
await connection.ShowBrowserAsync(body.OpenLogin, ct).ConfigureAwait(false);
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Il browser di Febe è in primo piano.");
});
// The Browser page («Ho finito») and the desktop window report that Alberto used the browser: «Riprendi» activates.
endpoints.MapPost("/api/browser/used", (BrowserUseTracker tracker, IClock clock) =>
{
tracker.MarkUsed(clock.Now);
return ApiHttp.Message("Bene: ora puoi premere «Riprendi».");
});
endpoints.MapGet("/api/eventi", StreamAsync);
}
/// <summary>
/// The engine as the interface needs it. The link comes from the session cookie, never from whether «Tu» is known:
/// the name of the connected account may come much later (H10), and meanwhile the sidebar says «Collegato» with
/// «Nome non ancora noto». The engine looks at the cookie on every turn and its mode says so, and whether the copy for
/// the requests is missing too (<see cref="EngineSnapshot.SessionCopyMissing"/>, no round trip to the browser at every
/// event); only when it does not run (or there is none in this process) the connection is asked.
/// </summary>
public static async Task<EngineDto> SnapshotAsync(IEngineMonitor monitor, IFebeStorage storage, BrowserUseTracker tracker, IClock clock, IConnectionService connection, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(monitor);
ArgumentNullException.ThrowIfNull(storage);
ArgumentNullException.ThrowIfNull(tracker);
ArgumentNullException.ThrowIfNull(clock);
ArgumentNullException.ThrowIfNull(connection);
var snapshot = await monitor.GetSnapshotAsync(ct).ConfigureAwait(false);
var mine = await storage.Accounts.GetMineAsync(ct).ConfigureAwait(false);
var state = snapshot.Mode switch
{
// The cookie is there but the copy for the requests is missing (S4b): «Serve «Ho finito»», with the account.
EngineMode.NotConnected => snapshot.SessionCopyMissing ? "copyMissing" : "notConnected",
EngineMode.StoppedForVerification => "verification",
EngineMode.Disconnected => "disconnected",
EngineMode.Off => (await connection.GetStatusAsync(ct).ConfigureAwait(false)).State switch
{
ConnectionState.Connected => "connected",
ConnectionState.SessionCopyMissing => "copyMissing",
_ => "notConnected",
},
_ => "connected",
};
var link = state == "notConnected"
? new ConnectionDto(state, null, null, null)
: new ConnectionDto(state, mine?.Username, mine?.DisplayName, null);
bool canResume;
if (snapshot.Banner is { NeedsResume: true })
{
var since = snapshot.Breaker.LastSignal?.At ?? DateTimeOffset.MinValue;
canResume = tracker.LastUsedAt is { } used && used >= since;
}
else
{
canResume = snapshot.Mode == EngineMode.Paused;
}
return new EngineDto(clock.Now.ToUnixTimeMilliseconds(), snapshot, link, canResume);
}
/// <summary>
/// <c>/api/eventi</c>: server-sent events. <c>motore</c> carries the engine (at once, at every change, at least every
/// minute); <c>libreria</c> says the library changed (at most every second and a half); a comment line keeps the
/// stream open. Never contains captions, bodies or addresses.
/// </summary>
public static async Task StreamAsync(
HttpContext context,
IEngineMonitor monitor,
IFebeStorage storage,
BrowserUseTracker tracker,
LibraryChanges library,
IClock clock,
IConnectionService connection)
{
ArgumentNullException.ThrowIfNull(context);
var response = context.Response;
response.ContentType = "text/event-stream; charset=utf-8";
response.Headers.CacheControl = "no-cache, no-transform";
response.Headers["X-Accel-Buffering"] = "no";
var ct = context.RequestAborted;
var signals = Channel.CreateBounded<string>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
using var stop = CancellationTokenSource.CreateLinkedTokenSource(ct);
var engineTask = Task.Run(
async () =>
{
await foreach (var _ in monitor.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("motore");
}
},
CancellationToken.None);
var libraryTask = Task.Run(
async () =>
{
await foreach (var change in library.SubscribeAsync(stop.Token).ConfigureAwait(false))
{
signals.Writer.TryWrite("libreria:" + JsonSerializer.Serialize(change, FebeJsonContext.Default.LibraryChange));
}
},
CancellationToken.None);
try
{
await WriteAsync(response, "retry: 3000\n\n", ct).ConfigureAwait(false);
await SendEngineAsync().ConfigureAwait(false);
var libraryGap = TimeSpan.FromMilliseconds(1500);
var lastEngine = DateTimeOffset.UtcNow;
var lastLibrary = DateTimeOffset.MinValue;
string? pendingLibrary = null;
var enginePending = false;
while (!ct.IsCancellationRequested)
{
var now = DateTimeOffset.UtcNow;
var wait = Heartbeat;
if (lastEngine + Refresh - now < wait)
{
wait = lastEngine + Refresh - now;
}
if (pendingLibrary is not null && lastLibrary + libraryGap - now < wait)
{
wait = lastLibrary + libraryGap - now;
}
var got = await WaitAsync(signals.Reader, wait < TimeSpan.Zero ? TimeSpan.Zero : wait, ct).ConfigureAwait(false);
if (got)
{
// Changes come in bursts: wait a moment and send one update for all of them.
await Task.Delay(TimeSpan.FromMilliseconds(300), ct).ConfigureAwait(false);
while (signals.Reader.TryRead(out var signal))
{
if (signal == "motore")
{
enginePending = true;
}
else
{
pendingLibrary = signal["libreria:".Length..];
}
}
}
now = DateTimeOffset.UtcNow;
var sent = false;
if (enginePending || now - lastEngine >= Refresh)
{
await SendEngineAsync().ConfigureAwait(false);
enginePending = false;
lastEngine = now;
sent = true;
}
if (pendingLibrary is not null && now - lastLibrary >= libraryGap)
{
await WriteAsync(response, "event: libreria\ndata: " + pendingLibrary + "\n\n", ct).ConfigureAwait(false);
pendingLibrary = null;
lastLibrary = now;
sent = true;
}
if (!sent && !got)
{
await WriteAsync(response, ": ancora qui\n\n", ct).ConfigureAwait(false);
}
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// The page closed the stream.
}
catch (IOException)
{
// The connection dropped.
}
finally
{
await stop.CancelAsync().ConfigureAwait(false);
await Task.WhenAll(Quiet(engineTask), Quiet(libraryTask)).ConfigureAwait(false);
}
async Task SendEngineAsync()
{
var dto = await SnapshotAsync(monitor, storage, tracker, clock, connection, ct).ConfigureAwait(false);
await WriteAsync(response, "event: motore\ndata: " + JsonSerializer.Serialize(dto, FebeJsonContext.Default.EngineDto) + "\n\n", ct).ConfigureAwait(false);
}
}
private static async Task<bool> WaitAsync(ChannelReader<string> reader, TimeSpan wait, CancellationToken ct)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(wait);
try
{
return await reader.WaitToReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return false;
}
}
private static async Task WriteAsync(HttpResponse response, string text, CancellationToken ct)
{
await response.Body.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false);
await response.Body.FlushAsync(ct).ConfigureAwait(false);
}
private static async Task Quiet(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
}
}