Publish CultCache registry snapshots atomically

This commit is contained in:
Meta Vens 2026-07-13 17:22:58 +01:00
commit 8472330f90
2 changed files with 109 additions and 62 deletions

View file

@ -404,11 +404,7 @@ namespace GameCult.Caching
private static readonly Lazy<CultDocumentRegistry> SharedRegistry =
new(() => new CultDocumentRegistry());
private readonly ConcurrentDictionary<Type, CultDocumentDescriptor> _byType = new();
private readonly ConcurrentDictionary<string, CultDocumentDescriptor> _bySchemaId =
new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, CultDocumentDescriptor[]> _bySchemaName =
new(StringComparer.Ordinal);
private volatile RegistryIndexes _indexes = new();
private readonly object _registrationGate = new();
/// <summary>
@ -427,28 +423,31 @@ namespace GameCult.Caching
/// <summary>
/// Gets all known document descriptors.
/// </summary>
public IEnumerable<CultDocumentDescriptor> AllDescriptors => _byType.Values.OrderBy(d => d.SchemaName, StringComparer.Ordinal);
public IEnumerable<CultDocumentDescriptor> AllDescriptors =>
_indexes.ByType.Values.OrderBy(d => d.SchemaName, StringComparer.Ordinal);
/// <summary>
/// Rebuilds the registry from generated metadata and reflected document attributes.
/// </summary>
public void Refresh()
{
_byType.Clear();
_bySchemaId.Clear();
_bySchemaName.Clear();
var generatedTypes = new HashSet<Type>();
foreach (var definition in CultGeneratedDocumentMetadataLoader.LoadDefinitions())
lock (_registrationGate)
{
var descriptor = BuildDescriptor(definition);
RegisterDescriptor(descriptor);
generatedTypes.Add(descriptor.DocumentType);
}
var rebuilt = new RegistryIndexes();
var generatedTypes = new HashSet<Type>();
foreach (var definition in CultGeneratedDocumentMetadataLoader.LoadDefinitions())
{
var descriptor = BuildDescriptor(definition);
RegisterDescriptor(rebuilt, descriptor);
generatedTypes.Add(descriptor.DocumentType);
}
foreach (var type in ReflectionExtensions.GetAttributedDocumentTypes().Where(type => !generatedTypes.Contains(type)))
{
RegisterDescriptor(BuildDescriptor(type));
foreach (var type in ReflectionExtensions.GetAttributedDocumentTypes().Where(type => !generatedTypes.Contains(type)))
{
RegisterDescriptor(rebuilt, BuildDescriptor(type));
}
_indexes = rebuilt;
}
}
@ -457,7 +456,7 @@ namespace GameCult.Caching
/// </summary>
public CultDocumentDescriptor GetRequired(Type type)
{
if (_byType.TryGetValue(type, out var descriptor))
if (_indexes.ByType.TryGetValue(type, out var descriptor))
{
return descriptor;
}
@ -465,8 +464,7 @@ namespace GameCult.Caching
descriptor = TryBuildGeneratedDescriptor(type);
if (descriptor != null)
{
RegisterDescriptor(descriptor);
return descriptor;
return RegisterDescriptor(descriptor);
}
var attribute = type.GetCustomAttribute<CultDocumentAttribute>();
@ -477,8 +475,7 @@ namespace GameCult.Caching
}
descriptor = BuildDescriptor(type);
RegisterDescriptor(descriptor);
return descriptor;
return RegisterDescriptor(descriptor);
}
/// <summary>
@ -494,7 +491,7 @@ namespace GameCult.Caching
/// </summary>
public CultDocumentDescriptor GetRequiredBySchemaId(string schemaId)
{
if (_bySchemaId.TryGetValue(schemaId, out var descriptor))
if (_indexes.BySchemaId.TryGetValue(schemaId, out var descriptor))
{
return descriptor;
}
@ -520,7 +517,8 @@ namespace GameCult.Caching
internal CultSchemaResolutionResult ResolvePersistedSchemaDetailed(string schemaId, IReadOnlyCollection<CultSchemaCatalogEntry> catalog)
{
if (_bySchemaId.TryGetValue(schemaId, out var exact))
var indexes = _indexes;
if (indexes.BySchemaId.TryGetValue(schemaId, out var exact))
{
return new CultSchemaResolutionResult(
exact,
@ -542,13 +540,13 @@ namespace GameCult.Caching
foreach (var compatibleSchemaId in persisted.CompatibleSchemaIds.Where(candidate => !string.IsNullOrWhiteSpace(candidate)))
{
if (_bySchemaId.TryGetValue(compatibleSchemaId, out var compatibleLocal))
if (indexes.BySchemaId.TryGetValue(compatibleSchemaId, out var compatibleLocal))
{
return BuildCompatibleResolutionResult(persisted, compatibleLocal);
}
}
if (_bySchemaName.TryGetValue(persisted.SchemaName, out var localVersions))
if (indexes.BySchemaName.TryGetValue(persisted.SchemaName, out var localVersions))
{
if (localVersions.Length == 1)
{
@ -565,48 +563,61 @@ namespace GameCult.Caching
$"No local CultCache schema matches persisted schema '{persisted.SchemaName}' ({schemaId}).");
}
private void RegisterDescriptor(CultDocumentDescriptor descriptor)
private CultDocumentDescriptor RegisterDescriptor(CultDocumentDescriptor descriptor)
{
lock (_registrationGate)
{
if (_byType.ContainsKey(descriptor.DocumentType))
return;
var current = _indexes;
if (current.ByType.TryGetValue(descriptor.DocumentType, out var registered))
return registered;
_bySchemaName.TryGetValue(descriptor.SchemaName, out var schemaNameVersions);
var schemaVersionOwner = schemaNameVersions?.FirstOrDefault(candidate =>
string.Equals(candidate.SchemaVersion, descriptor.SchemaVersion, StringComparison.Ordinal));
if (schemaVersionOwner != null)
{
if (IsExactWireAlias(schemaVersionOwner, descriptor))
{
_byType[descriptor.DocumentType] = descriptor;
return;
}
throw DuplicateSchemaRegistration(
"schema name and version",
$"{descriptor.SchemaName}' version '{descriptor.SchemaVersion}",
schemaVersionOwner.DocumentType,
descriptor.DocumentType);
}
if (_bySchemaId.TryGetValue(descriptor.SchemaId, out var schemaIdOwner))
{
throw DuplicateSchemaRegistration(
"schema id",
descriptor.SchemaId,
schemaIdOwner.DocumentType,
descriptor.DocumentType);
}
_byType[descriptor.DocumentType] = descriptor;
_bySchemaId[descriptor.SchemaId] = descriptor;
_bySchemaName[descriptor.SchemaName] = schemaNameVersions == null
? [descriptor]
: [.. schemaNameVersions, descriptor];
var updated = new RegistryIndexes(current);
registered = RegisterDescriptor(updated, descriptor);
_indexes = updated;
return registered;
}
}
private static CultDocumentDescriptor RegisterDescriptor(
RegistryIndexes indexes,
CultDocumentDescriptor descriptor)
{
if (indexes.ByType.TryGetValue(descriptor.DocumentType, out var registered))
return registered;
indexes.BySchemaName.TryGetValue(descriptor.SchemaName, out var schemaNameVersions);
var schemaVersionOwner = schemaNameVersions?.FirstOrDefault(candidate =>
string.Equals(candidate.SchemaVersion, descriptor.SchemaVersion, StringComparison.Ordinal));
if (schemaVersionOwner != null)
{
if (IsExactWireAlias(schemaVersionOwner, descriptor))
{
indexes.ByType[descriptor.DocumentType] = descriptor;
return descriptor;
}
throw DuplicateSchemaRegistration(
$"schema name '{descriptor.SchemaName}' version '{descriptor.SchemaVersion}'",
schemaVersionOwner.DocumentType,
descriptor.DocumentType);
}
if (indexes.BySchemaId.TryGetValue(descriptor.SchemaId, out var schemaIdOwner))
{
throw DuplicateSchemaRegistration(
$"schema id '{descriptor.SchemaId}'",
schemaIdOwner.DocumentType,
descriptor.DocumentType);
}
indexes.ByType[descriptor.DocumentType] = descriptor;
indexes.BySchemaId[descriptor.SchemaId] = descriptor;
indexes.BySchemaName[descriptor.SchemaName] = schemaNameVersions == null
? [descriptor]
: [.. schemaNameVersions, descriptor];
return descriptor;
}
private static bool IsExactWireAlias(
CultDocumentDescriptor canonical,
CultDocumentDescriptor candidate) =>
@ -617,15 +628,35 @@ namespace GameCult.Caching
string.Equals(canonical.CanonicalSchemaJson, candidate.CanonicalSchemaJson, StringComparison.Ordinal);
private static InvalidOperationException DuplicateSchemaRegistration(
string identityKind,
string identity,
Type existingType,
Type claimedType) =>
new(
$"CultCache {identityKind} '{identity}' is already registered to CLR type " +
$"CultCache {identity} is already registered to CLR type " +
$"'{existingType.FullName}' and cannot also be claimed by '{claimedType.FullName}'. " +
"Schema compatibility must be declared through explicit persisted-schema alias metadata.");
private sealed class RegistryIndexes
{
public RegistryIndexes()
{
ByType = new Dictionary<Type, CultDocumentDescriptor>();
BySchemaId = new Dictionary<string, CultDocumentDescriptor>(StringComparer.Ordinal);
BySchemaName = new Dictionary<string, CultDocumentDescriptor[]>(StringComparer.Ordinal);
}
public RegistryIndexes(RegistryIndexes source)
{
ByType = new Dictionary<Type, CultDocumentDescriptor>(source.ByType);
BySchemaId = new Dictionary<string, CultDocumentDescriptor>(source.BySchemaId, StringComparer.Ordinal);
BySchemaName = new Dictionary<string, CultDocumentDescriptor[]>(source.BySchemaName, StringComparer.Ordinal);
}
public Dictionary<Type, CultDocumentDescriptor> ByType { get; }
public Dictionary<string, CultDocumentDescriptor> BySchemaId { get; }
public Dictionary<string, CultDocumentDescriptor[]> BySchemaName { get; }
}
private static CultDocumentDescriptor? TryBuildGeneratedDescriptor(Type type)
{
var definition = CultGeneratedDocumentMetadataLoader.LoadDefinitions(type.Assembly)

View file

@ -1,7 +1,8 @@
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
namespace GameCult.Caching.Tests;
@ -88,13 +89,28 @@ public sealed class CultDocumentRegistryTests
Assert.That(
() => registry.GetRequired(secondType),
Throws.TypeOf<InvalidOperationException>()
.With.Message.Contains("schema name and version 'tests.registry.layout_collision' version 'v1'")
.With.Message.Contains("schema name 'tests.registry.layout_collision' version 'v1'")
.And.Message.Contains(firstType.FullName)
.And.Message.Contains(secondType.FullName));
Assert.That(registry.GetRequiredBySchemaId(first.SchemaId), Is.SameAs(first));
Assert.That(registry.AllDescriptors.Any(descriptor => descriptor.DocumentType == secondType), Is.False);
}
[Test]
public void ConcurrentRefreshAndReadsObserveCompleteRegistrySnapshots()
{
var registry = new CultDocumentRegistry();
var type = CreateDocumentType("refresh_visible", "tests.registry.refresh_visible", "v1");
var descriptor = registry.GetRequired(type);
Parallel.For(0, 20, _ =>
{
registry.Refresh();
Assert.That(registry.GetRequired(type).SchemaId, Is.EqualTo(descriptor.SchemaId));
Assert.That(registry.GetRequiredBySchemaId(descriptor.SchemaId).SchemaId, Is.EqualTo(descriptor.SchemaId));
});
}
private static Type CreateDocumentType(
string typeName,
string schemaName,