Apply snapshot aliases by payload schema

This commit is contained in:
Meta Vens 2026-06-27 21:12:05 +01:00
commit e430a725ad
2 changed files with 161 additions and 1 deletions

View file

@ -5,6 +5,7 @@ using System.Linq;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
namespace GameCult.Networking
{
@ -344,7 +345,7 @@ namespace GameCult.Networking
var binding = GetBySchemaId(message.Document.SchemaId);
var descriptor = binding != null
? _documents.GetRequired(binding.DocumentType)
: _documents.GetRequiredBySchemaId(message.Document.SchemaId);
: ResolveDescriptorForRawDocument(message.Document);
binding ??= new CultNetDocumentBinding(
descriptor.DocumentType,
descriptor.SchemaId,
@ -394,6 +395,96 @@ namespace GameCult.Networking
return applied;
}
private CultDocumentDescriptor ResolveDescriptorForRawDocument(CultNetRawDocumentRecord document)
{
try
{
return _documents.GetRequiredBySchemaId(document.SchemaId);
}
catch (InvalidOperationException) when (TryResolveDescriptorByPayloadSchema(document.Payload) is { } descriptor)
{
return descriptor;
}
}
private CultDocumentDescriptor? TryResolveDescriptorByPayloadSchema(byte[] payload)
{
var schemaVersion = TryReadSchemaVersion(payload);
if (string.IsNullOrWhiteSpace(schemaVersion))
return null;
var candidates = ResolvePayloadSchemaCandidates().ToArray();
var descriptor = candidates.FirstOrDefault(candidate =>
string.Equals(candidate.SchemaVersion, schemaVersion, StringComparison.Ordinal));
if (descriptor != null)
return descriptor;
var schemaName = InferSchemaName(schemaVersion!);
return string.IsNullOrWhiteSpace(schemaName)
? null
: candidates.FirstOrDefault(candidate =>
string.Equals(candidate.SchemaName, schemaName, StringComparison.Ordinal));
}
private IEnumerable<CultDocumentDescriptor> ResolvePayloadSchemaCandidates()
{
if (_bindingsBySchemaId.Count == 0 && _bindingsByType.Count == 0)
return _documents.AllDescriptors;
return _bindingsBySchemaId.Values
.Concat(_bindingsByType.Values)
.Select(binding => _documents.GetRequired(binding.DocumentType))
.GroupBy(descriptor => descriptor.DocumentType)
.Select(group => group.First());
}
private static string? TryReadSchemaVersion(byte[] payload)
{
try
{
var array = MessagePackSerializer.Deserialize<object[]>(
payload,
CultNetSchemaMessageSerialization.Options);
if (array.Length > 0 && array[0] is string schemaVersion)
return schemaVersion;
}
catch (Exception)
{
// Fall through to map decoding; different runtimes may encode object-like payloads.
}
try
{
var map = MessagePackSerializer.Deserialize<IReadOnlyDictionary<string, object?>>(
payload,
CultNetSchemaMessageSerialization.Options);
if (map.TryGetValue("schemaVersion", out var schemaVersion) &&
schemaVersion is string schemaVersionText)
return schemaVersionText;
if (map.TryGetValue("schema_version", out var snakeSchemaVersion) &&
snakeSchemaVersion is string snakeSchemaVersionText)
return snakeSchemaVersionText;
}
catch (Exception)
{
return null;
}
return null;
}
private static string? InferSchemaName(string schemaVersion)
{
var marker = schemaVersion.LastIndexOf(".v", StringComparison.Ordinal);
if (marker <= 0 || marker + 2 >= schemaVersion.Length)
return null;
var version = schemaVersion.Substring(marker + 2);
return version.All(char.IsDigit)
? schemaVersion.Substring(0, marker)
: null;
}
/// <summary>
/// Applies all typed documents from a raw snapshot response.
/// </summary>

View file

@ -2365,6 +2365,75 @@ public sealed class CultMeshStreamingTests
documents.Should().ContainSingle().Which.Text.Should().Be("foreign-schema-alias");
}
[Test]
public async Task SnapshotEndpoint_SyncsCompatibleForeignSchemaIdIntoLocalCache()
{
var key = new CultRecordKey("mesh-note:snapshot-sync-foreign-schema");
var snapshot = new CultNetSnapshotResponseRawMessage
{
MessageId = "foreign-schema-sync",
Documents = new[]
{
new CultNetRawDocumentRecord
{
SchemaId = "runtime.generated.mesh-note.ui.84",
RecordKey = key.Value,
StoredAt = DateTimeOffset.UtcNow.ToString("O"),
PayloadEncoding = "messagepack",
Payload = CultDocumentMessagePackSerialization.SerializeUntyped(
new MeshNoteDocument
{
Schema = "tests.mesh_note.v1",
Text = "foreign-schema-synced",
Revision = 45
},
typeof(MeshNoteDocument))
}
}
};
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(
typeof(MeshNoteDocument),
typeof(MeshNoteAliasDocument));
var registry = CultMesh.CreateCultNetDocumentRegistry(
new[] { typeof(MeshNoteDocument), typeof(MeshNoteAliasDocument) },
cacheRegistry);
var endpoint = CultMesh.SnapshotEndpoint(
"cultnet://foreign-schema.test:3075",
new CultMeshSnapshotEndpointOptions
{
DocumentRegistry = registry,
Request = new CultMeshSnapshotRequestOptions
{
CreateClient = () => new MeshSnapshotSchemaClient(request =>
{
snapshot.MessageId = request.MessageId;
return snapshot;
})
}
});
using var node = await CultMesh.CreateNodeAsync(
Path.Combine(Path.GetTempPath(), $"cultmesh-foreign-schema-sync-{Guid.NewGuid():N}.ccmp"),
new CultMeshNodeOptions
{
StartServer = false,
CacheOptions = new CultCacheOpenOptions
{
Registry = cacheRegistry,
PullOnOpen = false
},
DatabaseOptions = new CultNetDatabaseOptions
{
DocumentRegistry = registry
}
});
var synced = await endpoint.SyncDocumentAsync<MeshNoteAliasDocument>(node, key.Value);
synced.Text.Should().Be("foreign-schema-synced");
node.Cache.Get<MeshNoteDocument>(key)!.Text.Should().Be("foreign-schema-synced");
node.Cache.Get<MeshNoteDocument>(key)!.Revision.Should().Be(45);
}
[Test]
public async Task DocumentRegistryHelpers_CreateTypedNetworkRegistriesForAliases()
{