Add real browser CultMesh transport proof

This commit is contained in:
Meta Vens 2026-08-18 00:05:57 +02:00
commit 8eb89e38ec
29 changed files with 2936 additions and 47 deletions

View file

@ -4,23 +4,38 @@ Date: 2026-08-17
## Status
This is the implementation map for the missing real-browser checkpoint. The
current `samples/eve-two-runtime` proof uses jsdom and one local TypeScript
CultMesh node. It is a clean package-consumer and contract-validation proof,
not browser networking.
This is the implementation map for the browser Verse boundary.
`samples/eve-two-runtime` remains the clean package-consumer/jsdom checkpoint.
`samples/eve-browser-network` runs a durable C# provider, a real Chromium Eve
lowerer, and an independent C# headless observer over the same authenticated
binary CultNet WebSocket route. It proves one canonical command effect,
idempotent retry, shared observation, and provider restart.
The current substrate is incomplete:
The current substrate has a browser client boundary and local live proof, but
not a complete public Verse proof:
- `cultmesh-ts` is a Node package and imports `node:dgram` at its root;
- `cultnet-ts` mixes browser-safe schema contracts with Node transport,
filesystem, crypto, stream, and UDP modules;
- `cultnet-ts/contracts` is the browser-safe contract entrypoint; the package
root still includes Node transport, filesystem, crypto, stream, and UDP
modules and must not enter browser bundles;
- C# and TypeScript now share `cultnet.database_subscribe.v0`,
`cultnet.database_unsubscribe.v0`, and `cultnet.database_change_raw.v0`;
the browser-safe transport package that consumes them does not exist yet;
- Kotlin has a channel-aware WebSocket transport adapter; C# and TypeScript do
not expose the equivalent browser/server pair;
`cultmesh-browser` consumes those messages as explicit document leases;
- `cultmesh-browser` owns stable identity, route refresh, resubscription, and
typed operation correlation without exposing direct document writes;
- Kotlin has a channel-aware WebSocket transport adapter, TypeScript has the
browser client, and `GameCult.Networking.WebSockets` provides the bounded C#
schema server host adapter;
- Hermodr can lower Odin state into a browser, but it is an infrastructure
runtime, not the missing clean-consumer game API.
runtime, not the clean-consumer game API;
- the sample rendezvous port currently returns one configured local route;
discovery from a live Odin and automatic route rotation are not yet in the
executable cross-runtime gate.
- the sample validates its surface against Eve's canonical TypeScript contract,
but its provider still carries a minimal local C# DTO mirror. The
released-artifact gate requires the renderer-neutral C# Eve surface contract
as an independently consumable Eve artifact; Unity must not be that contract's
package owner.
## Authority Map
@ -83,12 +98,13 @@ Shared paths:
Deletion line:
- stop calling jsdom a browser runtime;
- split browser-safe CultNet contracts from the Node transport package;
- add the missing subscription messages to the shared generated contract
catalog instead of retyping them in a browser adapter;
- do not retain a sample-only WebSocket protocol after the canonical adapter
exists.
- the jsdom checkpoint remains labeled as a Node-hosted DOM proof;
- browser applications import `cultmesh-browser` and
`cultnet-ts/contracts`, never the Node-only package roots;
- subscription messages remain one shared schema contract across the C# and
TypeScript catalogs;
- the real provider adapter must consume the canonical WebSocket message lane;
no sample-only WebSocket protocol is permitted.
## Required Runtime Shape
@ -96,16 +112,24 @@ The browser-facing package must be importable by a standards-mode browser or a
normal bundler without Node polyfills. It exposes a narrow API shaped like:
```ts
const mesh = await CultMeshBrowser.connect({
const mesh = await CultMeshBrowserClient.connect({
rendezvous: odin,
verseId: "sample.counter",
providerId: "sample.counter-provider",
runtimeId: "sample.browser",
});
using surface = await mesh.leaseDocument(eveSurface, "eve:surface:counter");
surface.watch(render);
using surface = await mesh.leaseRawDocument({
schemaId: "gamecult.eve.surface.v1",
recordKey: "eve:surface:counter",
});
surface.watch(record => render(decodeCultNetPayload(record)));
const receipt = await mesh.invoke(incrementCounter, {}, {
const receipt = await mesh.invoke({
serviceId: "sample.counter",
operation: "increment",
payloadSchema: "sample.increment.v1",
payload: {},
idempotencyKey: crypto.randomUUID(),
});
```
@ -136,6 +160,20 @@ identity, authority, and idempotency validation happen before provider code.
## Acceptance Gate
Current executable coverage from `scripts/verify-eve-browser-network.mjs`:
- authenticated binary C# WebSocket provider;
- real Chromium and independent C# headless consumers;
- shared surface and counter document leases;
- Eve button to typed operation to provider receipt to shared state;
- duplicate idempotency key produces one effect;
- provider restart rehydrates the `.cc` state;
- generated browser bundle contains no `node:` builtin import.
The full public Verse gate still requires live Odin discovery, physical route
rotation during retained leases, released-artifact-only .NET consumption, and
Windows/Linux CI.
From an empty temporary consumer using packed/released artifacts only:
1. start a provider daemon with one durable counter document and one validated

