Add managed CultMesh content sessions

This commit is contained in:
Meta Vens 2026-07-14 01:13:23 +01:00
commit 7d57140275
6 changed files with 519 additions and 0 deletions

View file

@ -0,0 +1,191 @@
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Networking;
namespace GameCult.Mesh
{
/// <summary>
/// Serves bounded, content-addressed CDN chunks over the CultMesh content protocol.
/// Manifests and descriptors remain typed document state; payload bytes do not.
/// </summary>
public sealed class CultMeshContentServer : IDisposable
{
private readonly ICultNetSchemaServer _server;
private readonly CultCache _content;
private readonly Func<string, bool> _canServeHash;
private readonly Func<CultMeshContentChunkRequestMessage, ICultNetSchemaServerPeer, Task> _handler;
private bool _disposed;
/// <summary>Attaches content serving to an existing schema host and provider cache.</summary>
public CultMeshContentServer(
ICultNetSchemaServer server,
CultCache content,
Func<string, bool>? canServeHash = null)
{
_server = server ?? throw new ArgumentNullException(nameof(server));
_content = content ?? throw new ArgumentNullException(nameof(content));
_canServeHash = canServeHash ?? (_ => true);
_handler = HandleAsync;
_server.OnCultNet(_handler);
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_server.RemoveCultNetMessageListener<CultMeshContentChunkRequestMessage>(_handler);
}
private Task HandleAsync(
CultMeshContentChunkRequestMessage request,
ICultNetSchemaServerPeer peer)
{
var response = new CultMeshContentChunkResponseMessage
{
MessageId = request?.MessageId ?? string.Empty,
ChunkHash = request?.ChunkHash ?? string.Empty
};
try
{
if (request == null || string.IsNullOrWhiteSpace(request.MessageId))
throw new InvalidDataException("Content chunk request requires a message identity.");
var hash = CultMeshCdn.NormalizeHash(request.ChunkHash, nameof(request.ChunkHash));
if (!_canServeHash(hash))
throw new UnauthorizedAccessException("Content access policy rejected the requested hash.");
var canonicalKey = CultMeshCdnArtifactChunk.CreateRecordKey(hash);
if (!string.IsNullOrWhiteSpace(request.RecordKey) &&
!string.Equals(request.RecordKey, canonicalKey.Value, StringComparison.Ordinal))
throw new InvalidDataException("Content chunk record key disagrees with its content hash.");
var chunk = _content.Get<CultMeshCdnArtifactChunk>(canonicalKey)
?? throw new FileNotFoundException("Content chunk is not available.", canonicalKey.Value);
var reference = new CultMeshCdnChunkRef
{
ChunkHash = hash,
RecordKey = canonicalKey.Value,
SizeBytes = request.ExpectedSizeBytes
};
CultMeshCdn.ValidateChunkPayload(reference, chunk);
response.Found = true;
response.ChunkHash = hash;
response.SizeBytes = chunk.SizeBytes;
response.Payload = chunk.Payload;
}
catch (Exception error)
{
response.Found = false;
response.Error = error.GetType().Name + ": " + error.Message;
response.Payload = Array.Empty<byte>();
}
peer.SendCultNet(response);
return Task.CompletedTask;
}
}
/// <summary>Configures bounded response waiting for session-backed content requests.</summary>
public sealed class CultMeshSessionContentProviderOptions
{
/// <summary>Gets or sets the injected reliability clock.</summary>
public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance;
/// <summary>Gets or sets the maximum time to wait for one chunk response.</summary>
public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(10);
}
/// <summary>
/// Retrieves verified CDN chunks through one reusable identity-first CultMesh session.
/// Transfer verification and final cache promotion remain owned by CultMeshContentTransferService.
/// </summary>
public sealed class CultMeshSessionContentProvider : ICultMeshContentProvider
{
private readonly CultMeshSessionManager _sessions;
private readonly CultMeshEndpointId _endpointId;
private readonly CultMeshSessionContentProviderOptions _options;
/// <summary>Creates a content provider backed by a reusable identity-first session.</summary>
public CultMeshSessionContentProvider(
string providerId,
CultMeshSessionManager sessions,
CultMeshEndpointId endpointId,
CultMeshSessionContentProviderOptions? options = null)
{
ProviderId = string.IsNullOrWhiteSpace(providerId)
? throw new ArgumentException("Provider identity is required.", nameof(providerId))
: providerId;
_sessions = sessions ?? throw new ArgumentNullException(nameof(sessions));
_endpointId = endpointId ?? throw new ArgumentNullException(nameof(endpointId));
_options = options ?? new CultMeshSessionContentProviderOptions();
if (_options.ResponseTimeout <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options), "Content response timeout must be positive.");
}
/// <inheritdoc />
public string ProviderId { get; }
/// <inheritdoc />
public async Task<CultMeshCdnArtifactChunk?> GetChunkAsync(
CultMeshCdnChunkRef chunk,
CancellationToken cancellationToken = default)
{
if (chunk == null) throw new ArgumentNullException(nameof(chunk));
var hash = CultMeshCdn.NormalizeHash(chunk.ChunkHash, nameof(chunk.ChunkHash));
var session = await _sessions.ConnectAsync(
_endpointId,
CultMeshProtocols.Content,
cancellationToken).ConfigureAwait(false);
var messageId = Guid.NewGuid().ToString("N");
var completion = new TaskCompletionSource<CultMeshContentChunkResponseMessage>(
TaskCreationOptions.RunContinuationsAsynchronously);
using var responseSubscription = session.OnCultNet<CultMeshContentChunkResponseMessage>(response =>
{
if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal))
completion.TrySetResult(response);
});
using var errorSubscription = session.OnCultNet<CultNetErrorMessage>(error =>
completion.TrySetException(new IOException(error.Error)));
session.SendCultNet(new CultMeshContentChunkRequestMessage
{
MessageId = messageId,
ChunkHash = hash,
RecordKey = string.IsNullOrWhiteSpace(chunk.RecordKey)
? CultMeshCdnArtifactChunk.CreateRecordKey(hash).Value
: chunk.RecordKey,
ExpectedSizeBytes = chunk.SizeBytes
});
var response = await WaitForResponseAsync(completion.Task, cancellationToken).ConfigureAwait(false);
if (!response.Found)
throw new FileNotFoundException(
"Content provider '" + ProviderId + "' rejected chunk '" + hash + "': " + response.Error,
chunk.RecordKey);
var resolved = new CultMeshCdnArtifactChunk
{
ChunkHash = response.ChunkHash,
SizeBytes = response.SizeBytes,
Payload = response.Payload ?? Array.Empty<byte>()
};
CultMeshCdn.ValidateChunkPayload(chunk, resolved);
return resolved;
}
private async Task<CultMeshContentChunkResponseMessage> WaitForResponseAsync(
Task<CultMeshContentChunkResponseMessage> response,
CancellationToken cancellationToken)
{
using var deadlineCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var deadline = _options.Clock.DelayAsync(_options.ResponseTimeout, deadlineCancellation.Token);
var completed = await Task.WhenAny(response, deadline).ConfigureAwait(false);
if (completed == response)
{
deadlineCancellation.Cancel();
return await response.ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
throw new TimeoutException(
"Timed out fetching content from provider '" + ProviderId + "' through endpoint identity '" +
_endpointId.Value + "'.");
}
}
}

