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..0e03d284536 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("ReadTimeSpan(ref reader)"); + 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..a96a2d27e48 --- /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 = ReadTimeSpan(ref reader); + __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 = ReadTimeSpan(ref reader); + 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 = ReadTimeSpan(ref reader); + __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 = ReadTimeSpan(ref reader); + 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..5df0d649635 --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/NativeScalarSpec.cs @@ -0,0 +1,505 @@ +//----------------------------------------------------------------------- +// +// 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); + } + + // ------------------------------------------------------------------------------------------ + // 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_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')); + 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. + // (An absent one is nil; the scalars-nullable-all-null snapshot pins those bytes.) + populated.Should().Equal(nonNullable); + } + + // ------------------------------------------------------------------------------------------ + // 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 + // ------------------------------------------------------------------------------------------ + + /// + /// 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 = + { + 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); + break; + case ulong unsigned: + writer.Write(unsigned); + break; + case double floating: + writer.Write(floating); + break; + default: + writer.Write((string)value); + break; + } + } + + [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); + 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(), manifest); + + read.Should().Throw($"{typeName} at {position}").WithMessage($"*[{typeName}]*"); + } + + [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; + +[AkkaSerializable(Manifest = "timespan-v1")] +public sealed record ScalarOnlyTimeSpan([property: AkkaField(1)] TimeSpan Value) : INativeScalarProtocol; 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 new file mode 100644 index 00000000000..1d6cef7828c --- /dev/null +++ b/src/core/Akka.Serialization.V2.Tests/WireFormatSnapshotScalarSpec.cs @@ -0,0 +1,117 @@ +//----------------------------------------------------------------------- +// +// 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 Akka.TestKit; +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_NativeScalarShapesAreSerialized")] + [MemberData(nameof(CaseNames))] + 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); + + 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..cee4e75905c 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,143 @@ 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); + } + 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) + { + 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); + } + 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"); + 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) + { + 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( + $"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. ///