Add native QUIC realtime transport for Unity

This commit is contained in:
Meta Vens 2026-07-19 22:55:06 +01:00
commit 1d126f4a35
37 changed files with 1150 additions and 86 deletions

View file

@ -0,0 +1,257 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Mesh;
namespace GameCult.Mesh.Quic.Native
{
public sealed class CultMeshNativeQuicRealtimeConnectorOptions
{
public TimeSpan HandshakeTimeout { get; set; } = TimeSpan.FromSeconds(10);
public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(2);
}
/// <summary>
/// Creates receive-capable MsQuic sessions on Unity-compatible managed runtimes.
/// Commands and receipts remain on their typed control plane.
/// </summary>
public sealed class CultMeshNativeQuicRealtimeTransportConnector : ICultMeshRealtimeTransportConnector
{
public const string Scheme = "cultmesh-state+quic";
private readonly CultMeshNativeQuicRealtimeConnectorOptions _options;
public CultMeshNativeQuicRealtimeTransportConnector(
CultMeshNativeQuicRealtimeConnectorOptions? options = null)
{
_options = options ?? new CultMeshNativeQuicRealtimeConnectorOptions();
if (_options.HandshakeTimeout <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options), "QUIC handshake timeout must be positive.");
if (_options.PollInterval <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options), "QUIC poll interval must be positive.");
}
public string ConnectorId => "msquic-native-realtime";
public int Priority => 0;
public bool CanConnect(CultMeshTransportCandidate candidate) =>
candidate != null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
TryParseEndpoint(candidate.Endpoint, out _, out _, out _);
public async Task<ICultMeshRealtimeTransport> ConnectAsync(
CultMeshTransportCandidate candidate,
CultMeshEndpointId endpointId,
CancellationToken cancellationToken = default)
{
if (candidate == null) throw new ArgumentNullException(nameof(candidate));
if (endpointId == null) throw new ArgumentNullException(nameof(endpointId));
if (!TryParseEndpoint(candidate.Endpoint, out var host, out var port, out var pin))
throw new NotSupportedException($"Native QUIC connector does not support '{candidate.Endpoint}'.");
IntPtr handle;
int opened;
try
{
opened = NativeMethods.Open(host, checked((ushort)port), pin, out handle);
}
catch (DllNotFoundException error)
{
throw new PlatformNotSupportedException(
"CultMesh native QUIC requires gamecult_mesh_quic_native and msquic beside the managed runtime.",
error);
}
catch (EntryPointNotFoundException error)
{
throw new PlatformNotSupportedException("The installed CultMesh native QUIC bridge is incompatible.", error);
}
if (opened != 0 || handle == IntPtr.Zero)
throw new IOException($"CultMesh native QUIC initialization failed with status 0x{opened:X8}.");
var transport = new CultMeshNativeQuicRealtimeTransport(
candidate.Endpoint,
handle,
_options.PollInterval);
try
{
await transport.WaitUntilConnectedAsync(_options.HandshakeTimeout, cancellationToken).ConfigureAwait(false);
return transport;
}
catch
{
transport.Dispose();
throw;
}
}
private static bool TryParseEndpoint(
string? endpoint,
out string host,
out int port,
out string certificatePin)
{
host = string.Empty;
port = 0;
certificatePin = string.Empty;
if (!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) ||
!string.Equals(uri.Scheme, Scheme, StringComparison.OrdinalIgnoreCase) ||
string.IsNullOrWhiteSpace(uri.Host) || uri.Port <= 0)
return false;
var pin = ParseQueryValue(uri.Query, "cert-sha256");
if (pin == null || pin.Length != 64) return false;
for (var index = 0; index < pin.Length; index++)
if (!Uri.IsHexDigit(pin[index])) return false;
host = uri.Host;
port = uri.Port;
certificatePin = pin.ToUpperInvariant();
return true;
}
private static string? ParseQueryValue(string query, string key)
{
foreach (var component in query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
{
var separator = component.IndexOf('=');
var candidateKey = separator < 0 ? component : component.Substring(0, separator);
if (!string.Equals(Uri.UnescapeDataString(candidateKey), key, StringComparison.OrdinalIgnoreCase))
continue;
return separator < 0 ? string.Empty : Uri.UnescapeDataString(component.Substring(separator + 1));
}
return null;
}
}
internal sealed class CultMeshNativeQuicRealtimeTransport : ICultMeshRealtimeTransport
{
private readonly object _gate = new object();
private readonly TimeSpan _pollInterval;
private IntPtr _handle;
private bool _disposed;
public CultMeshNativeQuicRealtimeTransport(string endpoint, IntPtr handle, TimeSpan pollInterval)
{
Endpoint = endpoint;
_handle = handle;
_pollInterval = pollInterval;
}
public string TransportId => "msquic-native-realtime";
public string Endpoint { get; }
public Task SendAsync(CultMeshRealtimeFrame frame, CancellationToken cancellationToken = default) =>
Task.FromException(new NotSupportedException(
"The Unity-compatible native QUIC connector currently owns provider-to-client state only."));
public async Task<CultMeshRealtimeFrame> ReceiveAsync(CancellationToken cancellationToken = default)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
byte[]? bytes = null;
lock (_gate)
{
ThrowIfDisposed();
var state = NativeMethods.State(_handle);
if (state == 2) throw new IOException(ReadNativeError(_handle));
var first = NativeMethods.Poll(_handle, IntPtr.Zero, 0, out var required);
if (first < 0) throw new IOException(ReadNativeError(_handle));
if (first == 2 && required > 0)
{
bytes = new byte[required];
var pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
var second = NativeMethods.Poll(
_handle,
pinned.AddrOfPinnedObject(),
bytes.Length,
out var received);
if (second != 1 || received != bytes.Length)
throw new IOException("CultMesh native QUIC frame changed while it was acquired.");
}
finally
{
pinned.Free();
}
}
}
if (bytes != null) return CultMeshRealtimeWireProtocol.DecodeFrame(bytes);
await Task.Delay(_pollInterval, cancellationToken).ConfigureAwait(false);
}
}
internal async Task WaitUntilConnectedAsync(TimeSpan timeout, CancellationToken cancellationToken)
{
var deadline = DateTimeOffset.UtcNow + timeout;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
lock (_gate)
{
ThrowIfDisposed();
var state = NativeMethods.State(_handle);
if (state == 1) return;
if (state == 2) throw new IOException(ReadNativeError(_handle));
}
if (DateTimeOffset.UtcNow >= deadline)
throw new TimeoutException($"CultMesh native QUIC handshake with '{Endpoint}' timed out.");
await Task.Delay(_pollInterval, cancellationToken).ConfigureAwait(false);
}
}
public void Dispose()
{
lock (_gate)
{
if (_disposed) return;
_disposed = true;
if (_handle != IntPtr.Zero) NativeMethods.Close(_handle);
_handle = IntPtr.Zero;
}
}
private void ThrowIfDisposed()
{
if (_disposed || _handle == IntPtr.Zero)
throw new ObjectDisposedException(nameof(CultMeshNativeQuicRealtimeTransport));
}
private static string ReadNativeError(IntPtr handle)
{
var bytes = new byte[1024];
var pinned = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
var count = NativeMethods.Error(handle, pinned.AddrOfPinnedObject(), bytes.Length);
return count > 0
? Encoding.UTF8.GetString(bytes, 0, count)
: "CultMesh native QUIC transport failed.";
}
finally
{
pinned.Free();
}
}
}
internal static class NativeMethods
{
private const string Library = "gamecult_mesh_quic_native";
[DllImport(Library, EntryPoint = "cultmesh_quic_open", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
internal static extern int Open(string host, ushort port, string certificateSha256, out IntPtr client);
[DllImport(Library, EntryPoint = "cultmesh_quic_state", CallingConvention = CallingConvention.Cdecl)]
internal static extern int State(IntPtr client);
[DllImport(Library, EntryPoint = "cultmesh_quic_poll", CallingConvention = CallingConvention.Cdecl)]
internal static extern int Poll(IntPtr client, IntPtr destination, int destinationLength, out int requiredLength);
[DllImport(Library, EntryPoint = "cultmesh_quic_error", CallingConvention = CallingConvention.Cdecl)]
internal static extern int Error(IntPtr client, IntPtr destination, int destinationLength);
[DllImport(Library, EntryPoint = "cultmesh_quic_close", CallingConvention = CallingConvention.Cdecl)]
internal static extern void Close(IntPtr client);
}
}

View file

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<AssemblyName>GameCult.Mesh.Quic.Native</AssemblyName>
<RootNamespace>GameCult.Mesh.Quic.Native</RootNamespace>
<Description>Native MsQuic CultMesh realtime connector for Unity and other netstandard runtimes.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\GameCult.Mesh\GameCult.Mesh.csproj" />
</ItemGroup>
</Project>

View file

@ -6,7 +6,6 @@ using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Channels;
namespace GameCult.Mesh.Quic;
@ -539,79 +538,18 @@ internal sealed class CultMeshRealtimeInbox
internal static class CultMeshQuicRealtimeProtocol
{
public static readonly SslApplicationProtocol ApplicationProtocol = new("cultmesh-state-v1");
public const long ConnectionCloseCode = 0x43554c54;
public const long StreamAbortCode = 0x53544154;
public const byte ReliableStream = 1;
public const byte LatestOnlyStream = 2;
private const uint Magic = 0x31545343;
private const int FixedHeaderBytes = 37;
private const int MaximumFrameBytes = 64 * 1024 * 1024;
public static readonly SslApplicationProtocol ApplicationProtocol =
new(CultMeshRealtimeWireProtocol.ApplicationProtocolName);
public const long ConnectionCloseCode = CultMeshRealtimeWireProtocol.ConnectionCloseCode;
public const long StreamAbortCode = CultMeshRealtimeWireProtocol.StreamAbortCode;
public const byte ReliableStream = CultMeshRealtimeWireProtocol.ReliableStream;
public const byte LatestOnlyStream = CultMeshRealtimeWireProtocol.LatestOnlyStream;
public static byte[] EncodeFrame(CultMeshRealtimeFrame frame)
{
var channel = Encoding.UTF8.GetBytes(frame.ChannelId);
var schema = Encoding.UTF8.GetBytes(frame.SchemaId);
var body = Encoding.UTF8.GetBytes(frame.BodyId);
if (channel.Length > ushort.MaxValue || schema.Length > ushort.MaxValue || body.Length > ushort.MaxValue)
throw new InvalidDataException("Realtime frame identity exceeds the QUIC wire limit.");
if (frame.Payload.Length > MaximumFrameBytes)
throw new InvalidDataException("Realtime frame payload exceeds the QUIC wire limit.");
public static byte[] EncodeFrame(CultMeshRealtimeFrame frame) =>
CultMeshRealtimeWireProtocol.EncodeFrame(frame);
var result = new byte[checked(FixedHeaderBytes + channel.Length + schema.Length + body.Length + frame.Payload.Length)];
var span = result.AsSpan();
BinaryPrimitives.WriteUInt32LittleEndian(span, Magic);
span[4] = (byte)frame.Delivery;
BinaryPrimitives.WriteInt64LittleEndian(span[5..], frame.ProducerEpoch);
BinaryPrimitives.WriteInt64LittleEndian(span[13..], frame.Sequence);
BinaryPrimitives.WriteUInt16LittleEndian(span[21..], (ushort)channel.Length);
BinaryPrimitives.WriteUInt16LittleEndian(span[23..], (ushort)schema.Length);
BinaryPrimitives.WriteUInt16LittleEndian(span[25..], (ushort)body.Length);
BinaryPrimitives.WriteInt32LittleEndian(span[27..], frame.Payload.Length);
BinaryPrimitives.WriteInt32LittleEndian(span[31..], FixedHeaderBytes);
BinaryPrimitives.WriteUInt16LittleEndian(span[35..], 1);
var offset = FixedHeaderBytes;
channel.CopyTo(span[offset..]); offset += channel.Length;
schema.CopyTo(span[offset..]); offset += schema.Length;
body.CopyTo(span[offset..]); offset += body.Length;
frame.Payload.Span.CopyTo(span[offset..]);
return result;
}
public static CultMeshRealtimeFrame DecodeFrame(byte[] bytes)
{
if (bytes.Length < FixedHeaderBytes) throw new InvalidDataException("Realtime frame header is truncated.");
var span = bytes.AsSpan();
if (BinaryPrimitives.ReadUInt32LittleEndian(span) != Magic)
throw new InvalidDataException("Realtime frame magic is invalid.");
if (BinaryPrimitives.ReadUInt16LittleEndian(span[35..]) != 1 ||
BinaryPrimitives.ReadInt32LittleEndian(span[31..]) != FixedHeaderBytes)
throw new InvalidDataException("Realtime frame wire version is unsupported.");
var delivery = (CultMeshRealtimeDelivery)span[4];
if (delivery is < CultMeshRealtimeDelivery.ReliableOrdered or > CultMeshRealtimeDelivery.Unreliable)
throw new InvalidDataException("Realtime frame delivery mode is invalid.");
var channelLength = BinaryPrimitives.ReadUInt16LittleEndian(span[21..]);
var schemaLength = BinaryPrimitives.ReadUInt16LittleEndian(span[23..]);
var bodyLength = BinaryPrimitives.ReadUInt16LittleEndian(span[25..]);
var payloadLength = BinaryPrimitives.ReadInt32LittleEndian(span[27..]);
var expected = checked(FixedHeaderBytes + channelLength + schemaLength + bodyLength + payloadLength);
if (payloadLength < 0 || expected != bytes.Length)
throw new InvalidDataException("Realtime frame length is invalid.");
var offset = FixedHeaderBytes;
var channel = Encoding.UTF8.GetString(span.Slice(offset, channelLength)); offset += channelLength;
var schema = Encoding.UTF8.GetString(span.Slice(offset, schemaLength)); offset += schemaLength;
var body = Encoding.UTF8.GetString(span.Slice(offset, bodyLength)); offset += bodyLength;
return new CultMeshRealtimeFrame
{
ChannelId = channel,
SchemaId = schema,
BodyId = body,
ProducerEpoch = BinaryPrimitives.ReadInt64LittleEndian(span[5..]),
Sequence = BinaryPrimitives.ReadInt64LittleEndian(span[13..]),
Delivery = delivery,
Payload = bytes.AsMemory(offset, payloadLength)
};
}
public static CultMeshRealtimeFrame DecodeFrame(byte[] bytes) =>
CultMeshRealtimeWireProtocol.DecodeFrame(bytes);
public static async Task WriteFramedAsync(Stream stream, byte[] payload, CancellationToken cancellationToken)
{
@ -628,7 +566,7 @@ internal static class CultMeshQuicRealtimeProtocol
if (first == 0) return null;
await ReadExactlyAsync(stream, header.AsMemory(1), cancellationToken).ConfigureAwait(false);
var length = BinaryPrimitives.ReadInt32LittleEndian(header);
if (length <= 0 || length > MaximumFrameBytes + FixedHeaderBytes + (3 * ushort.MaxValue))
if (length <= 0 || length > CultMeshRealtimeWireProtocol.MaximumEncodedFrameBytes)
throw new InvalidDataException("Realtime QUIC frame length is invalid.");
var payload = new byte[length];
await ReadExactlyAsync(stream, payload, cancellationToken).ConfigureAwait(false);

View file

@ -0,0 +1,93 @@
using System;
using System.Buffers.Binary;
using System.IO;
using System.Text;
namespace GameCult.Mesh
{
/// <summary>
/// Stable CultMesh realtime frame encoding shared by managed and native QUIC connectors.
/// QUIC stream framing remains transport-owned; this codec owns only typed frame bytes.
/// </summary>
public static class CultMeshRealtimeWireProtocol
{
public const string ApplicationProtocolName = "cultmesh-state-v1";
public const long ConnectionCloseCode = 0x43554c54;
public const long StreamAbortCode = 0x53544154;
public const byte ReliableStream = 1;
public const byte LatestOnlyStream = 2;
public const int MaximumFrameBytes = 64 * 1024 * 1024;
public const int MaximumEncodedFrameBytes = MaximumFrameBytes + 37 + (3 * ushort.MaxValue);
private const uint Magic = 0x31545343;
private const int FixedHeaderBytes = 37;
public static byte[] EncodeFrame(CultMeshRealtimeFrame frame)
{
if (frame == null) throw new ArgumentNullException(nameof(frame));
frame.Validate();
var channel = Encoding.UTF8.GetBytes(frame.ChannelId);
var schema = Encoding.UTF8.GetBytes(frame.SchemaId);
var body = Encoding.UTF8.GetBytes(frame.BodyId);
if (channel.Length > ushort.MaxValue || schema.Length > ushort.MaxValue || body.Length > ushort.MaxValue)
throw new InvalidDataException("Realtime frame identity exceeds the QUIC wire limit.");
if (frame.Payload.Length > MaximumFrameBytes)
throw new InvalidDataException("Realtime frame payload exceeds the QUIC wire limit.");
var result = new byte[checked(FixedHeaderBytes + channel.Length + schema.Length + body.Length + frame.Payload.Length)];
var span = result.AsSpan();
BinaryPrimitives.WriteUInt32LittleEndian(span, Magic);
span[4] = (byte)frame.Delivery;
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(5), frame.ProducerEpoch);
BinaryPrimitives.WriteInt64LittleEndian(span.Slice(13), frame.Sequence);
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(21), (ushort)channel.Length);
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(23), (ushort)schema.Length);
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(25), (ushort)body.Length);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(27), frame.Payload.Length);
BinaryPrimitives.WriteInt32LittleEndian(span.Slice(31), FixedHeaderBytes);
BinaryPrimitives.WriteUInt16LittleEndian(span.Slice(35), 1);
var offset = FixedHeaderBytes;
channel.CopyTo(span.Slice(offset)); offset += channel.Length;
schema.CopyTo(span.Slice(offset)); offset += schema.Length;
body.CopyTo(span.Slice(offset)); offset += body.Length;
frame.Payload.Span.CopyTo(span.Slice(offset));
return result;
}
public static CultMeshRealtimeFrame DecodeFrame(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length < FixedHeaderBytes) throw new InvalidDataException("Realtime frame header is truncated.");
var span = bytes.AsSpan();
if (BinaryPrimitives.ReadUInt32LittleEndian(span) != Magic)
throw new InvalidDataException("Realtime frame magic is invalid.");
if (BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(35)) != 1 ||
BinaryPrimitives.ReadInt32LittleEndian(span.Slice(31)) != FixedHeaderBytes)
throw new InvalidDataException("Realtime frame wire version is unsupported.");
var delivery = (CultMeshRealtimeDelivery)span[4];
if (delivery < CultMeshRealtimeDelivery.ReliableOrdered || delivery > CultMeshRealtimeDelivery.Unreliable)
throw new InvalidDataException("Realtime frame delivery mode is invalid.");
var channelLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(21));
var schemaLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(23));
var bodyLength = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(25));
var payloadLength = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(27));
var expected = checked(FixedHeaderBytes + channelLength + schemaLength + bodyLength + payloadLength);
if (payloadLength < 0 || expected != bytes.Length)
throw new InvalidDataException("Realtime frame length is invalid.");
var offset = FixedHeaderBytes;
var channel = Encoding.UTF8.GetString(bytes, offset, channelLength); offset += channelLength;
var schema = Encoding.UTF8.GetString(bytes, offset, schemaLength); offset += schemaLength;
var body = Encoding.UTF8.GetString(bytes, offset, bodyLength); offset += bodyLength;
return new CultMeshRealtimeFrame
{
ChannelId = channel,
SchemaId = schema,
BodyId = body,
ProducerEpoch = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(5)),
Sequence = BinaryPrimitives.ReadInt64LittleEndian(span.Slice(13)),
Delivery = delivery,
Payload = bytes.AsMemory(offset, payloadLength)
};
}
}
}

