Keep the guard drill's engine off the internet (refs #102)
ci / test (postgres) (push) Successful in 3m38s
ci / test (sqlite) (push) Successful in 4m6s
ci / test (postgres) (pull_request) Failing after 4m7s
ci / test (sqlite) (pull_request) Successful in 4m24s
ci / image (pull_request) Skipped
ci / image (push) Successful in 1m25s

Since Phase 7 the drill's child engine read the real news feeds every two
minutes and downloaded the ONNX tone model, and it already asked the ECB,
the mood and calendar sources and the Binance archives. The drill is meant
to stay on the computer (ADR 0012 point 5) and that extra work loaded the
slow CI runner while the drill timed the engine.

Under a guard with the drill's loopback OKX, the market data now runs
offline: no news job, no model, and every request goes through a
loopback-only handler that answers anything else with a final 403, so no
source retries with back-off and the engine keeps its pace. No new
variable: the drill is recognised by the same conditions as its fake OKX.

The drill gains an eighth check (no news read, no model downloaded), and a
test runs every market data job, a history round and a news round as the
drill builds them and finds only loopback requests on the network. ADR 0016.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-16 09:41:45 +01:00
1 parent a77aa1b7eb
commit a5a6918dae
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}");
@@ -82,9 +77,15 @@ public sealed partial class MarketDataService : IDisposable
_universes = new UniverseStore(db, clock);
_builder = new UniverseBuilder(db, clock);
_states = new SourceStateStore(db, clock);
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = data is null ? null : Path.Combine(data.Root, "models") };
News = new News.NewsCollector(_http, db, clock, _logger) { ModelFolder = offline || data is null ? null : Path.Combine(data.Root, "models") };
}
/// <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; }
@@ -125,7 +126,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>
@@ -157,6 +158,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
{
@@ -126,6 +127,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);
}
}