Codec: confirm MessagePack writes every id-path type the way the walk reads it
CultElementIds is the walk's model of a type; MessagePack's StandardResolver owns how a type is written, and nothing checked that the two agree. ResolverClaim now asks, for each id-path type, whether StandardResolver's formatter is the object or union resolver's (a type read by key) or a collection resolver's (a collection), and refuses the document at first encode or decode when it is not, naming the type. A keyed type that enumerates objects goes on the path so a keyed List subclass is caught. A type MessagePack cannot build a formatter for, and a resolver ahead that throws, are typed refusals; the AllowPrivate catch is pinned (s4: keyed-enumerable-misclassified, allowprivate-catch-unpinned). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
ee3e262064
commit
5157c647af
3 changed files with 176 additions and 2 deletions
|
|
@ -8,6 +8,7 @@ using System.Reflection;
|
|||
using GameCult.Caching;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
using MessagePack.ImmutableCollection;
|
||||
using MessagePack.Resolvers;
|
||||
|
||||
namespace GameCult.Caching.MessagePack;
|
||||
|
|
@ -86,12 +87,36 @@ public static class CultDocumentMessagePackSerialization
|
|||
// composite stops there, so no later resolver is asked. StandardResolverAllowPrivate's formatter writes the same layout
|
||||
// plus non-public [Key] members, and registration refuses a non-public member on the way to an object list, so it
|
||||
// claims nothing either.
|
||||
var standard = generic.Invoke(StandardResolver.Instance, null);
|
||||
object? standard;
|
||||
try
|
||||
{
|
||||
standard = generic.Invoke(StandardResolver.Instance, null);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return $"Cult document {documentType.Name}: MessagePack cannot build a formatter for {type.Name}, which is on the path to a list whose elements carry ids ({(exception.InnerException ?? exception).Message}).";
|
||||
}
|
||||
|
||||
if (!WrittenAsWalked(type, generic, standard))
|
||||
{
|
||||
var owner = CultElementIds.WalksAsOwner(type);
|
||||
return $"Cult document {documentType.Name}: MessagePack writes {type.Name} {(owner ? "as a collection" : "by its [Key] layout")}, but the element-id walk reads it {(owner ? "by its [Key] layout" : "as a collection")}, so element ids would be lost or invented. A [MessagePackObject] type that is also a collection (ICollection<T>, IList, IDictionary) is written as a collection; make it one or the other.";
|
||||
}
|
||||
|
||||
var allowPrivateAsked = false;
|
||||
object? allowPrivate = null;
|
||||
foreach (var resolver in ahead)
|
||||
{
|
||||
var formatter = generic.Invoke(resolver, null);
|
||||
object? formatter;
|
||||
try
|
||||
{
|
||||
formatter = generic.Invoke(resolver, null);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return $"Cult document {documentType.Name}: formatter resolver {resolver.GetType().FullName} failed to build a formatter for {type.Name}, which is on the path to a list whose elements carry ids ({(exception.InnerException ?? exception).Message}); a resolver may not throw for such a type.";
|
||||
}
|
||||
|
||||
if (formatter == null)
|
||||
continue;
|
||||
if (ReferenceEquals(formatter, standard))
|
||||
|
|
@ -118,6 +143,32 @@ public static class CultDocumentMessagePackSerialization
|
|||
return null;
|
||||
}
|
||||
|
||||
// The walk's kind for a type on the id path, checked against the resolver MessagePack actually delegates to. The public
|
||||
// singletons hand out the same cached formatter instances StandardResolver does, so a reference match names the family. A
|
||||
// type the walk reads by key must be written by the object or union resolver, and one it reads as a collection by a
|
||||
// collection resolver; a keyed class that is also an ICollection<T> is written as a collection and its [Key] layout dropped.
|
||||
private static bool WrittenAsWalked(Type type, MethodInfo generic, object? standard)
|
||||
{
|
||||
if (standard == null)
|
||||
return true;
|
||||
var families = CultElementIds.WalksAsOwner(type)
|
||||
? new IFormatterResolver[] { DynamicUnionResolver.Instance, DynamicObjectResolver.Instance }
|
||||
: new IFormatterResolver[] { DynamicGenericResolver.Instance, ImmutableCollectionResolver.Instance, BuiltinResolver.Instance };
|
||||
return families.Any(family => ReferenceEquals(Formatter(family, generic), standard));
|
||||
}
|
||||
|
||||
private static object? Formatter(IFormatterResolver resolver, MethodInfo generic)
|
||||
{
|
||||
try
|
||||
{
|
||||
return generic.Invoke(resolver, null);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static (MessagePackSerializerOptions Options, IFormatterResolver[] Ahead) Compose(IFormatterResolver[] consumerResolvers)
|
||||
{
|
||||
// The guard goes first and wraps whatever formatter the rest of the composite would hand out, so a consumer
|
||||
|
|
|
|||
|
|
@ -113,6 +113,9 @@ namespace GameCult.Caching
|
|||
// and the walk reads public members only.
|
||||
public List<(Type Owner, MemberInfo? Member, Type Child, Type[] Through, bool Hidden)> Edges { get; } = new();
|
||||
public List<(Type Owner, MemberInfo Member, Type Element, List<Type> Concrete, Type[] Through, bool Hidden)> Lists { get; } = new();
|
||||
|
||||
// Keyed types that also enumerate objects: the walk reads them by key, so the codec must confirm MessagePack does too.
|
||||
public List<Type> Enumerating { get; } = new();
|
||||
}
|
||||
|
||||
private static readonly ConcurrentDictionary<Type, bool> IdCapable = new();
|
||||
|
|
@ -134,6 +137,8 @@ namespace GameCult.Caching
|
|||
{
|
||||
if (!seen.Add(type))
|
||||
return;
|
||||
if (EnumeratesObjects(type))
|
||||
graph.Enumerating.Add(type);
|
||||
foreach (var (member, memberType) in KeyedMembers(type))
|
||||
VisitMemberType(documentType, type, member, memberType, Array.Empty<Type>(), false, seen, survey, graph);
|
||||
foreach (var (member, memberType) in UnreadKeyedMembers(type))
|
||||
|
|
@ -229,6 +234,11 @@ namespace GameCult.Caching
|
|||
Add(concrete);
|
||||
}
|
||||
|
||||
// A keyed type the walk reads by key but whose enumeration holds objects is on the path: the codec asks whether
|
||||
// MessagePack writes it by key too.
|
||||
foreach (var type in graph.Enumerating)
|
||||
Add(type);
|
||||
|
||||
foreach (var type in path)
|
||||
{
|
||||
survey.IdPath.Add(type);
|
||||
|
|
@ -593,6 +603,12 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
|
||||
// True when the walk reads the type by its [Key] members: the codec compares this with how MessagePack writes it.
|
||||
internal static bool WalksAsOwner(Type type) => Classify(Nullable.GetUnderlyingType(type) ?? type).Kind == Kind.Owner;
|
||||
|
||||
private static bool EnumeratesObjects(Type type) =>
|
||||
(ElementTypeOf(type) ?? MapTypes(type)?.Value) is { } inner && Classify(inner).Kind != Kind.Leaf;
|
||||
|
||||
private static int? KeyOf(MemberInfo member) => member.GetCustomAttribute<KeyAttribute>(true)?.IntKey;
|
||||
|
||||
private static Type TypeOf(MemberInfo member) => member is FieldInfo field ? field.FieldType : ((PropertyInfo)member).PropertyType;
|
||||
|
|
|
|||
|
|
@ -357,6 +357,111 @@ namespace GameCult.Caching.Tests
|
|||
Assert.That(Convert.ToHexString(plainBytes), Is.EqualTo(Convert.ToHexString(MessagePackSerializer.Serialize(plain, CultDocumentMessagePackSerialization.Options))));
|
||||
}
|
||||
|
||||
// The walk reads a [MessagePackObject] type by its keys, but MessagePack writes one that is also an ICollection<T> as a
|
||||
// collection and drops the keys. The codec compares the two for every type on the id path and refuses the document.
|
||||
[Test]
|
||||
public void AKeyedTypeMessagePackWritesAsACollectionIsRefused()
|
||||
{
|
||||
var registry = CultDocumentRegistry.ForTypes(new[] { typeof(KCollDoc), typeof(KBagDoc) });
|
||||
Assert.That(CultElementIds.Inspect(typeof(KCollDoc)).IdPath, Does.Contain(typeof(KColl)));
|
||||
|
||||
var coll = new KCollDoc { Id = "k1" };
|
||||
coll.Items.Add(new FbArm { Id = "00000000000c" });
|
||||
var thrown = Assert.Throws<InvalidOperationException>(() => CultDocumentMessagePackSerialization.SerializeUntyped(coll, typeof(KCollDoc), registry))!;
|
||||
Assert.That(thrown.Message, Does.Contain(nameof(KColl)).And.Contain("as a collection"));
|
||||
|
||||
var bag = new KBagDoc { Id = "b1", Bag = new KBagE { Items = { new FbArm { Id = "00000000000d" } } } };
|
||||
var bytes = CultDocumentMessagePackSerialization.SerializeUntyped(bag, typeof(KBagDoc), registry);
|
||||
var back = (KBagDoc)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(KBagDoc), bytes, registry);
|
||||
Assert.That(back.Bag.Items.Single().Id, Is.EqualTo("00000000000d"));
|
||||
}
|
||||
|
||||
// Every collection shape the walk reads is one MessagePack writes through a collection formatter, so none is refused.
|
||||
[Test]
|
||||
public void EveryCollectionShapeTheWalkReadsIsWrittenByACollectionFormatter()
|
||||
{
|
||||
foreach (var holder in new[]
|
||||
{
|
||||
typeof(G<List<FbArm>>), typeof(G<FbArm[]>), typeof(G<FbArm[,]>), typeof(G<IList<FbArm>>), typeof(G<IReadOnlyList<FbArm>>),
|
||||
typeof(G<ICollection<FbArm>>), typeof(G<IReadOnlyCollection<FbArm>>), typeof(G<IEnumerable<FbArm>>), typeof(G<HashSet<FbArm>>),
|
||||
typeof(G<Queue<FbArm>>), typeof(G<Stack<FbArm>>), typeof(G<LinkedList<FbArm>>),
|
||||
typeof(G<System.Collections.ObjectModel.ReadOnlyCollection<FbArm>>), typeof(G<System.Collections.ObjectModel.ObservableCollection<FbArm>>),
|
||||
typeof(G<System.Collections.Immutable.ImmutableList<FbArm>>), typeof(G<ILookup<string, FbArm>>), typeof(G<List<List<FbArm>>>),
|
||||
typeof(G<Dictionary<string, FbArm>>), typeof(G<IDictionary<string, FbArm>>), typeof(G<IReadOnlyDictionary<string, FbArm>>),
|
||||
typeof(G<SortedDictionary<string, FbArm>>), typeof(G<System.Collections.Concurrent.ConcurrentDictionary<string, FbArm>>),
|
||||
typeof(G<System.Collections.ObjectModel.ReadOnlyDictionary<string, FbArm>>), typeof(G<System.Collections.Immutable.ImmutableDictionary<string, FbArm>>),
|
||||
typeof(G<SortedList<string, FbArm>>), typeof(G<FbArm>), typeof(G<IGu>), typeof(G<GStruct>),
|
||||
})
|
||||
{
|
||||
if (holder != typeof(G<FbArm>))
|
||||
Assert.That(CultElementIds.Inspect(holder).IdPath, Is.Not.Empty, holder.Name);
|
||||
Assert.DoesNotThrow(() => CultDocumentMessagePackSerialization.OptionsForDocument(holder), holder.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
// A resolver that throws while asked about an id-path type is a typed refusal, whether it is the AllowPrivate formatter
|
||||
// the claim check asks about (the claim stands) or a resolver ahead (it fails to build).
|
||||
[Test]
|
||||
public void AResolverThatThrowsIsATypedRefusal()
|
||||
{
|
||||
var first = Assert.Throws<InvalidOperationException>(() => CultDocumentMessagePackSerialization.OptionsForDocument(typeof(DkDoc)))!;
|
||||
Assert.That(first.Message, Does.Contain(nameof(ListClaimResolver)).And.Contain(nameof(DkEl)));
|
||||
var second = Assert.Throws<InvalidOperationException>(() => CultDocumentMessagePackSerialization.OptionsForDocument(typeof(DkDoc2)))!;
|
||||
Assert.That(second.Message, Does.Contain(nameof(ListClaimResolver)).And.Contain(nameof(DkEl2)).And.Contain("failed to build"));
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class KColl : List<FbArm>
|
||||
{
|
||||
[Key(0)] public int N;
|
||||
}
|
||||
|
||||
[CultDocument("tests.kcoll_doc", "tests.kcoll_doc.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class KCollDoc
|
||||
{
|
||||
[Key(0)] [CultName] public string Id = string.Empty;
|
||||
[Key(1)] public KColl Items = new();
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class KBagE : IEnumerable<FbArm>
|
||||
{
|
||||
[Key(0)] public List<FbArm> Items = new();
|
||||
public IEnumerator<FbArm> GetEnumerator() { yield break; }
|
||||
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
|
||||
}
|
||||
|
||||
[CultDocument("tests.kbag_doc", "tests.kbag_doc.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class KBagDoc
|
||||
{
|
||||
[Key(0)] [CultName] public string Id = string.Empty;
|
||||
[Key(1)] public KBagE Bag = new();
|
||||
}
|
||||
|
||||
[MessagePackObject] public sealed class G<T> { [Key(0)] public T? Value; }
|
||||
[Union(0, typeof(GuArm))] public interface IGu { }
|
||||
[MessagePackObject] public sealed class GuArm : IGu { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public List<FbArm> Items = new(); }
|
||||
[MessagePackObject] public struct GStruct { [Key(0)] public List<FbArm> Items; }
|
||||
|
||||
#pragma warning disable CS0169, CS0414, CS0649
|
||||
[MessagePackObject] public sealed class DkEl { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public int N; [Key(1)] private int shadow; }
|
||||
[MessagePackObject] public sealed class DkEl2 { [Key(0)] [CultElementId] public string Id = string.Empty; [Key(1)] public int N; [Key(1)] private int shadow; }
|
||||
#pragma warning restore CS0169, CS0414, CS0649
|
||||
[CultDocument("tests.dk_doc", "tests.dk_doc.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class DkDoc { [Key(0)] [CultName] public string Id = string.Empty; [Key(1)] public List<DkEl> Items = new(); }
|
||||
[CultDocument("tests.dk_doc2", "tests.dk_doc2.v1")]
|
||||
[MessagePackObject]
|
||||
public sealed class DkDoc2 { [Key(0)] [CultName] public string Id = string.Empty; [Key(1)] public List<DkEl2> Items = new(); }
|
||||
|
||||
public sealed class DkFormatter : IMessagePackFormatter<DkEl>
|
||||
{
|
||||
public void Serialize(ref MessagePackWriter writer, DkEl value, MessagePackSerializerOptions options) => writer.Write(value.N);
|
||||
public DkEl Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) => new DkEl { N = reader.ReadInt32() };
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public sealed class ApArm
|
||||
{
|
||||
|
|
@ -457,6 +562,8 @@ namespace GameCult.Caching.Tests
|
|||
if (typeof(T) == typeof(List<LcValue>)) return (IMessagePackFormatter<T>)(object)new ValuesFormatter();
|
||||
if (typeof(T) == typeof(List<Pair>)) return (IMessagePackFormatter<T>)(object)new PointsFormatter();
|
||||
if (typeof(T) == typeof(FbArm)) return global::MessagePack.Resolvers.StandardResolver.Instance.GetFormatter<T>();
|
||||
if (typeof(T) == typeof(DkEl)) return (IMessagePackFormatter<T>)(object)new DkFormatter();
|
||||
if (typeof(T) == typeof(DkEl2)) return global::MessagePack.Resolvers.StandardResolverAllowPrivate.Instance.GetFormatter<T>();
|
||||
if (typeof(T) == typeof(ApArm) || typeof(T) == typeof(ApDoc) || typeof(T) == typeof(List<ApArm>) ||
|
||||
typeof(T) == typeof(ApPlainArm) || typeof(T) == typeof(ApPlainDoc) || typeof(T) == typeof(List<ApPlainArm>))
|
||||
return global::MessagePack.Resolvers.StandardResolverAllowPrivate.Instance.GetFormatter<T>();
|
||||
|
|
|
|||
Loading…
Reference in a new issue