View file

@ -36,9 +36,18 @@ It maps reliable ordered frames to one persistent stream and latest-only frames
to independent streams with keyed `(producer epoch, sequence)` pending-state
replacement. Its
`System.Net.Quic` adapter fails closed for unreliable frames because that API
does not expose QUIC datagrams. A native MsQuic connector must own that mode and
the generic Unity runtime boundary. No RUDP implementation is installed
implicitly in its place.
does not expose QUIC datagrams. `GameCult.Mesh.Quic.Native` owns the generic
Unity/client boundary through the MsQuic C API. The Unity package carries its
managed connector and the pinned Windows x64 Schannel runtime; consumers
register `CultMeshNativeQuicRealtimeTransportConnector`, then ask CultMesh for
the advertised realtime route. The connector currently receives provider state
and fails closed if used to send; commands and receipts remain on the typed TCP
control plane. No RUDP implementation is installed implicitly in its place.
Local mapped bodies remain the first state plane. A consumer opens the
advertised mapping when it is actually reachable; otherwise it connects to the
advertised QUIC route. Latest-only receivers must replace pending generations
per body rather than queueing render debt.
**Derived state:** connector choice, physical endpoint, connection health, and
transport diagnostics. None of these grant provider authority or become content
@ -64,11 +73,10 @@ new seam does not pretend that migration has already occurred.
## Security and release gate
The current TCP connectors are a local-development transport and are plaintext.
Remote release requires authenticated encryption and binding the authenticated
peer to the advertised provider identity. Adding TLS must not move discovery,
authorization, content verification, or application semantics into the TCP
adapter.
The current TCP control and content connectors are plaintext and therefore
restricted to local or otherwise trusted deployment. Adding TLS must not move
discovery, authorization, content verification, or application semantics into
the TCP adapter.
The QUIC adapter always uses TLS 1.3. Its certificate validation callback is
given the advertised endpoint identity so the consumer can bind transport