Add online Verse observation daemons

This commit is contained in:
Meta Vens 2026-06-01 21:07:05 +01:00
commit 583bf2c140
9 changed files with 519 additions and 2 deletions

View file

@ -1,5 +1,6 @@
using System.Net;
using System.Net.Sockets;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
@ -14,7 +15,8 @@ internal sealed record EveSensorReceiverOptions(
int Port,
string Path,
string SourceId,
string ExpectedType)
string ExpectedType,
string SubscribePath)
{
public static EveSensorReceiverOptions Parse(string[] args)
{
@ -22,7 +24,8 @@ internal sealed record EveSensorReceiverOptions(
ParseInt(args, "--port", 8793),
ParseString(args, "--path", "/eve/camera"),
ParseString(args, "--source-id", "eve-camera"),
ParseString(args, "--type", "video-frame"));
ParseString(args, "--type", "video-frame"),
ParseString(args, "--subscribe-path", ParseString(args, "--path", "/eve/camera") + "/subscribe"));
}
private static string ParseString(IReadOnlyList<string> args, string name, string fallback)
@ -48,6 +51,8 @@ internal sealed class EveSensorReceiver(EveSensorReceiverOptions options) : IDis
{
private readonly TcpListener listener = new(IPAddress.Any, options.Port);
private readonly CancellationTokenSource stopping = new();
private readonly ConcurrentDictionary<int, WebSocketSubscriber> subscribers = new();
private int nextSubscriberId;
public async Task RunAsync()
{
@ -72,11 +77,21 @@ internal sealed class EveSensorReceiver(EveSensorReceiverOptions options) : IDis
options.SourceId,
options.ExpectedType,
options.Path,
options.SubscribePath,
Subscribers = subscribers.Count,
});
await WriteHttpResponseAsync(stream, "200 OK", "application/json", Encoding.UTF8.GetBytes(health)).ConfigureAwait(false);
return;
}
if (string.Equals(request.Path, options.SubscribePath, StringComparison.Ordinal)
&& request.Headers.TryGetValue("Sec-WebSocket-Key", out var subscriberKey))
{
await WriteWebSocketHandshakeAsync(stream, subscriberKey).ConfigureAwait(false);
await SubscribeAsync(stream).ConfigureAwait(false);
return;
}
if (!string.Equals(request.Path, options.Path, StringComparison.Ordinal)
|| !request.Headers.TryGetValue("Sec-WebSocket-Key", out var key))
{
@ -101,6 +116,7 @@ internal sealed class EveSensorReceiver(EveSensorReceiverOptions options) : IDis
{
Console.WriteLine(normalizedObservation);
Console.Out.Flush();
await BroadcastAsync(normalizedObservation).ConfigureAwait(false);
}
continue;
@ -116,6 +132,71 @@ internal sealed class EveSensorReceiver(EveSensorReceiverOptions options) : IDis
{
Console.WriteLine(normalized);
Console.Out.Flush();
await BroadcastAsync(normalized).ConfigureAwait(false);
}
}
}
private async Task SubscribeAsync(NetworkStream stream)
{
var id = Interlocked.Increment(ref nextSubscriberId);
var subscriber = new WebSocketSubscriber(id, stream);
subscribers[id] = subscriber;
Console.Error.WriteLine($"Eve sensor receiver subscriber {id} connected on {options.SubscribePath}.");
try
{
await subscriber.SendTextAsync(JsonSerializer.Serialize(new
{
type = "mimir-verse-subscription",
status = "connected",
options.Path,
options.SubscribePath,
options.SourceId,
options.ExpectedType,
})).ConfigureAwait(false);
while (!stopping.IsCancellationRequested)
{
var frame = await ReceiveFrameAsync(stream).ConfigureAwait(false);
if (frame.Opcode == 0x8)
{
await WriteCloseFrameAsync(stream).ConfigureAwait(false);
break;
}
}
}
catch (IOException)
{
}
catch (SocketException)
{
}
finally
{
subscribers.TryRemove(id, out _);
Console.Error.WriteLine($"Eve sensor receiver subscriber {id} disconnected.");
}
}
private async Task BroadcastAsync(string normalized)
{
foreach (var pair in subscribers.ToArray())
{
try
{
await pair.Value.SendTextAsync(normalized).ConfigureAwait(false);
}
catch (IOException)
{
subscribers.TryRemove(pair.Key, out _);
}
catch (SocketException)
{
subscribers.TryRemove(pair.Key, out _);
}
catch (ObjectDisposedException)
{
subscribers.TryRemove(pair.Key, out _);
}
}
}
@ -374,3 +455,46 @@ internal sealed class EveSensorReceiver(EveSensorReceiverOptions options) : IDis
internal sealed record HttpRequest(string Path, IReadOnlyDictionary<string, string> Headers);
internal sealed record WebSocketFrame(int Opcode, byte[] Payload);
internal sealed class WebSocketSubscriber(int id, NetworkStream stream)
{
private readonly SemaphoreSlim writeLock = new(1, 1);
public int Id => id;
public async Task SendTextAsync(string text)
{
var payload = Encoding.UTF8.GetBytes(text);
var header = new List<byte> { 0x81 };
if (payload.Length < 126)
{
header.Add((byte)payload.Length);
}
else if (payload.Length <= ushort.MaxValue)
{
header.Add(126);
header.Add((byte)(payload.Length >> 8));
header.Add((byte)(payload.Length & 0xff));
}
else
{
header.Add(127);
for (var shift = 56; shift >= 0; shift -= 8)
{
header.Add((byte)(((ulong)payload.Length >> shift) & 0xff));
}
}
await writeLock.WaitAsync().ConfigureAwait(false);
try
{
await stream.WriteAsync(header.ToArray()).ConfigureAwait(false);
await stream.WriteAsync(payload).ConfigureAwait(false);
await stream.FlushAsync().ConfigureAwait(false);
}
finally
{
writeLock.Release();
}
}
}

