Merge pull request 'Esercitazione della guardia: il motore della prova non esce più dal computer' (#103) from drill-offline into main
ci / test (postgres) (push) Successful in 3m42s
ci / test (sqlite) (push) Successful in 4m28s
ci / image (push) Successful in 2m0s

This commit was merged in pull request #103.
This commit is contained in:
Alby96 committed 2026-11-28 18:45:34 +01:00
commit ae4ae4ed92
6 files changed
+184 -13

No files matched your search

+6 -2
View File
@@ -313,9 +313,13 @@ internal sealed partial class AnubisHost(
}
var scheduler = new Scheduler(clock, bus);
// The guard drill's engine: prices from the drill's local OKX, and then nothing else leaves the computer either
// (no news, no model, no other source: ADR 0016). Honored only under a guard, like the drill's OKX itself.
var drill = Guard is null ? null : GuardDrill.DrillOkx(environment);
_market = MarketDataEnabled
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger,
Guard is null ? null : GuardDrill.DrillOkx(environment))
? new MarketDataService(_db, clock, bus, settings, secrets, Config.Data, overrides?.MarketHttp, overrides?.MarketSockets, logger, drill,
offline: drill is not null)
: null;
_trading = TradingEnabled && (identity.File ?? Installation.ReadFile(Config.Data)) is { } file
? new TradingService(_db, clock, bus, secrets, _market, new FxStore(_db, clock), TradingConsent.From(Config), file.InstallationId,
+29 -10
View File
@@ -54,7 +54,7 @@ public sealed partial class MarketDataService : IDisposable
private (string Key, string Secret, AlpacaClient Client)? _alpaca;
public MarketDataService(Database db, IClock clock, EventBus bus, SettingsStore settings, SecretStore secrets, DataDirectory? data,
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, OkxOptions? okx = null)
HttpMessageHandler? handler = null, Func<IWebSocketTransport>? sockets = null, ILogger? logger = null, OkxOptions? okx = null, bool offline = false)
{
_db = db;
_clock = clock;
@@ -63,13 +63,8 @@ public sealed partial class MarketDataService : IDisposable
_data = data;
_sockets = sockets;
_logger = logger ?? NullLogger.Instance;
_http = handler is null
? new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
AutomaticDecompression = System.Net.DecompressionMethods.All,
})
: new HttpClient(handler, disposeHandler: false);
Offline = offline;
_http = Client(handler, offline);
_http.Timeout = TimeSpan.FromSeconds(60);
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"{AnubisInfo.Name}/{AnubisInfo.Version}");
@@ -84,12 +79,18 @@ public sealed partial class MarketDataService : IDisposable
_states = new SourceStateStore(db, clock);
News = new News.NewsCollector(_http, db, clock, _logger)
{
ModelFolder = data is null ? null : Path.Combine(data.Root, "models"),
ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models"),
Watcher = new News.NewsWatcher(db, clock, settings),
Analyst = new News.NewsAnalyst(db, clock, settings, secrets.RevealAsync, (config, key) => new News.LanguageModel(_http, config, key), _logger),
};
}
/// <summary>
/// The guard drill's engine (ADR 0016): no news job, no model to download, and no request leaves the computer;
/// prices come from the drill's local OKX.
/// </summary>
public bool Offline { get; }
public OkxClient Okx { get; }
public FreshnessMonitor Freshness { get; }
@@ -130,7 +131,7 @@ public sealed partial class MarketDataService : IDisposable
RefreshCorporateActionsAsync) { MaxLateness = TimeSpan.FromMinutes(50) },
new("dati-pulizia", "Pulizia delle barre al minuto e degli spread vecchi", Schedule.Daily(new TimeOnly(3, 45), Zones.Rome), PruneAsync)
{ MaxLateness = TimeSpan.FromHours(12), CatchUpWithin = TimeSpan.FromDays(3650) },
News.Job(),
.. Offline ? Array.Empty<ScheduledJob>() : [News.Job()],
];
/// <summary>
@@ -162,6 +163,24 @@ public sealed partial class MarketDataService : IDisposable
_http.Dispose();
}
// The connection pool shared by every source; offline, only this computer's own addresses are reached.
private static HttpClient Client(HttpMessageHandler? handler, bool offline)
{
var owned = handler is null;
var network = handler ?? new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
AutomaticDecompression = System.Net.DecompressionMethods.All,
};
if (offline)
{
network = new Supervision.LoopbackOnlyHandler(network, owned);
owned = true;
}
return new HttpClient(network, disposeHandler: owned);
}
/// <summary>The Alpaca client with the paper account keys, or null when they are missing.</summary>
public async Task<AlpacaClient?> AlpacaAsync(CancellationToken cancellationToken)
{
+8 -1
View File
@@ -21,7 +21,8 @@ public sealed record DrillResult(bool Passed, IReadOnlyList<string> Lines);
/// decided; the engine starts with the fault that blocks its main loop right after the sale leaves, with the stop
/// removed. The drill passes when the guard intervened, the engine restarted, the sale left open was canceled, the
/// stop came back for the whole quantity and the guard's note reached the diary. Prices come from a small local
/// server that answers like OKX: nothing leaves the computer. Same drill in the tests and in the Docker image.
/// server that answers like OKX, and the engine sends nothing else out (ADR 0016): no news, no model to download,
/// any other source refused before it leaves the computer. Same drill in the tests and in the Docker image.
/// </summary>
public static class GuardDrill
{
@@ -138,6 +139,12 @@ public static class GuardDrill
passed &= Check(stops.Any(q => q == held), $"Lo stop è tornato per tutti i {Format.Quantity(held)} BTC.", "Lo stop non è tornato per l'intera quantità.", Say);
passed &= Check(again > 0, "La vendita già decisa è ripartita con un ordine nuovo.", "La vendita già decisa non è ripartita.", Say);
passed &= Check(noted > 0, "La nota della guardia è nel diario.", "La nota della guardia non è nel diario.", Say);
// The engine of the drill stays on this computer (ADR 0016): it reads no news and downloads no model.
var news = await db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM news_items"), cancellationToken).ConfigureAwait(false);
var model = Directory.Exists(data.Models) && Directory.EnumerateFileSystemEntries(data.Models).Any();
passed &= Check(news == 0 && !model, "Il motore non ha letto notizie né scaricato il modello: è rimasto sul computer.",
$"Il motore è uscito dal computer: {news} notizie lette{(model ? ", modello scaricato" : "")}.", Say);
}
return new DrillResult(passed, lines);
@@ -0,0 +1,49 @@
using System.Net;
using System.Text;
namespace Anubis.Supervision;
/// <summary>
/// The network of the guard drill's engine (ADR 0016): a request to this computer's own addresses (loopback) passes,
/// any other is answered here with 403 and never leaves. The answer is final, not a failure to retry, so a job that
/// would have gone out fails at once and the engine keeps its usual pace.
/// </summary>
public sealed class LoopbackOnlyHandler(HttpMessageHandler inner, bool ownsInner) : HttpMessageHandler
{
public const string Refusal = "Esercitazione della guardia: nessuna richiesta esce dal computer.";
private readonly HttpMessageInvoker _inner = new(inner, ownsInner);
private int _refused;
/// <summary>How many requests were stopped here.</summary>
public int Refused => Volatile.Read(ref _refused);
public static bool Allowed(Uri? url) => url is { IsAbsoluteUri: true, IsLoopback: true };
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(request);
if (Allowed(request.RequestUri))
{
return _inner.SendAsync(request, cancellationToken);
}
Interlocked.Increment(ref _refused);
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden)
{
RequestMessage = request,
ReasonPhrase = "Forbidden in the guard drill",
Content = new StringContent(Refusal, Encoding.UTF8, "text/plain"),
});
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_inner.Dispose();
}
base.Dispose(disposing);
}
}