Add typed CultNet operation dispatch

This commit is contained in:
Meta Vens 2026-08-18 05:59:11 +02:00
commit b0a876a220
13 changed files with 913 additions and 128 deletions

View file

@ -82,6 +82,29 @@ namespace GameCult.Mesh
public TResponse Value { get; }
}
/// <summary>Correlated framework-level failure returned before a typed domain reply exists.</summary>
public sealed class CultMeshRemoteOperationException : Exception
{
internal CultMeshRemoteOperationException(
CultNetOperationResponseMessage envelope,
CultNetOperationFailure failure)
: base(failure?.Message ?? "CultMesh operation failed.")
{
Status = envelope?.Status ?? "error";
Code = failure?.Code ?? "operation-error";
Diagnostics = envelope?.Diagnostics ?? Array.Empty<string>();
}
/// <summary>Gets the provider-authored failure status.</summary>
public string Status { get; }
/// <summary>Gets the stable machine-readable failure code.</summary>
public string Code { get; }
/// <summary>Gets provider diagnostics carried by the response.</summary>
public IReadOnlyList<string> Diagnostics { get; }
}
/// <summary>Owns one shared live document subscription until disposed.</summary>
public sealed class CultMeshDocumentLease<TDocument> : IDisposable where TDocument : class
{
@ -408,6 +431,24 @@ namespace GameCult.Mesh
if (!string.Equals(envelope.ServiceId, expectedService, StringComparison.Ordinal) ||
!string.Equals(envelope.Operation, expectedOperation, StringComparison.Ordinal))
throw new InvalidOperationException("CultMesh operation response did not match the requested service and operation.");
if (string.Equals(envelope.PayloadSchema, CultNetOperationServer.FailureSchemaId, StringComparison.Ordinal))
{
if (!string.Equals(envelope.PayloadEncoding, "messagepack-base64", StringComparison.Ordinal))
throw new InvalidOperationException(
$"CultMesh operation failure returned unsupported payload encoding '{envelope.PayloadEncoding}'.");
CultNetOperationFailure failure;
try
{
failure = MessagePackSerializer.Deserialize<CultNetOperationFailure>(
Convert.FromBase64String(envelope.Payload),
CultNetSchemaMessageSerialization.Options);
}
catch (Exception error) when (error is FormatException || error is MessagePackSerializationException)
{
throw new InvalidOperationException("CultMesh operation failure payload was malformed.", error);
}
throw new CultMeshRemoteOperationException(envelope, failure);
}
if (!string.Equals(envelope.PayloadSchema, expectedResponseSchema, StringComparison.Ordinal))
throw new InvalidOperationException(
$"CultMesh operation returned payload schema '{envelope.PayloadSchema}', expected '{expectedResponseSchema}'.");

View file

@ -34,13 +34,17 @@ wire, see [docs/typed-document-path.md](docs/typed-document-path.md).
## Eve / CultUI Surfaces
CultMesh includes the portable Eve/CultUI surface document contract and a fluent
builder for daemon-published UI. The builder is deliberately shaped like the
legacy CultUI/Unity properties panel API: compose menus and forms in readable
imperative code, while the emitted document carries typed CultMesh operation
bindings, state bindings, style tokens, and embedded surface slots.
CultMesh supplies the typed state and operation binding descriptors used by Eve.
The renderer-neutral `GameCult.Eve.Surface` package in the Eve repository owns
the portable surface document and fluent builder. Add that package when a daemon
publishes UI; do not add EveUnity to the provider. The emitted document carries
typed CultMesh operation bindings, state bindings, style tokens, and embedded
surface slots while remaining independent of any lowering runtime.
```csharp
using GameCult.Eve.Surface;
using GameCult.Mesh;
var menu = EveSurface.Create("aetheria.main_menu.root")
.Provider("aetheria", "game.menu")
.TitleSubtitle("AETHERIA", "TERMINUS")

View file

@ -29,6 +29,58 @@ CultMesh document session. Other runtime lowerers must preserve the same
boundary: they may reject or report unsupported capabilities, but they may not
import provider internals.
## The Application-Owned Part
Install the renderer-neutral `GameCult.Eve.Surface` package in the provider.
Do not install EveUnity or the browser lowerer there. A provider defines typed
state, one typed operation transaction, and one Eve surface. CultNet envelope
encoding is framework work:
```csharp
using GameCult.Eve.Surface;
using GameCult.Mesh;
using GameCult.Networking;
using var operations = new CultNetOperationServer(schemaServer, "sample.counter-provider")
.Register<IncrementRequest, IncrementReceipt>(
"sample.counter",
"sample.counter.increment",
"sample.increment.v1",
"gamecult.eve.command_receipt.v1",
async command => await IncrementExactlyOnceAsync(
command.IdempotencyKey,
command.Value));
var route = new CultMeshRouteHint(CultMeshLocalityKind.Network, "cultmesh");
var count = new CultMeshStateBindingDescriptor(
"value",
"sample.counter.count",
"sample.counter_state:counter:main",
"sample.counter_state.v1",
route);
var increment = CultMesh.OperationBinding(
"sample.counter.increment",
"Increment",
"sample.increment.v1",
route);
var surface = EveSurface.Create("sample.counter")
.Provider("sample.counter-provider", "sample.daemon")
.Title("CultMesh browser counter")
.RootColumn("counter.root", root => root
.Metric("counter.value", "Canonical count", "0", count)
.Button("counter.increment", "Increment", increment))
.Build();
```
`schemaServer` is a transport-neutral CultNet server port. WebSocket, RUDP, and
test transports attach the same dispatcher. The handler owns validation,
idempotency, state mutation, and its durable receipt. `CultNetOperationServer`
owns only route/schema checks and typed envelope serialization. The complete
provider transaction is in
[`samples/eve-browser-network/Program.cs`](../../../../samples/eve-browser-network/Program.cs);
it contains no hand-written operation base64 or MessagePack dispatch switch.
## Multi-Runtime Checkpoint
Run the same provider and connect at least two lowerers. Both must report the

View file

@ -0,0 +1,348 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MessagePack;
namespace GameCult.Networking
{
/// <summary>Portable failure payload for operation routing and envelope validation.</summary>
[MessagePackObject]
public sealed class CultNetOperationFailure
{
/// <summary>Gets or sets the stable machine-readable failure code.</summary>
[Key("code")] public string Code { get; set; } = "operation-error";
/// <summary>Gets or sets the human-readable failure description.</summary>
[Key("message")] public string Message { get; set; } = "CultNet operation failed.";
}
/// <summary>
/// Typed application input delivered through one CultNet operation envelope.
/// The message id is the caller's idempotency key; the application transaction
/// remains responsible for applying it exactly once.
/// </summary>
public sealed class CultNetOperationContext<TRequest>
{
internal CultNetOperationContext(CultNetOperationRequestMessage envelope, TRequest value)
{
Envelope = envelope ?? throw new ArgumentNullException(nameof(envelope));
Value = value;
}
/// <summary>Gets the decoded application request.</summary>
public TRequest Value { get; }
/// <summary>Gets the durable caller-supplied idempotency key.</summary>
public string IdempotencyKey => Envelope.MessageId;
/// <summary>Gets the calling runtime identity, when supplied.</summary>
public string? SourceRuntimeId => Envelope.SourceRuntimeId;
/// <summary>Gets the optional target runtime identity.</summary>
public string? TargetRuntimeId => Envelope.TargetRuntimeId;
/// <summary>Gets the original transport-neutral envelope for diagnostics.</summary>
public CultNetOperationRequestMessage Envelope { get; }
}
/// <summary>Provider-authored typed result for one CultNet operation.</summary>
public sealed class CultNetOperationReply<TResponse>
{
/// <summary>Creates one provider-authored typed reply.</summary>
public CultNetOperationReply(
string status,
TResponse value,
IEnumerable<string>? diagnostics = null)
{
Status = RequireNonEmpty(status, nameof(status));
Value = value;
Diagnostics = diagnostics == null ? Array.Empty<string>() : new List<string>(diagnostics).ToArray();
}
/// <summary>Gets the provider-authored operation status.</summary>
public string Status { get; }
/// <summary>Gets the typed response payload.</summary>
public TResponse Value { get; }
/// <summary>Gets provider-authored diagnostics.</summary>
public IReadOnlyList<string> Diagnostics { get; }
/// <summary>Creates an accepted typed reply.</summary>
public static CultNetOperationReply<TResponse> Accepted(TResponse value) => new("accepted", value);
/// <summary>Creates a rejected typed reply whose payload remains schema-valid.</summary>
public static CultNetOperationReply<TResponse> Rejected(
TResponse value,
params string[] diagnostics) => new("rejected", value, diagnostics);
private static string RequireNonEmpty(string value, string paramName) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", paramName)
: value.Trim();
}
/// <summary>
/// Transport-neutral typed dispatcher for CultNet application operations.
/// It owns envelope validation and serialization only; registered handlers own
/// domain validation, idempotency, state mutation, and durable receipts.
/// </summary>
public sealed class CultNetOperationServer : IDisposable
{
/// <summary>Schema used by correlated framework-level operation failures.</summary>
public const string FailureSchemaId = "gamecult.cultnet.operation_failure.v1";
private const string PayloadEncoding = "messagepack-base64";
private readonly ICultNetSchemaServer _server;
private readonly string? _sourceRuntimeId;
private readonly Dictionary<Route, IBinding> _bindings = new();
private readonly Func<CultNetOperationRequestMessage, ICultNetSchemaServerPeer, Task> _handler;
private bool _disposed;
/// <summary>Attaches one typed operation dispatcher to a schema server.</summary>
public CultNetOperationServer(ICultNetSchemaServer server, string? sourceRuntimeId = null)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_sourceRuntimeId = string.IsNullOrWhiteSpace(sourceRuntimeId) ? null : sourceRuntimeId!.Trim();
_handler = HandleAsync;
_server.OnCultNet(_handler);
}
/// <summary>
/// Registers one typed operation. Duplicate service/operation routes are rejected.
/// </summary>
public CultNetOperationServer Register<TRequest, TResponse>(
string serviceId,
string operation,
string requestSchema,
string responseSchema,
Func<CultNetOperationContext<TRequest>, Task<CultNetOperationReply<TResponse>>> handler)
{
ThrowIfDisposed();
var route = new Route(serviceId, operation);
if (_bindings.ContainsKey(route))
throw new InvalidOperationException($"CultNet operation '{route}' is already registered.");
_bindings.Add(route, new Binding<TRequest, TResponse>(
route,
requestSchema,
responseSchema,
handler ?? throw new ArgumentNullException(nameof(handler)),
_sourceRuntimeId));
return this;
}
/// <summary>
/// Registers one typed operation whose successful handler result is always accepted.
/// </summary>
public CultNetOperationServer Register<TRequest, TResponse>(
string serviceId,
string operation,
string requestSchema,
string responseSchema,
Func<CultNetOperationContext<TRequest>, Task<TResponse>> handler)
{
if (handler == null) throw new ArgumentNullException(nameof(handler));
return Register<TRequest, TResponse>(
serviceId,
operation,
requestSchema,
responseSchema,
async context => CultNetOperationReply<TResponse>.Accepted(await handler(context).ConfigureAwait(false)));
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultNetOperationRequestMessage>(_handler);
_bindings.Clear();
}
private async Task HandleAsync(CultNetOperationRequestMessage request, ICultNetSchemaServerPeer peer)
{
if (_disposed) return;
if (request == null) throw new ArgumentNullException(nameof(request));
if (peer == null) throw new ArgumentNullException(nameof(peer));
Route route;
try
{
route = new Route(request.ServiceId, request.Operation);
}
catch (ArgumentException error)
{
peer.SendCultNet(Failure(request, "invalid", "invalid-route", error.Message));
return;
}
if (!_bindings.TryGetValue(route, out var binding))
{
peer.SendCultNet(Failure(
request,
"unsupported",
"operation-not-registered",
$"CultNet operation '{route}' is not registered."));
return;
}
try
{
peer.SendCultNet(await binding.InvokeAsync(request).ConfigureAwait(false));
}
catch (RequestException error)
{
peer.SendCultNet(Failure(request, "invalid", error.Code, error.Message));
}
catch (Exception error)
{
peer.SendCultNet(Failure(
request,
"error",
"handler-failed",
$"CultNet operation '{route}' failed: {error.Message}"));
}
}
private CultNetOperationResponseMessage Failure(
CultNetOperationRequestMessage request,
string status,
string code,
string message)
{
return new CultNetOperationResponseMessage
{
MessageId = request.MessageId ?? "",
ServiceId = request.ServiceId ?? "",
Operation = request.Operation ?? "",
Status = status,
PayloadSchema = FailureSchemaId,
PayloadEncoding = PayloadEncoding,
Payload = Convert.ToBase64String(MessagePackSerializer.Serialize(
new CultNetOperationFailure { Code = code, Message = message },
CultNetSchemaMessageSerialization.Options)),
Diagnostics = new[] { message },
SourceRuntimeId = _sourceRuntimeId
};
}
private void ThrowIfDisposed()
{
if (_disposed) throw new ObjectDisposedException(nameof(CultNetOperationServer));
}
private interface IBinding
{
Task<CultNetOperationResponseMessage> InvokeAsync(CultNetOperationRequestMessage request);
}
private sealed class Binding<TRequest, TResponse> : IBinding
{
private readonly Route _route;
private readonly string _requestSchema;
private readonly string _responseSchema;
private readonly Func<CultNetOperationContext<TRequest>, Task<CultNetOperationReply<TResponse>>> _handler;
private readonly string? _sourceRuntimeId;
public Binding(
Route route,
string requestSchema,
string responseSchema,
Func<CultNetOperationContext<TRequest>, Task<CultNetOperationReply<TResponse>>> handler,
string? sourceRuntimeId)
{
_route = route;
_requestSchema = RequireNonEmpty(requestSchema, nameof(requestSchema));
_responseSchema = RequireNonEmpty(responseSchema, nameof(responseSchema));
_handler = handler;
_sourceRuntimeId = sourceRuntimeId;
}
public async Task<CultNetOperationResponseMessage> InvokeAsync(CultNetOperationRequestMessage request)
{
if (string.IsNullOrWhiteSpace(request.MessageId))
throw new RequestException("missing-idempotency-key", "CultNet operation omitted its idempotency key.");
if (!string.Equals(request.PayloadSchema, _requestSchema, StringComparison.Ordinal))
throw new RequestException(
"request-schema-mismatch",
$"CultNet operation '{_route}' expected payload schema '{_requestSchema}', got '{request.PayloadSchema}'.");
if (!string.Equals(request.PayloadEncoding, PayloadEncoding, StringComparison.Ordinal))
throw new RequestException(
"request-encoding-mismatch",
$"CultNet operation '{_route}' expected payload encoding '{PayloadEncoding}', got '{request.PayloadEncoding}'.");
TRequest value;
try
{
value = MessagePackSerializer.Deserialize<TRequest>(
Convert.FromBase64String(request.Payload),
CultNetSchemaMessageSerialization.Options);
}
catch (FormatException error)
{
throw new RequestException("request-payload-invalid", "CultNet operation payload was not valid base64.", error);
}
catch (MessagePackSerializationException error)
{
throw new RequestException("request-payload-invalid", "CultNet operation payload was not valid MessagePack.", error);
}
if (value == null) throw new RequestException("request-payload-null", "CultNet operation payload decoded to null.");
var reply = await _handler(new CultNetOperationContext<TRequest>(request, value)).ConfigureAwait(false)
?? throw new InvalidOperationException("CultNet operation handler returned no reply.");
if (reply.Value == null) throw new InvalidOperationException("CultNet operation handler returned a null payload.");
return new CultNetOperationResponseMessage
{
MessageId = request.MessageId,
ServiceId = _route.ServiceId,
Operation = _route.Operation,
Status = reply.Status,
PayloadSchema = _responseSchema,
PayloadEncoding = PayloadEncoding,
Payload = Convert.ToBase64String(MessagePackSerializer.Serialize(
reply.Value,
CultNetSchemaMessageSerialization.Options)),
Diagnostics = new List<string>(reply.Diagnostics).ToArray(),
SourceRuntimeId = _sourceRuntimeId
};
}
}
private sealed class RequestException : Exception
{
public RequestException(string code, string message, Exception? inner = null)
: base(message, inner)
{
Code = code;
}
public string Code { get; }
}
private readonly struct Route : IEquatable<Route>
{
public Route(string serviceId, string operation)
{
ServiceId = RequireNonEmpty(serviceId, nameof(serviceId));
Operation = RequireNonEmpty(operation, nameof(operation));
}
public string ServiceId { get; }
public string Operation { get; }
public bool Equals(Route other) =>
string.Equals(ServiceId, other.ServiceId, StringComparison.Ordinal) &&
string.Equals(Operation, other.Operation, StringComparison.Ordinal);
public override bool Equals(object? value) => value is Route route && Equals(route);
public override int GetHashCode() =>
(StringComparer.Ordinal.GetHashCode(ServiceId) * 397) ^ StringComparer.Ordinal.GetHashCode(Operation);
public override string ToString() => ServiceId + "/" + Operation;
}
private static string RequireNonEmpty(string value, string paramName) =>
string.IsNullOrWhiteSpace(value)
? throw new ArgumentException("Value must be non-empty.", paramName)
: value.Trim();
}
}

View file

@ -390,6 +390,33 @@ 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`.
## Typed Operations
`CultNetOperationServer` attaches typed application handlers to any
`ICultNetSchemaServer`. It owns route/schema validation, MessagePack envelope
encoding, correlation, and framework failure replies. The application handler
owns domain validation, state mutation, idempotency, and durable receipts:
```csharp
using var operations = new CultNetOperationServer(schemaServer, "counter.provider")
.Register<IncrementRequest, IncrementReceipt>(
"counter",
"counter.increment",
"counter.increment_request.v1",
"counter.increment_receipt.v1",
command => IncrementExactlyOnceAsync(
command.IdempotencyKey,
command.Value));
```
Returning `CultNetOperationReply<T>.Rejected(...)` preserves a schema-valid
domain receipt and status. Unknown routes, malformed payloads, and schema
mismatches return the correlated `gamecult.cultnet.operation_failure.v1`
payload; `CultMeshClient.InvokeAsync` raises
`CultMeshRemoteOperationException` immediately instead of timing out. The
browser client raises the equivalent `CultMeshBrowserOperationError` with the
same status and failure code.
## Browser WebSocket Host
`GameCult.Networking.WebSockets` keeps ASP.NET Core hosting out of the