View file

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<AssemblyName>Mimir.VerseRecorder</AssemblyName>
<RootNamespace>Mimir.VerseRecorder</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View file

@ -0,0 +1,151 @@
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
var options = VerseRecorderOptions.Parse(args);
Directory.CreateDirectory(options.OutputDirectory);
var runId = DateTimeOffset.Now.ToString("yyyyMMdd-HHmmss");
var runDirectory = Path.Combine(options.OutputDirectory, runId);
Directory.CreateDirectory(runDirectory);
var jsonlPath = Path.Combine(runDirectory, "observations.jsonl");
var sessionPath = Path.Combine(runDirectory, "session.json");
await File.WriteAllTextAsync(
sessionPath,
JsonSerializer.Serialize(
new
{
kind = "mimir.verse_recorder_session.v1",
runId,
options.Url,
startedAt = DateTimeOffset.Now.ToString("O"),
options.Seconds,
observations = jsonlPath,
},
new JsonSerializerOptions { WriteIndented = true }));
Console.Error.WriteLine($"Mimir Verse recorder subscribing to {options.Url}");
Console.Error.WriteLine($"Writing {jsonlPath}");
using var stopping = new CancellationTokenSource();
if (options.Seconds > 0)
{
stopping.CancelAfter(TimeSpan.FromSeconds(options.Seconds));
}
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
stopping.Cancel();
};
var count = 0L;
var lastMeter = DateTimeOffset.UtcNow;
await using var output = new StreamWriter(new FileStream(jsonlPath, FileMode.Create, FileAccess.Write, FileShare.Read), Encoding.UTF8);
while (!stopping.IsCancellationRequested)
{
using var socket = new ClientWebSocket();
try
{
await socket.ConnectAsync(options.Url, stopping.Token);
while (socket.State == WebSocketState.Open && !stopping.IsCancellationRequested)
{
var text = await ReceiveTextAsync(socket, stopping.Token);
if (text == null)
{
break;
}
await output.WriteLineAsync(text);
count++;
if (DateTimeOffset.UtcNow - lastMeter >= TimeSpan.FromSeconds(options.MeterSeconds))
{
await output.FlushAsync();
Console.Error.WriteLine($"verse-recorder observations={count} path={jsonlPath}");
lastMeter = DateTimeOffset.UtcNow;
}
}
}
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
Console.Error.WriteLine($"verse-recorder reconnect after {ex.GetType().Name}: {ex.Message}");
try
{
await Task.Delay(TimeSpan.FromSeconds(options.ReconnectSeconds), stopping.Token);
}
catch (OperationCanceledException)
{
break;
}
}
}
await output.FlushAsync();
Console.Error.WriteLine($"verse-recorder complete observations={count} path={jsonlPath}");
static async Task<string?> ReceiveTextAsync(ClientWebSocket socket, CancellationToken stopping)
{
var buffer = new byte[64 * 1024];
using var memory = new MemoryStream();
while (true)
{
var result = await socket.ReceiveAsync(buffer, stopping);
if (result.MessageType == WebSocketMessageType.Close)
{
return null;
}
memory.Write(buffer, 0, result.Count);
if (result.EndOfMessage)
{
return Encoding.UTF8.GetString(memory.ToArray());
}
}
}
internal sealed record VerseRecorderOptions(
Uri Url,
string OutputDirectory,
double Seconds,
double ReconnectSeconds,
double MeterSeconds)
{
public static VerseRecorderOptions Parse(string[] args)
{
var defaultOutput = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyVideos),
"Mimir",
"VerseCaptures");
return new VerseRecorderOptions(
new Uri(ParseString(args, "--url", "ws://127.0.0.1:8796/eve/periwinkle/subscribe")),
ParseString(args, "--out-dir", defaultOutput),
ParseDouble(args, "--seconds", 0.0),
ParseDouble(args, "--reconnect-seconds", 2.0),
ParseDouble(args, "--meter-seconds", 5.0));
}
private static string ParseString(IReadOnlyList<string> args, string name, string fallback)
{
for (var index = 0; index < args.Count - 1; index++)
{
if (string.Equals(args[index], name, StringComparison.OrdinalIgnoreCase))
{
return args[index + 1];
}
}
return fallback;
}
private static double ParseDouble(IReadOnlyList<string> args, string name, double fallback)
{
return double.TryParse(ParseString(args, name, ""), out var value)
? value
: fallback;
}
}