The guard (SPEC 9.3, 9.4) is now the container's main process and the parent of the engine. It listens on a named pipe for the engine's heartbeat and startup steps, and steps in after two minutes of silence, ten minutes of a startup that does not move, or an exit without notice. It stops the engine, cancels our purchases and sales left open on demo accounts, puts back the stops the positions need from the state file the engine writes every ten seconds, writes a note, warns the user and restarts the engine without any injected fault. The third forced restart within an hour writes the STOP file. The container's stop is passed on to the engine, which closes in order. At restart the engine adopts the guard's stops before reconciling, cancels the orders it left open and plans again the exits already decided, so the rules of SPEC 5.6 apply to them. The acceptance test blocks the main loop right after a sale leaves: in process on a demo-like broker, and with real processes in the drill, which also runs inside the Docker image (tasks ci and the CI workflow). The guard uses the ASP.NET shared runtime so both programs share /app. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
171 lines
5.9 KiB
C#
171 lines
5.9 KiB
C#
using System.IO.Pipes;
|
|
using System.Text;
|
|
using System.Threading.Channels;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
|
|
namespace Anubis.Supervision;
|
|
|
|
/// <summary>
|
|
/// The engine's end of the channel to the guard (SPEC 9.3): the beat of the main loop, the startup steps, the keys
|
|
/// and the stops it decides. Messages wait in a short queue and the oldest beats give way: a slow guard never slows
|
|
/// the engine. When the guard is gone the engine goes on by itself.
|
|
/// </summary>
|
|
public sealed partial class GuardLink : IAsyncDisposable
|
|
{
|
|
private readonly Lock _gate = new();
|
|
private readonly NamedPipeClientStream _pipe;
|
|
private readonly Channel<GuardMessage> _outgoing = Channel.CreateBounded<GuardMessage>(new BoundedChannelOptions(64) { FullMode = BoundedChannelFullMode.DropOldest });
|
|
private readonly CancellationTokenSource _stop = new();
|
|
private readonly ILogger _logger;
|
|
private readonly Task _loop;
|
|
private string _stage = GuardStages.Starting;
|
|
private string? _step;
|
|
|
|
private GuardLink(string pipeName, ILogger logger)
|
|
{
|
|
_logger = logger;
|
|
_pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
|
|
_loop = Task.Run(() => RunAsync(_stop.Token));
|
|
}
|
|
|
|
/// <summary>The link when a guard started this engine (<see cref="GuardChannel.PipeVariable"/>); null otherwise.</summary>
|
|
public static GuardLink? FromEnvironment(IReadOnlyDictionary<string, string?> environment, ILogger? logger = null)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(environment);
|
|
return environment.GetValueOrDefault(GuardChannel.PipeVariable) is { Length: > 0 } name ? new GuardLink(name, logger ?? NullLogger.Instance) : null;
|
|
}
|
|
|
|
/// <summary>The guard asked for an orderly stop.</summary>
|
|
public Action? StopRequested { get; set; }
|
|
|
|
public string Stage
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _stage;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>A new stage or startup step: told to the guard at once.</summary>
|
|
public void Set(string stage, string? step = null)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_stage == stage && _step == step)
|
|
{
|
|
return;
|
|
}
|
|
|
|
_stage = stage;
|
|
_step = step;
|
|
}
|
|
|
|
Beat();
|
|
}
|
|
|
|
/// <summary>A step of the startup of SPEC 9.4.</summary>
|
|
public void Step(string step) => Set(GuardStages.Starting, step);
|
|
|
|
/// <summary>Alive, at the current stage.</summary>
|
|
public void Beat()
|
|
{
|
|
GuardMessage message;
|
|
lock (_gate)
|
|
{
|
|
message = GuardMessage.Beat(_stage, _step);
|
|
}
|
|
|
|
_outgoing.Writer.TryWrite(message);
|
|
}
|
|
|
|
public void SendKeys(IReadOnlyList<GuardKeys> keys) => _outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Keys) { Keys = keys });
|
|
|
|
/// <summary>A stop decided by the engine: the guard will not restart it. Waits a moment for the message to leave.</summary>
|
|
public async Task AnnounceAsync(string reason)
|
|
{
|
|
_outgoing.Writer.TryWrite(new GuardMessage(GuardMessageTypes.Stopping) { Reason = reason });
|
|
for (var i = 0; i < 20 && _outgoing.Reader.Count > 0; i++)
|
|
{
|
|
await Task.Delay(50).ConfigureAwait(false);
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _stop.CancelAsync().ConfigureAwait(false);
|
|
try
|
|
{
|
|
await _loop.ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
}
|
|
|
|
await _pipe.DisposeAsync().ConfigureAwait(false);
|
|
_stop.Dispose();
|
|
}
|
|
|
|
private async Task RunAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
await _pipe.ConnectAsync(TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is TimeoutException or IOException or UnauthorizedAccessException)
|
|
{
|
|
LogNoGuard(_logger, ex.Message);
|
|
return;
|
|
}
|
|
|
|
var reading = ReadAsync(cancellationToken);
|
|
var writer = new StreamWriter(_pipe, new UTF8Encoding(false), leaveOpen: true) { AutoFlush = true, NewLine = "\n" };
|
|
await using (writer.ConfigureAwait(false))
|
|
{
|
|
try
|
|
{
|
|
await foreach (var message in _outgoing.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
|
|
{
|
|
await writer.WriteLineAsync(GuardChannel.Write(message).AsMemory(), cancellationToken).ConfigureAwait(false);
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
{
|
|
}
|
|
catch (IOException ex)
|
|
{
|
|
LogGuardLost(_logger, ex.Message);
|
|
}
|
|
}
|
|
|
|
await reading.ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task ReadAsync(CancellationToken cancellationToken)
|
|
{
|
|
using var reader = new StreamReader(_pipe, Encoding.UTF8, leaveOpen: true);
|
|
try
|
|
{
|
|
while (await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false) is { } line)
|
|
{
|
|
if (GuardChannel.Read(line) is { Type: GuardMessageTypes.Stop })
|
|
{
|
|
StopRequested?.Invoke();
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex) when (ex is OperationCanceledException or IOException or ObjectDisposedException)
|
|
{
|
|
}
|
|
}
|
|
|
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel not reached: {Reason}. The engine runs without its guard.")]
|
|
private static partial void LogNoGuard(ILogger logger, string reason);
|
|
|
|
[LoggerMessage(Level = LogLevel.Warning, Message = "Guard channel lost: {Reason}")]
|
|
private static partial void LogGuardLost(ILogger logger, string reason);
|
|
}
|