View file

@ -0,0 +1,44 @@
# CultMesh content sessions
Large immutable artifacts use CultMesh content sessions. Typed snapshots carry
manifests, body descriptors, leases, and progress; they do not carry artifact
payloads.
The provider attaches one generic content server to its existing CultNet
schema host:
```csharp
using var content = new CultMeshContentServer(schemaServer, providerCache);
```
The consumer creates a provider over its existing identity-first session
manager, then gives that provider to the transfer owner:
```csharp
var provider = new CultMeshSessionContentProvider(
"aetheria.daemon",
sessions,
CultMeshEndpointId.Parse("service:aetheria.daemon"));
var transfer = new CultMeshContentTransferService(
transferStateCache,
new[] { provider },
new CultMeshContentTransferOptions(cacheDirectory));
var verifiedBodyPath = await transfer.FetchAsync(manifest, cancellationToken);
```
`CultMeshContentTransferService` remains the only owner of verified partial
state and final cache promotion. It validates each chunk, resumes durable work,
verifies the complete SHA-256 identity, and atomically publishes
`<content-hash>.body`. The session provider owns no cache truth and does not
implement a second retry, failover, or promotion policy.
For local consumers, configure `CultMeshVerifiedBodyMappingBroker` and call
`FetchMappedBodyAsync`. The resulting descriptor maps only the completed body;
mapping failure remains observable and falls back through the equivalent
network descriptor without changing logical identity.
The content protocol uses one bounded response per manifest chunk. A snapshot
response containing `gamecult.mesh.cdn_artifact_chunk.v1` payload records is a
legacy transport path and must not be used for bulk delivery.

View file

