Skip to content
66 changes: 55 additions & 11 deletions docs/articles/serialization/source-generated-serialization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>` for any supported value type, plus nullable reference types | See [Nullable fields](#nullable-fields). |
Expand All @@ -337,17 +337,35 @@ public sealed record ShippingAddress(
| Read-only collections | `IReadOnlyCollection<T>` (for example a `ReadOnlyCollection<T>`) | |
| Immutable collections | `ImmutableArray<T>`, `ImmutableList<T>`, `ImmutableHashSet<T>`, `ImmutableDictionary<TKey,TValue>` | 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). |
| 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<T>` or `ISet<T>`. Use `ImmutableHashSet<T>` instead. Also not supported: a
dictionary whose key type is `object`. Any of these fails
compilation with **AKKASG003**, naming the offending property and type.
**Not supported:** a mutable `HashSet<T>` or `ISet<T>`. Use `ImmutableHashSet<T>` 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<T>` 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

Expand Down Expand Up @@ -874,8 +892,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<TTarget, TFormatter>]` to the `[AkkaSerializer]` class instead. It routes
every field of type `TTarget` through a hand-written `IAkkaMessagePackFormatter<TTarget>`
implementation:
every field of type `TTarget`, and every collection element, dictionary key, and dictionary value of
type `TTarget`, through a hand-written `IAkkaMessagePackFormatter<TTarget>` implementation:

```csharp
public interface IAkkaMessagePackFormatter<T>
Expand Down Expand Up @@ -954,6 +972,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<T>`, `IReadOnlyList<T>`, `IReadOnlyCollection<T>`,
`ImmutableArray<T>`, `ImmutableList<T>`, `ImmutableHashSet<T>`, the three dictionary shapes (as key
or as value), and nested combinations such as `Dictionary<string, List<Address>>`. With
`[AkkaSerializerFormatter<Address, AddressFormatter>]` registered, these all work:

```csharp
[AkkaSerializable(Manifest = "route-v1")]
public sealed record Route(
[property: AkkaField(1)] List<Address> Hops,
[property: AkkaField(2)] Dictionary<Address, long> LastSeen,
[property: AkkaField(3)] ImmutableArray<Address> 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<T>` 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<IActorRef>`
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
Expand Down Expand Up @@ -1065,11 +1109,11 @@ 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<T>]` 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`. |
| 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`. |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading