From 128228928eb15a71df673da03d28713aa8f7f8ed Mon Sep 17 00:00:00 2001 From: Aaron Stannard Date: Fri, 2 Oct 2026 19:25:47 +0000 Subject: [PATCH 1/5] Serialization V2 generator: formatters inside collections (G-1) A registered formatter (custom, or the built-in Address/ActorPath ones) now serves collection elements, dictionary keys and dictionary values, not only fields, for every collection shape the generator supports. The wire form is the array or map the collection already uses, with each element exactly what the formatter writes at field position. A collection keeps its structure through extraction even when a member is not natively representable; validation reports what formatter resolution left unusable (AKKASG003/AKKASG014), with the same diagnostics as before. Part of #8715 --- .../source-generated-serialization.md | 37 +- .../AkkaSerializerGenerator.Emission.cs | 157 +++++ .../AkkaSerializerGenerator.Extraction.cs | 73 +-- .../AkkaSerializerGenerator.Models.cs | 34 +- .../AkkaSerializerGenerator.Validation.cs | 63 +- .../FormatterCollectionCachingSpec.cs | 72 +++ .../FormatterCollectionDiagnosticsSpec.cs | 97 +++ .../FormatterCollectionSpec.cs | 602 ++++++++++++++++++ .../GeneratorGoldenFormatterCollectionSpec.cs | 142 +++++ ...alizer.AkkaSerialization.g.cs.verified.txt | 551 ++++++++++++++++ .../Harness/DiagnosticSource.cs | 75 +++ .../Harness/GoldenBaseline.cs | 68 ++ .../WireFormatSnapshotFormatterSpec.cs | 143 +++++ ...-ref-elements-override-native.verified.txt | 25 + ...address-shapes-single-element.verified.txt | 33 + ...ustom-reference-type-elements.verified.txt | 11 + ...-value-type-nullable-elements.verified.txt | 11 + ...atter-element-list-of-address.verified.txt | 9 + ...element-nullable-address-list.verified.txt | 8 + ...-and-value-address-dictionary.verified.txt | 10 + 20 files changed, 2164 insertions(+), 57 deletions(-) create mode 100644 src/core/Akka.Serialization.V2.Tests/FormatterCollectionCachingSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/GoldenOutput/FormatterPositionsSerializer.AkkaSerialization.g.cs.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/Harness/DiagnosticSource.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/Harness/GoldenBaseline.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-actor-ref-elements-override-native.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-all-address-shapes-single-element.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-reference-type-elements.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-value-type-nullable-elements.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-list-of-address.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-nullable-address-list.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-key-and-value-address-dictionary.verified.txt diff --git a/docs/articles/serialization/source-generated-serialization.md b/docs/articles/serialization/source-generated-serialization.md index 0c28f9b4d4d..2a8f9d2c392 100644 --- a/docs/articles/serialization/source-generated-serialization.md +++ b/docs/articles/serialization/source-generated-serialization.md @@ -337,7 +337,7 @@ public sealed record ShippingAddress( | Read-only collections | `IReadOnlyCollection` (for example a `ReadOnlyCollection`) | | | Immutable collections | `ImmutableArray`, `ImmutableList`, `ImmutableHashSet`, `ImmutableDictionary` | Every collection shape shares identical wire framing; only the in-memory construction on deserialize differs. | | Actor references | `IActorRef` | Native support via `Serialization.SerializedActorPath` and `Provider.ResolveActorRef`. No formatter needed. | -| Addresses and paths | `Akka.Actor.Address`, `Akka.Actor.ActorPath` | Via the built-in `AddressFormatter` and `ActorPathFormatter`. See [Hand-written formatters](#hand-written-formatters). Not native, since `Akka.Actor` cannot reference `Akka.Serialization.V2`. | +| Addresses and paths | `Akka.Actor.Address`, `Akka.Actor.ActorPath` | Via the built-in `AddressFormatter` and `ActorPathFormatter`, as fields or inside any collection above. See [Hand-written formatters](#hand-written-formatters). Not native, since `Akka.Actor` cannot reference `Akka.Serialization.V2`. | | Nested messages | Any `[AkkaSerializable]` class or struct | See [Nested value objects](#nested-akkaserializable-value-objects). | | Closed generic constructions | A `[AkkaSerializable]` generic type, registered per closed construction | See [Closed generic registrations](#closed-generic-registrations). | | Unions | A closed, explicitly enumerated set of concrete types | See [Unions](#unions). | @@ -347,7 +347,8 @@ public sealed record ShippingAddress( as scalar field types. These are only meaningful as an enum's underlying type. Also not supported: a mutable `HashSet` or `ISet`. Use `ImmutableHashSet` instead. Also not supported: a dictionary whose key type is `object`. Any of these fails -compilation with **AKKASG003**, naming the offending property and type. +compilation with **AKKASG003**, naming the offending property and type. So does a collection of a +type that neither the generator nor a registered [formatter](#hand-written-formatters) handles. ## Unions @@ -874,8 +875,8 @@ Some types cannot be annotated with `[AkkaSerializable]`. A core Akka type like `Akka.Actor.Address` is the most common case. It lives in an assembly that cannot reference `Akka.Serialization.V2` without creating a dependency cycle. Apply `[AkkaSerializerFormatter]` to the `[AkkaSerializer]` class instead. It routes -every field of type `TTarget` through a hand-written `IAkkaMessagePackFormatter` -implementation: +every field of type `TTarget`, and every collection element, dictionary key, and dictionary value of +type `TTarget`, through a hand-written `IAkkaMessagePackFormatter` implementation: ```csharp public interface IAkkaMessagePackFormatter @@ -954,6 +955,32 @@ public sealed partial class ControlMirrorSerializer : AkkaSerializer } ``` +### Formatters Inside Collections + +A registered formatter applies at every position a `TTarget` can sit, in every collection shape the +generator supports: `T[]`, `List`, `IReadOnlyList`, `IReadOnlyCollection`, +`ImmutableArray`, `ImmutableList`, `ImmutableHashSet`, the three dictionary shapes (as key +or as value), and nested combinations such as `Dictionary>`. With +`[AkkaSerializerFormatter]` registered, these all work: + +```csharp +[AkkaSerializable(Manifest = "route-v1")] +public sealed record Route( + [property: AkkaField(1)] List
Hops, + [property: AkkaField(2)] Dictionary LastSeen, + [property: AkkaField(3)] ImmutableArray
Candidates) : IRoutingProtocol; +``` + +The wire form is the array or map the collection already uses, with each element exactly the bytes the +formatter writes at field position. There is no wrapper, so `Hops` above is `array(n)` of the 4-element +`Address` arrays. As at field position, the generator owns `nil`: a `null` element, or an absent +`Nullable` element, is written as `nil` and the formatter only sees present values. `SizeOf` is +summed over the elements, so the exact-size contract holds for the whole collection. + +A formatter registered for a type the generator also supports natively takes precedence at every +position, not only at field position. Register an `IActorRef` formatter, for example, and `List` +uses it. Without one, `IActorRef` keeps its native encoding. + ### The Two Built-in Formatters `Akka.Serialization.V2` ships two formatters. They let `Address` and `ActorPath` fields work out @@ -1065,7 +1092,7 @@ diagnostic was retired with it, and the id stays a permanent gap. |---|---|---|---| | AKKASG001 | Error | Serializer name must be a non-empty string | The `Name` argument to `[AkkaSerializer]` is null, empty, or whitespace. | | AKKASG002 | Error | Serializer id must be a positive integer | The `SerializerId` argument is zero or negative. | -| AKKASG003 | Error | Unsupported field type | An `[AkkaField]` property's type isn't one the generator can encode. On an interface, an abstract class, or a type parameter, the message adds a hint: declare a closed member set with `[AkkaUnion]`, type it as the serializer's own protocol interface, or type the property as `object`. | +| AKKASG003 | Error | Unsupported field type | An `[AkkaField]` property's type isn't one the generator can encode, or it is a collection with an element, key, or value that neither the generator nor a registered formatter can encode. On an interface, an abstract class, or a type parameter, the message adds a hint: declare a closed member set with `[AkkaUnion]`, type it as the serializer's own protocol interface, or type the property as `object`. | | AKKASG004 | Error | No serializable fields | An `[AkkaSerializable]` type has no `[AkkaField]` properties and didn't opt in with `AllowEmpty`. | | AKKASG005 | Error | Duplicate field index | Two `[AkkaField]` properties on the same type share an index. | | AKKASG006 | Error | Top-level message manifest is required | A type implementing the serializer's protocol has no `Manifest`. | diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs index 392506fd603..d44fbde425d 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs @@ -599,6 +599,9 @@ bool NeedsResolution(MessageInfo message) field.Mapping.TypeFullName.Length > 0 && formattersByTarget.ContainsKey(field.Mapping.Key)) return true; + + if (IsCollectionKind(field.Mapping.Kind) && CollectionNeedsFormatter(field.Mapping, formattersByTarget)) + return true; } return false; @@ -641,6 +644,14 @@ bool NeedsResolution(MessageInfo message) { resolvedFields.Add(field.WithFormatter(new TypeMapping(FieldKind.Formatted, field.Mapping.Key), formatter)); } + else if (IsCollectionKind(field.Mapping.Kind) && CollectionNeedsFormatter(field.Mapping, formattersByTarget)) + { + // A formatter serves a collection's element, dictionary key, and dictionary value + // exactly as it serves a field: the position changes where the formatter is called, + // never what it writes, so the wire form is the array/map the collection already + // is, with each element exactly what the formatter writes at field position. + resolvedFields.Add(field.WithMapping(ResolveCollectionFormatters(field.Mapping, formattersByTarget))); + } else { resolvedFields.Add(field); @@ -653,6 +664,69 @@ bool NeedsResolution(MessageInfo message) return builder?.ToImmutable() ?? allMessagesByType; } + /// + /// Whether a registered formatter can serve this mapping when it sits in an element, key, or value + /// position -- the same rule applies at field position: the mapping + /// names a type (), and is not the object-typed envelope + /// boundary, which no formatter may claim. + /// + private static bool CanBeFormatted(TypeMapping mapping) + => mapping.Kind != FieldKind.EnvelopePayload && mapping.TypeFullName.Length > 0; + + /// + /// Whether any element, dictionary key, or dictionary value anywhere inside this collection mapping + /// (including nested collections) has a registered formatter. Cheap and allocation-free: it lets + /// skip every collection field in the common no-formatter case. + /// + private static bool CollectionNeedsFormatter(TypeMapping collection, Dictionary formattersByTarget) + { + foreach (var child in collection.TypeArguments) + { + if (CanBeFormatted(child) && formattersByTarget.ContainsKey(child.Key)) + return true; + + if (IsCollectionKind(child.Kind) && CollectionNeedsFormatter(child, formattersByTarget)) + return true; + } + + return false; + } + + /// + /// Rebuilds a collection mapping with every element, key, and value that has a registered formatter + /// swapped for a mapping carrying that formatter, recursing into + /// nested collections. The replacement keeps the position's declared type name and nullability (the + /// read temporaries and the nil handling depend on them) and takes its value-type-ness from the + /// formatter's target, mirroring at field position. + /// + private static TypeMapping ResolveCollectionFormatters(TypeMapping collection, Dictionary formattersByTarget) + { + var resolved = ImmutableArray.CreateBuilder(collection.TypeArguments.Length); + foreach (var child in collection.TypeArguments) + { + if (CanBeFormatted(child) && formattersByTarget.TryGetValue(child.Key, out var formatter)) + { + resolved.Add(new TypeMapping( + FieldKind.Formatted, + child.Key, + isValueType: formatter.IsTargetValueType, + declaredTypeName: child.DeclaredTypeName, + isNullable: child.IsNullable, + formatter: formatter)); + } + else if (IsCollectionKind(child.Kind)) + { + resolved.Add(ResolveCollectionFormatters(child, formattersByTarget)); + } + else + { + resolved.Add(child); + } + } + + return collection.WithTypeArguments(resolved.ToImmutable()); + } + /// /// Renders one serializer's generated source PURELY from its -- /// no , no other serializer's data, and (since @@ -753,6 +827,9 @@ private static ImmutableArray CollectUsedFormatters(ImmutableArra { if (field.Mapping.Kind == FieldKind.Formatted && field.Formatter is { } formatter && seen.Add(formatter.TargetTypeFullName)) used.Add(formatter); + + if (IsCollectionKind(field.Mapping.Kind)) + CollectCollectionFormatters(field.Mapping, seen, used); } } @@ -762,6 +839,17 @@ private static ImmutableArray CollectUsedFormatters(ImmutableArra return used.ToImmutable().Sort((a, b) => string.CompareOrdinal(a.TargetTypeFullName, b.TargetTypeFullName)); } + private static void CollectCollectionFormatters(TypeMapping collection, HashSet seen, ImmutableArray.Builder used) + { + foreach (var child in collection.TypeArguments) + { + if (child.Kind == FieldKind.Formatted && child.Formatter is { } formatter && seen.Add(formatter.TargetTypeFullName)) + used.Add(formatter); + else if (IsCollectionKind(child.Kind)) + CollectCollectionFormatters(child, seen, used); + } + } + private static void GenerateFormatterFields(CodeWriter w, ImmutableArray usedFormatters) { if (usedFormatters.Length == 0) @@ -1822,6 +1910,7 @@ private static bool ElementIsReference(TypeMapping mapping) { FieldKind.String or FieldKind.ByteArray or FieldKind.ActorRef or FieldKind.EnvelopePayload => true, FieldKind.Object => !mapping.IsValueType, + FieldKind.Formatted => !mapping.IsValueType, _ => false }; } @@ -1901,6 +1990,30 @@ private static void EmitWriteElement(CodeWriter w, TypeMapping mapping, ValueExp return; } + // A formatter-handled element, dictionary key, or dictionary value: exactly what the formatter + // writes at field position, with no wrapper. Nil handling mirrors FieldKind.Object above: a + // non-nullable value-type target goes straight to the formatter; anything that can be null (a + // reference target, which a collection may hold a null of whatever its annotation says, or a + // Nullable value target) writes nil for null, which the formatter itself is never asked to + // represent (see the IAkkaMessagePackFormatter Write remarks). + if (mapping.Kind == FieldKind.Formatted) + { + if (mapping.IsValueType && !mapping.IsNullable) + { + w.Identifier(GetFormatterFieldName(mapping.Formatter!)).Raw(".Write(ref writer, ").Value(value).Line(");"); + return; + } + + var formatted = mapping.IsValueType ? value.Member("Value") : value; + w.Raw("if (").Value(value).Line(" is null)"); + using (w.Indented()) + w.Line("writer.WriteNil();"); + w.Line("else"); + using (w.Indented()) + w.Identifier(GetFormatterFieldName(mapping.Formatter!)).Raw(".Write(ref writer, ").Value(formatted).Line(");"); + return; + } + if (mapping.IsNullable && IsScalarValueKind(mapping.Kind)) { w.Raw("if (").Value(value).Line(" is null)"); @@ -2184,6 +2297,25 @@ private static void EmitReadElement(CodeWriter w, TypeMapping mapping, Local res return; } + // Mirrors the Formatted case in EmitWriteElement: a non-nullable value-type target reads + // straight through the formatter; anything that can be null checks for nil first. + if (mapping.Kind == FieldKind.Formatted) + { + if (mapping.IsValueType && !mapping.IsNullable) + { + w.Local(resultVar).Raw(" = ").Identifier(GetFormatterFieldName(mapping.Formatter!)).Line(".Read(ref reader);"); + return; + } + + w.Line("if (reader.TryReadNil())"); + using (w.Indented()) + w.Local(resultVar).Line(" = null;"); + w.Line("else"); + using (w.Indented()) + w.Local(resultVar).Raw(" = ").Identifier(GetFormatterFieldName(mapping.Formatter!)).Line(".Read(ref reader);"); + return; + } + if (mapping.IsNullable && IsScalarValueKind(mapping.Kind)) { w.Line("if (reader.TryReadNil())"); @@ -2333,6 +2465,31 @@ private static void EmitSizeElement(CodeWriter w, TypeMapping mapping, ValueExpr return; } + // Mirrors the Formatted case in EmitWriteElement. A formatter may report UnknownSize, so the + // same "< 0" propagation guard as every other sized-by-callee kind applies. + if (mapping.Kind == FieldKind.Formatted) + { + var elementSize = alloc.Next("size"); + var formatterField = GetFormatterFieldName(mapping.Formatter!); + w.Raw("var ").Local(elementSize).Raw(" = "); + if (mapping.IsValueType && !mapping.IsNullable) + { + w.Identifier(formatterField).Raw(".SizeOf(").Value(value).Raw(")"); + } + else + { + var sizedValue = mapping.IsValueType ? value.Member("Value") : value; + w.Value(value).Raw(" is null ? SizeOfNil() : ").Identifier(formatterField).Raw(".SizeOf(").Value(sizedValue).Raw(")"); + } + + w.Line(";"); + w.Raw("if (").Local(elementSize).Line(" < 0)"); + using (w.Indented()) + w.Line("return global::Akka.Serialization.SerializerV2.UnknownSize;"); + w.Local(sizeVar).Raw(" += ").Local(elementSize).Line(";"); + return; + } + if (mapping.IsNullable && IsScalarValueKind(mapping.Kind)) { w.Local(sizeVar).Raw(" += ").Value(value).Raw(" is null ? SizeOfNil() : "); diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs index 8e7cf64428f..6968a67cc47 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs @@ -1179,7 +1179,19 @@ private static TypeMapping MapType(ITypeSymbol type, KnownTypes knownTypes) // carries the arity suffix, so this guard still matters even though the key is no longer a // bare arity-less string. Generic field types keep a default (empty) key, can never match a // formatter, and still fail with AKKASG003. - var mapping = MapTypeCore(type, knownTypes); + return WithFallbackKey(MapTypeCore(type, knownTypes), type); + } + + /// + /// Stamps a keyless mapping with the type's own when the type is a plain, + /// non-generic named type, so a formatter registered for it can match (the formatter dictionary is + /// keyed by ). Shared by FIELD position () and collection + /// ELEMENT/KEY/VALUE position (), which is what makes formatter + /// resolution position-independent. A mapping that already names its type (Object, Enum, ...) keeps + /// the key it has; a generic or array type stays keyless and can never match a formatter. + /// + private static TypeMapping WithFallbackKey(TypeMapping mapping, ITypeSymbol type) + { if (mapping.TypeFullName.Length == 0 && type is INamedTypeSymbol { IsGenericType: false } namedType) return mapping.WithKey(TypeKey.FromSymbol(namedType)); @@ -1273,12 +1285,14 @@ private static string GetForeignAssemblyName(ISymbol symbol, KnownTypes knownTyp /// and against the field's OWN declared generic type definition (not /// an "is-assignable" relationship, so e.g. a field declared IReadOnlyList<T> never matches /// the IReadOnlyCollection<T> shape even though the former extends the latter). - /// A collection whose element/key/value is itself unsupported collapses to - /// so AKKASG003 fires with the full field type -- except an - /// enum element with an unsupported underlying type, which propagates as - /// so AKKASG014 fires naming the enum. An + /// A collection keeps its structure even when an element/key/value is not natively representable + /// (, , or an + /// enum with an unsupported underlying type): whether a registered formatter can serve that position + /// is only known later, once the serializer's formatters are in hand (). + /// Validation then reports whatever is still unusable -- AKKASG003 with the full field type, or + /// AKKASG014 naming the enum -- see . An /// element/value typed object maps to instead (see - /// ); a dictionary KEY typed object also collapses to + /// ); a dictionary KEY typed object maps to /// . /// byte[] is never seen here (it is intercepted earlier as ). /// @@ -1289,9 +1303,7 @@ private static bool TryMapCollection(ITypeSymbol type, KnownTypes knownTypes, ou if (type is IArrayTypeSymbol { Rank: 1 } arrayType && arrayType.ElementType.SpecialType != SpecialType.System_Byte) { var element = MapCollectionElement(arrayType.ElementType, knownTypes); - mapping = TryCollapseBadElement(element, out var collapsed) - ? collapsed - : new TypeMapping(FieldKind.Array, typeArguments: ImmutableArray.Create(element)); + mapping = new TypeMapping(FieldKind.Array, typeArguments: ImmutableArray.Create(element)); return true; } @@ -1391,45 +1403,14 @@ private static bool TryMatchKeyValueKind(INamedTypeSymbol definition, KnownTypes private static TypeMapping MapSingleArgumentCollection(FieldKind kind, INamedTypeSymbol namedType, KnownTypes knownTypes) { var element = MapCollectionElement(namedType.TypeArguments[0], knownTypes); - return TryCollapseBadElement(element, out var collapsed) - ? collapsed - : new TypeMapping(kind, typeArguments: ImmutableArray.Create(element)); + return new TypeMapping(kind, typeArguments: ImmutableArray.Create(element)); } private static TypeMapping MapKeyValueCollection(FieldKind kind, INamedTypeSymbol namedType, KnownTypes knownTypes) { var key = MapCollectionElement(namedType.TypeArguments[0], knownTypes, isKeyPosition: true); var value = MapCollectionElement(namedType.TypeArguments[1], knownTypes); - return TryCollapseBadElement(key, out var collapsedKey) ? collapsedKey - : TryCollapseBadElement(value, out var collapsedValue) ? collapsedValue - : new TypeMapping(kind, typeArguments: ImmutableArray.Create(key, value)); - } - - /// - /// Collapses a bad collection element/key/value mapping into the mapping the containing field - /// should carry. An enum with an unsupported underlying type keeps its identity (enum name plus - /// backing type) so AKKASG014 can name it even through arbitrarily deep nesting; every other bad - /// element collapses to plain for AKKASG003. - /// - private static bool TryCollapseBadElement(TypeMapping element, out TypeMapping collapsed) - { - if (element.Kind == FieldKind.UnsupportedEnumUnderlyingType) - { - collapsed = new TypeMapping( - FieldKind.UnsupportedEnumUnderlyingType, - element.Key, - enumUnderlyingTypeName: element.EnumUnderlyingTypeName); - return true; - } - - if (element.Kind is FieldKind.Unsupported or FieldKind.MissingSerializableDefinition) - { - collapsed = new TypeMapping(FieldKind.Unsupported); - return true; - } - - collapsed = default; - return false; + return new TypeMapping(kind, typeArguments: ImmutableArray.Create(key, value)); } /// @@ -1456,7 +1437,7 @@ private static TypeMapping MapCollectionElement(ITypeSymbol type, KnownTypes kno var declaredTypeName = type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat); if (TryGetNullableValueType(type, out var underlyingType)) - return MapTypeCore(underlyingType, knownTypes).AsCollectionElement(declaredTypeName, isNullable: true); + return WithFallbackKey(MapTypeCore(underlyingType, knownTypes), underlyingType).AsCollectionElement(declaredTypeName, isNullable: true); var isNullable = type.IsReferenceType && type.NullableAnnotation == NullableAnnotation.Annotated; @@ -1465,8 +1446,8 @@ private static TypeMapping MapCollectionElement(ITypeSymbol type, KnownTypes kno // type alone carries that meaning, with no attribute involved, at every position a supported // collection can hold it: an array/list element, a set member, or a dictionary value. // - // A dictionary KEY typed `object` is rejected instead (AKKASG003, via the same Unsupported - // collapse every other bad element/key/value already uses -- see TryCollapseBadElement): + // A dictionary KEY typed `object` is rejected instead (AKKASG003: the key stays a plain + // Unsupported mapping, which FindUnusableLeaf reports for the whole field): // Dictionary<TKey,TValue> throws on a null key at runtime, so a nullable `object?` key // would crash the first time an envelope legitimately decodes to null; and even a non-null // envelope payload has no stable identity across a round trip (ReadEnvelopePayload always @@ -1479,7 +1460,7 @@ private static TypeMapping MapCollectionElement(ITypeSymbol type, KnownTypes kno : new TypeMapping(FieldKind.EnvelopePayload).AsCollectionElement(declaredTypeName, isNullable); } - return MapTypeCore(type, knownTypes).AsCollectionElement(declaredTypeName, isNullable); + return WithFallbackKey(MapTypeCore(type, knownTypes), type).AsCollectionElement(declaredTypeName, isNullable); } private static bool IsNullableValueType(ITypeSymbol type) diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs index d3663246aaf..3377ce1309f 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs @@ -1318,6 +1318,16 @@ public FieldInfo(int index, string name, string typeFullName, TypeMapping mappin /// public bool UnionDeclaredOnObjectField { get; } + /// + /// Replaces this field's mapping, keeping everything else. Used by formatter resolution when a + /// registered formatter swaps a collection's element, key, or value mapping for a + /// one -- the field itself stays an ordinary collection field. + /// + public FieldInfo WithMapping(TypeMapping mapping) + { + return new FieldInfo(Index, Name, TypeFullName, mapping, IsNullable, Formatter, UnionMembers, UnionDeclaredOnObjectField); + } + public FieldInfo WithFormatter(TypeMapping mapping, FormatterInfo formatter) { return new FieldInfo(Index, Name, TypeFullName, mapping, IsNullable, formatter, UnionMembers, UnionDeclaredOnObjectField); @@ -1384,7 +1394,8 @@ public TypeMapping( string enumUnderlyingTypeName = "", string foreignAssemblyName = "", bool suggestsEnvelopeOrUnion = false, - bool isGenericConstruction = false) + bool isGenericConstruction = false, + FormatterInfo? formatter = null) { Kind = kind; Key = key; @@ -1396,6 +1407,7 @@ public TypeMapping( ForeignAssemblyName = foreignAssemblyName; SuggestsEnvelopeOrUnion = suggestsEnvelopeOrUnion; IsGenericConstruction = isGenericConstruction; + Formatter = formatter; } public FieldKind Kind { get; } @@ -1474,11 +1486,25 @@ public TypeMapping( /// public bool IsGenericConstruction { get; } + /// + /// For a collection element/key/value: the registered + /// formatter that reads and writes it. Set only by formatter resolution (see + /// ) -- never at extraction time, because + /// the formatter set belongs to the serializer, not the message. A + /// FIELD keeps its formatter on instead, so every field-position + /// model stays exactly as it was; null for every other mapping. + /// + public FormatterInfo? Formatter { get; } + public TypeMapping WithKey(TypeKey key) - => new(Kind, key, IsValueType, DeclaredTypeName, IsNullable, TypeArguments, EnumUnderlyingTypeName, ForeignAssemblyName, SuggestsEnvelopeOrUnion, IsGenericConstruction); + => new(Kind, key, IsValueType, DeclaredTypeName, IsNullable, TypeArguments, EnumUnderlyingTypeName, ForeignAssemblyName, SuggestsEnvelopeOrUnion, IsGenericConstruction, Formatter); public TypeMapping AsCollectionElement(string declaredTypeName, bool isNullable) - => new(Kind, Key, IsValueType, declaredTypeName, isNullable, TypeArguments, EnumUnderlyingTypeName, ForeignAssemblyName, SuggestsEnvelopeOrUnion, IsGenericConstruction); + => new(Kind, Key, IsValueType, declaredTypeName, isNullable, TypeArguments, EnumUnderlyingTypeName, ForeignAssemblyName, SuggestsEnvelopeOrUnion, IsGenericConstruction, Formatter); + + /// Replaces the child mappings of a collection kind, keeping everything else. + public TypeMapping WithTypeArguments(ImmutableArray typeArguments) + => new(Kind, Key, IsValueType, DeclaredTypeName, IsNullable, typeArguments, EnumUnderlyingTypeName, ForeignAssemblyName, SuggestsEnvelopeOrUnion, IsGenericConstruction, Formatter); // Explicit IEquatable implementation: the compiler-provided struct equality would compare // the TypeArguments ImmutableArray by underlying-array REFERENCE, breaking value equality @@ -1494,6 +1520,7 @@ public bool Equals(TypeMapping other) && string.Equals(ForeignAssemblyName, other.ForeignAssemblyName, StringComparison.Ordinal) && SuggestsEnvelopeOrUnion == other.SuggestsEnvelopeOrUnion && IsGenericConstruction == other.IsGenericConstruction + && Equals(Formatter, other.Formatter) && ValueEquality.SequenceEquals(TypeArguments, other.TypeArguments); } @@ -1511,6 +1538,7 @@ public override int GetHashCode() hash = ValueEquality.Combine(hash, ForeignAssemblyName); hash = ValueEquality.Combine(hash, SuggestsEnvelopeOrUnion); hash = ValueEquality.Combine(hash, IsGenericConstruction); + hash = ValueEquality.Combine(hash, Formatter?.GetHashCode() ?? 0); hash = ValueEquality.Combine(hash, TypeArguments); return hash; } diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Validation.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Validation.cs index 9333e4535e2..a260ed90604 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Validation.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Validation.cs @@ -614,6 +614,55 @@ private static ImmutableArray CollectReachableMessages( return messages.ToImmutable(); } + /// + /// The kind that decides which diagnostic a field gets. A non-collection field is its own + /// . A collection field is usable only if every element, key, and + /// value is, so one that still holds an unusable leaf after formatter resolution (see + /// ) reports exactly what it did when extraction collapsed such a + /// collection up front: (AKKASG014, naming + /// the enum) when the first unusable leaf is an unsupported enum, otherwise + /// (AKKASG003, naming the full field type). "First" is + /// depth-first with a dictionary key before its value -- the order the old collapse resolved + /// ties in. is the leaf (or, for a non-collection field, the field's + /// own mapping) the diagnostic's details come from. + /// + private static FieldKind GetDiagnosticKind(FieldInfo field, out TypeMapping deciding) + { + deciding = field.Mapping; + if (field.Mapping.TypeArguments.IsEmpty || !FindUnusableLeaf(field.Mapping, out var leaf)) + return field.Mapping.Kind; + + deciding = leaf; + return leaf.Kind == FieldKind.UnsupportedEnumUnderlyingType + ? FieldKind.UnsupportedEnumUnderlyingType + : FieldKind.Unsupported; + } + + /// + /// Depth-first search (key before value) for the first collection element/key/value mapping that no + /// generated code path can serve: , + /// , or + /// . A leaf a formatter resolved is already + /// by the time validation runs, so it is never found here. + /// + private static bool FindUnusableLeaf(TypeMapping mapping, out TypeMapping leaf) + { + foreach (var argument in mapping.TypeArguments) + { + if (argument.Kind is FieldKind.Unsupported or FieldKind.MissingSerializableDefinition or FieldKind.UnsupportedEnumUnderlyingType) + { + leaf = argument; + return true; + } + + if (FindUnusableLeaf(argument, out leaf)) + return true; + } + + leaf = default; + return false; + } + // Walks a mapping and its collection element/key/value mappings, yielding every Object mapping // found. A nested [AkkaSerializable] type used only inside a collection (a List // element, say) is found this way too. Yields the full mapping, not just its name, so a caller @@ -727,7 +776,7 @@ private static bool ValidateMessages( isValid = false; } - foreach (var field in message.Fields.Where(field => field.Mapping.Kind == FieldKind.Unsupported)) + foreach (var field in message.Fields.Where(field => GetDiagnosticKind(field, out _) == FieldKind.Unsupported)) { var at = new LocationKey(message.Key, field.Name); diagnostics.Add(field.Mapping.SuggestsEnvelopeOrUnion @@ -742,10 +791,12 @@ private static bool ValidateMessages( isValid = false; } - foreach (var field in message.Fields.Where(field => field.Mapping.Kind == FieldKind.UnsupportedEnumUnderlyingType)) + foreach (var field in message.Fields.Where(field => GetDiagnosticKind(field, out _) == FieldKind.UnsupportedEnumUnderlyingType)) { + // For a collection field the enum is the unusable element/key/value, not the field. + GetDiagnosticKind(field, out var enumMapping); var at = new LocationKey(message.Key, field.Name); - diagnostics.Add(new DiagnosticSpec(DiagnosticKey.UnsupportedEnumUnderlyingType, at, field.Name, ToDisplayName(message.FullyQualifiedName), ToDisplayName(field.Mapping.TypeFullName), ToDisplayName(field.Mapping.EnumUnderlyingTypeName))); + diagnostics.Add(new DiagnosticSpec(DiagnosticKey.UnsupportedEnumUnderlyingType, at, field.Name, ToDisplayName(message.FullyQualifiedName), ToDisplayName(enumMapping.TypeFullName), ToDisplayName(enumMapping.EnumUnderlyingTypeName))); isValid = false; } @@ -764,6 +815,12 @@ private static bool ValidateMessages( // declaring assembly says so). foreach (var field in message.Fields) { + // A collection that already failed on an unusable element/key/value is reported once, + // for the whole field (AKKASG003/AKKASG014 above), exactly as when extraction used to + // collapse it -- its other, healthy-looking leaves must not add a second diagnostic. + if (!field.Mapping.TypeArguments.IsEmpty && FindUnusableLeaf(field.Mapping, out _)) + continue; + var seenTypeKeys = new HashSet(); foreach (var objectMapping in EnumerateObjectMappings(field.Mapping)) { diff --git a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionCachingSpec.cs b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionCachingSpec.cs new file mode 100644 index 00000000000..7c32fb277e9 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionCachingSpec.cs @@ -0,0 +1,72 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Akka.Serialization.V2.Generators; +using Akka.Serialization.V2.Tests.Harness; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Cache-safety for formatter-handled collection members: a collection mapping now carries the +/// FormatterInfo of each formatted element, key or value, so that model must stay symbol-free +/// and value-equatable, and a formatter registration change must still re-resolve the collection. +/// +public sealed class FormatterCollectionCachingSpec +{ + [Fact(DisplayName = "Should_ReuseEveryCachedStage_When_AnUnrelatedTypeIsAddedToTheSameFile")] + public void Should_ReuseEveryCachedStage_When_AnUnrelatedTypeIsAddedToTheSameFile() + { + var before = GeneratorGoldenFormatterCollectionSpec.Source; + var after = before + "\npublic static class Untouched { public static int Value => 1; }\n"; + + var run = GeneratorTestHarness.RunIncremental(before, after); + + run.Before.GeneratedSources.Should().NotBeEmpty("the baseline must actually generate, or this guard passes vacuously"); + run.After.GeneratedSources.Should().Equal(run.Before.GeneratedSources); + + var trackedSteps = run.After.RunResult.Results.Single().TrackedSteps; + foreach (var trackingName in AkkaSerializerGenerator.TrackingNames.All) + { + foreach (var (_, reason) in trackedSteps[trackingName].SelectMany(step => step.Outputs)) + { + (reason == IncrementalStepRunReason.Cached || reason == IncrementalStepRunReason.Unchanged) + .Should().BeTrue($"step '{trackingName}' must not recompute, but reported '{reason}'"); + } + } + } + + [Fact(DisplayName = "Should_ReportAKKASG003_When_TheFormatterOfACollectionMemberIsRemovedOnARerun")] + public void Should_ReportAKKASG003_When_TheFormatterOfACollectionMemberIsRemovedOnARerun() + { + var before = GeneratorGoldenFormatterCollectionSpec.Source; + var after = before.Replace("[AkkaSerializerFormatter]", string.Empty); + + var run = GeneratorTestHarness.RunIncremental(before, after); + + run.Before.GeneratorDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Should().BeEmpty(); + run.After.GeneratorDiagnostics.Should().ContainSingle(d => d.Id == "AKKASG003" && d.GetMessage(null).Contains("'MapOfTagLists'")); + run.After.GeneratedSources.Should().BeEmpty(); + } + + [Fact(DisplayName = "Should_GenerateAgain_When_TheFormatterOfACollectionMemberIsRestoredOnARerun")] + public void Should_GenerateAgain_When_TheFormatterOfACollectionMemberIsRestoredOnARerun() + { + var withFormatter = GeneratorGoldenFormatterCollectionSpec.Source; + var withoutFormatter = withFormatter.Replace("[AkkaSerializerFormatter]", string.Empty); + + var run = GeneratorTestHarness.RunIncremental(withoutFormatter, withFormatter); + + run.Before.GeneratedSources.Should().BeEmpty(); + run.After.GeneratorDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Should().BeEmpty(); + run.After.GeneratedSources.Keys.Should().Contain("FormatterPositionsSerializer.AkkaSerialization.g.cs"); + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs new file mode 100644 index 00000000000..507df50ef9f --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs @@ -0,0 +1,97 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Akka.Serialization.V2.Tests.Harness; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Xunit; +using static Akka.Serialization.V2.Tests.Harness.DiagnosticSource; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Diagnostics for the shapes that stay unsupported once a formatter can serve a collection's element, key +/// or value (G-1): a collection shape the generator does not support, a member nothing handles, and the +/// diagnostic a collection reports when one member is unusable. +/// +public sealed class FormatterCollectionDiagnosticsSpec +{ + [Theory(DisplayName = "Should_ReportAKKASG003_When_CollectionShapeIsStillUnsupportedEvenWithAFormatter")] + [InlineData("IImmutableDictionary")] + [InlineData("IImmutableList")] + [InlineData("IImmutableSet")] + [InlineData("ImmutableSortedSet")] + [InlineData("ImmutableSortedDictionary")] + [InlineData("HashSet")] + [InlineData("ISet")] + [InlineData("IEnumerable")] + [InlineData("Foreign[,]")] + public void Should_ReportAKKASG003_When_CollectionShapeIsStillUnsupportedEvenWithAFormatter(string fieldType) + { + var run = Run(ForeignFormatterAttribute, $"[property: AkkaField(1)] {fieldType} Items"); + + var diagnostic = run.Errors.Should().ContainSingle(d => d.Id == "AKKASG003").Subject; + diagnostic.GetMessage(null).Should().Contain("'Items'").And.Contain("DiagnosticSample.Foreign"); + run.Result.GeneratedSources.Should().BeEmpty("a serializer with an error generates nothing"); + } + + [Theory(DisplayName = "Should_ReportAKKASG003WithTheFullFieldType_When_ACollectionHoldsATypeNoFormatterHandles")] + [InlineData("List", "List<")] + [InlineData("Foreign[]", "Foreign[]")] + [InlineData("ImmutableArray", "ImmutableArray<")] + [InlineData("Dictionary", "Dictionary", "Dictionary<")] + [InlineData("Dictionary>", "Dictionary got before collection positions learned about formatters. + var run = Run(string.Empty, $"[property: AkkaField(1)] {fieldType} Items"); + + var diagnostic = run.Errors.Should().ContainSingle(d => d.Id == "AKKASG003").Subject; + diagnostic.GetMessage(null).Should().Contain("'Items'").And.Contain(expectedTypeFragment).And.Contain("DiagnosticSample.Foreign"); + run.Errors.Should().NotContain(d => d.Id == "AKKASG007", "the whole collection field is reported once, not its element separately"); + } + + [Fact(DisplayName = "Should_ReportAKKASG003_When_DictionaryKeyIsObjectEvenIfValueHasAFormatter")] + public void Should_ReportAKKASG003_When_DictionaryKeyIsObjectEvenIfValueHasAFormatter() + { + var run = Run(ForeignFormatterAttribute, "[property: AkkaField(1)] Dictionary Items"); + + run.Errors.Should().ContainSingle(d => d.Id == "AKKASG003"); + } + + [Fact(DisplayName = "Should_ReportAKKASG014_When_AnEnumWithAnUnsupportedUnderlyingTypeIsACollectionMember")] + public void Should_ReportAKKASG014_When_AnEnumWithAnUnsupportedUnderlyingTypeIsACollectionMember() + { + var run = Run(ForeignFormatterAttribute, "[property: AkkaField(1)] Dictionary Items"); + + // The enum is declared next to the message; the formatter on Foreign does not rescue the value. + var diagnostic = run.Errors.Should().ContainSingle(d => d.Id == "AKKASG014").Subject; + diagnostic.GetMessage(null).Should().Contain("WideEnum").And.Contain("long"); + } + + [Fact(DisplayName = "Should_ReportOnlyTheFirstUnusableMember_When_AKeyAndAValueAreBothUnusable")] + public void Should_ReportOnlyTheFirstUnusableMember_When_AKeyAndAValueAreBothUnusable() + { + // Key first, as before: the unregistered key type decides (AKKASG003), the wide enum value does not add a second diagnostic. + var run = Run(string.Empty, "[property: AkkaField(1)] Dictionary Items"); + + run.Errors.Select(d => d.Id).Should().Equal("AKKASG003"); + } + + [Fact(DisplayName = "Should_AcceptTheFormatter_When_AFormatterIsRegisteredForAnUnsupportedForeignType")] + public void Should_AcceptTheFormatter_When_AFormatterIsRegisteredForAnUnsupportedForeignType() + { + var run = Run(ForeignFormatterAttribute, "[property: AkkaField(1)] Foreign A, [property: AkkaField(2)] List B"); + + run.Errors.Should().BeEmpty(); + run.Result.GeneratedSources.Keys.Should().Contain("SampleSerializer.AkkaSerialization.g.cs"); + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs new file mode 100644 index 00000000000..37e3dbd6c49 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs @@ -0,0 +1,602 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Akka.Actor; +using FluentAssertions; +using MessagePack; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Formatter resolution at collection ELEMENT, dictionary KEY and dictionary VALUE position (G-1): +/// every collection shape the generator supports holds a formatter-handled type (built-in +/// , a custom reference-type formatter, a custom value-type formatter, and a custom +/// formatter that overrides the native encoding) exactly as a field does. +/// The wire contract under test: an array or map whose elements are exactly what the formatter writes at +/// field position, with no wrapper. +/// +public sealed class FormatterCollectionSpec : IAsyncLifetime +{ + private static readonly Address Local = new("akka", "sys", "localhost", 2552); + private static readonly Address Remote = new("akka.tcp", "other", "10.0.0.2", 4053); + private static readonly Address NoHost = new("akka", "sys"); + + private ActorSystem _system = null!; + private FormatterPositionSerializer _serializer = null!; + private NativeRefPositionSerializer _nativeRefSerializer = null!; + + public ValueTask InitializeAsync() + { + _system = ActorSystem.Create("formatter-collection-spec"); + _serializer = new FormatterPositionSerializer((ExtendedActorSystem)_system); + _nativeRefSerializer = new NativeRefPositionSerializer((ExtendedActorSystem)_system); + return ValueTask.CompletedTask; + } + + public async ValueTask DisposeAsync() + { + await _system.Terminate(); + } + + // ------------------------------------------------------------------------------------------ + // Address (built-in formatter, reference type) in every position of every collection shape + // ------------------------------------------------------------------------------------------ + + private static AddressPositions PopulatedAddressPositions() => new( + ListOf: new List
{ Local, Remote, NoHost }, + ArrayOf: new[] { Remote, Local }, + ImmutableArrayOf: ImmutableArray.Create(Local, NoHost), + ReadOnlyListOf: new List
{ NoHost, Remote }, + ReadOnlyCollectionOf: new List
{ Local }, + ImmutableListOf: ImmutableList.Create(Remote, Local), + ImmutableSetOf: ImmutableHashSet.Create(Local, Remote, NoHost), + ByKey: new Dictionary { [Local] = long.MaxValue, [Remote] = long.MinValue, [NoHost] = 0 }, + ReadOnlyByKey: new Dictionary { [Local] = "local", [Remote] = "remote" }, + ImmutableByKey: ImmutableDictionary.Empty.Add(Local, 1).Add(NoHost, 2), + ByValue: new Dictionary { ["a"] = Local, ["b"] = Remote }, + ReadOnlyByValue: new Dictionary { ["c"] = NoHost }, + ImmutableByValue: ImmutableDictionary.Empty.Add("d", Remote), + KeyAndValue: new Dictionary { [Local] = Remote, [Remote] = NoHost }, + NullableElements: new List { Local, null, Remote, null }, + Nested: new List> { new() { Local }, new(), new() { Remote, NoHost } }, + MapOfLists: new Dictionary> { ["x"] = new() { Local, Remote }, ["y"] = new() }); + + [Fact(DisplayName = "Should_RoundTripEveryShape_When_AddressIsFormattedInElementKeyAndValuePosition")] + public void Should_RoundTripEveryShape_When_AddressIsFormattedInElementKeyAndValuePosition() + { + var recovered = RoundTrip(PopulatedAddressPositions()); + + recovered.ListOf.Should().Equal(Local, Remote, NoHost); + recovered.ArrayOf.Should().Equal(Remote, Local); + recovered.ImmutableArrayOf.Should().Equal(Local, NoHost); + recovered.ReadOnlyListOf.Should().Equal(NoHost, Remote); + recovered.ReadOnlyCollectionOf.Should().Equal(Local); + recovered.ImmutableListOf.Should().Equal(Remote, Local); + recovered.ImmutableSetOf.Should().BeEquivalentTo(new[] { Local, Remote, NoHost }); + recovered.ByKey.Should().BeEquivalentTo(new Dictionary { [Local] = long.MaxValue, [Remote] = long.MinValue, [NoHost] = 0 }); + recovered.ReadOnlyByKey.Should().BeEquivalentTo(new Dictionary { [Local] = "local", [Remote] = "remote" }); + recovered.ImmutableByKey.Should().BeEquivalentTo(new Dictionary { [Local] = 1, [NoHost] = 2 }); + recovered.ByValue.Should().BeEquivalentTo(new Dictionary { ["a"] = Local, ["b"] = Remote }); + recovered.ReadOnlyByValue.Should().BeEquivalentTo(new Dictionary { ["c"] = NoHost }); + recovered.ImmutableByValue.Should().BeEquivalentTo(new Dictionary { ["d"] = Remote }); + recovered.KeyAndValue.Should().BeEquivalentTo(new Dictionary { [Local] = Remote, [Remote] = NoHost }); + recovered.NullableElements.Should().Equal(Local, null, Remote, null); + recovered.Nested!.Select(inner => inner.ToArray()).Should().BeEquivalentTo(new[] + { + new[] { Local }, Array.Empty
(), new[] { Remote, NoHost } + }, options => options.WithStrictOrdering()); + recovered.MapOfLists!["x"].Should().Equal(Local, Remote); + recovered.MapOfLists["y"].Should().BeEmpty(); + } + + [Fact(DisplayName = "Should_ReportExactSizeHint_When_ElementsKeysAndValuesAreFormatted")] + public void Should_ReportExactSizeHint_When_ElementsKeysAndValuesAreFormatted() + { + var message = PopulatedAddressPositions(); + + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_RoundTripNullAndEmpty_When_FormattedCollectionFieldsAreNullOrEmpty")] + public void Should_RoundTripNullAndEmpty_When_FormattedCollectionFieldsAreNullOrEmpty() + { + var allNull = new AddressPositions(null, null, default, null, null, null, null, null, null, null, null, null, null, null, new List(), null, null); + var recoveredNull = RoundTrip(allNull); + + recoveredNull.ListOf.Should().BeNull(); + recoveredNull.ArrayOf.Should().BeNull(); + recoveredNull.ImmutableArrayOf.IsDefault.Should().BeTrue(); + recoveredNull.ByKey.Should().BeNull(); + recoveredNull.ImmutableByValue.Should().BeNull(); + _serializer.SizeHint(allNull).Should().Be(_serializer.ToBinary(allNull).Length); + + var allEmpty = new AddressPositions( + new List
(), Array.Empty
(), ImmutableArray
.Empty, new List
(), new List
(), + ImmutableList
.Empty, ImmutableHashSet
.Empty, new Dictionary(), new Dictionary(), + ImmutableDictionary.Empty, new Dictionary(), new Dictionary(), + ImmutableDictionary.Empty, new Dictionary(), new List(), + new List>(), new Dictionary>()); + var recoveredEmpty = RoundTrip(allEmpty); + + recoveredEmpty.ListOf.Should().NotBeNull().And.BeEmpty(); + recoveredEmpty.ImmutableArrayOf.IsDefault.Should().BeFalse(); + recoveredEmpty.ImmutableArrayOf.Should().BeEmpty(); + recoveredEmpty.ByKey.Should().NotBeNull().And.BeEmpty(); + recoveredEmpty.ImmutableByValue.Should().NotBeNull().And.BeEmpty(); + _serializer.SizeHint(allEmpty).Should().Be(_serializer.ToBinary(allEmpty).Length); + } + + // ------------------------------------------------------------------------------------------ + // Wire contract: elements are exactly what the formatter writes at field position + // ------------------------------------------------------------------------------------------ + + [Fact(DisplayName = "Should_WriteFormatterBytesAsArrayElements_When_ListOfAddress")] + public void Should_WriteFormatterBytesAsArrayElements_When_ListOfAddress() + { + var message = new ListOfAddressMessage(new List
{ Local, NoHost }); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(1); + writer.Write(1); + writer.WriteArrayHeader(2); + new AddressFormatter().Write(ref writer, Local); + new AddressFormatter().Write(ref writer, NoHost); + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_WriteFormatterBytesForKeysAndValues_When_DictionaryOfAddressToAddress")] + public void Should_WriteFormatterBytesForKeysAndValues_When_DictionaryOfAddressToAddress() + { + var message = new AddressToAddressMessage(new Dictionary { [Local] = Remote }); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(1); + writer.Write(1); + writer.WriteMapHeader(1); + new AddressFormatter().Write(ref writer, Local); + new AddressFormatter().Write(ref writer, Remote); + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_WriteSameBytesAsFieldPosition_When_FormattedTypeIsAFieldAndAnElement")] + public void Should_WriteSameBytesAsFieldPosition_When_FormattedTypeIsAFieldAndAnElement() + { + var asField = _serializer.ToBinary(new SingleAddressMessage(Remote)); + var asElement = _serializer.ToBinary(new ListOfAddressMessage(new List
{ Remote })); + + // Field position: map(1) { 1:
}. Element position: map(1) { 1: array(1) [
] }. + // The address bytes are identical; the only difference is the one-byte array header. + asElement.Should().Equal(asField.Take(2).Concat(new byte[] { 0x91 }).Concat(asField.Skip(2))); + } + + [Fact(DisplayName = "Should_WriteNilForNullElements_When_FormattedElementIsNull")] + public void Should_WriteNilForNullElements_When_FormattedElementIsNull() + { + var message = new NullableAddressElementsMessage(new List { null, Local }); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(1); + writer.Write(1); + writer.WriteArrayHeader(2); + writer.WriteNil(); + new AddressFormatter().Write(ref writer, Local); + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + // ------------------------------------------------------------------------------------------ + // Custom formatters: a reference type, a value type (plain and Nullable), and IActorRef + // ------------------------------------------------------------------------------------------ + + [Fact(DisplayName = "Should_RoundTripReferenceFormatter_When_UsedAsElementKeyAndValue")] + public void Should_RoundTripReferenceFormatter_When_UsedAsElementKeyAndValue() + { + var message = new TagPositions( + ListOf: new List { new("a"), new("b") }, + ArrayOf: new[] { new PositionTag("c") }, + ByKey: new Dictionary { [new PositionTag("k")] = 7 }, + ByValue: new Dictionary { [1] = new PositionTag("v") }, + KeyAndValue: new Dictionary { [new PositionTag("kk")] = new PositionTag("vv") }, + ImmutableSetOf: ImmutableHashSet.Create(new PositionTag("s1"), new PositionTag("s2"))); + + var recovered = RoundTrip(message); + + recovered.ListOf.Should().Equal(new PositionTag("a"), new PositionTag("b")); + recovered.ArrayOf.Should().Equal(new PositionTag("c")); + recovered.ByKey.Should().BeEquivalentTo(new Dictionary { [new PositionTag("k")] = 7 }); + recovered.ByValue.Should().BeEquivalentTo(new Dictionary { [1] = new PositionTag("v") }); + recovered.KeyAndValue.Should().BeEquivalentTo(new Dictionary { [new PositionTag("kk")] = new PositionTag("vv") }); + recovered.ImmutableSetOf.Should().BeEquivalentTo(new[] { new PositionTag("s1"), new PositionTag("s2") }); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_UseTheFormatterEncoding_When_ReferenceFormatterIsAnElement")] + public void Should_UseTheFormatterEncoding_When_ReferenceFormatterIsAnElement() + { + var message = new TagPositions(new List { new("a") }, null, null, null, null, null); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(6); + writer.Write(1); + writer.WriteArrayHeader(1); + writer.Write("tag:a"); // PositionTagFormatter's own wire form, not a nested { 1: "a" } map + for (var field = 2; field <= 6; field++) + { + writer.Write(field); + writer.WriteNil(); + } + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_RoundTripValueTypeFormatter_When_UsedAsElementKeyAndNullableValue")] + public void Should_RoundTripValueTypeFormatter_When_UsedAsElementKeyAndNullableValue() + { + var message = new CelsiusPositions( + ListOf: new List { new(-273.15), new(0), new(100.5) }, + ArrayOf: new[] { new PositionCelsius(1) }, + NullableListOf: new List { new PositionCelsius(2), null, new PositionCelsius(3) }, + ImmutableArrayOfNullable: ImmutableArray.Create(null, new PositionCelsius(4)), + ByKey: new Dictionary { [new PositionCelsius(5)] = "five" }, + ByNullableValue: new Dictionary { ["has"] = new PositionCelsius(6), ["none"] = null }); + + var recovered = RoundTrip(message); + + recovered.ListOf.Should().Equal(new PositionCelsius(-273.15), new PositionCelsius(0), new PositionCelsius(100.5)); + recovered.ArrayOf.Should().Equal(new PositionCelsius(1)); + recovered.NullableListOf.Should().Equal(new PositionCelsius(2), null, new PositionCelsius(3)); + recovered.ImmutableArrayOfNullable.Should().Equal(null, new PositionCelsius(4)); + recovered.ByKey.Should().BeEquivalentTo(new Dictionary { [new PositionCelsius(5)] = "five" }); + recovered.ByNullableValue.Should().BeEquivalentTo(new Dictionary { ["has"] = new PositionCelsius(6), ["none"] = null }); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_WriteNilForNullElements_When_ValueTypeFormatterElementIsNullable")] + public void Should_WriteNilForNullElements_When_ValueTypeFormatterElementIsNullable() + { + var message = new CelsiusPositions(null, null, new List { null, new PositionCelsius(2.5) }, default, null, null); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(6); + writer.Write(1); + writer.WriteNil(); + writer.Write(2); + writer.WriteNil(); + writer.Write(3); + writer.WriteArrayHeader(2); + writer.WriteNil(); + writer.Write(2.5); // PositionCelsiusFormatter writes a bare float64, no wrapper + for (var field = 4; field <= 6; field++) + { + writer.Write(field); + writer.WriteNil(); + } + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_RoundTripActorRefs_When_CustomFormatterOverridesNativeEncodingInCollections")] + public void Should_RoundTripActorRefs_When_CustomFormatterOverridesNativeEncodingInCollections() + { + var worker = _system.ActorOf(Props.Create(() => new IdleActor()), "worker"); + var message = new RefPositions( + ListOf: new List { worker, _system.DeadLetters }, + ReadOnlyListOf: new List { worker }, + ByValue: new Dictionary { ["w"] = worker }, + ByKey: new Dictionary { [worker] = 9 }, + ImmutableArrayOf: ImmutableArray.Create(worker, _system.DeadLetters)); + + var recovered = RoundTrip(message); + + recovered.ListOf!.Select(r => r.Path).Should().Equal(worker.Path, _system.DeadLetters.Path); + recovered.ReadOnlyListOf!.Single().Path.Should().Be(worker.Path); + recovered.ByValue!["w"].Path.Should().Be(worker.Path); + recovered.ByKey!.Keys.Single().Path.Should().Be(worker.Path); + recovered.ImmutableArrayOf.Select(r => r.Path).Should().Equal(worker.Path, _system.DeadLetters.Path); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_UseTheCustomActorRefFormatter_When_ActorRefIsAnElement")] + public void Should_UseTheCustomActorRefFormatter_When_ActorRefIsAnElement() + { + var path = Akka.Serialization.Serialization.SerializedActorPath(_system.DeadLetters); + var message = new RefPositions(new List { _system.DeadLetters }, null, null, null, ImmutableArray.Empty); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(5); + writer.Write(1); + writer.WriteArrayHeader(1); + writer.WriteArrayHeader(2); // PositionRefFormatter's own wire form: ["ref", path] + writer.Write("ref"); + writer.Write(path); + writer.Write(2); + writer.WriteNil(); + writer.Write(3); + writer.WriteNil(); + writer.Write(4); + writer.WriteNil(); + writer.Write(5); + writer.WriteArrayHeader(0); + }); + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_KeepNativeActorRefEncoding_When_NoActorRefFormatterIsRegistered")] + public void Should_KeepNativeActorRefEncoding_When_NoActorRefFormatterIsRegistered() + { + var path = Akka.Serialization.Serialization.SerializedActorPath(_system.DeadLetters); + var message = new NativeRefListMessage(new List { _system.DeadLetters }); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(1); + writer.Write(1); + writer.WriteArrayHeader(1); + writer.Write(path); // native: a bare serialized-path string + }); + + _nativeRefSerializer.ToBinary(message).Should().Equal(expected); + var recovered = (NativeRefListMessage)_nativeRefSerializer.FromBinary(_nativeRefSerializer.ToBinary(message), _nativeRefSerializer.Manifest(message)); + recovered.Refs.Single().Path.Should().Be(_system.DeadLetters.Path); + } + + // ------------------------------------------------------------------------------------------ + // Built-in ActorPath formatter (needs the system) in collections + // ------------------------------------------------------------------------------------------ + + [Fact(DisplayName = "Should_RoundTripActorPaths_When_BuiltInActorPathFormatterIsAnElementKeyAndValue")] + public void Should_RoundTripActorPaths_When_BuiltInActorPathFormatterIsAnElementKeyAndValue() + { + var a = ActorPath.Parse($"akka://{_system.Name}/user/a"); + var b = ActorPath.Parse($"akka://{_system.Name}/user/b"); + var message = new ActorPathPositions( + new List { a, b }, + new Dictionary { [a] = b }); + + var recovered = RoundTrip(message); + + recovered.ListOf.Should().Equal(a, b); + recovered.KeyAndValue.Should().BeEquivalentTo(new Dictionary { [a] = b }); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + // ------------------------------------------------------------------------------------------ + // Native collections keep working next to formatted ones + // ------------------------------------------------------------------------------------------ + + [Fact(DisplayName = "Should_KeepNativeEncoding_When_ANativeCollectionSharesAMessageWithAFormattedOne")] + public void Should_KeepNativeEncoding_When_ANativeCollectionSharesAMessageWithAFormattedOne() + { + var message = new MixedMessage(new List { "x", "y" }, new List
{ Local }); + + var expected = WriteBytes((ref MessagePackWriter writer) => + { + writer.WriteMapHeader(2); + writer.Write(1); + writer.WriteArrayHeader(2); + writer.Write("x"); + writer.Write("y"); + writer.Write(2); + writer.WriteArrayHeader(1); + new AddressFormatter().Write(ref writer, Local); + }); + + _serializer.ToBinary(message).Should().Equal(expected); + RoundTrip(message).Natives.Should().Equal("x", "y"); + } + + private TMessage RoundTrip(TMessage message) + where TMessage : class, IFormatterPositionProtocol + { + var bytes = _serializer.ToBinary(message); + return _serializer.FromBinary(bytes, _serializer.Manifest(message)).Should().BeOfType().Subject; + } + + private static byte[] WriteBytes(WriteAction write) + { + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + write(ref writer); + writer.Flush(); + return buffer.WrittenMemory.ToArray(); + } + + private delegate void WriteAction(ref MessagePackWriter writer); +} + +// ---------------------------------------------------------------------------------------------- +// Fixtures +// ---------------------------------------------------------------------------------------------- + +public interface IFormatterPositionProtocol +{ +} + +public interface INativeRefProtocol +{ +} + +public sealed class IdleActor : ReceiveActor +{ +} + +/// A reference-type formatter target whose formatter writes a bare, tagged string. +public sealed record PositionTag(string Value); + +public sealed class PositionTagFormatter : IAkkaMessagePackFormatter +{ + public void Write(ref MessagePackWriter writer, PositionTag value) => writer.Write("tag:" + value.Value); + + public PositionTag Read(ref MessagePackReader reader) + { + var raw = reader.ReadString() ?? throw new MessagePackSerializationException("Missing tag."); + return new PositionTag(raw.Substring("tag:".Length)); + } + + public int SizeOf(PositionTag value) => MessagePackSizes.SizeOfString("tag:" + value.Value); +} + +/// A value-type formatter target (constructed with the system) whose formatter writes a bare float64. +public readonly record struct PositionCelsius(double Degrees); + +public sealed class PositionCelsiusFormatter : IAkkaMessagePackFormatter +{ + public PositionCelsiusFormatter(ExtendedActorSystem system) + { + } + + public void Write(ref MessagePackWriter writer, PositionCelsius value) => writer.Write(value.Degrees); + + public PositionCelsius Read(ref MessagePackReader reader) => new(reader.ReadDouble()); + + public int SizeOf(PositionCelsius value) => MessagePackSizes.SizeOfDouble(value.Degrees); +} + +/// An IActorRef formatter with its own wire form, so a test can tell it from the native path-string encoding. +public sealed class PositionRefFormatter : IAkkaMessagePackFormatter +{ + private readonly ExtendedActorSystem _system; + + public PositionRefFormatter(ExtendedActorSystem system) + { + _system = system; + } + + public void Write(ref MessagePackWriter writer, IActorRef value) + { + writer.WriteArrayHeader(2); + writer.Write("ref"); + writer.Write(Akka.Serialization.Serialization.SerializedActorPath(value)); + } + + public IActorRef Read(ref MessagePackReader reader) + { + reader.ReadArrayHeader(); + reader.ReadString(); + return _system.Provider.ResolveActorRef(reader.ReadString()!); + } + + public int SizeOf(IActorRef value) => + MessagePackSizes.SizeOfArrayHeader(2) + + MessagePackSizes.SizeOfString("ref") + + MessagePackSizes.SizeOfString(Akka.Serialization.Serialization.SerializedActorPath(value)); +} + +[AkkaSerializer("formatter-position-test", 122001)] +[AkkaSerializerFormatter] +[AkkaSerializerFormatter] +[AkkaSerializerFormatter] +[AkkaSerializerFormatter] +[AkkaSerializerFormatter] +public sealed partial class FormatterPositionSerializer : AkkaSerializer +{ + public static partial SerializerRegistration CreateRegistration(); +} + +[AkkaSerializer("native-ref-position-test", 122002)] +public sealed partial class NativeRefPositionSerializer : AkkaSerializer +{ + public static partial SerializerRegistration CreateRegistration(); +} + +[AkkaSerializable(Manifest = "native-ref-list-v1")] +public sealed record NativeRefListMessage( + [property: AkkaField(1)] List Refs) : INativeRefProtocol; + +[AkkaSerializable(Manifest = "address-positions-v1")] +public sealed record AddressPositions( + [property: AkkaField(1)] List
? ListOf, + [property: AkkaField(2)] Address[]? ArrayOf, + [property: AkkaField(3)] ImmutableArray
ImmutableArrayOf, + [property: AkkaField(4)] IReadOnlyList
? ReadOnlyListOf, + [property: AkkaField(5)] IReadOnlyCollection
? ReadOnlyCollectionOf, + [property: AkkaField(6)] ImmutableList
? ImmutableListOf, + [property: AkkaField(7)] ImmutableHashSet
? ImmutableSetOf, + [property: AkkaField(8)] Dictionary? ByKey, + [property: AkkaField(9)] IReadOnlyDictionary? ReadOnlyByKey, + [property: AkkaField(10)] ImmutableDictionary? ImmutableByKey, + [property: AkkaField(11)] Dictionary? ByValue, + [property: AkkaField(12)] IReadOnlyDictionary? ReadOnlyByValue, + [property: AkkaField(13)] ImmutableDictionary? ImmutableByValue, + [property: AkkaField(14)] Dictionary? KeyAndValue, + [property: AkkaField(15)] List NullableElements, + [property: AkkaField(16)] List>? Nested, + [property: AkkaField(17)] Dictionary>? MapOfLists) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "list-of-address-v1")] +public sealed record ListOfAddressMessage( + [property: AkkaField(1)] List
Addresses) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "single-address-v1")] +public sealed record SingleAddressMessage( + [property: AkkaField(1)] Address Address) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "nullable-address-elements-v1")] +public sealed record NullableAddressElementsMessage( + [property: AkkaField(1)] List Addresses) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "address-to-address-v1")] +public sealed record AddressToAddressMessage( + [property: AkkaField(1)] Dictionary Map) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "tag-positions-v1")] +public sealed record TagPositions( + [property: AkkaField(1)] List? ListOf, + [property: AkkaField(2)] PositionTag[]? ArrayOf, + [property: AkkaField(3)] Dictionary? ByKey, + [property: AkkaField(4)] Dictionary? ByValue, + [property: AkkaField(5)] Dictionary? KeyAndValue, + [property: AkkaField(6)] ImmutableHashSet? ImmutableSetOf) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "celsius-positions-v1")] +public sealed record CelsiusPositions( + [property: AkkaField(1)] List? ListOf, + [property: AkkaField(2)] PositionCelsius[]? ArrayOf, + [property: AkkaField(3)] List? NullableListOf, + [property: AkkaField(4)] ImmutableArray ImmutableArrayOfNullable, + [property: AkkaField(5)] Dictionary? ByKey, + [property: AkkaField(6)] Dictionary? ByNullableValue) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "ref-positions-v1")] +public sealed record RefPositions( + [property: AkkaField(1)] List? ListOf, + [property: AkkaField(2)] IReadOnlyList? ReadOnlyListOf, + [property: AkkaField(3)] Dictionary? ByValue, + [property: AkkaField(4)] Dictionary? ByKey, + [property: AkkaField(5)] ImmutableArray ImmutableArrayOf) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "actor-path-positions-v1")] +public sealed record ActorPathPositions( + [property: AkkaField(1)] List ListOf, + [property: AkkaField(2)] Dictionary KeyAndValue) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "mixed-v1")] +public sealed record MixedMessage( + [property: AkkaField(1)] List Natives, + [property: AkkaField(2)] List
Addresses) : IFormatterPositionProtocol; diff --git a/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs new file mode 100644 index 00000000000..9fbfc04c5de --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs @@ -0,0 +1,142 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Akka.Serialization.V2.Tests.Harness; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Golden-output gate for formatter resolution at collection ELEMENT, dictionary KEY and dictionary +/// VALUE position (G-1). Kept apart from GeneratorGoldenOutputSpec on purpose: that spec's +/// baselines were captured before this feature and must not move; this corpus adds one new +/// serializer with its own baseline. +/// +public sealed class GeneratorGoldenFormatterCollectionSpec +{ + private const string HintName = "FormatterPositionsSerializer.AkkaSerialization.g.cs"; + + // Each field is a distinct emission path: a reference-type element (nullable and not), a value-type + // key and a reference-type value, a Nullable value-type element, a nested collection, and an + // IActorRef formatter that overrides the native IActorRef encoding. The other collection shapes + // share these paths; FormatterCollectionSpec round-trips every shape. + internal const string Source = """ + #nullable enable + using System.Collections.Generic; + using System.Collections.Immutable; + using Akka.Actor; + using Akka.Serialization.V2; + using MessagePack; + + namespace FormatterGolden; + + public interface IProtocol + { + } + + public sealed record Tag(string Value); + + public sealed class TagFormatter : IAkkaMessagePackFormatter + { + public void Write(ref MessagePackWriter writer, Tag value) => writer.Write(value.Value); + public Tag Read(ref MessagePackReader reader) => new Tag(reader.ReadString() ?? string.Empty); + public int SizeOf(Tag value) => MessagePackSizes.SizeOfString(value.Value); + } + + public readonly record struct Celsius(double Degrees); + + public sealed class CelsiusFormatter : IAkkaMessagePackFormatter + { + public CelsiusFormatter(ExtendedActorSystem system) + { + } + + public void Write(ref MessagePackWriter writer, Celsius value) => writer.Write(value.Degrees); + public Celsius Read(ref MessagePackReader reader) => new Celsius(reader.ReadDouble()); + public int SizeOf(Celsius value) => 9; + } + + public sealed class RefFormatter : IAkkaMessagePackFormatter + { + public void Write(ref MessagePackWriter writer, IActorRef value) => writer.Write(value.Path.ToString()); + public IActorRef Read(ref MessagePackReader reader) => ActorRefs.Nobody; + public int SizeOf(IActorRef value) => Akka.Serialization.SerializerV2.UnknownSize; + } + + [AkkaSerializable(Manifest = "positions-v1")] + public sealed record Positions( + [property: AkkaField(1)] List
ListOfAddress, + [property: AkkaField(2)] List NullableAddressElements, + [property: AkkaField(3)] Dictionary AddressByCelsiusKey, + [property: AkkaField(4)] List ListOfNullableCelsius, + [property: AkkaField(5)] Dictionary> MapOfTagLists, + [property: AkkaField(6)] List ListOfRef) : IProtocol; + + [AkkaSerializer("formatter-positions", 150201)] + [AkkaSerializerFormatter] + [AkkaSerializerFormatter] + [AkkaSerializerFormatter] + [AkkaSerializerFormatter] + public sealed partial class FormatterPositionsSerializer : AkkaSerializer + { + public static partial SerializerRegistration CreateRegistration(); + } + """; + + [Fact(DisplayName = "Should_EmitByteIdenticalOutput_When_FormattersAppearInEveryCollectionPosition")] + public void Should_EmitByteIdenticalOutput_When_FormattersAppearInEveryCollectionPosition() + { + var result = GeneratorTestHarness.Run(Source); + + result.GeneratorDiagnostics.Should().BeEmpty("the formatter-position corpus is designed to be diagnostics-clean"); + result.GeneratedSources.Keys.Should().BeEquivalentTo(new[] { HintName }); + + var failure = GoldenBaseline.Compare(HintName, result.GeneratedSources[HintName]); + failure.Should().BeNull(); + } + + [Fact(DisplayName = "Should_CompileCleanly_When_GeneratedFromFormatterPositionCorpus")] + public void Should_CompileCleanly_When_GeneratedFromFormatterPositionCorpus() + { + var result = GeneratorTestHarness.Run(Source); + + result.GeneratorDiagnostics.Should().BeEmpty(); + result.CompileDiagnostics + .Where(diagnostic => diagnostic.Severity >= DiagnosticSeverity.Warning && diagnostic.Id != "CS1701") + .Select(diagnostic => diagnostic.ToString()) + .Should().BeEmpty("generated code must compile with no errors and no warnings under #nullable enable"); + } + + [Fact(DisplayName = "Should_EmitOneFormatterFieldPerTarget_When_ManyPositionsShareAFormatter")] + public void Should_EmitOneFormatterFieldPerTarget_When_ManyPositionsShareAFormatter() + { + var generated = GeneratorTestHarness.Run(Source).GeneratedSources[HintName]; + + // Address is used in three positions but is one formatter instance. + CountOccurrences(generated, "private readonly global::Akka.Serialization.V2.AddressFormatter ").Should().Be(1); + CountOccurrences(generated, "private readonly global::FormatterGolden.CelsiusFormatter ").Should().Be(1); + CountOccurrences(generated, " = new global::Akka.Serialization.V2.AddressFormatter(").Should().Be(1); + CountOccurrences(generated, " = new global::FormatterGolden.CelsiusFormatter(system)").Should().Be(1); + } + + private static int CountOccurrences(string text, string value) + { + var count = 0; + var index = 0; + while ((index = text.IndexOf(value, index, System.StringComparison.Ordinal)) >= 0) + { + count++; + index += value.Length; + } + + return count; + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/GoldenOutput/FormatterPositionsSerializer.AkkaSerialization.g.cs.verified.txt b/src/core/Akka.Serialization.V2.Tests/GoldenOutput/FormatterPositionsSerializer.AkkaSerialization.g.cs.verified.txt new file mode 100644 index 00000000000..916cbd1650c --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/GoldenOutput/FormatterPositionsSerializer.AkkaSerialization.g.cs.verified.txt @@ -0,0 +1,551 @@ +// +#nullable enable +using System; +using System.Buffers; + +namespace FormatterGolden; + +public sealed partial class FormatterPositionsSerializer +{ + private readonly global::Akka.Serialization.V2.AddressFormatter _akkaFormatter_Akka_Actor_Address; + private readonly global::FormatterGolden.RefFormatter _akkaFormatter_Akka_Actor_IActorRef; + private readonly global::FormatterGolden.CelsiusFormatter _akkaFormatter_FormatterGolden_Celsius; + private readonly global::FormatterGolden.TagFormatter _akkaFormatter_FormatterGolden_Tag; + + public FormatterPositionsSerializer(global::Akka.Actor.ExtendedActorSystem system) : base(system) + { + _akkaFormatter_Akka_Actor_Address = new global::Akka.Serialization.V2.AddressFormatter(); + _akkaFormatter_Akka_Actor_IActorRef = new global::FormatterGolden.RefFormatter(); + _akkaFormatter_FormatterGolden_Celsius = new global::FormatterGolden.CelsiusFormatter(system); + _akkaFormatter_FormatterGolden_Tag = new global::FormatterGolden.TagFormatter(); + } + + public override int Identifier => 150201; + + public static partial global::Akka.Serialization.V2.SerializerRegistration CreateRegistration() + { + return global::Akka.Serialization.V2.SerializerRegistration.Create("formatter-positions", + system => new FormatterPositionsSerializer(system), + global::System.Collections.Immutable.ImmutableHashSet.Create( + typeof(global::FormatterGolden.IProtocol))); + } + + public override string Manifest(object obj) + { + return obj switch + { + global::FormatterGolden.Positions => "positions-v1", + _ => throw new global::System.ArgumentException($"Unsupported generated serializer type '{obj.GetType()}' from assembly '{obj.GetType().Assembly.GetName().Name}'. This serializer was generated in assembly 'AkkaSerializationGeneratorHarness', which does not recognize this type.", nameof(obj)) + }; + } + + public override int Serialize(object obj, IBufferWriter writer) + { + var countingWriter = new AkkaGeneratedCountingBufferWriter(writer); + var messagePackWriter = new global::MessagePack.MessagePackWriter(countingWriter); + SerializeMessagePack(obj, ref messagePackWriter); + messagePackWriter.Flush(); + return checked((int)countingWriter.BytesWritten); + } + + private void SerializeMessagePack(object obj, ref global::MessagePack.MessagePackWriter writer) + { + switch (obj) + { + case global::FormatterGolden.Positions message: + WritePositions(ref writer, message); + break; + default: + throw new global::System.ArgumentException($"Unsupported generated serializer type '{obj.GetType()}' from assembly '{obj.GetType().Assembly.GetName().Name}'. This serializer was generated in assembly 'AkkaSerializationGeneratorHarness', which does not recognize this type.", nameof(obj)); + } + } + + public override object Deserialize(ReadOnlySequence bytes, string manifest) + { + var reader = new global::MessagePack.MessagePackReader(bytes); + return manifest switch + { + "positions-v1" => ReadPositions(ref reader), + _ => throw new global::System.Runtime.Serialization.SerializationException($"Unknown generated serializer manifest [{manifest}] for serializer [{GetType()}].") + }; + } + + public override int SizeHint(object obj) + { + return obj switch + { + global::FormatterGolden.Positions message => SizeOfPositions(message), + _ => global::Akka.Serialization.SerializerV2.UnknownSize + }; + } + + private sealed class AkkaGeneratedCountingBufferWriter : global::System.Buffers.IBufferWriter + { + private readonly global::System.Buffers.IBufferWriter _inner; + + public AkkaGeneratedCountingBufferWriter(global::System.Buffers.IBufferWriter inner) + { + _inner = inner; + } + + public long BytesWritten { get; private set; } + + public void Advance(int count) + { + _inner.Advance(count); + BytesWritten += count; + } + + public global::System.Memory GetMemory(int sizeHint = 0) + { + return _inner.GetMemory(sizeHint); + } + + public global::System.Span GetSpan(int sizeHint = 0) + { + return _inner.GetSpan(sizeHint); + } + } + + private int SizeOfPositions(global::FormatterGolden.Positions message) + { + checked + { + var size = SizeOfMapHeader(6); + size += SizeOfInt32(1); + int __size0; + if (message.ListOfAddress is null) + { + __size0 = SizeOfNil(); + } + else + { + __size0 = SizeOfArrayHeader(message.ListOfAddress.Count); + foreach (var __item1 in message.ListOfAddress) + { + var __size2 = __item1 is null ? SizeOfNil() : _akkaFormatter_Akka_Actor_Address.SizeOf(__item1); + if (__size2 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size0 += __size2; + } + } + size += __size0; + size += SizeOfInt32(2); + int __size3; + if (message.NullableAddressElements is null) + { + __size3 = SizeOfNil(); + } + else + { + __size3 = SizeOfArrayHeader(message.NullableAddressElements.Count); + foreach (var __item4 in message.NullableAddressElements) + { + var __size5 = __item4 is null ? SizeOfNil() : _akkaFormatter_Akka_Actor_Address.SizeOf(__item4); + if (__size5 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size3 += __size5; + } + } + size += __size3; + size += SizeOfInt32(3); + int __size6; + if (message.AddressByCelsiusKey is null) + { + __size6 = SizeOfNil(); + } + else + { + __size6 = SizeOfMapHeader(message.AddressByCelsiusKey.Count); + foreach (var __kvp7 in message.AddressByCelsiusKey) + { + var __size8 = _akkaFormatter_FormatterGolden_Celsius.SizeOf(__kvp7.Key); + if (__size8 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size6 += __size8; + var __size9 = __kvp7.Value is null ? SizeOfNil() : _akkaFormatter_Akka_Actor_Address.SizeOf(__kvp7.Value); + if (__size9 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size6 += __size9; + } + } + size += __size6; + size += SizeOfInt32(4); + int __size10; + if (message.ListOfNullableCelsius is null) + { + __size10 = SizeOfNil(); + } + else + { + __size10 = SizeOfArrayHeader(message.ListOfNullableCelsius.Count); + foreach (var __item11 in message.ListOfNullableCelsius) + { + var __size12 = __item11 is null ? SizeOfNil() : _akkaFormatter_FormatterGolden_Celsius.SizeOf(__item11.Value); + if (__size12 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size10 += __size12; + } + } + size += __size10; + size += SizeOfInt32(5); + int __size13; + if (message.MapOfTagLists is null) + { + __size13 = SizeOfNil(); + } + else + { + __size13 = SizeOfMapHeader(message.MapOfTagLists.Count); + foreach (var __kvp14 in message.MapOfTagLists) + { + __size13 += SizeOfString(__kvp14.Key); + int __size15; + if (__kvp14.Value is null) + { + __size15 = SizeOfNil(); + } + else + { + __size15 = SizeOfArrayHeader(__kvp14.Value.Count); + foreach (var __item16 in __kvp14.Value) + { + var __size17 = __item16 is null ? SizeOfNil() : _akkaFormatter_FormatterGolden_Tag.SizeOf(__item16); + if (__size17 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size15 += __size17; + } + } + __size13 += __size15; + } + } + size += __size13; + size += SizeOfInt32(6); + int __size18; + if (message.ListOfRef is null) + { + __size18 = SizeOfNil(); + } + else + { + __size18 = SizeOfArrayHeader(message.ListOfRef.Count); + foreach (var __item19 in message.ListOfRef) + { + var __size20 = __item19 is null ? SizeOfNil() : _akkaFormatter_Akka_Actor_IActorRef.SizeOf(__item19); + if (__size20 < 0) + return global::Akka.Serialization.SerializerV2.UnknownSize; + __size18 += __size20; + } + } + size += __size18; + return size; + } + } + + private void WritePositions(ref global::MessagePack.MessagePackWriter writer, global::FormatterGolden.Positions message) + { + writer.WriteMapHeader(6); + writer.Write(1); + if (message.ListOfAddress is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.ListOfAddress.Count); + foreach (var __item0 in message.ListOfAddress) + { + if (__item0 is null) + writer.WriteNil(); + else + _akkaFormatter_Akka_Actor_Address.Write(ref writer, __item0); + } + } + writer.Write(2); + if (message.NullableAddressElements is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.NullableAddressElements.Count); + foreach (var __item1 in message.NullableAddressElements) + { + if (__item1 is null) + writer.WriteNil(); + else + _akkaFormatter_Akka_Actor_Address.Write(ref writer, __item1); + } + } + writer.Write(3); + if (message.AddressByCelsiusKey is null) + { + writer.WriteNil(); + } + else + { + writer.WriteMapHeader(message.AddressByCelsiusKey.Count); + foreach (var __kvp2 in message.AddressByCelsiusKey) + { + _akkaFormatter_FormatterGolden_Celsius.Write(ref writer, __kvp2.Key); + if (__kvp2.Value is null) + writer.WriteNil(); + else + _akkaFormatter_Akka_Actor_Address.Write(ref writer, __kvp2.Value); + } + } + writer.Write(4); + if (message.ListOfNullableCelsius is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.ListOfNullableCelsius.Count); + foreach (var __item3 in message.ListOfNullableCelsius) + { + if (__item3 is null) + writer.WriteNil(); + else + _akkaFormatter_FormatterGolden_Celsius.Write(ref writer, __item3.Value); + } + } + writer.Write(5); + if (message.MapOfTagLists is null) + { + writer.WriteNil(); + } + else + { + writer.WriteMapHeader(message.MapOfTagLists.Count); + foreach (var __kvp4 in message.MapOfTagLists) + { + writer.Write(__kvp4.Key); + if (__kvp4.Value is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(__kvp4.Value.Count); + foreach (var __item5 in __kvp4.Value) + { + if (__item5 is null) + writer.WriteNil(); + else + _akkaFormatter_FormatterGolden_Tag.Write(ref writer, __item5); + } + } + } + } + writer.Write(6); + if (message.ListOfRef is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.ListOfRef.Count); + foreach (var __item6 in message.ListOfRef) + { + if (__item6 is null) + writer.WriteNil(); + else + _akkaFormatter_Akka_Actor_IActorRef.Write(ref writer, __item6); + } + } + } + + private global::FormatterGolden.Positions ReadPositions(ref global::MessagePack.MessagePackReader reader) + { + var __fieldCount = reader.ReadMapHeader(); + global::System.Collections.Generic.List? listOfAddress = default; + var __hasListOfAddress = false; + global::System.Collections.Generic.List? nullableAddressElements = default; + var __hasNullableAddressElements = false; + global::System.Collections.Generic.Dictionary? addressByCelsiusKey = default; + var __hasAddressByCelsiusKey = false; + global::System.Collections.Generic.List? listOfNullableCelsius = default; + var __hasListOfNullableCelsius = false; + global::System.Collections.Generic.Dictionary>? mapOfTagLists = default; + var __hasMapOfTagLists = false; + global::System.Collections.Generic.List? listOfRef = default; + var __hasListOfRef = false; + for (var __entryIndex = 0; __entryIndex < __fieldCount; __entryIndex++) + { + var __fieldId = reader.ReadInt32(); + switch (__fieldId) + { + case 1: + if (reader.TryReadNil()) + { + listOfAddress = null; + } + else + { + var __len0 = reader.ReadArrayHeader(); + var __col1 = new global::System.Collections.Generic.List(__len0); + for (var __i2 = 0; __i2 < __len0; __i2++) + { + global::Akka.Actor.Address? __item3; + if (reader.TryReadNil()) + __item3 = null; + else + __item3 = _akkaFormatter_Akka_Actor_Address.Read(ref reader); + __col1.Add(__item3!); + } + listOfAddress = __col1; + } + __hasListOfAddress = true; + break; + case 2: + if (reader.TryReadNil()) + { + nullableAddressElements = null; + } + else + { + var __len4 = reader.ReadArrayHeader(); + var __col5 = new global::System.Collections.Generic.List(__len4); + for (var __i6 = 0; __i6 < __len4; __i6++) + { + global::Akka.Actor.Address? __item7; + if (reader.TryReadNil()) + __item7 = null; + else + __item7 = _akkaFormatter_Akka_Actor_Address.Read(ref reader); + __col5.Add(__item7!); + } + nullableAddressElements = __col5; + } + __hasNullableAddressElements = true; + break; + case 3: + if (reader.TryReadNil()) + { + addressByCelsiusKey = null; + } + else + { + var __len8 = reader.ReadMapHeader(); + var __col9 = new global::System.Collections.Generic.Dictionary(__len8); + for (var __i10 = 0; __i10 < __len8; __i10++) + { + global::FormatterGolden.Celsius __key11; + __key11 = _akkaFormatter_FormatterGolden_Celsius.Read(ref reader); + global::Akka.Actor.Address? __val12; + if (reader.TryReadNil()) + __val12 = null; + else + __val12 = _akkaFormatter_Akka_Actor_Address.Read(ref reader); + __col9[__key11] = __val12!; + } + addressByCelsiusKey = __col9; + } + __hasAddressByCelsiusKey = true; + break; + case 4: + if (reader.TryReadNil()) + { + listOfNullableCelsius = null; + } + else + { + var __len13 = reader.ReadArrayHeader(); + var __col14 = new global::System.Collections.Generic.List(__len13); + for (var __i15 = 0; __i15 < __len13; __i15++) + { + global::FormatterGolden.Celsius? __item16; + if (reader.TryReadNil()) + __item16 = null; + else + __item16 = _akkaFormatter_FormatterGolden_Celsius.Read(ref reader); + __col14.Add(__item16); + } + listOfNullableCelsius = __col14; + } + __hasListOfNullableCelsius = true; + break; + case 5: + if (reader.TryReadNil()) + { + mapOfTagLists = null; + } + else + { + var __len17 = reader.ReadMapHeader(); + var __col18 = new global::System.Collections.Generic.Dictionary>(__len17); + for (var __i19 = 0; __i19 < __len17; __i19++) + { + string? __key20; + __key20 = reader.ReadString(); + global::System.Collections.Generic.List? __val21; + if (reader.TryReadNil()) + { + __val21 = null; + } + else + { + var __len22 = reader.ReadArrayHeader(); + var __col23 = new global::System.Collections.Generic.List(__len22); + for (var __i24 = 0; __i24 < __len22; __i24++) + { + global::FormatterGolden.Tag? __item25; + if (reader.TryReadNil()) + __item25 = null; + else + __item25 = _akkaFormatter_FormatterGolden_Tag.Read(ref reader); + __col23.Add(__item25!); + } + __val21 = __col23; + } + __col18[__key20!] = __val21!; + } + mapOfTagLists = __col18; + } + __hasMapOfTagLists = true; + break; + case 6: + if (reader.TryReadNil()) + { + listOfRef = null; + } + else + { + var __len26 = reader.ReadArrayHeader(); + var __col27 = new global::System.Collections.Generic.List(__len26); + for (var __i28 = 0; __i28 < __len26; __i28++) + { + global::Akka.Actor.IActorRef? __item29; + if (reader.TryReadNil()) + __item29 = null; + else + __item29 = _akkaFormatter_Akka_Actor_IActorRef.Read(ref reader); + __col27.Add(__item29!); + } + listOfRef = __col27; + } + __hasListOfRef = true; + break; + default: + reader.Skip(); + break; + } + } + + if (!__hasListOfAddress || listOfAddress is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [ListOfAddress] with index [1] while deserializing [global::FormatterGolden.Positions]."); + if (!__hasNullableAddressElements || nullableAddressElements is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [NullableAddressElements] with index [2] while deserializing [global::FormatterGolden.Positions]."); + if (!__hasAddressByCelsiusKey || addressByCelsiusKey is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [AddressByCelsiusKey] with index [3] while deserializing [global::FormatterGolden.Positions]."); + if (!__hasListOfNullableCelsius || listOfNullableCelsius is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [ListOfNullableCelsius] with index [4] while deserializing [global::FormatterGolden.Positions]."); + if (!__hasMapOfTagLists || mapOfTagLists is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [MapOfTagLists] with index [5] while deserializing [global::FormatterGolden.Positions]."); + if (!__hasListOfRef || listOfRef is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [ListOfRef] with index [6] while deserializing [global::FormatterGolden.Positions]."); + return new global::FormatterGolden.Positions(ListOfAddress: listOfAddress!, NullableAddressElements: nullableAddressElements!, AddressByCelsiusKey: addressByCelsiusKey!, ListOfNullableCelsius: listOfNullableCelsius!, MapOfTagLists: mapOfTagLists!, ListOfRef: listOfRef!); + } + +} diff --git a/src/core/Akka.Serialization.V2.Tests/Harness/DiagnosticSource.cs b/src/core/Akka.Serialization.V2.Tests/Harness/DiagnosticSource.cs new file mode 100644 index 00000000000..1e721e0ad31 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/Harness/DiagnosticSource.cs @@ -0,0 +1,75 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Microsoft.CodeAnalysis; + +namespace Akka.Serialization.V2.Tests.Harness; + +/// +/// Shared source template for the diagnostics specs that probe one message field type at a time: a +/// serializer over IProtocol, a message Outer whose constructor is the caller's field list, +/// a Foreign type with a ready-made formatter, and a long-backed enum. +/// +internal static class DiagnosticSource +{ + internal const string Header = """ + #nullable enable + using System; + using System.Collections.Generic; + using System.Collections.Immutable; + using Akka.Actor; + using Akka.Serialization.V2; + using MessagePack; + + namespace DiagnosticSample; + + public interface IProtocol + { + } + + public sealed record Foreign(string Value); + + public enum WideEnum : long + { + A = 1 + } + + public sealed class ForeignFormatter : IAkkaMessagePackFormatter + { + public void Write(ref MessagePackWriter writer, Foreign value) => writer.Write(value.Value); + public Foreign Read(ref MessagePackReader reader) => new Foreign(reader.ReadString() ?? string.Empty); + public int SizeOf(Foreign value) => Akka.Serialization.SerializerV2.UnknownSize; + } + + """; + + internal const string ForeignFormatterAttribute = "[AkkaSerializerFormatter]"; + + private static string Source(string serializerAttributes, string messageBody) + => Header + $$""" + [AkkaSerializer("sample", 199001)] + {{serializerAttributes}} + public sealed partial class SampleSerializer : AkkaSerializer + { + public static partial SerializerRegistration CreateRegistration(); + } + + [AkkaSerializable(Manifest = "outer-v1")] + public sealed record Outer({{messageBody}}) : IProtocol; + """; + + /// Runs the generator over Outer() and returns its error diagnostics plus the whole result. + internal static RunOutcome Run(string serializerAttributes, string messageBody) + { + var result = GeneratorTestHarness.Run(Source(serializerAttributes, messageBody)); + return new RunOutcome(result.GeneratorDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToArray(), result); + } + + internal readonly record struct RunOutcome(Diagnostic[] Errors, GeneratorRunResult Result); +} diff --git a/src/core/Akka.Serialization.V2.Tests/Harness/GoldenBaseline.cs b/src/core/Akka.Serialization.V2.Tests/Harness/GoldenBaseline.cs new file mode 100644 index 00000000000..4fa70fee117 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/Harness/GoldenBaseline.cs @@ -0,0 +1,68 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System; +using System.IO; +using System.Runtime.CompilerServices; + +namespace Akka.Serialization.V2.Tests.Harness; + +/// +/// Strict byte-for-byte comparison of one generated file against its checked-in baseline under +/// GoldenOutput/ beside the calling spec file, the same convention GeneratorGoldenOutputSpec uses: no scrubbing, no +/// newline normalization, and *.received.txt written next to the baseline on a mismatch. +/// Run with AKKA_GOLDEN_REGEN=1 to (re)capture a baseline deliberately, then review the diff. +/// +internal static class GoldenBaseline +{ + private const string RegenEnvVar = "AKKA_GOLDEN_REGEN"; + + /// Null when matches its baseline; otherwise a failure description. + public static string? Compare(string hintName, string actual, [CallerFilePath] string callerFilePath = "") + { + var goldenDirectory = Path.Combine(Path.GetDirectoryName(callerFilePath)!, "GoldenOutput"); + var verifiedPath = Path.GetFullPath(Path.Combine(goldenDirectory, hintName + ".verified.txt")); + + if (Environment.GetEnvironmentVariable(RegenEnvVar) == "1") + { + Directory.CreateDirectory(Path.GetDirectoryName(verifiedPath)!); + File.WriteAllText(verifiedPath, actual); + return null; + } + + if (!File.Exists(verifiedPath)) + return $"Missing baseline [{verifiedPath}]. Run once with {RegenEnvVar}=1 to capture it, then review and check it in."; + + var expected = File.ReadAllText(verifiedPath); + if (string.Equals(expected, actual, StringComparison.Ordinal)) + return null; + + var receivedPath = Path.Combine(Path.GetDirectoryName(verifiedPath)!, hintName + ".received.txt"); + File.WriteAllText(receivedPath, actual); + return $"Generated output for [{hintName}] differs from baseline. {DescribeFirstDifference(expected, actual)} Actual output written to [{receivedPath}] for diffing against [{verifiedPath}]."; + } + + private static string DescribeFirstDifference(string expected, string actual) + { + var length = Math.Min(expected.Length, actual.Length); + var index = 0; + while (index < length && expected[index] == actual[index]) + index++; + + if (index == length && expected.Length == actual.Length) + return "Contents differ but no differing index was found (unexpected)."; + + string Snippet(string text) + { + var start = Math.Max(0, index - 40); + return text.Substring(start, Math.Min(80, text.Length - start)).Replace("\r", "\\r").Replace("\n", "\\n"); + } + + return $"First difference at char index {index}: expected [...{Snippet(expected)}...] but got [...{Snippet(actual)}...]."; + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs new file mode 100644 index 00000000000..a762e6ebe1b --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs @@ -0,0 +1,143 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Akka.Actor; +using VerifyXunit; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// COMMITTED WIRE-FORMAT SNAPSHOTS for formatter-handled collection members (G-1): a formatter-handled type +/// as a collection element, dictionary key and dictionary value. Same mechanism and update procedure as (see +/// WireSnapshots/README.md); a separate spec so those existing cases, and their snapshots, stay +/// untouched. Every input is a hardcoded constant, so a mismatch always means the wire format changed. +/// +public sealed class WireFormatSnapshotFormatterSpec : IAsyncLifetime +{ + private static readonly Address Local = new("akka", "sys", "localhost", 2552); + private static readonly Address Remote = new("akka.tcp", "other", "10.0.0.2", 4053); + private static readonly Address NoHost = new("akka", "sys"); + + private static readonly string[] AllCaseNames = + { + // G-1: formatter-handled types in collection element, dictionary key and dictionary value position. + "formatter-element-list-of-address", + "formatter-element-nullable-address-list", + "formatter-key-and-value-address-dictionary", + "formatter-all-address-shapes-single-element", + "formatter-custom-reference-type-elements", + "formatter-custom-value-type-nullable-elements", + "formatter-actor-ref-elements-override-native", + }; + + private ActorSystem _system = null!; + private FormatterPositionSerializer _formatterSerializer = null!; + + public ValueTask InitializeAsync() + { + _system = ActorSystem.Create("wire-format-snapshot-formatter"); + var extendedSystem = (ExtendedActorSystem)_system; + _formatterSerializer = new FormatterPositionSerializer(extendedSystem); + return ValueTask.CompletedTask; + } + + public async ValueTask DisposeAsync() + { + await _system.Terminate(); + } + + public static IEnumerable CaseNames() => AllCaseNames.Select(name => new object[] { name }); + + [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized")] + [MemberData(nameof(CaseNames))] + public Task Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized(string caseName) + { + var wireCase = BuildCase(caseName); + var hexDump = HexDumpFormatter.Format(caseName, wireCase.MessageType, wireCase.Manifest, wireCase.SerializerId, wireCase.Bytes); + + return Verifier.Verify(hexDump) + .UseDirectory("WireSnapshots") + .UseFileName(caseName); + } + + private WireSnapshotCase BuildCase(string caseName) => caseName switch + { + "formatter-element-list-of-address" => Case(_formatterSerializer, new ListOfAddressMessage( + new List
{ Local, NoHost })), + + "formatter-element-nullable-address-list" => Case(_formatterSerializer, new NullableAddressElementsMessage( + new List { null, Remote })), + + "formatter-key-and-value-address-dictionary" => Case(_formatterSerializer, new AddressToAddressMessage( + new Dictionary { [Local] = Remote })), + + // One snapshot for every collection shape with a formatter-handled member: single-element sets and + // dictionaries only, since multi-element hash iteration order is not stable (see README.md). + "formatter-all-address-shapes-single-element" => Case(_formatterSerializer, new AddressPositions( + ListOf: new List
{ Local }, + ArrayOf: new[] { Remote }, + ImmutableArrayOf: ImmutableArray.Create(NoHost), + ReadOnlyListOf: new List
{ Local }, + ReadOnlyCollectionOf: new List
{ Remote }, + ImmutableListOf: ImmutableList.Create(NoHost), + ImmutableSetOf: ImmutableHashSet.Create(Local), + ByKey: new Dictionary { [Local] = 1L }, + ReadOnlyByKey: new Dictionary { [Remote] = "r" }, + ImmutableByKey: ImmutableDictionary.Empty.Add(NoHost, 2), + ByValue: new Dictionary { ["k"] = Local }, + ReadOnlyByValue: new Dictionary { ["k"] = Remote }, + ImmutableByValue: ImmutableDictionary.Empty.Add("k", NoHost), + KeyAndValue: new Dictionary { [Local] = Remote }, + NullableElements: new List { null }, + Nested: new List> { new() { Local } }, + MapOfLists: new Dictionary> { ["k"] = new() { Remote } })), + + "formatter-custom-reference-type-elements" => Case(_formatterSerializer, new TagPositions( + ListOf: new List { new("a"), new("b") }, + ArrayOf: new[] { new PositionTag("c") }, + ByKey: new Dictionary { [new PositionTag("k")] = 7 }, + ByValue: new Dictionary { [1] = new PositionTag("v") }, + KeyAndValue: new Dictionary { [new PositionTag("kk")] = new PositionTag("vv") }, + ImmutableSetOf: ImmutableHashSet.Create(new PositionTag("s")))), + + "formatter-custom-value-type-nullable-elements" => Case(_formatterSerializer, new CelsiusPositions( + ListOf: new List { new(-273.15), new(0) }, + ArrayOf: new[] { new PositionCelsius(1.5) }, + NullableListOf: new List { new PositionCelsius(2), null }, + ImmutableArrayOfNullable: ImmutableArray.Create(null, new PositionCelsius(4)), + ByKey: new Dictionary { [new PositionCelsius(5)] = "five" }, + ByNullableValue: new Dictionary { ["none"] = null })), + + // The IActorRef formatter registered on the serializer wins over the native path-string encoding, + // at element, key and value position alike. + "formatter-actor-ref-elements-override-native" => Case(_formatterSerializer, new RefPositions( + ListOf: new List { _system.DeadLetters }, + ReadOnlyListOf: new List { _system.DeadLetters }, + ByValue: new Dictionary { ["dl"] = _system.DeadLetters }, + ByKey: new Dictionary { [_system.DeadLetters] = 1 }, + ImmutableArrayOf: ImmutableArray.Create(_system.DeadLetters))), + + _ => throw new ArgumentOutOfRangeException(nameof(caseName), caseName, "Unknown wire snapshot case.") + }; + + private static WireSnapshotCase Case(AkkaSerializer serializer, TMessage message) + where TMessage : notnull + { + var bytes = serializer.ToBinary(message); + var manifest = serializer.Manifest(message); + return new WireSnapshotCase(HexDumpFormatter.FriendlyTypeName(typeof(TMessage)), manifest, serializer.Identifier, bytes); + } + + private readonly record struct WireSnapshotCase(string MessageType, string Manifest, int SerializerId, byte[] Bytes); +} diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-actor-ref-elements-override-native.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-actor-ref-elements-override-native.verified.txt new file mode 100644 index 00000000000..ae2c87842b1 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-actor-ref-elements-override-native.verified.txt @@ -0,0 +1,25 @@ +case: formatter-actor-ref-elements-override-native +message-type: RefPositions +manifest: ref-positions-v1 +serializer-id: 122001 +byte-count: 295 + +0000 85 01 91 92 a3 72 65 66 d9 31 61 6b 6b 61 3a 2f |.....ref.1akka:/| +0010 2f 77 69 72 65 2d 66 6f 72 6d 61 74 2d 73 6e 61 |/wire-format-sna| +0020 70 73 68 6f 74 2d 66 6f 72 6d 61 74 74 65 72 2f |pshot-formatter/| +0030 64 65 61 64 4c 65 74 74 65 72 73 02 91 92 a3 72 |deadLetters....r| +0040 65 66 d9 31 61 6b 6b 61 3a 2f 2f 77 69 72 65 2d |ef.1akka://wire-| +0050 66 6f 72 6d 61 74 2d 73 6e 61 70 73 68 6f 74 2d |format-snapshot-| +0060 66 6f 72 6d 61 74 74 65 72 2f 64 65 61 64 4c 65 |formatter/deadLe| +0070 74 74 65 72 73 03 81 a2 64 6c 92 a3 72 65 66 d9 |tters...dl..ref.| +0080 31 61 6b 6b 61 3a 2f 2f 77 69 72 65 2d 66 6f 72 |1akka://wire-for| +0090 6d 61 74 2d 73 6e 61 70 73 68 6f 74 2d 66 6f 72 |mat-snapshot-for| +00a0 6d 61 74 74 65 72 2f 64 65 61 64 4c 65 74 74 65 |matter/deadLette| +00b0 72 73 04 81 92 a3 72 65 66 d9 31 61 6b 6b 61 3a |rs....ref.1akka:| +00c0 2f 2f 77 69 72 65 2d 66 6f 72 6d 61 74 2d 73 6e |//wire-format-sn| +00d0 61 70 73 68 6f 74 2d 66 6f 72 6d 61 74 74 65 72 |apshot-formatter| +00e0 2f 64 65 61 64 4c 65 74 74 65 72 73 01 05 91 92 |/deadLetters....| +00f0 a3 72 65 66 d9 31 61 6b 6b 61 3a 2f 2f 77 69 72 |.ref.1akka://wir| +0100 65 2d 66 6f 72 6d 61 74 2d 73 6e 61 70 73 68 6f |e-format-snapsho| +0110 74 2d 66 6f 72 6d 61 74 74 65 72 2f 64 65 61 64 |t-formatter/dead| +0120 4c 65 74 74 65 72 73 |Letters| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-all-address-shapes-single-element.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-all-address-shapes-single-element.verified.txt new file mode 100644 index 00000000000..a0c83888670 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-all-address-shapes-single-element.verified.txt @@ -0,0 +1,33 @@ +case: formatter-all-address-shapes-single-element +message-type: AddressPositions +manifest: address-positions-v1 +serializer-id: 122001 +byte-count: 429 + +0000 de 00 11 01 91 94 a4 61 6b 6b 61 a3 73 79 73 a9 |.......akka.sys.| +0010 6c 6f 63 61 6c 68 6f 73 74 cd 09 f8 02 91 94 a8 |localhost.......| +0020 61 6b 6b 61 2e 74 63 70 a5 6f 74 68 65 72 a8 31 |akka.tcp.other.1| +0030 30 2e 30 2e 30 2e 32 cd 0f d5 03 91 94 a4 61 6b |0.0.0.2.......ak| +0040 6b 61 a3 73 79 73 c0 c0 04 91 94 a4 61 6b 6b 61 |ka.sys......akka| +0050 a3 73 79 73 a9 6c 6f 63 61 6c 68 6f 73 74 cd 09 |.sys.localhost..| +0060 f8 05 91 94 a8 61 6b 6b 61 2e 74 63 70 a5 6f 74 |.....akka.tcp.ot| +0070 68 65 72 a8 31 30 2e 30 2e 30 2e 32 cd 0f d5 06 |her.10.0.0.2....| +0080 91 94 a4 61 6b 6b 61 a3 73 79 73 c0 c0 07 91 94 |...akka.sys.....| +0090 a4 61 6b 6b 61 a3 73 79 73 a9 6c 6f 63 61 6c 68 |.akka.sys.localh| +00a0 6f 73 74 cd 09 f8 08 81 94 a4 61 6b 6b 61 a3 73 |ost.......akka.s| +00b0 79 73 a9 6c 6f 63 61 6c 68 6f 73 74 cd 09 f8 01 |ys.localhost....| +00c0 09 81 94 a8 61 6b 6b 61 2e 74 63 70 a5 6f 74 68 |....akka.tcp.oth| +00d0 65 72 a8 31 30 2e 30 2e 30 2e 32 cd 0f d5 a1 72 |er.10.0.0.2....r| +00e0 0a 81 94 a4 61 6b 6b 61 a3 73 79 73 c0 c0 02 0b |....akka.sys....| +00f0 81 a1 6b 94 a4 61 6b 6b 61 a3 73 79 73 a9 6c 6f |..k..akka.sys.lo| +0100 63 61 6c 68 6f 73 74 cd 09 f8 0c 81 a1 6b 94 a8 |calhost......k..| +0110 61 6b 6b 61 2e 74 63 70 a5 6f 74 68 65 72 a8 31 |akka.tcp.other.1| +0120 30 2e 30 2e 30 2e 32 cd 0f d5 0d 81 a1 6b 94 a4 |0.0.0.2......k..| +0130 61 6b 6b 61 a3 73 79 73 c0 c0 0e 81 94 a4 61 6b |akka.sys......ak| +0140 6b 61 a3 73 79 73 a9 6c 6f 63 61 6c 68 6f 73 74 |ka.sys.localhost| +0150 cd 09 f8 94 a8 61 6b 6b 61 2e 74 63 70 a5 6f 74 |.....akka.tcp.ot| +0160 68 65 72 a8 31 30 2e 30 2e 30 2e 32 cd 0f d5 0f |her.10.0.0.2....| +0170 91 c0 10 91 91 94 a4 61 6b 6b 61 a3 73 79 73 a9 |.......akka.sys.| +0180 6c 6f 63 61 6c 68 6f 73 74 cd 09 f8 11 81 a1 6b |localhost......k| +0190 91 94 a8 61 6b 6b 61 2e 74 63 70 a5 6f 74 68 65 |...akka.tcp.othe| +01a0 72 a8 31 30 2e 30 2e 30 2e 32 cd 0f d5 |r.10.0.0.2...| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-reference-type-elements.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-reference-type-elements.verified.txt new file mode 100644 index 00000000000..267560f70b8 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-reference-type-elements.verified.txt @@ -0,0 +1,11 @@ +case: formatter-custom-reference-type-elements +message-type: TagPositions +manifest: tag-positions-v1 +serializer-id: 122001 +byte-count: 65 + +0000 86 01 92 a5 74 61 67 3a 61 a5 74 61 67 3a 62 02 |....tag:a.tag:b.| +0010 91 a5 74 61 67 3a 63 03 81 a5 74 61 67 3a 6b 07 |..tag:c...tag:k.| +0020 04 81 01 a5 74 61 67 3a 76 05 81 a6 74 61 67 3a |....tag:v...tag:| +0030 6b 6b a6 74 61 67 3a 76 76 06 91 a5 74 61 67 3a |kk.tag:vv...tag:| +0040 73 |s| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-value-type-nullable-elements.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-value-type-nullable-elements.verified.txt new file mode 100644 index 00000000000..a9581b57ae6 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-custom-value-type-nullable-elements.verified.txt @@ -0,0 +1,11 @@ +case: formatter-custom-value-type-nullable-elements +message-type: CelsiusPositions +manifest: celsius-positions-v1 +serializer-id: 122001 +byte-count: 80 + +0000 86 01 92 cb c0 71 12 66 66 66 66 66 cb 00 00 00 |.....q.fffff....| +0010 00 00 00 00 00 02 91 cb 3f f8 00 00 00 00 00 00 |........?.......| +0020 03 92 cb 40 00 00 00 00 00 00 00 c0 04 92 c0 cb |...@............| +0030 40 10 00 00 00 00 00 00 05 81 cb 40 14 00 00 00 |@..........@....| +0040 00 00 00 a4 66 69 76 65 06 81 a4 6e 6f 6e 65 c0 |....five...none.| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-list-of-address.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-list-of-address.verified.txt new file mode 100644 index 00000000000..e38b13a471a --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-list-of-address.verified.txt @@ -0,0 +1,9 @@ +case: formatter-element-list-of-address +message-type: ListOfAddressMessage +manifest: list-of-address-v1 +serializer-id: 122001 +byte-count: 38 + +0000 81 01 92 94 a4 61 6b 6b 61 a3 73 79 73 a9 6c 6f |.....akka.sys.lo| +0010 63 61 6c 68 6f 73 74 cd 09 f8 94 a4 61 6b 6b 61 |calhost.....akka| +0020 a3 73 79 73 c0 c0 |.sys..| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-nullable-address-list.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-nullable-address-list.verified.txt new file mode 100644 index 00000000000..a8328f8f8c2 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-element-nullable-address-list.verified.txt @@ -0,0 +1,8 @@ +case: formatter-element-nullable-address-list +message-type: NullableAddressElementsMessage +manifest: nullable-address-elements-v1 +serializer-id: 122001 +byte-count: 32 + +0000 81 01 92 c0 94 a8 61 6b 6b 61 2e 74 63 70 a5 6f |......akka.tcp.o| +0010 74 68 65 72 a8 31 30 2e 30 2e 30 2e 32 cd 0f d5 |ther.10.0.0.2...| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-key-and-value-address-dictionary.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-key-and-value-address-dictionary.verified.txt new file mode 100644 index 00000000000..6dacbd7a21f --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/formatter-key-and-value-address-dictionary.verified.txt @@ -0,0 +1,10 @@ +case: formatter-key-and-value-address-dictionary +message-type: AddressToAddressMessage +manifest: address-to-address-v1 +serializer-id: 122001 +byte-count: 54 + +0000 81 01 81 94 a4 61 6b 6b 61 a3 73 79 73 a9 6c 6f |.....akka.sys.lo| +0010 63 61 6c 68 6f 73 74 cd 09 f8 94 a8 61 6b 6b 61 |calhost.....akka| +0020 2e 74 63 70 a5 6f 74 68 65 72 a8 31 30 2e 30 2e |.tcp.other.10.0.| +0030 30 2e 32 cd 0f d5 |0.2...| From 19ffa1b676506dd17feaaced936ccda7bff9bbd5 Mon Sep 17 00:00:00 2001 From: Aaron Stannard Date: Fri, 2 Oct 2026 19:30:21 +0000 Subject: [PATCH 2/5] Serialization V2 generator: native TimeSpan and small scalars (G-3) TimeSpan, float, short, byte, sbyte, ushort, uint, ulong and char are now native, as fields, Nullable fields, and collection elements, keys and values. Wire encodings: TimeSpan is the MessagePack integer (int64) of its Ticks; float is float32; short/sbyte/byte/ushort/uint/ulong use the smallest MessagePack integer encoding, as int and long do; char is the unsigned integer of its UTF-16 code unit. Reads range-check and throw a MessagePackSerializationException naming the type instead of truncating. AKKASG007 for a type from another assembly no longer claims the generator cannot read referenced schemas, and no longer suggests declaring a BCL type in this assembly. Closes #8715 --- .../source-generated-serialization.md | 33 +- .../AkkaSerializerGenerator.Diagnostics.cs | 19 +- .../AkkaSerializerGenerator.Emission.cs | 105 ++- .../AkkaSerializerGenerator.Extraction.cs | 11 + .../AkkaSerializerGenerator.Models.cs | 11 +- .../GeneratorGoldenNativeScalarSpec.cs | 102 +++ ...alizer.AkkaSerialization.g.cs.verified.txt | 664 ++++++++++++++++++ .../NativeScalarDiagnosticsSpec.cs | 97 +++ .../NativeScalarSpec.cs | 493 +++++++++++++ .../WireFormatSnapshotScalarSpec.cs | 116 +++ ...llection-shape-single-element.verified.txt | 12 + .../WireSnapshots/scalars-max.verified.txt | 10 + .../WireSnapshots/scalars-min.verified.txt | 9 + .../scalars-nullable-all-null.verified.txt | 8 + .../scalars-nullable-populated.verified.txt | 9 + .../WireSnapshots/scalars-zero.verified.txt | 8 + .../Akka.Serialization.V2/AkkaSerializer.cs | 120 ++++ .../Akka.Serialization.V2/MessagePackSizes.cs | 12 + 18 files changed, 1821 insertions(+), 18 deletions(-) create mode 100644 src/core/Akka.Serialization.V2.Tests/GeneratorGoldenNativeScalarSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/GoldenOutput/ScalarGoldenSerializer.AkkaSerialization.g.cs.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/NativeScalarDiagnosticsSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/NativeScalarSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-in-every-collection-shape-single-element.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-max.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-min.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-all-null.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-populated.verified.txt create mode 100644 src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-zero.verified.txt diff --git a/docs/articles/serialization/source-generated-serialization.md b/docs/articles/serialization/source-generated-serialization.md index 2a8f9d2c392..89d312f7c05 100644 --- a/docs/articles/serialization/source-generated-serialization.md +++ b/docs/articles/serialization/source-generated-serialization.md @@ -327,7 +327,7 @@ public sealed record ShippingAddress( | Kind | Types | Notes | |---|---|---| -| Scalars | `string`, `int`, `long`, `bool`, `double`, `decimal`, `Guid`, `DateTime`, `DateTimeOffset` | Native `MessagePackWriter`/`Reader` calls; see [Wire format](#wire-format) for the encoding each one uses. | +| Scalars | `string`, `int`, `long`, `bool`, `double`, `float`, `short`, `byte`, `sbyte`, `ushort`, `uint`, `ulong`, `char`, `decimal`, `Guid`, `DateTime`, `DateTimeOffset`, `TimeSpan` | Native `MessagePackWriter`/`Reader` calls; see [Scalar encodings](#scalar-encodings) for the encoding each one uses. | | Raw bytes | `byte[]` | Encoded as a MessagePack `bin`, not an array of integers. | | Enums | Any `enum` backed by `sbyte`, `byte`, `short`, `ushort`, or `int` | Written as an `int32`. A `long`- or `uint`-backed enum fails compilation with **AKKASG014**. | | Nullable | `Nullable` for any supported value type, plus nullable reference types | See [Nullable fields](#nullable-fields). | @@ -343,12 +343,29 @@ public sealed record ShippingAddress( | Unions | A closed, explicitly enumerated set of concrete types | See [Unions](#unions). | | Envelope payloads | A property typed `object` or `object?`, resolved through Akka's own serializer lookup at runtime | See [Envelope payloads](#envelope-payloads). | -**Not supported:** `float`, `single`, plain `byte`, `sbyte`, `short`, `ushort`, `uint`, and `ulong` -as scalar field types. These are only meaningful as an enum's underlying type. Also not supported: -a mutable `HashSet` or `ISet`. Use `ImmutableHashSet` instead. Also not supported: a -dictionary whose key type is `object`. Any of these fails -compilation with **AKKASG003**, naming the offending property and type. So does a collection of a -type that neither the generator nor a registered [formatter](#hand-written-formatters) handles. +**Not supported:** a mutable `HashSet` or `ISet`. Use `ImmutableHashSet` instead. Also not +supported: a dictionary whose key type is `object`. Any of these fails compilation with +**AKKASG003**, naming the offending property and type. So does a collection of a type that neither +the generator nor a registered [formatter](#hand-written-formatters) handles. A foreign type that +has no support at all, such as `Uri` or `Half`, fails with **AKKASG007**. Register a formatter for it. + +### Scalar Encodings + +| Type | Wire encoding | +|---|---| +| `string`, `bool`, `int`, `long` | MessagePack `str`, `bool`, and the smallest MessagePack integer that holds the value. | +| `double` | MessagePack `float64`. | +| `float` | MessagePack `float32`. | +| `short`, `sbyte`, `byte`, `ushort`, `uint`, `ulong` | MessagePack integer, in the smallest encoding that holds the value, exactly as `int` and `long` are written. | +| `char` | MessagePack unsigned integer of the character's UTF-16 code unit. | +| `TimeSpan` | MessagePack integer (`int64`) of its `Ticks`. | + +Every one of these works as a field, as a `Nullable` field, and as a collection element, +dictionary key, or dictionary value. A nullable value that is absent is MessagePack `nil`; a present +one is written exactly as the non-nullable type. Integers are read by value, not by width, so a peer +may write the same number with a different MessagePack integer encoding. A value the target type +cannot hold, such as `70000` read into a `short` or `-1` read into a `ulong`, throws a +`MessagePackSerializationException` that names the type. It is never truncated. ## Unions @@ -1096,7 +1113,7 @@ diagnostic was retired with it, and the id stays a permanent gap. | AKKASG004 | Error | No serializable fields | An `[AkkaSerializable]` type has no `[AkkaField]` properties and didn't opt in with `AllowEmpty`. | | AKKASG005 | Error | Duplicate field index | Two `[AkkaField]` properties on the same type share an index. | | AKKASG006 | Error | Top-level message manifest is required | A type implementing the serializer's protocol has no `Manifest`. | -| AKKASG007 | Error | Nested value object serialization definition is required | A nested field's type isn't `[AkkaSerializable]` with its own `[AkkaField]`s. | +| AKKASG007 | Error | Nested value object serialization definition is required | A field's type isn't `[AkkaSerializable]` with its own `[AkkaField]`s and has no registered formatter. For a type declared in another assembly (including the BCL), the message names the assembly and offers a formatter, or `[AkkaSerializable]` in the type's own assembly. | | AKKASG008 | Error | Formatter type must not be abstract | A registered `TFormatter` is abstract and can't be instantiated. | | AKKASG009 | Error | Duplicate formatter registration | A serializer registers more than one formatter for the same target type. | | AKKASG010 | Error | Formatter constructor not usable | A formatter has neither a public parameterless constructor nor one taking `ExtendedActorSystem`. | diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Diagnostics.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Diagnostics.cs index 474641930a0..dac52e29a4b 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Diagnostics.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Diagnostics.cs @@ -92,17 +92,20 @@ public sealed partial class AkkaSerializerGenerator DiagnosticSeverity.Error, isEnabledByDefault: true); - // Same id/title/severity as MissingNestedSerializableDefinition. Used only when the nested - // type's assembly is not the one being compiled and the generator found no [AkkaSerializable] - // schema it can read there. The generator reads a referenced type's schema from that assembly's - // metadata, so the usual cause is a missing [AkkaSerializable] (or [AkkaField]) in the other - // assembly. An inaccessible type or member is AKKASG039 instead. + // Same id/title/severity as MissingNestedSerializableDefinition. Used only when the type's + // assembly is not the one being compiled and the generator found no [AkkaSerializable] + // schema it can read there. That is a BCL type such as System.Uri or a third-party type as often + // as a sibling project's message. The generator reads a referenced type's schema from that + // assembly's metadata, so for a type the author owns the usual cause is a missing + // [AkkaSerializable] (or [AkkaField]) in the other assembly. "Declare the type in this assembly" + // is not offered: it is impossible for a type the author does not own. An inaccessible type or + // member is AKKASG039 instead. private static readonly DiagnosticDescriptor MissingNestedSerializableDefinitionCrossAssembly = new( "AKKASG007", "Nested value object serialization definition is required", - "Property '{0}' on type '{1}' uses nested value object type '{2}', which is declared in assembly '{3}' but has no [AkkaSerializable] schema this generator can read there. " + - "Annotate it with [AkkaSerializable] and [AkkaField] properties in that assembly, " + - "register [AkkaSerializerFormatter<{2}, TFormatter>] on '{4}', or declare the type in this assembly.", + "Property '{0}' on type '{1}' uses type '{2}', which is declared in assembly '{3}' but has no [AkkaSerializable] schema this generator can read there. " + + "Register [AkkaSerializerFormatter<{2}, TFormatter>] on '{4}', or, if you own the type, " + + "annotate it with [AkkaSerializable] and [AkkaField] properties in that assembly.", "Akka.Serialization.V2", DiagnosticSeverity.Error, isEnabledByDefault: true); diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs index d44fbde425d..28424443891 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs @@ -1214,6 +1214,27 @@ private static void EmitScalarSizeExpression(CodeWriter w, TypeMapping mapping, case FieldKind.Double: w.Raw("SizeOfDouble(").Value(value).Raw(")"); break; + case FieldKind.Single: + w.Raw("SizeOfSingle(").Value(value).Raw(")"); + break; + case FieldKind.Int16: + case FieldKind.SByte: + case FieldKind.Byte: + case FieldKind.UInt16: + case FieldKind.Char: + // Every one of these widens to int without loss and encodes exactly as that int does + // (a non-negative value uses the unsigned MessagePack codes either way). + w.Raw("SizeOfInt32((int)").Value(value).Raw(")"); + break; + case FieldKind.UInt32: + w.Raw("SizeOfInt64((long)").Value(value).Raw(")"); + break; + case FieldKind.UInt64: + w.Raw("SizeOfUInt64(").Value(value).Raw(")"); + break; + case FieldKind.TimeSpan: + w.Raw("SizeOfInt64(").Value(value).Raw(".Ticks)"); + break; case FieldKind.Decimal: w.Raw("SizeOfDecimal(").Value(value).Raw(")"); break; @@ -1643,8 +1664,21 @@ private static void GenerateWriteFieldValue(CodeWriter w, ImmutableDictionary kind is FieldKind.Int32 or FieldKind.Int64 or FieldKind.Boolean or FieldKind.Double - or FieldKind.Decimal or FieldKind.Guid or FieldKind.DateTime or FieldKind.DateTimeOffset or FieldKind.Enum; + or FieldKind.Decimal or FieldKind.Guid or FieldKind.DateTime or FieldKind.DateTimeOffset or FieldKind.Enum + or FieldKind.Int16 or FieldKind.SByte or FieldKind.Byte or FieldKind.UInt16 or FieldKind.UInt32 or FieldKind.UInt64 + or FieldKind.Single or FieldKind.Char or FieldKind.TimeSpan; // ----- WRITE ----- @@ -2038,8 +2101,21 @@ private static void EmitScalarWrite(CodeWriter w, TypeMapping mapping, ValueExpr case FieldKind.Int64: case FieldKind.Boolean: case FieldKind.Double: + case FieldKind.Single: + case FieldKind.Int16: + case FieldKind.SByte: + case FieldKind.Byte: + case FieldKind.UInt16: + case FieldKind.UInt32: + case FieldKind.UInt64: w.Raw("writer.Write(").Value(value).Line(");"); break; + case FieldKind.Char: + w.Raw("writer.Write((ushort)").Value(value).Line(");"); + break; + case FieldKind.TimeSpan: + w.Raw("writer.Write(").Value(value).Line(".Ticks);"); + break; case FieldKind.Decimal: w.Raw("WriteDecimal(ref writer, ").Value(value).Line(");"); break; @@ -2359,6 +2435,33 @@ private static void EmitScalarReadExpression(CodeWriter w, TypeMapping mapping) case FieldKind.Double: w.Raw("reader.ReadDouble()"); break; + case FieldKind.Single: + w.Raw("ReadSingle(ref reader)"); + break; + case FieldKind.Int16: + w.Raw("ReadInt16(ref reader)"); + break; + case FieldKind.SByte: + w.Raw("ReadSByte(ref reader)"); + break; + case FieldKind.Byte: + w.Raw("ReadByte(ref reader)"); + break; + case FieldKind.UInt16: + w.Raw("ReadUInt16(ref reader)"); + break; + case FieldKind.UInt32: + w.Raw("ReadUInt32(ref reader)"); + break; + case FieldKind.UInt64: + w.Raw("ReadUInt64(ref reader)"); + break; + case FieldKind.Char: + w.Raw("ReadChar(ref reader)"); + break; + case FieldKind.TimeSpan: + w.Raw("new global::System.TimeSpan(reader.ReadInt64())"); + break; case FieldKind.Decimal: w.Raw("ReadDecimal(ref reader)"); break; diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs index 6968a67cc47..35815da1c30 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Extraction.cs @@ -1241,10 +1241,19 @@ private static TypeMapping MapTypeCore(ITypeSymbol type, KnownTypes knownTypes) SpecialType.System_Int64 => new TypeMapping(FieldKind.Int64), SpecialType.System_Boolean => new TypeMapping(FieldKind.Boolean), SpecialType.System_Double => new TypeMapping(FieldKind.Double), + SpecialType.System_Single => new TypeMapping(FieldKind.Single), + SpecialType.System_Int16 => new TypeMapping(FieldKind.Int16), + SpecialType.System_SByte => new TypeMapping(FieldKind.SByte), + SpecialType.System_Byte => new TypeMapping(FieldKind.Byte), + SpecialType.System_UInt16 => new TypeMapping(FieldKind.UInt16), + SpecialType.System_UInt32 => new TypeMapping(FieldKind.UInt32), + SpecialType.System_UInt64 => new TypeMapping(FieldKind.UInt64), + SpecialType.System_Char => new TypeMapping(FieldKind.Char), SpecialType.System_Decimal => new TypeMapping(FieldKind.Decimal), SpecialType.System_DateTime => new TypeMapping(FieldKind.DateTime), _ when SymbolEqualityComparer.Default.Equals(type, knownTypes.Guid) => new TypeMapping(FieldKind.Guid), _ when SymbolEqualityComparer.Default.Equals(type, knownTypes.DateTimeOffset) => new TypeMapping(FieldKind.DateTimeOffset), + _ when SymbolEqualityComparer.Default.Equals(type, knownTypes.TimeSpan) => new TypeMapping(FieldKind.TimeSpan), _ when SymbolEqualityComparer.Default.Equals(type, knownTypes.ActorRef) => new TypeMapping(FieldKind.ActorRef), _ => new TypeMapping(FieldKind.Unsupported) }; @@ -1578,6 +1587,7 @@ private KnownTypes(Compilation compilation) GenericSerializableAttribute = compilation.GetTypeByMetadataName(GenericSerializableAttributeFullName); Guid = compilation.GetTypeByMetadataName("System.Guid"); DateTimeOffset = compilation.GetTypeByMetadataName("System.DateTimeOffset"); + TimeSpan = compilation.GetTypeByMetadataName("System.TimeSpan"); ActorRef = compilation.GetTypeByMetadataName("Akka.Actor.IActorRef"); ListOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); ReadOnlyListOfT = compilation.GetTypeByMetadataName("System.Collections.Generic.IReadOnlyList`1"); @@ -1613,6 +1623,7 @@ private KnownTypes(Compilation compilation) public INamedTypeSymbol? Guid { get; } public INamedTypeSymbol? DateTimeOffset { get; } + public INamedTypeSymbol? TimeSpan { get; } public INamedTypeSymbol? ActorRef { get; } public INamedTypeSymbol? ListOfT { get; } public INamedTypeSymbol? ReadOnlyListOfT { get; } diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs index 3377ce1309f..13e44c9a6b9 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Models.cs @@ -1648,7 +1648,16 @@ internal enum FieldKind ImmutableArray, ImmutableList, ImmutableHashSet, - ImmutableDictionary + ImmutableDictionary, + Int16, + SByte, + Byte, + UInt16, + UInt32, + UInt64, + Single, + Char, + TimeSpan } /// diff --git a/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenNativeScalarSpec.cs b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenNativeScalarSpec.cs new file mode 100644 index 00000000000..a83e4fac676 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenNativeScalarSpec.cs @@ -0,0 +1,102 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Akka.Serialization.V2.Tests.Harness; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Golden-output gate for the native TimeSpan, float, short, byte, +/// sbyte, ushort, uint, ulong and char support (G-3). Kept apart from +/// GeneratorGoldenOutputSpec on purpose: that spec's baselines predate this feature and must not +/// move; this corpus adds one new serializer with its own baseline. +/// +public sealed class GeneratorGoldenNativeScalarSpec +{ + private const string HintName = "ScalarGoldenSerializer.AkkaSerialization.g.cs"; + + // Every new scalar as a required field, as a Nullable field, and in the three collection positions + // (element, dictionary key, dictionary value), with a Nullable element in one of them. + private const string Source = """ + #nullable enable + using System; + using System.Collections.Generic; + using Akka.Serialization.V2; + + namespace ScalarGolden; + + public interface IProtocol + { + } + + [AkkaSerializable(Manifest = "required-v1")] + public sealed record Required( + [property: AkkaField(1)] TimeSpan Span, + [property: AkkaField(2)] float Single, + [property: AkkaField(3)] short Int16, + [property: AkkaField(4)] byte Byte, + [property: AkkaField(5)] sbyte SByte, + [property: AkkaField(6)] ushort UInt16, + [property: AkkaField(7)] uint UInt32, + [property: AkkaField(8)] ulong UInt64, + [property: AkkaField(9)] char Char) : IProtocol; + + [AkkaSerializable(Manifest = "optional-v1")] + public sealed record Optional( + [property: AkkaField(1)] TimeSpan? Span, + [property: AkkaField(2)] float? Single, + [property: AkkaField(3)] short? Int16, + [property: AkkaField(4)] byte? Byte, + [property: AkkaField(5)] sbyte? SByte, + [property: AkkaField(6)] ushort? UInt16, + [property: AkkaField(7)] uint? UInt32, + [property: AkkaField(8)] ulong? UInt64, + [property: AkkaField(9)] char? Char) : IProtocol; + + [AkkaSerializable(Manifest = "positions-v1")] + public sealed record Positions( + [property: AkkaField(1)] List Spans, + [property: AkkaField(2)] List NullableShorts, + [property: AkkaField(3)] Dictionary ByChar, + [property: AkkaField(4)] Dictionary NullableFloatBySpan) : IProtocol; + + [AkkaSerializer("scalar-golden", 150202)] + public sealed partial class ScalarGoldenSerializer : AkkaSerializer + { + public static partial SerializerRegistration CreateRegistration(); + } + """; + + [Fact(DisplayName = "Should_EmitByteIdenticalOutput_When_NativeScalarsAreFieldsAndCollectionMembers")] + public void Should_EmitByteIdenticalOutput_When_NativeScalarsAreFieldsAndCollectionMembers() + { + var result = GeneratorTestHarness.Run(Source); + + result.GeneratorDiagnostics.Should().BeEmpty("the scalar corpus is designed to be diagnostics-clean"); + result.GeneratedSources.Keys.Should().BeEquivalentTo(new[] { HintName }); + + var failure = GoldenBaseline.Compare(HintName, result.GeneratedSources[HintName]); + failure.Should().BeNull(); + } + + [Fact(DisplayName = "Should_CompileCleanly_When_GeneratedFromNativeScalarCorpus")] + public void Should_CompileCleanly_When_GeneratedFromNativeScalarCorpus() + { + var result = GeneratorTestHarness.Run(Source); + + result.GeneratorDiagnostics.Should().BeEmpty(); + result.CompileDiagnostics + .Where(diagnostic => diagnostic.Severity >= DiagnosticSeverity.Warning && diagnostic.Id != "CS1701") + .Select(diagnostic => diagnostic.ToString()) + .Should().BeEmpty("generated code must compile with no errors and no warnings under #nullable enable"); + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/GoldenOutput/ScalarGoldenSerializer.AkkaSerialization.g.cs.verified.txt b/src/core/Akka.Serialization.V2.Tests/GoldenOutput/ScalarGoldenSerializer.AkkaSerialization.g.cs.verified.txt new file mode 100644 index 00000000000..355c672c788 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/GoldenOutput/ScalarGoldenSerializer.AkkaSerialization.g.cs.verified.txt @@ -0,0 +1,664 @@ +// +#nullable enable +using System; +using System.Buffers; + +namespace ScalarGolden; + +public sealed partial class ScalarGoldenSerializer +{ + public ScalarGoldenSerializer(global::Akka.Actor.ExtendedActorSystem system) : base(system) + { + } + + public override int Identifier => 150202; + + public static partial global::Akka.Serialization.V2.SerializerRegistration CreateRegistration() + { + return global::Akka.Serialization.V2.SerializerRegistration.Create("scalar-golden", + system => new ScalarGoldenSerializer(system), + global::System.Collections.Immutable.ImmutableHashSet.Create( + typeof(global::ScalarGolden.IProtocol))); + } + + public override string Manifest(object obj) + { + return obj switch + { + global::ScalarGolden.Required => "required-v1", + global::ScalarGolden.Optional => "optional-v1", + global::ScalarGolden.Positions => "positions-v1", + _ => throw new global::System.ArgumentException($"Unsupported generated serializer type '{obj.GetType()}' from assembly '{obj.GetType().Assembly.GetName().Name}'. This serializer was generated in assembly 'AkkaSerializationGeneratorHarness', which does not recognize this type.", nameof(obj)) + }; + } + + public override int Serialize(object obj, IBufferWriter writer) + { + var countingWriter = new AkkaGeneratedCountingBufferWriter(writer); + var messagePackWriter = new global::MessagePack.MessagePackWriter(countingWriter); + SerializeMessagePack(obj, ref messagePackWriter); + messagePackWriter.Flush(); + return checked((int)countingWriter.BytesWritten); + } + + private void SerializeMessagePack(object obj, ref global::MessagePack.MessagePackWriter writer) + { + switch (obj) + { + case global::ScalarGolden.Required message: + WriteRequired(ref writer, message); + break; + case global::ScalarGolden.Optional message: + WriteOptional(ref writer, message); + break; + case global::ScalarGolden.Positions message: + WritePositions(ref writer, message); + break; + default: + throw new global::System.ArgumentException($"Unsupported generated serializer type '{obj.GetType()}' from assembly '{obj.GetType().Assembly.GetName().Name}'. This serializer was generated in assembly 'AkkaSerializationGeneratorHarness', which does not recognize this type.", nameof(obj)); + } + } + + public override object Deserialize(ReadOnlySequence bytes, string manifest) + { + var reader = new global::MessagePack.MessagePackReader(bytes); + return manifest switch + { + "required-v1" => ReadRequired(ref reader), + "optional-v1" => ReadOptional(ref reader), + "positions-v1" => ReadPositions(ref reader), + _ => throw new global::System.Runtime.Serialization.SerializationException($"Unknown generated serializer manifest [{manifest}] for serializer [{GetType()}].") + }; + } + + public override int SizeHint(object obj) + { + return obj switch + { + global::ScalarGolden.Required message => SizeOfRequired(message), + global::ScalarGolden.Optional message => SizeOfOptional(message), + global::ScalarGolden.Positions message => SizeOfPositions(message), + _ => global::Akka.Serialization.SerializerV2.UnknownSize + }; + } + + private sealed class AkkaGeneratedCountingBufferWriter : global::System.Buffers.IBufferWriter + { + private readonly global::System.Buffers.IBufferWriter _inner; + + public AkkaGeneratedCountingBufferWriter(global::System.Buffers.IBufferWriter inner) + { + _inner = inner; + } + + public long BytesWritten { get; private set; } + + public void Advance(int count) + { + _inner.Advance(count); + BytesWritten += count; + } + + public global::System.Memory GetMemory(int sizeHint = 0) + { + return _inner.GetMemory(sizeHint); + } + + public global::System.Span GetSpan(int sizeHint = 0) + { + return _inner.GetSpan(sizeHint); + } + } + + private int SizeOfRequired(global::ScalarGolden.Required message) + { + checked + { + var size = SizeOfMapHeader(9); + size += SizeOfInt32(1); + size += SizeOfInt64(message.Span.Ticks); + size += SizeOfInt32(2); + size += SizeOfSingle(message.Single); + size += SizeOfInt32(3); + size += SizeOfInt32((int)message.Int16); + size += SizeOfInt32(4); + size += SizeOfInt32((int)message.Byte); + size += SizeOfInt32(5); + size += SizeOfInt32((int)message.SByte); + size += SizeOfInt32(6); + size += SizeOfInt32((int)message.UInt16); + size += SizeOfInt32(7); + size += SizeOfInt64((long)message.UInt32); + size += SizeOfInt32(8); + size += SizeOfUInt64(message.UInt64); + size += SizeOfInt32(9); + size += SizeOfInt32((int)message.Char); + return size; + } + } + + private void WriteRequired(ref global::MessagePack.MessagePackWriter writer, global::ScalarGolden.Required message) + { + writer.WriteMapHeader(9); + writer.Write(1); + writer.Write(message.Span.Ticks); + writer.Write(2); + writer.Write(message.Single); + writer.Write(3); + writer.Write(message.Int16); + writer.Write(4); + writer.Write(message.Byte); + writer.Write(5); + writer.Write(message.SByte); + writer.Write(6); + writer.Write(message.UInt16); + writer.Write(7); + writer.Write(message.UInt32); + writer.Write(8); + writer.Write(message.UInt64); + writer.Write(9); + writer.Write((ushort)message.Char); + } + + private global::ScalarGolden.Required ReadRequired(ref global::MessagePack.MessagePackReader reader) + { + var __fieldCount = reader.ReadMapHeader(); + global::System.TimeSpan span = default; + var __hasSpan = false; + float single = default; + var __hasSingle = false; + short int16 = default; + var __hasInt16 = false; + byte @byte = default; + var __hasByte = false; + sbyte sByte = default; + var __hasSByte = false; + ushort uInt16 = default; + var __hasUInt16 = false; + uint uInt32 = default; + var __hasUInt32 = false; + ulong uInt64 = default; + var __hasUInt64 = false; + char @char = default; + var __hasChar = false; + for (var __entryIndex = 0; __entryIndex < __fieldCount; __entryIndex++) + { + var __fieldId = reader.ReadInt32(); + switch (__fieldId) + { + case 1: + span = new global::System.TimeSpan(reader.ReadInt64()); + __hasSpan = true; + break; + case 2: + single = ReadSingle(ref reader); + __hasSingle = true; + break; + case 3: + int16 = ReadInt16(ref reader); + __hasInt16 = true; + break; + case 4: + @byte = ReadByte(ref reader); + __hasByte = true; + break; + case 5: + sByte = ReadSByte(ref reader); + __hasSByte = true; + break; + case 6: + uInt16 = ReadUInt16(ref reader); + __hasUInt16 = true; + break; + case 7: + uInt32 = ReadUInt32(ref reader); + __hasUInt32 = true; + break; + case 8: + uInt64 = ReadUInt64(ref reader); + __hasUInt64 = true; + break; + case 9: + @char = ReadChar(ref reader); + __hasChar = true; + break; + default: + reader.Skip(); + break; + } + } + + if (!__hasSpan) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Span] with index [1] while deserializing [global::ScalarGolden.Required]."); + if (!__hasSingle) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Single] with index [2] while deserializing [global::ScalarGolden.Required]."); + if (!__hasInt16) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Int16] with index [3] while deserializing [global::ScalarGolden.Required]."); + if (!__hasByte) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Byte] with index [4] while deserializing [global::ScalarGolden.Required]."); + if (!__hasSByte) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [SByte] with index [5] while deserializing [global::ScalarGolden.Required]."); + if (!__hasUInt16) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [UInt16] with index [6] while deserializing [global::ScalarGolden.Required]."); + if (!__hasUInt32) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [UInt32] with index [7] while deserializing [global::ScalarGolden.Required]."); + if (!__hasUInt64) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [UInt64] with index [8] while deserializing [global::ScalarGolden.Required]."); + if (!__hasChar) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Char] with index [9] while deserializing [global::ScalarGolden.Required]."); + return new global::ScalarGolden.Required(Span: span, Single: single, Int16: int16, Byte: @byte, SByte: sByte, UInt16: uInt16, UInt32: uInt32, UInt64: uInt64, Char: @char); + } + + private int SizeOfOptional(global::ScalarGolden.Optional message) + { + checked + { + var size = SizeOfMapHeader(9); + size += SizeOfInt32(1); + size += message.Span is null ? SizeOfNil() : SizeOfInt64(message.Span.Value.Ticks); + size += SizeOfInt32(2); + size += message.Single is null ? SizeOfNil() : SizeOfSingle(message.Single.Value); + size += SizeOfInt32(3); + size += message.Int16 is null ? SizeOfNil() : SizeOfInt32((int)message.Int16.Value); + size += SizeOfInt32(4); + size += message.Byte is null ? SizeOfNil() : SizeOfInt32((int)message.Byte.Value); + size += SizeOfInt32(5); + size += message.SByte is null ? SizeOfNil() : SizeOfInt32((int)message.SByte.Value); + size += SizeOfInt32(6); + size += message.UInt16 is null ? SizeOfNil() : SizeOfInt32((int)message.UInt16.Value); + size += SizeOfInt32(7); + size += message.UInt32 is null ? SizeOfNil() : SizeOfInt64((long)message.UInt32.Value); + size += SizeOfInt32(8); + size += message.UInt64 is null ? SizeOfNil() : SizeOfUInt64(message.UInt64.Value); + size += SizeOfInt32(9); + size += message.Char is null ? SizeOfNil() : SizeOfInt32((int)message.Char.Value); + return size; + } + } + + private void WriteOptional(ref global::MessagePack.MessagePackWriter writer, global::ScalarGolden.Optional message) + { + writer.WriteMapHeader(9); + writer.Write(1); + if (message.Span is null) + writer.WriteNil(); + else + writer.Write(message.Span.Value.Ticks); + writer.Write(2); + if (message.Single is null) + writer.WriteNil(); + else + writer.Write(message.Single.Value); + writer.Write(3); + if (message.Int16 is null) + writer.WriteNil(); + else + writer.Write(message.Int16.Value); + writer.Write(4); + if (message.Byte is null) + writer.WriteNil(); + else + writer.Write(message.Byte.Value); + writer.Write(5); + if (message.SByte is null) + writer.WriteNil(); + else + writer.Write(message.SByte.Value); + writer.Write(6); + if (message.UInt16 is null) + writer.WriteNil(); + else + writer.Write(message.UInt16.Value); + writer.Write(7); + if (message.UInt32 is null) + writer.WriteNil(); + else + writer.Write(message.UInt32.Value); + writer.Write(8); + if (message.UInt64 is null) + writer.WriteNil(); + else + writer.Write(message.UInt64.Value); + writer.Write(9); + if (message.Char is null) + writer.WriteNil(); + else + writer.Write((ushort)message.Char.Value); + } + + private global::ScalarGolden.Optional ReadOptional(ref global::MessagePack.MessagePackReader reader) + { + var __fieldCount = reader.ReadMapHeader(); + global::System.TimeSpan? span = null; + float? single = null; + short? int16 = null; + byte? @byte = null; + sbyte? sByte = null; + ushort? uInt16 = null; + uint? uInt32 = null; + ulong? uInt64 = null; + char? @char = null; + for (var __entryIndex = 0; __entryIndex < __fieldCount; __entryIndex++) + { + var __fieldId = reader.ReadInt32(); + switch (__fieldId) + { + case 1: + if (reader.TryReadNil()) + span = null; + else + span = new global::System.TimeSpan(reader.ReadInt64()); + break; + case 2: + if (reader.TryReadNil()) + single = null; + else + single = ReadSingle(ref reader); + break; + case 3: + if (reader.TryReadNil()) + int16 = null; + else + int16 = ReadInt16(ref reader); + break; + case 4: + if (reader.TryReadNil()) + @byte = null; + else + @byte = ReadByte(ref reader); + break; + case 5: + if (reader.TryReadNil()) + sByte = null; + else + sByte = ReadSByte(ref reader); + break; + case 6: + if (reader.TryReadNil()) + uInt16 = null; + else + uInt16 = ReadUInt16(ref reader); + break; + case 7: + if (reader.TryReadNil()) + uInt32 = null; + else + uInt32 = ReadUInt32(ref reader); + break; + case 8: + if (reader.TryReadNil()) + uInt64 = null; + else + uInt64 = ReadUInt64(ref reader); + break; + case 9: + if (reader.TryReadNil()) + @char = null; + else + @char = ReadChar(ref reader); + break; + default: + reader.Skip(); + break; + } + } + + return new global::ScalarGolden.Optional(Span: span, Single: single, Int16: int16, Byte: @byte, SByte: sByte, UInt16: uInt16, UInt32: uInt32, UInt64: uInt64, Char: @char); + } + + private int SizeOfPositions(global::ScalarGolden.Positions message) + { + checked + { + var size = SizeOfMapHeader(4); + size += SizeOfInt32(1); + int __size0; + if (message.Spans is null) + { + __size0 = SizeOfNil(); + } + else + { + __size0 = SizeOfArrayHeader(message.Spans.Count); + foreach (var __item1 in message.Spans) + { + __size0 += SizeOfInt64(__item1.Ticks); + } + } + size += __size0; + size += SizeOfInt32(2); + int __size2; + if (message.NullableShorts is null) + { + __size2 = SizeOfNil(); + } + else + { + __size2 = SizeOfArrayHeader(message.NullableShorts.Count); + foreach (var __item3 in message.NullableShorts) + { + __size2 += __item3 is null ? SizeOfNil() : SizeOfInt32((int)__item3.Value); + } + } + size += __size2; + size += SizeOfInt32(3); + int __size4; + if (message.ByChar is null) + { + __size4 = SizeOfNil(); + } + else + { + __size4 = SizeOfMapHeader(message.ByChar.Count); + foreach (var __kvp5 in message.ByChar) + { + __size4 += SizeOfInt32((int)__kvp5.Key); + __size4 += SizeOfUInt64(__kvp5.Value); + } + } + size += __size4; + size += SizeOfInt32(4); + int __size6; + if (message.NullableFloatBySpan is null) + { + __size6 = SizeOfNil(); + } + else + { + __size6 = SizeOfMapHeader(message.NullableFloatBySpan.Count); + foreach (var __kvp7 in message.NullableFloatBySpan) + { + __size6 += SizeOfInt64(__kvp7.Key.Ticks); + __size6 += __kvp7.Value is null ? SizeOfNil() : SizeOfSingle(__kvp7.Value.Value); + } + } + size += __size6; + return size; + } + } + + private void WritePositions(ref global::MessagePack.MessagePackWriter writer, global::ScalarGolden.Positions message) + { + writer.WriteMapHeader(4); + writer.Write(1); + if (message.Spans is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.Spans.Count); + foreach (var __item0 in message.Spans) + { + writer.Write(__item0.Ticks); + } + } + writer.Write(2); + if (message.NullableShorts is null) + { + writer.WriteNil(); + } + else + { + writer.WriteArrayHeader(message.NullableShorts.Count); + foreach (var __item1 in message.NullableShorts) + { + if (__item1 is null) + writer.WriteNil(); + else + writer.Write(__item1.Value); + } + } + writer.Write(3); + if (message.ByChar is null) + { + writer.WriteNil(); + } + else + { + writer.WriteMapHeader(message.ByChar.Count); + foreach (var __kvp2 in message.ByChar) + { + writer.Write((ushort)__kvp2.Key); + writer.Write(__kvp2.Value); + } + } + writer.Write(4); + if (message.NullableFloatBySpan is null) + { + writer.WriteNil(); + } + else + { + writer.WriteMapHeader(message.NullableFloatBySpan.Count); + foreach (var __kvp3 in message.NullableFloatBySpan) + { + writer.Write(__kvp3.Key.Ticks); + if (__kvp3.Value is null) + writer.WriteNil(); + else + writer.Write(__kvp3.Value.Value); + } + } + } + + private global::ScalarGolden.Positions ReadPositions(ref global::MessagePack.MessagePackReader reader) + { + var __fieldCount = reader.ReadMapHeader(); + global::System.Collections.Generic.List? spans = default; + var __hasSpans = false; + global::System.Collections.Generic.List? nullableShorts = default; + var __hasNullableShorts = false; + global::System.Collections.Generic.Dictionary? byChar = default; + var __hasByChar = false; + global::System.Collections.Generic.Dictionary? nullableFloatBySpan = default; + var __hasNullableFloatBySpan = false; + for (var __entryIndex = 0; __entryIndex < __fieldCount; __entryIndex++) + { + var __fieldId = reader.ReadInt32(); + switch (__fieldId) + { + case 1: + if (reader.TryReadNil()) + { + spans = null; + } + else + { + var __len0 = reader.ReadArrayHeader(); + var __col1 = new global::System.Collections.Generic.List(__len0); + for (var __i2 = 0; __i2 < __len0; __i2++) + { + global::System.TimeSpan __item3; + __item3 = new global::System.TimeSpan(reader.ReadInt64()); + __col1.Add(__item3); + } + spans = __col1; + } + __hasSpans = true; + break; + case 2: + if (reader.TryReadNil()) + { + nullableShorts = null; + } + else + { + var __len4 = reader.ReadArrayHeader(); + var __col5 = new global::System.Collections.Generic.List(__len4); + for (var __i6 = 0; __i6 < __len4; __i6++) + { + short? __item7; + if (reader.TryReadNil()) + __item7 = null; + else + __item7 = ReadInt16(ref reader); + __col5.Add(__item7); + } + nullableShorts = __col5; + } + __hasNullableShorts = true; + break; + case 3: + if (reader.TryReadNil()) + { + byChar = null; + } + else + { + var __len8 = reader.ReadMapHeader(); + var __col9 = new global::System.Collections.Generic.Dictionary(__len8); + for (var __i10 = 0; __i10 < __len8; __i10++) + { + char __key11; + __key11 = ReadChar(ref reader); + ulong __val12; + __val12 = ReadUInt64(ref reader); + __col9[__key11] = __val12; + } + byChar = __col9; + } + __hasByChar = true; + break; + case 4: + if (reader.TryReadNil()) + { + nullableFloatBySpan = null; + } + else + { + var __len13 = reader.ReadMapHeader(); + var __col14 = new global::System.Collections.Generic.Dictionary(__len13); + for (var __i15 = 0; __i15 < __len13; __i15++) + { + global::System.TimeSpan __key16; + __key16 = new global::System.TimeSpan(reader.ReadInt64()); + float? __val17; + if (reader.TryReadNil()) + __val17 = null; + else + __val17 = ReadSingle(ref reader); + __col14[__key16] = __val17; + } + nullableFloatBySpan = __col14; + } + __hasNullableFloatBySpan = true; + break; + default: + reader.Skip(); + break; + } + } + + if (!__hasSpans || spans is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [Spans] with index [1] while deserializing [global::ScalarGolden.Positions]."); + if (!__hasNullableShorts || nullableShorts is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [NullableShorts] with index [2] while deserializing [global::ScalarGolden.Positions]."); + if (!__hasByChar || byChar is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [ByChar] with index [3] while deserializing [global::ScalarGolden.Positions]."); + if (!__hasNullableFloatBySpan || nullableFloatBySpan is null) + throw new global::System.Runtime.Serialization.SerializationException("Missing required field [NullableFloatBySpan] with index [4] while deserializing [global::ScalarGolden.Positions]."); + return new global::ScalarGolden.Positions(Spans: spans!, NullableShorts: nullableShorts!, ByChar: byChar!, NullableFloatBySpan: nullableFloatBySpan!); + } + +} diff --git a/src/core/Akka.Serialization.V2.Tests/NativeScalarDiagnosticsSpec.cs b/src/core/Akka.Serialization.V2.Tests/NativeScalarDiagnosticsSpec.cs new file mode 100644 index 00000000000..2c5ef1a0cfd --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/NativeScalarDiagnosticsSpec.cs @@ -0,0 +1,97 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System.Linq; +using Akka.Serialization.V2.Tests.Harness; +using FluentAssertions; +using Microsoft.CodeAnalysis; +using Xunit; +using static Akka.Serialization.V2.Tests.Harness.DiagnosticSource; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Diagnostics around the native TimeSpan and small scalars (G-3): they no longer fail, a type that +/// is still unsupported gets an AKKASG007 that says what to do about it, and a registered formatter still +/// wins over a native encoding. +/// +public sealed class NativeScalarDiagnosticsSpec +{ + [Fact(DisplayName = "Should_NotReportAKKASG007_When_AFieldIsTimeSpanOrASmallScalar")] + public void Should_NotReportAKKASG007_When_AFieldIsTimeSpanOrASmallScalar() + { + var run = Run( + string.Empty, + "[property: AkkaField(1)] TimeSpan A, [property: AkkaField(2)] float B, [property: AkkaField(3)] short C, [property: AkkaField(4)] byte D, " + + "[property: AkkaField(5)] sbyte E, [property: AkkaField(6)] ushort F, [property: AkkaField(7)] uint G, [property: AkkaField(8)] ulong H, " + + "[property: AkkaField(9)] char I, [property: AkkaField(10)] TimeSpan? J, [property: AkkaField(11)] List K"); + + run.Errors.Should().BeEmpty(); + } + + [Theory(DisplayName = "Should_ReportAKKASG007NamingAFormatter_When_AFieldIsAForeignTypeWithNoSupport")] + [InlineData("Uri", "System.Uri")] + [InlineData("Half", "System.Half")] + [InlineData("DateOnly", "System.DateOnly")] + [InlineData("TimeOnly", "System.TimeOnly")] + public void Should_ReportAKKASG007NamingAFormatter_When_AFieldIsAForeignTypeWithNoSupport(string fieldType, string expectedDisplayType) + { + var run = Run(string.Empty, $"[property: AkkaField(1)] {fieldType} Value"); + + var message = run.Errors.Should().ContainSingle(d => d.Id == "AKKASG007").Subject.GetMessage(null); + + // Says what is wrong with THIS type and the fixes that exist for a type the author does not own. + message.Should().Contain($"'{expectedDisplayType}'") + .And.Contain("declared in assembly") + .And.Contain($"[AkkaSerializerFormatter<{expectedDisplayType}, TFormatter>]") + .And.Contain("'SampleSerializer'"); + + // The stale wording is gone: no "yet" (cross-assembly [AkkaSerializable] has worked since #8534) + // and no "declare the type in this assembly" (impossible for a BCL type). + message.Should().NotContain("cannot read a schema").And.NotContain("declare the type in this assembly").And.NotContain("nested value object"); + } + + [Fact(DisplayName = "Should_UseTheRegisteredFormatter_When_AFormatterIsRegisteredForTimeSpan")] + public void Should_UseTheRegisteredFormatter_When_AFormatterIsRegisteredForTimeSpan() + { + // A registered formatter takes precedence over a native encoding at field position today; collection + // positions follow the same rule, so a serializer that already formats TimeSpan keeps doing so everywhere. + const string formatter = """ + public sealed class SecondsFormatter : IAkkaMessagePackFormatter + { + public void Write(ref MessagePackWriter writer, TimeSpan value) => writer.Write(value.TotalSeconds); + public TimeSpan Read(ref MessagePackReader reader) => TimeSpan.FromSeconds(reader.ReadDouble()); + public int SizeOf(TimeSpan value) => 9; + } + + """; + var source = DiagnosticSource.Header + formatter + """ + [AkkaSerializer("sample", 199301)] + [AkkaSerializerFormatter] + public sealed partial class SampleSerializer : AkkaSerializer + { + public static partial SerializerRegistration CreateRegistration(); + } + + [AkkaSerializable(Manifest = "outer-v1")] + public sealed record Outer( + [property: AkkaField(1)] TimeSpan Single, + [property: AkkaField(2)] List Many, + [property: AkkaField(3)] Dictionary ByName) : IProtocol; + """; + + var result = GeneratorTestHarness.Run(source); + + result.GeneratorDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).Should().BeEmpty(); + var generated = result.GeneratedSources["SampleSerializer.AkkaSerialization.g.cs"]; + generated.Should().NotContain(".Ticks").And.NotContain("new global::System.TimeSpan("); + generated.Should().Contain("_akkaFormatter_System_TimeSpan.Write(ref writer, message.Single)"); + generated.Should().Contain("_akkaFormatter_System_TimeSpan.Write(ref writer, __item"); + generated.Should().Contain("_akkaFormatter_System_TimeSpan.Write(ref writer, __kvp"); + } +} diff --git a/src/core/Akka.Serialization.V2.Tests/NativeScalarSpec.cs b/src/core/Akka.Serialization.V2.Tests/NativeScalarSpec.cs new file mode 100644 index 00000000000..23a011e66ca --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/NativeScalarSpec.cs @@ -0,0 +1,493 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Akka.Actor; +using FluentAssertions; +using MessagePack; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// Native support for , , , , +/// , , , and (G-3), +/// as fields, as Nullable fields, and as collection elements, dictionary keys and dictionary values. +/// +/// +/// Wire encodings under test: TimeSpan is the MessagePack integer of its Ticks (int64); float is MessagePack +/// float32; the integer types use MessagePack's smallest integer encoding (as int and long already do); char +/// is the unsigned integer of its UTF-16 code unit. Reads range-check and throw instead of truncating. +/// +public sealed class NativeScalarSpec : IAsyncLifetime +{ + private ActorSystem _system = null!; + private NativeScalarSerializer _serializer = null!; + + public ValueTask InitializeAsync() + { + _system = ActorSystem.Create("native-scalar-spec"); + _serializer = new NativeScalarSerializer((ExtendedActorSystem)_system); + return ValueTask.CompletedTask; + } + + public async ValueTask DisposeAsync() + { + await _system.Terminate(); + } + + private static SmallScalarsMessage ScalarCase(string caseName) => caseName switch + { + "min" => new SmallScalarsMessage(TimeSpan.MinValue, float.MinValue, short.MinValue, byte.MinValue, sbyte.MinValue, ushort.MinValue, uint.MinValue, ulong.MinValue, char.MinValue), + "max" => new SmallScalarsMessage(TimeSpan.MaxValue, float.MaxValue, short.MaxValue, byte.MaxValue, sbyte.MaxValue, ushort.MaxValue, uint.MaxValue, ulong.MaxValue, char.MaxValue), + "zero" => new SmallScalarsMessage(TimeSpan.Zero, 0f, 0, 0, 0, 0, 0u, 0ul, '\0'), + "negative-and-fractional" => new SmallScalarsMessage(TimeSpan.FromTicks(-1), -1.5f, -1, 1, -1, 1, 1u, 1ul, 'A'), + "encoding-boundaries" => new SmallScalarsMessage(TimeSpan.FromTicks(128), float.Epsilon, -33, 128, -128, 256, 65536u, 4294967296ul, '\uD800'), + "float-nan" => new SmallScalarsMessage(TimeSpan.FromSeconds(30), float.NaN, 127, 127, 127, 127, 127u, 127ul, 'z'), + "float-negative-infinity" => new SmallScalarsMessage(TimeSpan.FromDays(1), float.NegativeInfinity, -32, 255, -32, 65535, 255u, 255ul, '\uFFFE'), + _ => throw new ArgumentOutOfRangeException(nameof(caseName), caseName, "Unknown scalar case.") + }; + + [Theory(DisplayName = "Should_RoundTripEveryScalar_When_ValuesAreAtTheirLimits")] + [InlineData("min")] + [InlineData("max")] + [InlineData("zero")] + [InlineData("negative-and-fractional")] + [InlineData("encoding-boundaries")] + [InlineData("float-nan")] + [InlineData("float-negative-infinity")] + public void Should_RoundTripEveryScalar_When_ValuesAreAtTheirLimits(string caseName) + { + var message = ScalarCase(caseName); + + var recovered = RoundTrip(message); + + recovered.Span.Should().Be(message.Span, caseName); + recovered.Single.Should().Be(message.Single, caseName); + recovered.Int16.Should().Be(message.Int16, caseName); + recovered.Byte.Should().Be(message.Byte, caseName); + recovered.SByte.Should().Be(message.SByte, caseName); + recovered.UInt16.Should().Be(message.UInt16, caseName); + recovered.UInt32.Should().Be(message.UInt32, caseName); + recovered.UInt64.Should().Be(message.UInt64, caseName); + recovered.Char.Should().Be(message.Char, caseName); + } + + [Theory(DisplayName = "Should_ReportExactSizeHint_When_ScalarsAreAtTheirLimits")] + [InlineData("min")] + [InlineData("max")] + [InlineData("zero")] + [InlineData("negative-and-fractional")] + [InlineData("encoding-boundaries")] + [InlineData("float-nan")] + [InlineData("float-negative-infinity")] + public void Should_ReportExactSizeHint_When_ScalarsAreAtTheirLimits(string caseName) + { + var message = ScalarCase(caseName); + + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length, caseName); + } + + [Fact(DisplayName = "Should_RoundTripNegativeZeroFloat_When_FloatIsNegativeZero")] + public void Should_RoundTripNegativeZeroFloat_When_FloatIsNegativeZero() + { + var recovered = RoundTrip(new SmallScalarsMessage(TimeSpan.Zero, -0f, 0, 0, 0, 0, 0, 0, '\0')); + + float.IsNegative(recovered.Single).Should().BeTrue(); + } + + [Fact(DisplayName = "Should_WriteTheDocumentedEncoding_When_ScalarsAreSerialized")] + public void Should_WriteTheDocumentedEncoding_When_ScalarsAreSerialized() + { + var message = new SmallScalarsMessage( + TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A'); + + var expected = new byte[] + { + 0x89, // map(9) + 0x01, 0xcd, 0x01, 0x2c, // 1 TimeSpan: Ticks 300 as uint16 + 0x02, 0xca, 0x3f, 0xc0, 0x00, 0x00, // 2 float: float32 1.5 + 0x03, 0xd1, 0xff, 0x38, // 3 short: int16 -200 + 0x04, 0xcc, 0xc8, // 4 byte: uint8 200 + 0x05, 0xfb, // 5 sbyte: negative fixint -5 + 0x06, 0xcd, 0x9c, 0x40, // 6 ushort: uint16 40000 + 0x07, 0xce, 0xb2, 0xd0, 0x5e, 0x00, // 7 uint: uint32 3000000000 + 0x08, 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, // 8 ulong: uint64 max + 0x09, 0x41 // 9 char: code unit 0x41 as positive fixint + }; + + _serializer.ToBinary(message).Should().Equal(expected); + } + + [Fact(DisplayName = "Should_UseTheSmallestIntegerEncoding_When_SmallScalarsAreWritten")] + public void Should_UseTheSmallestIntegerEncoding_When_SmallScalarsAreWritten() + { + // The integer types must encode exactly as long/ulong would for the same value: the generator + // writes them through MessagePackWriter's compact overloads, and the size hint depends on it. + foreach (var value in new[] { 0, 1, 127, 128, 255, 256, 32767 }) + { + Encode((ref MessagePackWriter w) => w.Write((short)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "short {0}", value); + Encode((ref MessagePackWriter w) => w.Write((ushort)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "ushort {0}", value); + } + + foreach (var value in new[] { -1, -32, -33, -128, -129, -32768 }) + Encode((ref MessagePackWriter w) => w.Write((short)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "short {0}", value); + + foreach (var value in new[] { -1, -32, -33, -128 }) + Encode((ref MessagePackWriter w) => w.Write((sbyte)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "sbyte {0}", value); + + foreach (var value in new byte[] { 0, 127, 128, 255 }) + Encode((ref MessagePackWriter w) => w.Write(value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "byte {0}", value); + + foreach (var value in new[] { 0u, 127u, 128u, 255u, 256u, 65535u, 65536u, uint.MaxValue }) + Encode((ref MessagePackWriter w) => w.Write(value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "uint {0}", value); + } + + private static byte[] Encode(EncodeAction action) + { + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + action(ref writer); + writer.Flush(); + return buffer.WrittenMemory.ToArray(); + } + + private delegate void EncodeAction(ref MessagePackWriter writer); + + // ------------------------------------------------------------------------------------------ + // Nullable variants + // ------------------------------------------------------------------------------------------ + + [Fact(DisplayName = "Should_RoundTripNull_When_EveryNullableScalarIsNull")] + public void Should_RoundTripNull_When_EveryNullableScalarIsNull() + { + var message = new NullableScalarsMessage(null, null, null, null, null, null, null, null, null); + + var recovered = RoundTrip(message); + + recovered.Should().Be(message); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_RoundTripValues_When_EveryNullableScalarIsPopulatedAtItsLimits")] + public void Should_RoundTripValues_When_EveryNullableScalarIsPopulatedAtItsLimits() + { + foreach (var message in new[] + { + new NullableScalarsMessage(TimeSpan.MinValue, float.MinValue, short.MinValue, byte.MinValue, sbyte.MinValue, ushort.MinValue, uint.MinValue, ulong.MinValue, char.MinValue), + new NullableScalarsMessage(TimeSpan.MaxValue, float.MaxValue, short.MaxValue, byte.MaxValue, sbyte.MaxValue, ushort.MaxValue, uint.MaxValue, ulong.MaxValue, char.MaxValue), + new NullableScalarsMessage(TimeSpan.Zero, 0f, 0, 0, 0, 0, 0u, 0ul, '\0') + }) + { + RoundTrip(message).Should().Be(message); + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + } + + [Fact(DisplayName = "Should_WriteNilForNullAndTheSameBytesAsNonNullable_When_ScalarsAreNullable")] + public void Should_WriteNilForNullAndTheSameBytesAsNonNullable_When_ScalarsAreNullable() + { + var populated = _serializer.ToBinary(new NullableScalarsMessage( + TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A')); + var nonNullable = _serializer.ToBinary(new SmallScalarsMessage( + TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A')); + + // A present nullable value is written exactly as the non-nullable one: same map, same bytes. + populated.Should().Equal(nonNullable); + + var allNull = _serializer.ToBinary(new NullableScalarsMessage(null, null, null, null, null, null, null, null, null)); + allNull.Should().Equal( + 0x89, + 0x01, 0xc0, 0x02, 0xc0, 0x03, 0xc0, 0x04, 0xc0, 0x05, 0xc0, 0x06, 0xc0, 0x07, 0xc0, 0x08, 0xc0, 0x09, 0xc0); + } + + // ------------------------------------------------------------------------------------------ + // Collections: element, key and value positions + // ------------------------------------------------------------------------------------------ + + private static ScalarCollectionsMessage PopulatedCollections() => new( + Spans: new List { TimeSpan.MinValue, TimeSpan.Zero, TimeSpan.FromMilliseconds(250), TimeSpan.MaxValue }, + Floats: new[] { float.MinValue, -0.5f, 0f, float.MaxValue }, + NullableShorts: new List { short.MinValue, null, 0, short.MaxValue }, + Bytes: ImmutableArray.Create(0, 1, 127, 128, 255), + SBytes: new List { sbyte.MinValue, -1, 0, sbyte.MaxValue }, + UShorts: ImmutableList.Create(0, 255, 256, ushort.MaxValue), + NullableUInts: new List { null, 0u, uint.MaxValue }, + ULongs: new[] { 0ul, 1ul, ulong.MaxValue }, + Chars: ImmutableHashSet.Create('a', '\0', char.MaxValue), + SpanToULong: new Dictionary { [TimeSpan.Zero] = 0ul, [TimeSpan.FromTicks(1)] = ulong.MaxValue }, + CharToUInt: new Dictionary { ['x'] = 7u, [char.MaxValue] = uint.MaxValue }, + ShortToFloat: ImmutableDictionary.Empty.Add(short.MinValue, float.MinValue).Add(5, 2.5f), + NullableSpanByName: new Dictionary { ["has"] = TimeSpan.FromHours(1), ["none"] = null }, + NullableSpans: new List { null, TimeSpan.MinValue, null }, + ByteToNullableSByte: new Dictionary { [0] = null, [255] = sbyte.MinValue }); + + [Fact(DisplayName = "Should_RoundTripEveryCollectionShape_When_ScalarsAreElementsKeysAndValues")] + public void Should_RoundTripEveryCollectionShape_When_ScalarsAreElementsKeysAndValues() + { + var message = PopulatedCollections(); + + var recovered = RoundTrip(message); + + recovered.Spans.Should().Equal(message.Spans); + recovered.Floats.Should().Equal(message.Floats); + recovered.NullableShorts.Should().Equal(message.NullableShorts); + recovered.Bytes.Should().Equal(message.Bytes); + recovered.SBytes.Should().Equal(message.SBytes); + recovered.UShorts.Should().Equal(message.UShorts); + recovered.NullableUInts.Should().Equal(message.NullableUInts); + recovered.ULongs.Should().Equal(message.ULongs); + recovered.Chars.Should().BeEquivalentTo(message.Chars); + recovered.SpanToULong.Should().BeEquivalentTo(message.SpanToULong); + recovered.CharToUInt.Should().BeEquivalentTo(message.CharToUInt); + recovered.ShortToFloat.Should().BeEquivalentTo(message.ShortToFloat); + recovered.NullableSpanByName.Should().BeEquivalentTo(message.NullableSpanByName); + recovered.NullableSpans.Should().Equal(message.NullableSpans); + recovered.ByteToNullableSByte.Should().BeEquivalentTo(message.ByteToNullableSByte); + } + + [Fact(DisplayName = "Should_ReportExactSizeHint_When_ScalarsAreCollectionMembers")] + public void Should_ReportExactSizeHint_When_ScalarsAreCollectionMembers() + { + var message = PopulatedCollections(); + + _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); + } + + [Fact(DisplayName = "Should_RoundTripNullAndEmpty_When_ScalarCollectionsAreNullOrEmpty")] + public void Should_RoundTripNullAndEmpty_When_ScalarCollectionsAreNullOrEmpty() + { + var allNull = new ScalarCollectionsMessage(null, null, null, default, null, null, null, null, null, null, null, null, null, null, null); + var recoveredNull = RoundTrip(allNull); + + recoveredNull.Spans.Should().BeNull(); + recoveredNull.Bytes.IsDefault.Should().BeTrue(); + recoveredNull.SpanToULong.Should().BeNull(); + _serializer.SizeHint(allNull).Should().Be(_serializer.ToBinary(allNull).Length); + + var allEmpty = new ScalarCollectionsMessage( + new List(), Array.Empty(), new List(), ImmutableArray.Empty, new List(), + ImmutableList.Empty, new List(), Array.Empty(), ImmutableHashSet.Empty, + new Dictionary(), new Dictionary(), ImmutableDictionary.Empty, + new Dictionary(), new List(), new Dictionary()); + var recoveredEmpty = RoundTrip(allEmpty); + + recoveredEmpty.Spans.Should().NotBeNull().And.BeEmpty(); + recoveredEmpty.Bytes.IsDefault.Should().BeFalse(); + recoveredEmpty.SpanToULong.Should().NotBeNull().And.BeEmpty(); + _serializer.SizeHint(allEmpty).Should().Be(_serializer.ToBinary(allEmpty).Length); + } + + [Fact(DisplayName = "Should_WriteBareEncodedElements_When_ScalarsAreInAList")] + public void Should_WriteBareEncodedElements_When_ScalarsAreInAList() + { + var message = new SpanListMessage(new List { TimeSpan.FromTicks(5), null, TimeSpan.FromTicks(-5) }); + + // map(1) { 1: array(3) [ int 5, nil, int -5 ] } -- TimeSpan is its Ticks, no wrapper. + _serializer.ToBinary(message).Should().Equal(0x81, 0x01, 0x93, 0x05, 0xc0, 0xfb); + } + + // ------------------------------------------------------------------------------------------ + // Reads range-check: a value the target type cannot hold throws, it never truncates + // ------------------------------------------------------------------------------------------ + + [Theory(DisplayName = "Should_Throw_When_WireValueDoesNotFitTheScalarType")] + [InlineData("short above max", "int16-v1", 32768L)] + [InlineData("short below min", "int16-v1", -32769L)] + [InlineData("short from a uint64 beyond int64", "int16-v1", ulong.MaxValue)] + [InlineData("sbyte above max", "sbyte-v1", 128L)] + [InlineData("sbyte below min", "sbyte-v1", -129L)] + [InlineData("byte above max", "byte-v1", 256L)] + [InlineData("byte negative", "byte-v1", -1L)] + [InlineData("ushort above max", "uint16-v1", 65536L)] + [InlineData("ushort negative", "uint16-v1", -1L)] + [InlineData("uint above max", "uint32-v1", 4294967296L)] + [InlineData("uint negative", "uint32-v1", -1L)] + [InlineData("ulong negative", "uint64-v1", -1L)] + [InlineData("ulong most negative", "uint64-v1", long.MinValue)] + [InlineData("char above max", "char-v1", 65536L)] + [InlineData("char negative", "char-v1", -1L)] + [InlineData("float from a double beyond float range", "single-v1", 1e300d)] + [InlineData("float from a string", "single-v1", "not a number")] + [InlineData("short from a string", "int16-v1", "not a number")] + public void Should_Throw_When_WireValueDoesNotFitTheScalarType(string caseName, string manifest, object wireValue) + { + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteMapHeader(1); + writer.Write(1); + switch (wireValue) + { + case long signed: + writer.Write(signed); + break; + case ulong unsigned: + writer.Write(unsigned); + break; + case double floating: + writer.Write(floating); + break; + default: + writer.Write((string)wireValue); + break; + } + + writer.Flush(); + + Action read = () => _serializer.FromBinary(buffer.WrittenMemory.ToArray(), manifest); + + read.Should().Throw(caseName); + } + + [Fact(DisplayName = "Should_NameTheTargetType_When_WireValueOverflowsAShort")] + public void Should_NameTheTargetType_When_WireValueOverflowsAShort() + { + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteMapHeader(1); + writer.Write(1); + writer.Write(70000); + writer.Flush(); + + Action read = () => _serializer.FromBinary(buffer.WrittenMemory.ToArray(), "int16-v1"); + + read.Should().Throw().WithMessage("*70000*System.Int16*"); + } + + [Theory(DisplayName = "Should_ReadTheValue_When_WireIntegerWasWrittenWithAWiderOrNarrowerWidth")] + [InlineData(100)] + [InlineData(-100)] + [InlineData(short.MaxValue)] + [InlineData(short.MinValue)] + public void Should_ReadTheValue_When_WireIntegerWasWrittenWithAWiderOrNarrowerWidth(int value) + { + // A peer may legally write the same integer with any width (for example a fixed int64): reading + // is by value, not by encoding. + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteMapHeader(1); + writer.Write(1); + writer.WriteInt64((long)value); + writer.Flush(); + + var recovered = (ScalarOnlyInt16)_serializer.FromBinary(buffer.WrittenMemory.ToArray(), "int16-v1"); + + recovered.Value.Should().Be((short)value); + } + + [Fact(DisplayName = "Should_ReadFloat32_When_WireHoldsAFloat64ThatFits")] + public void Should_ReadFloat32_When_WireHoldsAFloat64ThatFits() + { + var buffer = new ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteMapHeader(1); + writer.Write(1); + writer.Write(1.5d); + writer.Flush(); + + var recovered = (ScalarOnlySingle)_serializer.FromBinary(buffer.WrittenMemory.ToArray(), "single-v1"); + + recovered.Value.Should().Be(1.5f); + } + + private TMessage RoundTrip(TMessage message) + where TMessage : class, INativeScalarProtocol + { + var bytes = _serializer.ToBinary(message); + return _serializer.FromBinary(bytes, _serializer.Manifest(message)).Should().BeOfType().Subject; + } +} + +// ---------------------------------------------------------------------------------------------- +// Fixtures +// ---------------------------------------------------------------------------------------------- + +public interface INativeScalarProtocol +{ +} + +[AkkaSerializer("native-scalar-test", 122003)] +public sealed partial class NativeScalarSerializer : AkkaSerializer +{ + public static partial SerializerRegistration CreateRegistration(); +} + +[AkkaSerializable(Manifest = "small-scalars-v1")] +public sealed record SmallScalarsMessage( + [property: AkkaField(1)] TimeSpan Span, + [property: AkkaField(2)] float Single, + [property: AkkaField(3)] short Int16, + [property: AkkaField(4)] byte Byte, + [property: AkkaField(5)] sbyte SByte, + [property: AkkaField(6)] ushort UInt16, + [property: AkkaField(7)] uint UInt32, + [property: AkkaField(8)] ulong UInt64, + [property: AkkaField(9)] char Char) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "nullable-scalars-v1")] +public sealed record NullableScalarsMessage( + [property: AkkaField(1)] TimeSpan? Span, + [property: AkkaField(2)] float? Single, + [property: AkkaField(3)] short? Int16, + [property: AkkaField(4)] byte? Byte, + [property: AkkaField(5)] sbyte? SByte, + [property: AkkaField(6)] ushort? UInt16, + [property: AkkaField(7)] uint? UInt32, + [property: AkkaField(8)] ulong? UInt64, + [property: AkkaField(9)] char? Char) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "scalar-collections-v1")] +public sealed record ScalarCollectionsMessage( + [property: AkkaField(1)] List? Spans, + [property: AkkaField(2)] float[]? Floats, + [property: AkkaField(3)] List? NullableShorts, + [property: AkkaField(4)] ImmutableArray Bytes, + [property: AkkaField(5)] IReadOnlyList? SBytes, + [property: AkkaField(6)] ImmutableList? UShorts, + [property: AkkaField(7)] IReadOnlyCollection? NullableUInts, + [property: AkkaField(8)] ulong[]? ULongs, + [property: AkkaField(9)] ImmutableHashSet? Chars, + [property: AkkaField(10)] Dictionary? SpanToULong, + [property: AkkaField(11)] Dictionary? CharToUInt, + [property: AkkaField(12)] ImmutableDictionary? ShortToFloat, + [property: AkkaField(13)] IReadOnlyDictionary? NullableSpanByName, + [property: AkkaField(14)] List? NullableSpans, + [property: AkkaField(15)] Dictionary? ByteToNullableSByte) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "span-list-v1")] +public sealed record SpanListMessage( + [property: AkkaField(1)] List Spans) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "int16-v1")] +public sealed record ScalarOnlyInt16([property: AkkaField(1)] short Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "sbyte-v1")] +public sealed record ScalarOnlySByte([property: AkkaField(1)] sbyte Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "byte-v1")] +public sealed record ScalarOnlyByte([property: AkkaField(1)] byte Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "uint16-v1")] +public sealed record ScalarOnlyUInt16([property: AkkaField(1)] ushort Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "uint32-v1")] +public sealed record ScalarOnlyUInt32([property: AkkaField(1)] uint Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "uint64-v1")] +public sealed record ScalarOnlyUInt64([property: AkkaField(1)] ulong Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "char-v1")] +public sealed record ScalarOnlyChar([property: AkkaField(1)] char Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "single-v1")] +public sealed record ScalarOnlySingle([property: AkkaField(1)] float Value) : INativeScalarProtocol; diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs new file mode 100644 index 00000000000..25a56777c1d --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs @@ -0,0 +1,116 @@ +//----------------------------------------------------------------------- +// +// Copyright (C) 2009-2022 Lightbend Inc. +// Copyright (C) 2013-2026 .NET Foundation +// +//----------------------------------------------------------------------- + +#nullable enable +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using System.Threading.Tasks; +using Akka.Actor; +using VerifyXunit; +using Xunit; + +namespace Akka.Serialization.V2.Tests; + +/// +/// COMMITTED WIRE-FORMAT SNAPSHOTS for the native TimeSpan, float, short, byte, +/// sbyte, ushort, uint, ulong and char (G-3), as fields, Nullable fields and +/// collection members. Same mechanism and update procedure as (see +/// WireSnapshots/README.md); a separate spec so those existing cases, and their snapshots, stay +/// untouched. Every input is a hardcoded constant, so a mismatch always means the wire format changed. +/// +public sealed class WireFormatSnapshotScalarSpec : IAsyncLifetime +{ + private static readonly string[] AllCaseNames = + { + // G-3: native TimeSpan, float, short, byte, sbyte, ushort, uint, ulong, char. + "scalars-min", + "scalars-max", + "scalars-zero", + "scalars-nullable-all-null", + "scalars-nullable-populated", + "scalars-in-every-collection-shape-single-element", + }; + + private ActorSystem _system = null!; + private NativeScalarSerializer _scalarSerializer = null!; + + public ValueTask InitializeAsync() + { + _system = ActorSystem.Create("wire-format-snapshot-scalar"); + var extendedSystem = (ExtendedActorSystem)_system; + _scalarSerializer = new NativeScalarSerializer(extendedSystem); + return ValueTask.CompletedTask; + } + + public async ValueTask DisposeAsync() + { + await _system.Terminate(); + } + + public static IEnumerable CaseNames() => AllCaseNames.Select(name => new object[] { name }); + + [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized")] + [MemberData(nameof(CaseNames))] + public Task Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized(string caseName) + { + var wireCase = BuildCase(caseName); + var hexDump = HexDumpFormatter.Format(caseName, wireCase.MessageType, wireCase.Manifest, wireCase.SerializerId, wireCase.Bytes); + + return Verifier.Verify(hexDump) + .UseDirectory("WireSnapshots") + .UseFileName(caseName); + } + + private WireSnapshotCase BuildCase(string caseName) => caseName switch + { + "scalars-min" => Case(_scalarSerializer, new SmallScalarsMessage( + TimeSpan.MinValue, float.MinValue, short.MinValue, byte.MinValue, sbyte.MinValue, ushort.MinValue, uint.MinValue, ulong.MinValue, char.MinValue)), + + "scalars-max" => Case(_scalarSerializer, new SmallScalarsMessage( + TimeSpan.MaxValue, float.MaxValue, short.MaxValue, byte.MaxValue, sbyte.MaxValue, ushort.MaxValue, uint.MaxValue, ulong.MaxValue, char.MaxValue)), + + "scalars-zero" => Case(_scalarSerializer, new SmallScalarsMessage( + TimeSpan.Zero, 0f, 0, 0, 0, 0, 0u, 0ul, '\0')), + + "scalars-nullable-all-null" => Case(_scalarSerializer, new NullableScalarsMessage( + null, null, null, null, null, null, null, null, null)), + + "scalars-nullable-populated" => Case(_scalarSerializer, new NullableScalarsMessage( + TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A')), + + "scalars-in-every-collection-shape-single-element" => Case(_scalarSerializer, new ScalarCollectionsMessage( + Spans: new List { TimeSpan.FromMilliseconds(250) }, + Floats: new[] { -0.5f }, + NullableShorts: new List { null, 300 }, + Bytes: ImmutableArray.Create(255), + SBytes: new List { -100 }, + UShorts: ImmutableList.Create(40000), + NullableUInts: new List { uint.MaxValue }, + ULongs: new[] { ulong.MaxValue }, + Chars: ImmutableHashSet.Create('x'), + SpanToULong: new Dictionary { [TimeSpan.FromTicks(1)] = 2ul }, + CharToUInt: new Dictionary { ['y'] = 70000u }, + ShortToFloat: ImmutableDictionary.Empty.Add(-3, 2.5f), + NullableSpanByName: new Dictionary { ["none"] = null }, + NullableSpans: new List { null, TimeSpan.FromTicks(-5) }, + ByteToNullableSByte: new Dictionary { [9] = null })), + + _ => throw new ArgumentOutOfRangeException(nameof(caseName), caseName, "Unknown wire snapshot case.") + }; + + private static WireSnapshotCase Case(AkkaSerializer serializer, TMessage message) + where TMessage : notnull + { + var bytes = serializer.ToBinary(message); + var manifest = serializer.Manifest(message); + return new WireSnapshotCase(HexDumpFormatter.FriendlyTypeName(typeof(TMessage)), manifest, serializer.Identifier, bytes); + } + + private readonly record struct WireSnapshotCase(string MessageType, string Manifest, int SerializerId, byte[] Bytes); +} diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-in-every-collection-shape-single-element.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-in-every-collection-shape-single-element.verified.txt new file mode 100644 index 00000000000..adb93194059 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-in-every-collection-shape-single-element.verified.txt @@ -0,0 +1,12 @@ +case: scalars-in-every-collection-shape-single-element +message-type: ScalarCollectionsMessage +manifest: scalar-collections-v1 +serializer-id: 122003 +byte-count: 91 + +0000 8f 01 91 ce 00 26 25 a0 02 91 ca bf 00 00 00 03 |.....&%.........| +0010 92 c0 cd 01 2c 04 91 cc ff 05 91 d0 9c 06 91 cd |....,...........| +0020 9c 40 07 91 ce ff ff ff ff 08 91 cf ff ff ff ff |.@..............| +0030 ff ff ff ff 09 91 78 0a 81 01 02 0b 81 79 ce 00 |......x......y..| +0040 01 11 70 0c 81 fd ca 40 20 00 00 0d 81 a4 6e 6f |..p....@ .....no| +0050 6e 65 c0 0e 92 c0 fb 0f 81 09 c0 |ne.........| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-max.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-max.verified.txt new file mode 100644 index 00000000000..ad4a13aa596 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-max.verified.txt @@ -0,0 +1,10 @@ +case: scalars-max +message-type: SmallScalarsMessage +manifest: small-scalars-v1 +serializer-id: 122003 +byte-count: 50 + +0000 89 01 cf 7f ff ff ff ff ff ff ff 02 ca 7f 7f ff |................| +0010 ff 03 cd 7f ff 04 cc ff 05 7f 06 cd ff ff 07 ce |................| +0020 ff ff ff ff 08 cf ff ff ff ff ff ff ff ff 09 cd |................| +0030 ff ff |..| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-min.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-min.verified.txt new file mode 100644 index 00000000000..027ee908b8e --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-min.verified.txt @@ -0,0 +1,9 @@ +case: scalars-min +message-type: SmallScalarsMessage +manifest: small-scalars-v1 +serializer-id: 122003 +byte-count: 34 + +0000 89 01 d3 80 00 00 00 00 00 00 00 02 ca ff 7f ff |................| +0010 ff 03 d1 80 00 04 00 05 d0 80 06 00 07 00 08 00 |................| +0020 09 00 |..| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-all-null.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-all-null.verified.txt new file mode 100644 index 00000000000..8932ad5b466 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-all-null.verified.txt @@ -0,0 +1,8 @@ +case: scalars-nullable-all-null +message-type: NullableScalarsMessage +manifest: nullable-scalars-v1 +serializer-id: 122003 +byte-count: 19 + +0000 89 01 c0 02 c0 03 c0 04 c0 05 c0 06 c0 07 c0 08 |................| +0010 c0 09 c0 |...| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-populated.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-populated.verified.txt new file mode 100644 index 00000000000..a4fbe80211b --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-nullable-populated.verified.txt @@ -0,0 +1,9 @@ +case: scalars-nullable-populated +message-type: NullableScalarsMessage +manifest: nullable-scalars-v1 +serializer-id: 122003 +byte-count: 42 + +0000 89 01 cd 01 2c 02 ca 3f c0 00 00 03 d1 ff 38 04 |....,..?......8.| +0010 cc c8 05 fb 06 cd 9c 40 07 ce b2 d0 5e 00 08 cf |.......@....^...| +0020 ff ff ff ff ff ff ff ff 09 41 |.........A| diff --git a/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-zero.verified.txt b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-zero.verified.txt new file mode 100644 index 00000000000..1ad3b38de1a --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireSnapshots/scalars-zero.verified.txt @@ -0,0 +1,8 @@ +case: scalars-zero +message-type: SmallScalarsMessage +manifest: small-scalars-v1 +serializer-id: 122003 +byte-count: 23 + +0000 89 01 00 02 ca 00 00 00 00 03 00 04 00 05 00 06 |................| +0010 00 07 00 08 00 09 00 |.......| diff --git a/src/core/Akka.Serialization.V2/AkkaSerializer.cs b/src/core/Akka.Serialization.V2/AkkaSerializer.cs index 46abe525e8b..8ffd6947c52 100644 --- a/src/core/Akka.Serialization.V2/AkkaSerializer.cs +++ b/src/core/Akka.Serialization.V2/AkkaSerializer.cs @@ -8,6 +8,7 @@ #nullable enable using System; using System.Buffers; +using System.Globalization; using System.Runtime.Serialization; using Akka.Actor; using MessagePack; @@ -208,6 +209,10 @@ protected int SizeOfEnvelopePayload(object? payload) protected static int SizeOfInt64(long value) => MessagePackSizes.SizeOfInt64(value); + protected static int SizeOfUInt64(ulong value) => MessagePackSizes.SizeOfUInt64(value); + + protected static int SizeOfSingle(float value) => MessagePackSizes.SizeOfSingle(value); + protected static int SizeOfEnum(int value) => MessagePackSizes.SizeOfEnum(value); protected static int SizeOfMapHeader(int count) => MessagePackSizes.SizeOfMapHeader(count); @@ -386,4 +391,119 @@ protected static void WriteGuid(ref MessagePackWriter writer, Guid value) value.TryWriteBytes(writer.GetSpan(16)); writer.Advance(16); } + + // --------------------------------------------------------------------------------------------- + // Small-scalar readers (short, sbyte, byte, ushort, uint, ulong, float, char). + // + // Writers need no helper: the generator calls MessagePackWriter.Write(...) directly, which picks + // the smallest MessagePack integer encoding for the value, exactly as it does for int and long. + // Readers DO need one: the wire carries "an integer" with no width, so a value written by a wider + // peer (or a corrupt/hostile frame) can exceed the target type. Every reader below range-checks + // and throws a MessagePackSerializationException naming the target type, never truncating. + // --------------------------------------------------------------------------------------------- + + private static long ReadSignedInteger(ref MessagePackReader reader, string targetType) + { + try + { + return reader.ReadInt64(); + } + catch (OverflowException ex) + { + throw new MessagePackSerializationException( + $"The integer on the wire does not fit in a signed 64-bit integer, so it cannot be read as [{targetType}].", ex); + } + } + + private static ulong ReadUnsignedInteger(ref MessagePackReader reader, string targetType) + { + try + { + return reader.ReadUInt64(); + } + catch (OverflowException ex) + { + throw new MessagePackSerializationException( + $"The integer on the wire is negative or too large for an unsigned 64-bit integer, so it cannot be read as [{targetType}].", ex); + } + } + + private static MessagePackSerializationException OutOfRange(string targetType, string value, string range) + => new($"The integer [{value}] on the wire is outside the range of [{targetType}] ({range})."); + + protected static short ReadInt16(ref MessagePackReader reader) + { + var value = ReadSignedInteger(ref reader, "System.Int16"); + if (value < short.MinValue || value > short.MaxValue) + throw OutOfRange("System.Int16", value.ToString(CultureInfo.InvariantCulture), $"{short.MinValue} to {short.MaxValue}"); + + return (short)value; + } + + protected static sbyte ReadSByte(ref MessagePackReader reader) + { + var value = ReadSignedInteger(ref reader, "System.SByte"); + if (value < sbyte.MinValue || value > sbyte.MaxValue) + throw OutOfRange("System.SByte", value.ToString(CultureInfo.InvariantCulture), $"{sbyte.MinValue} to {sbyte.MaxValue}"); + + return (sbyte)value; + } + + protected static byte ReadByte(ref MessagePackReader reader) + { + var value = ReadUnsignedInteger(ref reader, "System.Byte"); + if (value > byte.MaxValue) + throw OutOfRange("System.Byte", value.ToString(CultureInfo.InvariantCulture), $"0 to {byte.MaxValue}"); + + return (byte)value; + } + + protected static ushort ReadUInt16(ref MessagePackReader reader) + { + var value = ReadUnsignedInteger(ref reader, "System.UInt16"); + if (value > ushort.MaxValue) + throw OutOfRange("System.UInt16", value.ToString(CultureInfo.InvariantCulture), $"0 to {ushort.MaxValue}"); + + return (ushort)value; + } + + protected static uint ReadUInt32(ref MessagePackReader reader) + { + var value = ReadUnsignedInteger(ref reader, "System.UInt32"); + if (value > uint.MaxValue) + throw OutOfRange("System.UInt32", value.ToString(CultureInfo.InvariantCulture), $"0 to {uint.MaxValue}"); + + return (uint)value; + } + + protected static ulong ReadUInt64(ref MessagePackReader reader) + => ReadUnsignedInteger(ref reader, "System.UInt64"); + + /// + /// Reads a written as the unsigned integer of its UTF-16 code unit. + /// + protected static char ReadChar(ref MessagePackReader reader) + { + var value = ReadUnsignedInteger(ref reader, "System.Char"); + if (value > char.MaxValue) + throw OutOfRange("System.Char", value.ToString(CultureInfo.InvariantCulture), $"0 to {(int)char.MaxValue}"); + + return (char)value; + } + + /// + /// Reads a . MessagePack float32 (what the generator writes) is read exactly; + /// a float64 on the wire is accepted only when it fits in a float32, so a too-large double is + /// rejected instead of silently becoming infinity. + /// + protected static float ReadSingle(ref MessagePackReader reader) + { + var wide = reader.ReadDouble(); + var narrow = (float)wide; + if (float.IsInfinity(narrow) && !double.IsInfinity(wide)) + throw new MessagePackSerializationException( + $"The floating-point value [{wide.ToString("R", CultureInfo.InvariantCulture)}] on the wire is outside the range of [System.Single]."); + + return narrow; + } } diff --git a/src/core/Akka.Serialization.V2/MessagePackSizes.cs b/src/core/Akka.Serialization.V2/MessagePackSizes.cs index 8bd2fb40f64..14c1319bb00 100644 --- a/src/core/Akka.Serialization.V2/MessagePackSizes.cs +++ b/src/core/Akka.Serialization.V2/MessagePackSizes.cs @@ -44,6 +44,12 @@ public static class MessagePackSizes /// The value; double encoding is always nine bytes. public static int SizeOfDouble(double _) => 9; + /// + /// Returns the encoded size of a single-precision float value. + /// + /// The value; float encoding is always five bytes (MessagePack float32). + public static int SizeOfSingle(float _) => 5; + /// /// Returns the encoded size of a 32-bit integer value. /// @@ -56,6 +62,12 @@ public static class MessagePackSizes /// The value whose variable-length encoded size is being computed. public static int SizeOfInt64(long value) => MessagePackWriter.GetEncodedLength(value); + /// + /// Returns the encoded size of an unsigned 64-bit integer value. + /// + /// The value whose variable-length encoded size is being computed. + public static int SizeOfUInt64(ulong value) => MessagePackWriter.GetEncodedLength(value); + /// /// Returns the encoded size of an enum value written using the generated int32 convention. /// From e9be19235bf81d45532a2f420a8df0e20ddddb3f Mon Sep 17 00:00:00 2001 From: Aaron Stannard Date: Fri, 2 Oct 2026 21:08:09 +0000 Subject: [PATCH 3/5] Formatter collection tests: cover UnknownSize, drop duplicates Add a test that runs a formatter returning UnknownSize at element, key and value position. Drop hand-built byte tests that the formatter-* wire snapshots already pin, the one-formatter-field golden check, and the AKKASG-free control diagnostics test. Rename the snapshot theory so it names formatter shapes only. --- .../FormatterCollectionDiagnosticsSpec.cs | 9 -- .../FormatterCollectionSpec.cs | 149 +++++------------- .../GeneratorGoldenFormatterCollectionSpec.cs | 25 --- .../WireFormatSnapshotFormatterSpec.cs | 4 +- 4 files changed, 43 insertions(+), 144 deletions(-) diff --git a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs index 507df50ef9f..9c470bd81df 100644 --- a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionDiagnosticsSpec.cs @@ -85,13 +85,4 @@ public void Should_ReportOnlyTheFirstUnusableMember_When_AKeyAndAValueAreBothUnu run.Errors.Select(d => d.Id).Should().Equal("AKKASG003"); } - - [Fact(DisplayName = "Should_AcceptTheFormatter_When_AFormatterIsRegisteredForAnUnsupportedForeignType")] - public void Should_AcceptTheFormatter_When_AFormatterIsRegisteredForAnUnsupportedForeignType() - { - var run = Run(ForeignFormatterAttribute, "[property: AkkaField(1)] Foreign A, [property: AkkaField(2)] List B"); - - run.Errors.Should().BeEmpty(); - run.Result.GeneratedSources.Keys.Should().Contain("SampleSerializer.AkkaSerialization.g.cs"); - } } diff --git a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs index 37e3dbd6c49..a30b2ecf636 100644 --- a/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/FormatterCollectionSpec.cs @@ -159,23 +159,6 @@ public void Should_WriteFormatterBytesAsArrayElements_When_ListOfAddress() _serializer.ToBinary(message).Should().Equal(expected); } - [Fact(DisplayName = "Should_WriteFormatterBytesForKeysAndValues_When_DictionaryOfAddressToAddress")] - public void Should_WriteFormatterBytesForKeysAndValues_When_DictionaryOfAddressToAddress() - { - var message = new AddressToAddressMessage(new Dictionary { [Local] = Remote }); - - var expected = WriteBytes((ref MessagePackWriter writer) => - { - writer.WriteMapHeader(1); - writer.Write(1); - writer.WriteMapHeader(1); - new AddressFormatter().Write(ref writer, Local); - new AddressFormatter().Write(ref writer, Remote); - }); - - _serializer.ToBinary(message).Should().Equal(expected); - } - [Fact(DisplayName = "Should_WriteSameBytesAsFieldPosition_When_FormattedTypeIsAFieldAndAnElement")] public void Should_WriteSameBytesAsFieldPosition_When_FormattedTypeIsAFieldAndAnElement() { @@ -187,23 +170,6 @@ public void Should_WriteSameBytesAsFieldPosition_When_FormattedTypeIsAFieldAndAn asElement.Should().Equal(asField.Take(2).Concat(new byte[] { 0x91 }).Concat(asField.Skip(2))); } - [Fact(DisplayName = "Should_WriteNilForNullElements_When_FormattedElementIsNull")] - public void Should_WriteNilForNullElements_When_FormattedElementIsNull() - { - var message = new NullableAddressElementsMessage(new List { null, Local }); - - var expected = WriteBytes((ref MessagePackWriter writer) => - { - writer.WriteMapHeader(1); - writer.Write(1); - writer.WriteArrayHeader(2); - writer.WriteNil(); - new AddressFormatter().Write(ref writer, Local); - }); - - _serializer.ToBinary(message).Should().Equal(expected); - } - // ------------------------------------------------------------------------------------------ // Custom formatters: a reference type, a value type (plain and Nullable), and IActorRef // ------------------------------------------------------------------------------------------ @@ -230,27 +196,6 @@ public void Should_RoundTripReferenceFormatter_When_UsedAsElementKeyAndValue() _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); } - [Fact(DisplayName = "Should_UseTheFormatterEncoding_When_ReferenceFormatterIsAnElement")] - public void Should_UseTheFormatterEncoding_When_ReferenceFormatterIsAnElement() - { - var message = new TagPositions(new List { new("a") }, null, null, null, null, null); - - var expected = WriteBytes((ref MessagePackWriter writer) => - { - writer.WriteMapHeader(6); - writer.Write(1); - writer.WriteArrayHeader(1); - writer.Write("tag:a"); // PositionTagFormatter's own wire form, not a nested { 1: "a" } map - for (var field = 2; field <= 6; field++) - { - writer.Write(field); - writer.WriteNil(); - } - }); - - _serializer.ToBinary(message).Should().Equal(expected); - } - [Fact(DisplayName = "Should_RoundTripValueTypeFormatter_When_UsedAsElementKeyAndNullableValue")] public void Should_RoundTripValueTypeFormatter_When_UsedAsElementKeyAndNullableValue() { @@ -273,32 +218,6 @@ public void Should_RoundTripValueTypeFormatter_When_UsedAsElementKeyAndNullableV _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); } - [Fact(DisplayName = "Should_WriteNilForNullElements_When_ValueTypeFormatterElementIsNullable")] - public void Should_WriteNilForNullElements_When_ValueTypeFormatterElementIsNullable() - { - var message = new CelsiusPositions(null, null, new List { null, new PositionCelsius(2.5) }, default, null, null); - - var expected = WriteBytes((ref MessagePackWriter writer) => - { - writer.WriteMapHeader(6); - writer.Write(1); - writer.WriteNil(); - writer.Write(2); - writer.WriteNil(); - writer.Write(3); - writer.WriteArrayHeader(2); - writer.WriteNil(); - writer.Write(2.5); // PositionCelsiusFormatter writes a bare float64, no wrapper - for (var field = 4; field <= 6; field++) - { - writer.Write(field); - writer.WriteNil(); - } - }); - - _serializer.ToBinary(message).Should().Equal(expected); - } - [Fact(DisplayName = "Should_RoundTripActorRefs_When_CustomFormatterOverridesNativeEncodingInCollections")] public void Should_RoundTripActorRefs_When_CustomFormatterOverridesNativeEncodingInCollections() { @@ -320,33 +239,6 @@ public void Should_RoundTripActorRefs_When_CustomFormatterOverridesNativeEncodin _serializer.SizeHint(message).Should().Be(_serializer.ToBinary(message).Length); } - [Fact(DisplayName = "Should_UseTheCustomActorRefFormatter_When_ActorRefIsAnElement")] - public void Should_UseTheCustomActorRefFormatter_When_ActorRefIsAnElement() - { - var path = Akka.Serialization.Serialization.SerializedActorPath(_system.DeadLetters); - var message = new RefPositions(new List { _system.DeadLetters }, null, null, null, ImmutableArray.Empty); - - var expected = WriteBytes((ref MessagePackWriter writer) => - { - writer.WriteMapHeader(5); - writer.Write(1); - writer.WriteArrayHeader(1); - writer.WriteArrayHeader(2); // PositionRefFormatter's own wire form: ["ref", path] - writer.Write("ref"); - writer.Write(path); - writer.Write(2); - writer.WriteNil(); - writer.Write(3); - writer.WriteNil(); - writer.Write(4); - writer.WriteNil(); - writer.Write(5); - writer.WriteArrayHeader(0); - }); - - _serializer.ToBinary(message).Should().Equal(expected); - } - [Fact(DisplayName = "Should_KeepNativeActorRefEncoding_When_NoActorRefFormatterIsRegistered")] public void Should_KeepNativeActorRefEncoding_When_NoActorRefFormatterIsRegistered() { @@ -411,6 +303,22 @@ public void Should_KeepNativeEncoding_When_ANativeCollectionSharesAMessageWithAF RoundTrip(message).Natives.Should().Equal("x", "y"); } + [Fact(DisplayName = "Should_ReportUnknownSizeAndStillRoundTrip_When_AFormatterCannotSizeAnElementKeyOrValue")] + public void Should_ReportUnknownSizeAndStillRoundTrip_When_AFormatterCannotSizeAnElementKeyOrValue() + { + var element = new UnsizedElementMessage(new List { new("a"), new("b") }); + var key = new UnsizedKeyMessage(new Dictionary { [new UnsizedTag("k")] = 1 }); + var value = new UnsizedValueMessage(new Dictionary { [1] = new UnsizedTag("v") }); + + _serializer.SizeHint(element).Should().Be(Akka.Serialization.SerializerV2.UnknownSize); + _serializer.SizeHint(key).Should().Be(Akka.Serialization.SerializerV2.UnknownSize); + _serializer.SizeHint(value).Should().Be(Akka.Serialization.SerializerV2.UnknownSize); + + RoundTrip(element).Tags.Should().Equal(new UnsizedTag("a"), new UnsizedTag("b")); + RoundTrip(key).Tags.Should().BeEquivalentTo(new Dictionary { [new UnsizedTag("k")] = 1 }); + RoundTrip(value).Tags.Should().BeEquivalentTo(new Dictionary { [1] = new UnsizedTag("v") }); + } + private TMessage RoundTrip(TMessage message) where TMessage : class, IFormatterPositionProtocol { @@ -513,6 +421,7 @@ public int SizeOf(IActorRef value) => [AkkaSerializerFormatter] [AkkaSerializerFormatter] [AkkaSerializerFormatter] +[AkkaSerializerFormatter] [AkkaSerializerFormatter] public sealed partial class FormatterPositionSerializer : AkkaSerializer { @@ -600,3 +509,27 @@ public sealed record ActorPathPositions( public sealed record MixedMessage( [property: AkkaField(1)] List Natives, [property: AkkaField(2)] List
Addresses) : IFormatterPositionProtocol; + +/// A formatter that cannot cheaply size its value, so it reports . +public sealed record UnsizedTag(string Value); + +public sealed class UnsizedTagFormatter : IAkkaMessagePackFormatter +{ + public void Write(ref MessagePackWriter writer, UnsizedTag value) => writer.Write(value.Value); + + public UnsizedTag Read(ref MessagePackReader reader) => new(reader.ReadString() ?? string.Empty); + + public int SizeOf(UnsizedTag value) => Akka.Serialization.SerializerV2.UnknownSize; +} + +[AkkaSerializable(Manifest = "unsized-element-v1")] +public sealed record UnsizedElementMessage( + [property: AkkaField(1)] List Tags) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "unsized-key-v1")] +public sealed record UnsizedKeyMessage( + [property: AkkaField(1)] Dictionary Tags) : IFormatterPositionProtocol; + +[AkkaSerializable(Manifest = "unsized-value-v1")] +public sealed record UnsizedValueMessage( + [property: AkkaField(1)] Dictionary Tags) : IFormatterPositionProtocol; diff --git a/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs index 9fbfc04c5de..82689a53a87 100644 --- a/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/GeneratorGoldenFormatterCollectionSpec.cs @@ -114,29 +114,4 @@ public void Should_CompileCleanly_When_GeneratedFromFormatterPositionCorpus() .Select(diagnostic => diagnostic.ToString()) .Should().BeEmpty("generated code must compile with no errors and no warnings under #nullable enable"); } - - [Fact(DisplayName = "Should_EmitOneFormatterFieldPerTarget_When_ManyPositionsShareAFormatter")] - public void Should_EmitOneFormatterFieldPerTarget_When_ManyPositionsShareAFormatter() - { - var generated = GeneratorTestHarness.Run(Source).GeneratedSources[HintName]; - - // Address is used in three positions but is one formatter instance. - CountOccurrences(generated, "private readonly global::Akka.Serialization.V2.AddressFormatter ").Should().Be(1); - CountOccurrences(generated, "private readonly global::FormatterGolden.CelsiusFormatter ").Should().Be(1); - CountOccurrences(generated, " = new global::Akka.Serialization.V2.AddressFormatter(").Should().Be(1); - CountOccurrences(generated, " = new global::FormatterGolden.CelsiusFormatter(system)").Should().Be(1); - } - - private static int CountOccurrences(string text, string value) - { - var count = 0; - var index = 0; - while ((index = text.IndexOf(value, index, System.StringComparison.Ordinal)) >= 0) - { - count++; - index += value.Length; - } - - return count; - } } diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs index a762e6ebe1b..f60cde6fbb4 100644 --- a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs @@ -59,9 +59,9 @@ public async ValueTask DisposeAsync() public static IEnumerable CaseNames() => AllCaseNames.Select(name => new object[] { name }); - [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized")] + [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_FormatterCollectionShapesAreSerialized")] [MemberData(nameof(CaseNames))] - public Task Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized(string caseName) + public Task Should_MatchCommittedSnapshot_When_FormatterCollectionShapesAreSerialized(string caseName) { var wireCase = BuildCase(caseName); var hexDump = HexDumpFormatter.Format(caseName, wireCase.MessageType, wireCase.Manifest, wireCase.SerializerId, wireCase.Bytes); From cbff3dea3324b9f604bbd8a5d9510773783311f0 Mon Sep 17 00:00:00 2001 From: Aaron Stannard Date: Fri, 2 Oct 2026 21:18:33 +0000 Subject: [PATCH 4/5] Native scalars: range-check TimeSpan reads, widen range-check coverage, trim duplicates TimeSpan now reads through a range-checked helper like the other types, so a wire value beyond int64 or of the wrong type throws a MessagePackSerializationException naming System.TimeSpan. The integer and float readers also name the type when the wire holds the wrong MessagePack type. The out-of-range theory now covers every type at field, Nullable, list element and dictionary value position, with uint64-beyond-int64, below -float.MaxValue and wrong-wire-type cases, and checks the message names the type. Drop the test of MessagePackWriter's own integer widths and the all-null byte check the scalars-nullable-all-null snapshot already pins. Rename the scalar snapshot theory. --- .../AkkaSerializerGenerator.Emission.cs | 4 +- ...alizer.AkkaSerialization.g.cs.verified.txt | 8 +- .../NativeScalarSpec.cs | 172 ++++++++++-------- .../WireFormatSnapshotScalarSpec.cs | 4 +- .../Akka.Serialization.V2/AkkaSerializer.cs | 26 ++- 5 files changed, 125 insertions(+), 89 deletions(-) diff --git a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs index 28424443891..0e03d284536 100644 --- a/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs +++ b/src/core/Akka.Serialization.V2.Generators/AkkaSerializerGenerator.Emission.cs @@ -1853,7 +1853,7 @@ private static void GenerateReadFieldValue(CodeWriter w, ImmutableDictionary w.Write((short)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "short {0}", value); - Encode((ref MessagePackWriter w) => w.Write((ushort)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "ushort {0}", value); - } - - foreach (var value in new[] { -1, -32, -33, -128, -129, -32768 }) - Encode((ref MessagePackWriter w) => w.Write((short)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "short {0}", value); - - foreach (var value in new[] { -1, -32, -33, -128 }) - Encode((ref MessagePackWriter w) => w.Write((sbyte)value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((long)value)), "sbyte {0}", value); - - foreach (var value in new byte[] { 0, 127, 128, 255 }) - Encode((ref MessagePackWriter w) => w.Write(value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "byte {0}", value); - - foreach (var value in new[] { 0u, 127u, 128u, 255u, 256u, 65535u, 65536u, uint.MaxValue }) - Encode((ref MessagePackWriter w) => w.Write(value)).Should().Equal(Encode((ref MessagePackWriter w) => w.Write((ulong)value)), "uint {0}", value); - } - - private static byte[] Encode(EncodeAction action) - { - var buffer = new ArrayBufferWriter(); - var writer = new MessagePackWriter(buffer); - action(ref writer); - writer.Flush(); - return buffer.WrittenMemory.ToArray(); - } - - private delegate void EncodeAction(ref MessagePackWriter writer); - // ------------------------------------------------------------------------------------------ // Nullable variants // ------------------------------------------------------------------------------------------ @@ -194,8 +159,8 @@ public void Should_RoundTripValues_When_EveryNullableScalarIsPopulatedAtItsLimit } } - [Fact(DisplayName = "Should_WriteNilForNullAndTheSameBytesAsNonNullable_When_ScalarsAreNullable")] - public void Should_WriteNilForNullAndTheSameBytesAsNonNullable_When_ScalarsAreNullable() + [Fact(DisplayName = "Should_WriteTheSameBytesAsNonNullable_When_ANullableScalarIsPresent")] + public void Should_WriteTheSameBytesAsNonNullable_When_ANullableScalarIsPresent() { var populated = _serializer.ToBinary(new NullableScalarsMessage( TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A')); @@ -203,12 +168,8 @@ public void Should_WriteNilForNullAndTheSameBytesAsNonNullable_When_ScalarsAreNu TimeSpan.FromTicks(300), 1.5f, -200, 200, -5, 40000, 3000000000u, ulong.MaxValue, 'A')); // A present nullable value is written exactly as the non-nullable one: same map, same bytes. + // (An absent one is nil; the scalars-nullable-all-null snapshot pins those bytes.) populated.Should().Equal(nonNullable); - - var allNull = _serializer.ToBinary(new NullableScalarsMessage(null, null, null, null, null, null, null, null, null)); - allNull.Should().Equal( - 0x89, - 0x01, 0xc0, 0x02, 0xc0, 0x03, 0xc0, 0x04, 0xc0, 0x05, 0xc0, 0x06, 0xc0, 0x07, 0xc0, 0x08, 0xc0, 0x09, 0xc0); } // ------------------------------------------------------------------------------------------ @@ -301,32 +262,58 @@ public void Should_WriteBareEncodedElements_When_ScalarsAreInAList() // Reads range-check: a value the target type cannot hold throws, it never truncates // ------------------------------------------------------------------------------------------ - [Theory(DisplayName = "Should_Throw_When_WireValueDoesNotFitTheScalarType")] - [InlineData("short above max", "int16-v1", 32768L)] - [InlineData("short below min", "int16-v1", -32769L)] - [InlineData("short from a uint64 beyond int64", "int16-v1", ulong.MaxValue)] - [InlineData("sbyte above max", "sbyte-v1", 128L)] - [InlineData("sbyte below min", "sbyte-v1", -129L)] - [InlineData("byte above max", "byte-v1", 256L)] - [InlineData("byte negative", "byte-v1", -1L)] - [InlineData("ushort above max", "uint16-v1", 65536L)] - [InlineData("ushort negative", "uint16-v1", -1L)] - [InlineData("uint above max", "uint32-v1", 4294967296L)] - [InlineData("uint negative", "uint32-v1", -1L)] - [InlineData("ulong negative", "uint64-v1", -1L)] - [InlineData("ulong most negative", "uint64-v1", long.MinValue)] - [InlineData("char above max", "char-v1", 65536L)] - [InlineData("char negative", "char-v1", -1L)] - [InlineData("float from a double beyond float range", "single-v1", 1e300d)] - [InlineData("float from a string", "single-v1", "not a number")] - [InlineData("short from a string", "int16-v1", "not a number")] - public void Should_Throw_When_WireValueDoesNotFitTheScalarType(string caseName, string manifest, object wireValue) + /// + /// Where each scalar type can be hand-fed a bad wire value: its single-field message, the field index in + /// , the field index of a collection that holds it as a list-like + /// element in , and (for three types) a dictionary whose VALUE it is. + /// + private sealed record ScalarSpec(string TypeName, string FieldManifest, int NullableIndex, int ElementIndex, int MapValueIndex = 0, object? MapKey = null); + + private static readonly ScalarSpec[] Specs = { - var buffer = new ArrayBufferWriter(); - var writer = new MessagePackWriter(buffer); - writer.WriteMapHeader(1); - writer.Write(1); - switch (wireValue) + new("System.Int16", "int16-v1", 3, 3), + new("System.SByte", "sbyte-v1", 5, 5, MapValueIndex: 15, MapKey: 0L), + new("System.Byte", "byte-v1", 4, 4), + new("System.UInt16", "uint16-v1", 6, 6), + new("System.UInt32", "uint32-v1", 7, 7), + new("System.UInt64", "uint64-v1", 8, 8, MapValueIndex: 10, MapKey: 0L), + new("System.Char", "char-v1", 9, 9), + new("System.TimeSpan", "timespan-v1", 1, 1, MapValueIndex: 13, MapKey: "k"), + new("System.Single", "single-v1", 2, 2), + }; + + private static IEnumerable BadWireValues(string typeName) => typeName switch + { + "System.Int16" => new object[] { 32768L, -32769L, ulong.MaxValue, "text" }, + "System.SByte" => new object[] { 128L, -129L, ulong.MaxValue, "text" }, + "System.Byte" => new object[] { 256L, -1L, ulong.MaxValue, "text" }, + "System.UInt16" => new object[] { 65536L, -1L, ulong.MaxValue, "text" }, + "System.UInt32" => new object[] { 4294967296L, -1L, ulong.MaxValue, "text" }, + "System.UInt64" => new object[] { -1L, long.MinValue, "text" }, + "System.Char" => new object[] { 65536L, -1L, ulong.MaxValue, "text" }, + "System.TimeSpan" => new object[] { ulong.MaxValue, "text" }, + "System.Single" => new object[] { 1e300d, -1e300d, "text" }, + _ => throw new ArgumentOutOfRangeException(nameof(typeName), typeName, null) + }; + + public static IEnumerable RangeCases() + { + foreach (var spec in Specs) + { + foreach (var value in BadWireValues(spec.TypeName)) + { + yield return new[] { spec.TypeName, "field", value }; + yield return new[] { spec.TypeName, "nullable", value }; + yield return new[] { spec.TypeName, "element", value }; + if (spec.MapValueIndex != 0) + yield return new[] { spec.TypeName, "map-value", value }; + } + } + } + + private static void WriteWire(ref MessagePackWriter writer, object value) + { + switch (value) { case long signed: writer.Write(signed); @@ -338,30 +325,52 @@ public void Should_Throw_When_WireValueDoesNotFitTheScalarType(string caseName, writer.Write(floating); break; default: - writer.Write((string)wireValue); + writer.Write((string)value); break; } - - writer.Flush(); - - Action read = () => _serializer.FromBinary(buffer.WrittenMemory.ToArray(), manifest); - - read.Should().Throw(caseName); } - [Fact(DisplayName = "Should_NameTheTargetType_When_WireValueOverflowsAShort")] - public void Should_NameTheTargetType_When_WireValueOverflowsAShort() + [Theory(DisplayName = "Should_ThrowNamingTheType_When_WireValueCannotBeReadAsTheScalarType")] + [MemberData(nameof(RangeCases))] + public void Should_ThrowNamingTheType_When_WireValueCannotBeReadAsTheScalarType(string typeName, string position, object wireValue) { + var spec = Specs.Single(candidate => candidate.TypeName == typeName); var buffer = new ArrayBufferWriter(); var writer = new MessagePackWriter(buffer); + string manifest; writer.WriteMapHeader(1); - writer.Write(1); - writer.Write(70000); + switch (position) + { + case "field": + manifest = spec.FieldManifest; + writer.Write(1); + WriteWire(ref writer, wireValue); + break; + case "nullable": + manifest = "nullable-scalars-v1"; + writer.Write(spec.NullableIndex); + WriteWire(ref writer, wireValue); + break; + case "element": + manifest = "scalar-collections-v1"; + writer.Write(spec.ElementIndex); + writer.WriteArrayHeader(1); + WriteWire(ref writer, wireValue); + break; + default: + manifest = "scalar-collections-v1"; + writer.Write(spec.MapValueIndex); + writer.WriteMapHeader(1); + WriteWire(ref writer, spec.MapKey!); + WriteWire(ref writer, wireValue); + break; + } + writer.Flush(); - Action read = () => _serializer.FromBinary(buffer.WrittenMemory.ToArray(), "int16-v1"); + Action read = () => _serializer.FromBinary(buffer.WrittenMemory.ToArray(), manifest); - read.Should().Throw().WithMessage("*70000*System.Int16*"); + read.Should().Throw($"{typeName} at {position}").WithMessage($"*[{typeName}]*"); } [Theory(DisplayName = "Should_ReadTheValue_When_WireIntegerWasWrittenWithAWiderOrNarrowerWidth")] @@ -491,3 +500,6 @@ public sealed record ScalarOnlyChar([property: AkkaField(1)] char Value) : INati [AkkaSerializable(Manifest = "single-v1")] public sealed record ScalarOnlySingle([property: AkkaField(1)] float Value) : INativeScalarProtocol; + +[AkkaSerializable(Manifest = "timespan-v1")] +public sealed record ScalarOnlyTimeSpan([property: AkkaField(1)] TimeSpan Value) : INativeScalarProtocol; diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs index 25a56777c1d..fb14b8c76f6 100644 --- a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs @@ -55,9 +55,9 @@ public async ValueTask DisposeAsync() public static IEnumerable CaseNames() => AllCaseNames.Select(name => new object[] { name }); - [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized")] + [Theory(DisplayName = "Should_MatchCommittedSnapshot_When_NativeScalarShapesAreSerialized")] [MemberData(nameof(CaseNames))] - public Task Should_MatchCommittedSnapshot_When_FormatterAndScalarShapesAreSerialized(string caseName) + public Task Should_MatchCommittedSnapshot_When_NativeScalarShapesAreSerialized(string caseName) { var wireCase = BuildCase(caseName); var hexDump = HexDumpFormatter.Format(caseName, wireCase.MessageType, wireCase.Manifest, wireCase.SerializerId, wireCase.Bytes); diff --git a/src/core/Akka.Serialization.V2/AkkaSerializer.cs b/src/core/Akka.Serialization.V2/AkkaSerializer.cs index 8ffd6947c52..cee4e75905c 100644 --- a/src/core/Akka.Serialization.V2/AkkaSerializer.cs +++ b/src/core/Akka.Serialization.V2/AkkaSerializer.cs @@ -413,6 +413,10 @@ private static long ReadSignedInteger(ref MessagePackReader reader, string targe throw new MessagePackSerializationException( $"The integer on the wire does not fit in a signed 64-bit integer, so it cannot be read as [{targetType}].", ex); } + catch (MessagePackSerializationException ex) + { + throw new MessagePackSerializationException($"The value on the wire cannot be read as [{targetType}]: {ex.Message}", ex); + } } private static ulong ReadUnsignedInteger(ref MessagePackReader reader, string targetType) @@ -426,11 +430,22 @@ private static ulong ReadUnsignedInteger(ref MessagePackReader reader, string ta throw new MessagePackSerializationException( $"The integer on the wire is negative or too large for an unsigned 64-bit integer, so it cannot be read as [{targetType}].", ex); } + catch (MessagePackSerializationException ex) + { + throw new MessagePackSerializationException($"The value on the wire cannot be read as [{targetType}]: {ex.Message}", ex); + } } private static MessagePackSerializationException OutOfRange(string targetType, string value, string range) => new($"The integer [{value}] on the wire is outside the range of [{targetType}] ({range})."); + /// + /// Reads a written as the signed integer of its . + /// Every int64 is a valid tick count, so only a value beyond int64 (or a non-integer) is rejected. + /// + protected static TimeSpan ReadTimeSpan(ref MessagePackReader reader) + => new(ReadSignedInteger(ref reader, "System.TimeSpan")); + protected static short ReadInt16(ref MessagePackReader reader) { var value = ReadSignedInteger(ref reader, "System.Int16"); @@ -498,7 +513,16 @@ protected static char ReadChar(ref MessagePackReader reader) /// protected static float ReadSingle(ref MessagePackReader reader) { - var wide = reader.ReadDouble(); + double wide; + try + { + wide = reader.ReadDouble(); + } + catch (MessagePackSerializationException ex) + { + throw new MessagePackSerializationException($"The value on the wire cannot be read as [System.Single]: {ex.Message}", ex); + } + var narrow = (float)wide; if (float.IsInfinity(narrow) && !double.IsInfinity(wide)) throw new MessagePackSerializationException( From 91a76114b0d5797c96e1faf1502eb50e1655df58 Mon Sep 17 00:00:00 2001 From: Aaron Stannard Date: Fri, 2 Oct 2026 22:57:05 +0000 Subject: [PATCH 5/5] Import Akka.TestKit for HexDumpFormatter after merging dev (#8725 moved it) --- .../WireFormatSnapshotFormatterSpec.cs | 1 + .../Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs index f60cde6fbb4..310bfd2f5bb 100644 --- a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotFormatterSpec.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Threading.Tasks; using Akka.Actor; +using Akka.TestKit; using VerifyXunit; using Xunit; diff --git a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs index fb14b8c76f6..1d6cef7828c 100644 --- a/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Threading.Tasks; using Akka.Actor; +using Akka.TestKit; using VerifyXunit; using Xunit;