View file

@ -61,11 +61,17 @@ cd E:\Projects\EveUnity
powershell -ExecutionPolicy Bypass -File .\scripts\run-release-consumer-tests.ps1
```
This checkpoint proves clean package consumption, canonical Eve contract
This first checkpoint proves clean package consumption, canonical Eve contract
validation, and two independent lowering/observation consumers inside Node. It
does **not** claim a real browser process, an Odin-discovered network hop, or
cross-language command execution. Those are the next public Verse conformance
gates; do not cite this sample as evidence that they exist. Their owner map and
executable acceptance contract are recorded in
cross-language command execution. Do not cite it as evidence for those layers.
The next executable checkpoint is
[`samples/eve-browser-network`](../../../../samples/eve-browser-network/README.md).
It runs a durable C# provider, a real Chromium Eve lowerer, and an independent
C# headless observer over the same authenticated binary CultNet WebSocket lane.
It proves command idempotency and provider restart. Live Odin discovery and
route rotation remain separate gates. Their owner map and full acceptance
contract are recorded in
[`browser-verse-transport.md`](../browser-verse-transport.md).

View file

@ -0,0 +1,166 @@
using System.Collections.Concurrent;
using System.Net.WebSockets;
using GameCult.Networking;
namespace GameCult.Networking.WebSockets;
/// <summary>Schema-v0 client over a binary WebSocket route.</summary>
public sealed class CultNetWebSocketSchemaClient : ICultNetSchemaClient, ICultNetSchemaClientHealth
{
private readonly ConcurrentDictionary<Type, List<Delegate>> _handlers = new();
private readonly object _handlerGate = new();
private readonly SemaphoreSlim _sendGate = new(1, 1);
private readonly CancellationTokenSource _shutdown = new();
private readonly TaskCompletionSource<Exception> _backgroundFailure = new(
TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Action<ClientWebSocketOptions>? _configure;
private readonly int _maxMessageBytes;
private ClientWebSocket? _socket;
private bool _disposed;
/// <summary>Creates a binary WebSocket schema client.</summary>
public CultNetWebSocketSchemaClient(
Action<ClientWebSocketOptions>? configure = null,
int maxMessageBytes = 4 * 1024 * 1024)
{
if (maxMessageBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxMessageBytes));
_configure = configure;
_maxMessageBytes = maxMessageBytes;
}
/// <inheritdoc />
public bool Connected => !_disposed && _socket?.State == WebSocketState.Open;
/// <inheritdoc />
public Task<Exception> BackgroundFailure => _backgroundFailure.Task;
/// <inheritdoc />
public void Connect(string host, int port)
{
ArgumentException.ThrowIfNullOrWhiteSpace(host);
if (port <= 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port));
ConnectAsync(new Uri($"ws://{host}:{port}/cultmesh"), CancellationToken.None)
.GetAwaiter().GetResult();
}
/// <summary>Connects to an exact WebSocket route.</summary>
public async Task ConnectAsync(Uri endpoint, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(endpoint);
if (endpoint.Scheme is not ("ws" or "wss"))
throw new ArgumentException("CultNet WebSocket endpoint must use ws:// or wss://.", nameof(endpoint));
ThrowIfDisposed();
if (_socket != null) throw new InvalidOperationException("CultNet WebSocket client is already connected.");
var socket = new ClientWebSocket();
_configure?.Invoke(socket.Options);
try
{
await socket.ConnectAsync(endpoint, cancellationToken).ConfigureAwait(false);
_socket = socket;
_ = ReceiveLoopAsync(socket, _shutdown.Token);
}
catch
{
socket.Dispose();
throw;
}
}
/// <inheritdoc />
public void SendCultNet<T>(T message) where T : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(message);
ThrowIfDisposed();
var socket = _socket;
if (socket?.State != WebSocketState.Open)
throw new InvalidOperationException("CultNet WebSocket client is not connected.");
var payload = CultNetSchemaMessageSerialization.Serialize(message);
if (payload.Length > _maxMessageBytes)
throw new InvalidOperationException(
$"CultNet message exceeds the {_maxMessageBytes}-byte WebSocket limit.");
_sendGate.Wait();
try
{
CultNetWebSocketMessageIO.SendAsync(socket, payload, _shutdown.Token).GetAwaiter().GetResult();
}
finally
{
_sendGate.Release();
}
}
/// <inheritdoc />
public void OnCultNet<T>(Action<T> callback) where T : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(callback);
ThrowIfDisposed();
lock (_handlerGate)
{
if (!_handlers.TryGetValue(typeof(T), out var handlers))
_handlers[typeof(T)] = handlers = new List<Delegate>();
handlers.Add(callback);
}
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_shutdown.Cancel();
var socket = _socket;
_socket = null;
try
{
if (socket?.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "CultNet client disposed", closeTimeout.Token)
.GetAwaiter().GetResult();
}
}
catch (Exception error) when (error is WebSocketException or OperationCanceledException)
{
socket?.Abort();
}
socket?.Dispose();
_sendGate.Dispose();
_shutdown.Dispose();
}
private async Task ReceiveLoopAsync(WebSocket socket, CancellationToken cancellationToken)
{
try
{
while (!_disposed && socket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
{
var payload = await CultNetWebSocketMessageIO.ReceiveAsync(socket, _maxMessageBytes, cancellationToken)
.ConfigureAwait(false);
if (payload == null) return;
Dispatch(CultNetSchemaMessageSerialization.Deserialize(payload));
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
catch (Exception error) when (!_disposed)
{
_backgroundFailure.TrySetResult(error);
}
}
private void Dispatch(ICultNetSchemaMessage message)
{
Delegate[] handlers;
lock (_handlerGate)
handlers = _handlers.TryGetValue(message.GetType(), out var registered)
? registered.ToArray()
: Array.Empty<Delegate>();
foreach (var handler in handlers) handler.DynamicInvoke(message);
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
}

View file

@ -0,0 +1,260 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.WebSockets;
using GameCult.Networking;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
namespace GameCult.Networking.WebSockets;
/// <summary>Controls the bounded CultNet schema-v0 WebSocket endpoint.</summary>
public sealed class CultNetWebSocketEndpointOptions
{
/// <summary>Maximum accepted binary CultNet message size.</summary>
public int MaxMessageBytes { get; init; } = 4 * 1024 * 1024;
/// <summary>
/// Authorizes the HTTP upgrade before it can become a CultNet peer. Production hosts
/// should bind this to their authenticated session middleware.
/// </summary>
public Func<HttpContext, ValueTask<bool>>? AuthorizeAsync { get; init; }
/// <summary>Allows an unauthenticated endpoint for explicit local development only.</summary>
public bool AllowAnonymousDevelopment { get; init; }
}
/// <summary>
/// Adapts one binary WebSocket endpoint to the transport-neutral CultNet schema server port.
/// The host owns HTTP, TLS, and authentication; this adapter owns bounded binary message
/// assembly, schema validation, handler dispatch, peer lifetime, and serialized sends.
/// </summary>
public sealed class CultNetWebSocketSchemaServer :
ICultNetSchemaServer,
ICultNetSchemaServerPeerLifecycle,
IAsyncDisposable
{
private readonly ConcurrentDictionary<Type, Delegate> _handlers = new();
private readonly ConcurrentDictionary<WebSocketPeer, byte> _peers = new();
private bool _disposed;
/// <inheritdoc />
public event Action<ICultNetSchemaServerPeer>? PeerDisconnected;
/// <summary>Gets the active upgraded peer count.</summary>
public int PeerCount => _peers.Count;
/// <inheritdoc />
public void OnCultNet<TMessage>(Func<TMessage, ICultNetSchemaServerPeer, Task> callback)
where TMessage : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(callback);
ThrowIfDisposed();
_handlers[typeof(TMessage)] = callback;
}
/// <inheritdoc />
public void RemoveCultNetMessageListener<TMessage>(Delegate callback)
where TMessage : ICultNetSchemaMessage
{
if (_handlers.TryGetValue(typeof(TMessage), out var existing) && existing == callback)
_handlers.TryRemove(typeof(TMessage), out _);
}
/// <summary>Serves one already-authorized WebSocket until it closes.</summary>
public async Task AcceptAsync(
WebSocket socket,
EndPoint? remoteEndPoint = null,
int maxMessageBytes = 4 * 1024 * 1024,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(socket);
ThrowIfDisposed();
if (maxMessageBytes <= 0) throw new ArgumentOutOfRangeException(nameof(maxMessageBytes));
var peer = new WebSocketPeer(socket, remoteEndPoint, maxMessageBytes);
if (!_peers.TryAdd(peer, 0)) throw new InvalidOperationException("CultNet WebSocket peer already exists.");
try
{
while (!_disposed && socket.State == WebSocketState.Open && !cancellationToken.IsCancellationRequested)
{
var payload = await CultNetWebSocketMessageIO.ReceiveAsync(socket, maxMessageBytes, cancellationToken)
.ConfigureAwait(false);
if (payload == null) break;
var message = CultNetSchemaMessageSerialization.Deserialize(payload);
if (!_handlers.TryGetValue(message.GetType(), out var handler)) continue;
if (handler.DynamicInvoke(message, peer) is Task task) await task.ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
finally
{
if (_peers.TryRemove(peer, out _)) PeerDisconnected?.Invoke(peer);
await peer.DisposeAsync().ConfigureAwait(false);
}
}
/// <inheritdoc />
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
var peers = _peers.Keys.ToArray();
_peers.Clear();
foreach (var peer in peers)
{
PeerDisconnected?.Invoke(peer);
await peer.DisposeAsync().ConfigureAwait(false);
}
_handlers.Clear();
}
private void ThrowIfDisposed()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
private sealed class WebSocketPeer :
ICultNetSchemaServerPeer,
ICultNetSchemaServerPeerLocation,
IAsyncDisposable
{
private readonly WebSocket _socket;
private readonly SemaphoreSlim _sendGate = new(1, 1);
private readonly int _maxMessageBytes;
private bool _disposed;
public WebSocketPeer(WebSocket socket, EndPoint? remoteEndPoint, int maxMessageBytes)
{
_socket = socket;
RemoteEndPoint = remoteEndPoint;
_maxMessageBytes = maxMessageBytes;
}
public EndPoint? RemoteEndPoint { get; }
public void SendCultNet<TMessage>(TMessage message) where TMessage : ICultNetSchemaMessage
{
ArgumentNullException.ThrowIfNull(message);
if (_disposed || _socket.State != WebSocketState.Open)
throw new InvalidOperationException("CultNet WebSocket peer is not open.");
var payload = CultNetSchemaMessageSerialization.Serialize(message);
if (payload.Length > _maxMessageBytes)
throw new InvalidOperationException(
$"CultNet message exceeds the {_maxMessageBytes}-byte WebSocket limit.");
_sendGate.Wait();
try
{
CultNetWebSocketMessageIO.SendAsync(_socket, payload, CancellationToken.None)
.GetAwaiter().GetResult();
}
finally
{
_sendGate.Release();
}
}
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
try
{
if (_socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
using var closeTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(1));
await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "CultNet peer closed", closeTimeout.Token)
.ConfigureAwait(false);
}
}
catch (Exception error) when (error is WebSocketException or OperationCanceledException)
{
_socket.Abort();
}
_socket.Dispose();
_sendGate.Dispose();
}
}
}
internal static class CultNetWebSocketMessageIO
{
public static Task SendAsync(WebSocket socket, byte[] payload, CancellationToken cancellationToken) =>
socket.SendAsync(payload, WebSocketMessageType.Binary, true, cancellationToken);
public static async Task<byte[]?> ReceiveAsync(
WebSocket socket,
int maxMessageBytes,
CancellationToken cancellationToken)
{
var segment = new byte[Math.Min(16 * 1024, maxMessageBytes)];
using var message = new MemoryStream();
while (true)
{
var result = await socket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close) return null;
if (result.MessageType != WebSocketMessageType.Binary)
{
await socket.CloseAsync(
WebSocketCloseStatus.InvalidMessageType,
"CultNet requires binary MessagePack WebSocket messages.",
cancellationToken).ConfigureAwait(false);
return null;
}
if (message.Length + result.Count > maxMessageBytes)
{
await socket.CloseAsync(
WebSocketCloseStatus.MessageTooBig,
"CultNet message exceeds the configured maximum.",
cancellationToken).ConfigureAwait(false);
return null;
}
message.Write(segment, 0, result.Count);
if (result.EndOfMessage) return message.ToArray();
}
}
}
/// <summary>ASP.NET Core endpoint mapping for the CultNet WebSocket schema server.</summary>
public static class CultNetWebSocketEndpointRouteBuilderExtensions
{
/// <summary>Maps one authenticated binary CultNet WebSocket endpoint.</summary>
public static IEndpointConventionBuilder MapCultNetWebSocket(
this IEndpointRouteBuilder endpoints,
string pattern,
CultNetWebSocketSchemaServer server,
CultNetWebSocketEndpointOptions options)
{
ArgumentNullException.ThrowIfNull(endpoints);
ArgumentException.ThrowIfNullOrWhiteSpace(pattern);
ArgumentNullException.ThrowIfNull(server);
ArgumentNullException.ThrowIfNull(options);
if (options.MaxMessageBytes <= 0) throw new ArgumentOutOfRangeException(nameof(options.MaxMessageBytes));
if (options.AuthorizeAsync == null && !options.AllowAnonymousDevelopment)
throw new InvalidOperationException(
"CultNet WebSocket endpoints require AuthorizeAsync unless AllowAnonymousDevelopment is explicitly enabled.");
return endpoints.Map(pattern, async context =>
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = StatusCodes.Status426UpgradeRequired;
return;
}
if (options.AuthorizeAsync != null && !await options.AuthorizeAsync(context).ConfigureAwait(false))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
await server.AcceptAsync(
socket,
context.Connection.RemoteIpAddress == null
? null
: new IPEndPoint(context.Connection.RemoteIpAddress, context.Connection.RemotePort),
options.MaxMessageBytes,
context.RequestAborted).ConfigureAwait(false);
});
}
}

View file

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Description>CultNet schema-v0 WebSocket host adapter for browser and web runtimes</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GameCult.Networking\GameCult.Networking.csproj" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>

View file

@ -390,6 +390,21 @@ peer lookup and handshake before returning the same RUDP transport. Packet
semantics, schema-channel send/receive helpers, and reconnect state still live
in `GameCult.Networking`.
## Browser WebSocket Host
`GameCult.Networking.WebSockets` keeps ASP.NET Core hosting out of the
netstandard CultNet core while adapting an authenticated binary WebSocket to
the same `ICultNetSchemaServer` and `ICultNetSchemaClient` ports. A host calls
`UseWebSockets()` and maps `MapCultNetWebSocket(...)` with an authorization
predicate. Anonymous use requires the explicit `AllowAnonymousDevelopment`
opt-in. Text frames and messages over the configured size bound are closed
before schema dispatch.
The matching `CultNetWebSocketSchemaClient` is suitable for C# headless and
service consumers. Browser applications use `cultmesh-browser`, which owns
stable Verse/provider identity, document leases, resubscription, and operation
correlation above the raw WebSocket route.
## Important Constraints
- `Server` currently centers on `PlayerData` as the built-in account model.