@ -566,6 +566,43 @@ provider corruption and failover, forged checkpoint rejection, final-hash
failure, atomic visibility, and concurrent request coalescing. Existing CDN
tests cover the compatibility reader.
### Phase 4 managed content-session slice
**Owner:** `CultMeshContentTransferService` still owns verification, resumable
state, provider failover, and atomic promotion. `CultMeshSessionContentProvider`
owns only one bounded request/response projection over a reusable
`cultmesh.content.v1` session; `CultMeshContentServer` owns only serving
canonical content-addressed chunks from provider storage.
**Inputs:** stable provider endpoint identity, the shared session manager, a
validated manifest chunk reference, provider CultCache content, response
deadline, and caller cancellation.
**Outputs:** one manifest-bound chunk response to the transfer service. The
session manager retains connection/reconnect/path authority, and the transfer
service decides whether the response becomes verified partial state.
**Derived state:** request correlation identities and content-session physical
channels. Neither is content identity, authority evidence, or cache truth.
**Forbidden writers:** snapshot servers cannot embed artifact payloads in raw
document responses; the session provider cannot write partial/final files,
mark ranges verified, choose a replacement endpoint, or authorize a producer.
**Shared paths:** every cold network chunk enters the same incremental and
final verification path used by database and test providers. Concurrent chunks
borrow the same logical content session.
**Cut line:** bulk CDN bytes no longer require
`CultNetSnapshotResponseRawMessage` records. Snapshots retain manifests and
descriptors; the managed content protocol carries bounded payload responses.
**Verification layer:** Mesh tests transfer a multi-chunk body through one
managed session, assert zero snapshot requests, assert warm committed reuse
without another network request, and round-trip both wire messages through the
schema dispatcher. The released EveUnity/Aetheria cold witness remains the real
RUDP consumer proof required to close the slice.
### Phase 5 verified CDN mapped-body slice
**Owner:** `CultMeshContentTransferService` remains the sole writer and promoter

View file

@ -74,6 +74,8 @@ namespace GameCult.Networking
CultNetSchemaVersions.VerseCatalogResponse => Deserialize<CultMeshVerseCatalogResponseMessage>(payload),
CultNetSchemaVersions.PeerExchangeRequest => Deserialize<CultMeshPeerExchangeRequestMessage>(payload),
CultNetSchemaVersions.PeerExchangeResponse => Deserialize<CultMeshPeerExchangeResponseMessage>(payload),
CultNetSchemaVersions.ContentChunkRequest => Deserialize<CultMeshContentChunkRequestMessage>(payload),
CultNetSchemaVersions.ContentChunkResponse => Deserialize<CultMeshContentChunkResponseMessage>(payload),
CultNetSchemaVersions.SchemaCatalogRequest => Deserialize<CultNetSchemaCatalogRequestMessage>(payload),
CultNetSchemaVersions.SchemaCatalogResponse => Deserialize<CultNetSchemaCatalogResponseMessage>(payload),
_ => throw new MessagePackSerializationException(

View file

@ -143,6 +143,14 @@ namespace GameCult.Networking
/// CultMesh peer exchange response contract identifier.
/// </summary>
public const string PeerExchangeResponse = "cultmesh.peer_exchange_response.v0";
/// <summary>
/// CultMesh content chunk request contract identifier.
/// </summary>
public const string ContentChunkRequest = "cultmesh.content_chunk_request.v1";
/// <summary>
/// CultMesh content chunk response contract identifier.
/// </summary>
public const string ContentChunkResponse = "cultmesh.content_chunk_response.v1";
}
/// <summary>
@ -1303,6 +1311,46 @@ namespace GameCult.Networking
[Key("peers")] public CultMeshPeerCardMessage[] Peers { get; set; } = Array.Empty<CultMeshPeerCardMessage>();
}
/// <summary>
/// Requests one bounded content-addressed chunk over a managed CultMesh content session.
/// </summary>
[MessagePackObject]
public class CultMeshContentChunkRequestMessage : ICultNetSchemaMessage
{
/// <summary>Gets or sets the wire schema identity.</summary>
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ContentChunkRequest;
/// <summary>Gets or sets the request correlation identity.</summary>
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
/// <summary>Gets or sets the canonical SHA-256 chunk identity.</summary>
[Key("chunkHash")] public string ChunkHash { get; set; } = string.Empty;
/// <summary>Gets or sets the optional canonical CultCache record key.</summary>
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
/// <summary>Gets or sets the manifest-bound expected payload size.</summary>
[Key("expectedSizeBytes")] public int ExpectedSizeBytes { get; set; }
}
/// <summary>
/// Returns one bounded content-addressed chunk without publishing it as snapshot state.
/// </summary>
[MessagePackObject]
public class CultMeshContentChunkResponseMessage : ICultNetSchemaMessage
{
/// <summary>Gets or sets the wire schema identity.</summary>
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ContentChunkResponse;
/// <summary>Gets or sets the matching request correlation identity.</summary>
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
/// <summary>Gets or sets whether a validated chunk is present.</summary>
[Key("found")] public bool Found { get; set; }
/// <summary>Gets or sets the canonical SHA-256 chunk identity.</summary>
[Key("chunkHash")] public string ChunkHash { get; set; } = string.Empty;
/// <summary>Gets or sets the payload byte count.</summary>
[Key("sizeBytes")] public int SizeBytes { get; set; }
/// <summary>Gets or sets the bounded content payload.</summary>
[Key("payload")] public byte[] Payload { get; set; } = Array.Empty<byte>();
/// <summary>Gets or sets a typed-boundary failure description when the chunk is unavailable.</summary>
[Key("error")] public string Error { get; set; } = string.Empty;
}
/// <summary>
/// Wire representation of a CultMesh peer candidate.
/// </summary>