Reeve Docs

Docs / Development

JSON source generation

System.Text.Json can bind a type in two ways. Reflection inspects the type the first time it is serialized, at runtime. A source-generated JsonSerializerContext produces the same metadata at compile time. The seams below, where Reeve serializes a plugin's or an adapter's own type, accept generated metadata as a JsonTypeInfo<T>.

What you get from it:

  • A missing type fails the build. MyJson.Default.MyRecord exists only if the context lists MyRecord. With reflection, the same mistake shows up as an exception, or an empty object, in a running plugin.
  • NativeAOT and trimming. An out-of-process adapter or workload written in .NET can publish with PublishAot. Reflection-bound serialization does not work there at all.
  • Cheaper first call and serialization. Generated metadata skips the reflection warm-up for each type.

Declaring a context

A context is a partial class in your own assembly. The options on it decide how the JSON looks, so pick the options of the seam you pass it to:

// Values in IIntegrationSettingsStore: web defaults, the same JSON the reflection overload stores.
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(SyncCursor))]
internal sealed partial class PluginJson : JsonSerializerContext { }

// Payloads on the workload session plane (Reeve.Adapters.Protocol): camelCase, nulls omitted.
[JsonSourceGenerationOptions(
    PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(DownstreamPing))]
internal sealed partial class WireJson : JsonSerializerContext { }

The seams

Seam Reflection overload Generated-metadata overload
Stored values (IIntegrationSettingsStore) SaveValueAsync<T>(key, setting, value, at, ct), GetValueAsync<T>(key, setting, ct) SaveValueAsync(key, setting, value, PluginJson.Default.SyncCursor, at, ct), GetValueAsync(key, setting, PluginJson.Default.SyncCursor, ct)
Session-plane data kinds (SessionProtocol) CreateData<T>(payload, kind), TryReadData<T>(envelope, kind) CreateData(payload, kind, WireJson.Default.DownstreamPing), TryReadData(envelope, kind, WireJson.Default.DownstreamPing)

Values written by one overload are read by the other, as long as the context uses the options in the table. The reflection overloads carry [RequiresUnreferencedCode] and [RequiresDynamicCode]. So does the MQTT path (MqttExtensions), which has no generated-metadata form: a trim- or AOT-safe adapter uses the session plane.

The session plane's own records (frames, DeviceStateMessage, DiscoveredDeviceMessage, AdapterHealthMessage) already go through AdapterProtocolJsonContext, so CreateData(state) needs nothing from you.

Making the analyzer enforce it

An in-process (native) plugin always runs JIT-compiled inside the host. Turn on the analyzers only, so every call to a reflection overload becomes a build error:

<PropertyGroup>
  <EnableTrimAnalyzer>true</EnableTrimAnalyzer>
  <EnableAotAnalyzer>true</EnableAotAnalyzer>
  <WarningsAsErrors>$(WarningsAsErrors);IL2026;IL3050</WarningsAsErrors>
</PropertyGroup>

An out-of-process adapter or workload can go further and publish with <PublishAot>true</PublishAot>. Reeve.Adapters.Protocol is IsAotCompatible. Under NativeAOT, an object value in telemetry or metadata can hold only a type AdapterProtocolJsonContext lists: string, bool, int, long, double, float, decimal, DateTime, DateTimeOffset, Guid, JsonElement, string[], int[], double[], object[], List<object>, Dictionary<string, object> and Dictionary<string, string> (plus byte[], which the generator adds on its own). Any other runtime type, such as a byte or a List<string>, throws NotSupportedException. The same holds for a trimmed JIT publish (PublishTrimmed), which turns reflection off too. An untrimmed JIT process writes such values through reflection.

Every SDK package a plugin or workload ships with is IsAotCompatible: Reeve.Contracts, Reeve.PluginAbstractions, Reeve.PluginAuthoring, Reeve.Discovery.Contracts, Reeve.Ble.Decoding and the adapter-protocol packages. A trim or AOT warning in one of them fails its build. So with the analyzers on, a plugin's warnings come only from its own code. An out-of-process .NET workload can use Reeve.Discovery.Contracts, Reeve.Ble.Decoding and the adapter-protocol packages under PublishAot. So can it use Reeve.Contracts: its dependencies Reeve.Workloads.Abstractions and ReeveWorkflow.Abstractions are IsAotCompatible in their own repositories.

In this repository, a project that sets IsAotCompatible adds $(ReeveAotAnalyzerErrors) from the root Directory.Build.props to its WarningsAsErrors.

Validation attributes on contracts

[MaxLength] and [MinLength] bind by reflection, which the trim analyzer reports. Contracts in an IsAotCompatible package bound a string with [StringLength(max)], or with [StringLength(max, MinimumLength = min)] when it has a lower bound too, and cap a collection with [MaxItems(count)] from Reeve.Contracts.Validation. Both reach the OpenAPI schema, as maxLength and maxItems; [MaxItems] does so only on a positional record parameter, which is where every contract declares it.

An app that trims in partial mode, as the Android release build does, trims every assembly marked trimmable, and IsAotCompatible marks these packages trimmable. If such an app still binds contracts by reflection, it lists them as a TrimmerRootAssembly. Reeve.Mobile does that for Reeve.Contracts, Reeve.Workloads.Abstractions and ReeveWorkflow.Abstractions.