feat(galaxy): handle the replay-gap sentinel and sparse-array values
v2-ci / build (push) Successful in 4m39s
v2-ci / unit-tests (push) Failing after 19m35s

Closes the two follow-ups left open by the MxGateway 0.2.0 bump. Reading the
gateway's own contract first changed what each of them is, and one of my earlier
claims was simply wrong -- both corrections are recorded below.

Replay gap
----------
A sentinel MxEvent carries family = UNSPECIFIED, so it fell through EventPump's
family switch into the default drop: we silently ignored a documented MUST ("you
missed events -- discard local state and re-snapshot"). It is now intercepted and
answered by re-issuing SubscribeBulk for every tracked subscription, since
MXAccess delivers an initial value per item on subscribe -- re-subscribing IS the
re-snapshot. It does not restart the event pump (the stream carrying the sentinel
is healthy, and the handler runs on that stream's own read loop, so disposing the
pump from there would deadlock on itself), it does not block the read loop, and
re-entry is gated so a burst collapses to one pass instead of a subscribe storm
per sentinel.

Handled on the READ loop, not in the dispatch loop, because everything past that
point is subject to newest-dropped channel pressure -- and "you missed events" is
the one signal whose loss is unrecoverable. Pinned by a test that fills the
channel and still expects the sentinel.

⚠️ This cannot fire in the shipped configuration, and I did not pretend otherwise
or paper over it by enabling resume. The gateway emits the sentinel only for a
stream opened with after_worker_sequence > 0; GatewayGalaxySubscriber passes 0,
which the gateway treats as "fresh stream, not a resume -- plain attach, no
replay, no sentinel". Enabling resume is a larger and genuinely delicate change:
the sequence is only meaningful within ONE gateway session, our reconnect
recreates the session, and replaying a remembered sequence against a fresh
session sets the server's live watermark ABOVE every event it is about to send --
silencing the stream instead of recovering it. That deserves its own change with
a live gate, which I cannot run from here.

Sparse arrays -- correcting the last commit message
---------------------------------------------------
I wrote that the bump "makes handling it possible" on the decode path. That is
wrong: MxSparseArray is documented write-only, the gateway expands it before
forwarding, and "the worker never receives or produces it". So the decode path
is unreachable by contract and the write path has no use for it either -- it is a
wire compaction for a WHOLE-array write, not a partial update (unmentioned
indices are RESET, deliberately, because the gateway cannot read-modify-write
without racing the provider). It is therefore the wrong primitive for an OPC UA
IndexRange write, which expects untouched elements preserved -- and WriteRequest
carries no IndexRange in the first place.

It is decoded anyway, as contract defence: the alternative if a future gateway
ever emits one is a silent null published under Good quality. Fill semantics
mirror the gateway's own SparseArrayExpander exactly (epoch for Time, empty
string, Integer widening to long[] when any element is int64) so a value that
round-trips through a write reads back as the same CLR array.

Also: the decoder is now total by contract, since it runs inside the dispatch
loop where an escaping exception kills dispatch for the life of the pump. A
malformed payload degrades instead of throwing.

A real defect found in the same code
------------------------------------
A stream the GATEWAY completes -- a closed or evicted session -- ends the RPC
without an error, so nothing threw, the supervisor was never notified, and the
pump exited silently. GetHealth() kept reporting Healthy, which also means the
#527 comms-loss watchdog could never trip, because it requires a non-Healthy
state. The driver went permanently deaf with no signal anywhere. This one is
live, unlike the two above. Now reported as a fault; the falsification control is
the existing CleanShutdown_DoesNotInvokeOnStreamFault, since our own disposal
also ends the stream and must NOT be reported.

Value kinds we cannot represent are now counted and warned once rather than
published as an indistinguishable null. The status is deliberately NOT downgraded
to Bad: nothing can reach that branch today, and changing what an OPC UA client
sees for a live shape is not a change to make without a gate. The counter exists
so the next person has evidence instead of a guess.

Verified: 330 Galaxy tests green (12 new), plus Galaxy.Browser 21, Runtime 558,
Core 351; full solution builds 0 errors with the warning census unchanged. Every
new test was falsified first -- disabling the gap interception reds 3 of 4 (the
throwing-callback test passes vacuously when the callback never runs, by
construction), disabling sparse decode plus the representability signal reds all
7 decoder tests, and both were restored and re-verified green.

Docs: the Galaxy.Performance invariant was stated as received = dispatched +
dropped + in-flight, which this breaks -- a sentinel is received but never enters
the channel -- so it now reads + replay_gaps. Galaxy.md gains the three
operational notes; DriverLifecycle.md records that "reaches a non-Healthy state"
is an obligation a driver can silently fail to meet, which is the general shape
of the clean-end bug.
This commit is contained in:
Joseph Doherty
2026-08-12 02:56:17 -04:00
parent d14a75dfef
commit 4769044f88
8 changed files with 824 additions and 45 deletions
@@ -101,6 +101,13 @@ public sealed class GalaxyDriver
private EventPump? _eventPump;
private readonly Lock _pumpLock = new();
/// <summary>
/// Re-entry gate for the replay-gap re-snapshot (0 = idle, 1 = running). Interlocked
/// rather than a lock because the setter runs on the event pump's read loop and must
/// never block it.
/// </summary>
private int _resnapshotInFlight;
// IAlarmSource implementation. Production-side acks route through
// GatewayGalaxyAlarmAcknowledger which calls the session-less
// MxGatewayClient.AcknowledgeAlarmAsync RPC; alarm transitions arrive on the
@@ -464,6 +471,25 @@ public sealed class GalaxyDriver
// completed loop. Recreate the pump so the replayed subscriptions have a consumer.
RestartEventPumpForReplay();
var tagCount = await ResubscribeAllAsync(entries, cancellationToken).ConfigureAwait(false);
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Count, tagCount);
}
/// <summary>
/// Re-issues <c>SubscribeBulk</c> for every tracked subscription and rebinds the registry
/// with the item handles the gateway returned. Shared by the reconnect replay path and
/// the replay-gap re-snapshot — the difference between them is the event pump, which
/// replay must recreate (its loop died with the stream) and a gap must NOT touch (the
/// stream carrying the sentinel is still healthy and still delivering).
/// </summary>
/// <returns>The number of tag references re-subscribed.</returns>
private async Task<int> ResubscribeAllAsync(
IReadOnlyList<(long SubscriptionId, IReadOnlyList<TagBinding> Bindings)> entries,
CancellationToken cancellationToken)
{
var tagCount = 0;
foreach (var (subscriptionId, oldBindings) in entries)
{
@@ -473,7 +499,7 @@ public sealed class GalaxyDriver
.ToArray();
if (refs.Length == 0) continue;
var results = await _subscriber
var results = await _subscriber!
.SubscribeBulkAsync(refs, _options.MxAccess.PublishingIntervalMs, cancellationToken)
.ConfigureAwait(false);
@@ -493,9 +519,7 @@ public sealed class GalaxyDriver
tagCount += refs.Length;
}
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Count, tagCount);
return tagCount;
}
/// <summary>
@@ -1065,13 +1089,89 @@ public sealed class GalaxyDriver
_subscriber!, _subscriptions, _logger,
channelCapacity: _options.MxAccess.EventPumpChannelCapacity,
clientName: _options.MxAccess.ClientName,
onStreamFault: OnEventPumpStreamFault);
onStreamFault: OnEventPumpStreamFault,
onReplayGap: OnEventPumpReplayGap);
_eventPump.OnDataChange += OnPumpDataChange;
_eventPump.Start();
return _eventPump;
}
}
/// <summary>
/// Replay-gap callback for the <see cref="EventPump"/>. The gateway told us it evicted
/// events we can never receive, so every cached value may be stale by an unknown amount.
/// The contract's remedy is to re-snapshot, which for this driver means re-issuing
/// SubscribeBulk: MXAccess delivers an initial value per item on subscribe, so the
/// re-subscribe is the re-snapshot.
/// </summary>
/// <remarks>
/// Three things this must not do, in order of how badly they would bite:
/// <list type="bullet">
/// <item>It must <b>not</b> restart the event pump. A gap is not a fault — the stream
/// that delivered the sentinel is healthy — and this runs ON that stream's read loop,
/// so disposing the pump from here would deadlock on its own loop.</item>
/// <item>It must <b>not</b> block. The read loop is stopped for as long as this runs,
/// and re-subscribing thousands of tags is a round-trip per subscription, so the work
/// goes to the thread pool and the loop returns to draining the stream immediately.</item>
/// <item>It must <b>not</b> stack. Re-entry is gated, so a burst of sentinels (or one
/// arriving while a re-snapshot is still running) collapses to a single pass rather
/// than queueing a subscribe storm per sentinel.</item>
/// </list>
/// <see cref="GalaxyReconnectOptions.ReplayOnSessionLost"/> is honoured here even though the
/// trigger is not a session loss: an operator who turned driver-side re-subscription off
/// is delegating recovery to the gateway, and quietly re-subscribing behind that choice
/// on a different trigger would be the same surprise they opted out of.
/// </remarks>
private void OnEventPumpReplayGap(ReplayGap gap)
{
if (_subscriber is null) return;
if (!_options.Reconnect.ReplayOnSessionLost)
{
_logger.LogWarning(
"GalaxyDriver {InstanceId} replay-gap re-snapshot skipped — ReplayOnSessionLost=false. " +
"Values missed between worker_sequence {RequestedAfter} and {OldestAvailable} stay stale " +
"until the gateway or an operator re-primes them.",
_driverInstanceId, gap.RequestedAfterSequence, gap.OldestAvailableSequence);
return;
}
if (Interlocked.Exchange(ref _resnapshotInFlight, 1) == 1)
{
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay-gap re-snapshot already in flight — coalescing.",
_driverInstanceId);
return;
}
_ = Task.Run(async () =>
{
try
{
var entries = _subscriptions.SnapshotEntries();
if (entries.Count == 0) return;
var tagCount = await ResubscribeAllAsync(entries, CancellationToken.None).ConfigureAwait(false);
_logger.LogInformation(
"GalaxyDriver {InstanceId} replay-gap re-snapshot completed — {SubCount} subscriptions, {TagCount} tags re-subscribed",
_driverInstanceId, entries.Count, tagCount);
}
catch (Exception ex)
{
// Never surface into the pump's read loop; the stream is still healthy and
// must keep draining. A failed re-snapshot leaves stale values, which the
// next reconnect or subscribe will correct.
_logger.LogWarning(ex,
"GalaxyDriver {InstanceId} replay-gap re-snapshot failed — cached values may stay stale.",
_driverInstanceId);
}
finally
{
Interlocked.Exchange(ref _resnapshotInFlight, 0);
}
});
}
/// <summary>
/// Stream-fault callback for the <see cref="EventPump"/>. The gw StreamEvents
/// stream faulted (transient gateway drop, network blip, gw restart). Forward
@@ -47,12 +47,19 @@ internal sealed class EventPump : IAsyncDisposable
private static readonly Counter<long> EventsDropped =
Meter.CreateCounter<long>("galaxy.events.dropped", unit: "{event}",
description: "MxEvents dropped because the bounded channel was full (newest-dropped).");
private static readonly Counter<long> ReplayGapsObserved =
Meter.CreateCounter<long>("galaxy.events.replay_gaps", unit: "{gap}",
description: "Replay-gap sentinels received — the gateway evicted events we can never see.");
private static readonly Counter<long> ValuesUndecodable =
Meter.CreateCounter<long>("galaxy.events.undecodable", unit: "{event}",
description: "Data-change events carrying a value kind this driver cannot represent.");
private readonly IGalaxySubscriber _subscriber;
private readonly SubscriptionRegistry _registry;
private readonly ILogger _logger;
private readonly Func<long, ISubscriptionHandle> _handleFactory;
private readonly Action<Exception>? _onStreamFault;
private readonly Action<ReplayGap>? _onReplayGap;
private readonly Channel<MxEvent> _channel;
private readonly KeyValuePair<string, object?> _clientTag;
private readonly CancellationTokenSource _cts = new();
@@ -60,6 +67,7 @@ internal sealed class EventPump : IAsyncDisposable
private Task? _loop;
private Task? _dispatchLoop;
private bool _disposed;
private int _undecodableWarned;
/// <summary>Occurs when a data change event is received from the Galaxy subscriber.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
@@ -72,6 +80,10 @@ internal sealed class EventPump : IAsyncDisposable
/// <param name="channelCapacity">The bounded channel capacity for buffering events.</param>
/// <param name="clientName">The client name for metric tagging; if null, uses "&lt;unknown&gt;".</param>
/// <param name="onStreamFault">Optional callback invoked when the stream faults.</param>
/// <param name="onReplayGap">
/// Optional callback invoked when the gateway reports a replay gap. The contract
/// obliges the client to re-snapshot; see <see cref="HandleReplayGap"/>.
/// </param>
public EventPump(
IGalaxySubscriber subscriber,
SubscriptionRegistry registry,
@@ -79,13 +91,15 @@ internal sealed class EventPump : IAsyncDisposable
Func<long, ISubscriptionHandle>? handleFactory = null,
int channelCapacity = DefaultChannelCapacity,
string? clientName = null,
Action<Exception>? onStreamFault = null)
Action<Exception>? onStreamFault = null,
Action<ReplayGap>? onReplayGap = null)
{
_subscriber = subscriber ?? throw new ArgumentNullException(nameof(subscriber));
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
_logger = logger ?? NullLogger.Instance;
_handleFactory = handleFactory ?? (id => new GalaxySubscriptionHandle(id));
_onStreamFault = onStreamFault;
_onReplayGap = onReplayGap;
if (channelCapacity < 1)
{
@@ -130,6 +144,17 @@ internal sealed class EventPump : IAsyncDisposable
if (ct.IsCancellationRequested) break;
EventsReceived.Add(1, _clientTag);
// The replay-gap sentinel is a control signal, not data, and is handled HERE
// rather than in the dispatch loop for one reason: everything past this point
// is subject to newest-dropped channel pressure, and a dropped "you have
// missed events" signal is the one loss that cannot be recovered from later.
// It carries no item payload, so there is nothing to fan out downstream.
if (ev.ReplayGap is { } gap)
{
HandleReplayGap(gap);
continue;
}
// Newest-dropped: TryWrite fast-paths the common case (channel has room).
// When full we count the drop and continue reading the gw stream so
// back-pressure doesn't propagate upstream.
@@ -138,6 +163,23 @@ internal sealed class EventPump : IAsyncDisposable
EventsDropped.Add(1, _clientTag);
}
}
// Falling out of the loop without an exception means the SERVER completed the
// stream — a closed or evicted gateway session, not a transport failure. That is
// just as fatal to this driver as a fault (the pump is now dead and no further
// data-change events can ever arrive) but it raises nothing, so without this the
// pump exits silently, the supervisor is never told, GetHealth() keeps reporting
// Healthy, and the #527 comms-loss watchdog never trips either — it requires a
// non-Healthy state. The result is a driver that is permanently, invisibly deaf.
if (!ct.IsCancellationRequested)
{
var cause = new InvalidOperationException(
"The gateway completed the StreamEvents stream without an error. The session was " +
"closed or evicted server-side; the event pump cannot receive further events.");
_logger.LogWarning(
"Galaxy EventPump stream was completed by the gateway — notifying reconnect supervisor.");
NotifyStreamFault(cause);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -151,15 +193,7 @@ internal sealed class EventPump : IAsyncDisposable
// The gw StreamEvents stream faulted. Signal the reconnect supervisor so it
// drives reopen → replay. Without this the stream silently dies and a
// transient gateway drop permanently stops data-change notifications.
if (_onStreamFault is not null)
{
try { _onStreamFault(ex); }
catch (Exception cbEx)
{
_logger.LogWarning(cbEx,
"Galaxy EventPump stream-fault callback threw — supervisor may not have been notified.");
}
}
NotifyStreamFault(ex);
}
finally
{
@@ -168,6 +202,54 @@ internal sealed class EventPump : IAsyncDisposable
}
}
private void NotifyStreamFault(Exception cause)
{
if (_onStreamFault is null) return;
try { _onStreamFault(cause); }
catch (Exception cbEx)
{
_logger.LogWarning(cbEx,
"Galaxy EventPump stream-fault callback threw — supervisor may not have been notified.");
}
}
/// <summary>
/// Handles the gateway's replay-gap sentinel: events between the sequence we asked to
/// resume after and the oldest the gateway still retains were evicted and can never be
/// delivered. The contract is explicit that a client "MUST treat a present replay_gap as
/// 'you missed events — discard local state and re-snapshot'".
/// </summary>
/// <remarks>
/// ⚠️ <b>This is unreachable in the current configuration and that is deliberate.</b>
/// The gateway emits the sentinel only on a stream opened with
/// <c>after_worker_sequence &gt; 0</c>; <c>GatewayGalaxySubscriber</c> passes 0, which the
/// gateway treats as "fresh stream, not a resume: plain attach, no replay, no sentinel".
/// It is implemented anyway because the alternative — the sentinel falling through the
/// family switch into the default drop, which is what happened before, since a sentinel
/// carries <c>family = UNSPECIFIED</c> — means silently ignoring a documented MUST if
/// resume is ever switched on. Enabling resume is a larger change than it looks: the
/// sequence is only meaningful within one gateway session, and our reconnect path
/// recreates the session, so a remembered sequence replayed against a fresh session
/// would set the server's live watermark above every event it is about to send.
/// </remarks>
private void HandleReplayGap(ReplayGap gap)
{
ReplayGapsObserved.Add(1, _clientTag);
_logger.LogWarning(
"Galaxy event stream reported a replay gap: events after worker_sequence {RequestedAfter} " +
"up to {OldestAvailable} were evicted from the gateway's replay ring and cannot be " +
"recovered. Forcing a re-snapshot of every active subscription.",
gap.RequestedAfterSequence, gap.OldestAvailableSequence);
if (_onReplayGap is null) return;
try { _onReplayGap(gap); }
catch (Exception ex)
{
_logger.LogWarning(ex,
"Galaxy EventPump replay-gap callback threw — the re-snapshot may not have run.");
}
}
private async Task DispatchLoopAsync(CancellationToken ct)
{
try
@@ -230,7 +312,25 @@ internal sealed class EventPump : IAsyncDisposable
private DataValueSnapshot ToSnapshot(MxEvent ev)
{
var value = MxValueDecoder.Decode(ev.Value);
if (!MxValueDecoder.TryDecode(ev.Value, out var value))
{
// The status is deliberately NOT downgraded here. Publishing null-under-Good is
// dishonest, but changing what an OPC UA client sees for a live shape is not a
// change to make blind: today nothing can reach this branch (every declared
// MxValue kind decodes), so it only fires on a wire type a future gateway adds.
// Surfacing it on a counter first means the next person has evidence to act on
// rather than a guess. Warn once per pump — a broken producer would flood.
ValuesUndecodable.Add(1, _clientTag);
if (Interlocked.Exchange(ref _undecodableWarned, 1) == 0)
{
_logger.LogWarning(
"Galaxy event for item handle {ItemHandle} carried a value kind this driver cannot " +
"represent ({KindCase}); publishing null under the event's own quality. Further " +
"occurrences are counted on galaxy.events.undecodable but not logged.",
ev.ItemHandle, ev.Value?.KindCase);
}
}
var statusCode = ev.Statuses.Count > 0
? StatusCodeMap.FromMxStatus(ev.Statuses[0], _logger)
: StatusCodeMap.FromQualityByte((byte)(ev.Quality & 0xFF), _logger);
@@ -11,47 +11,190 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// back to the <c>raw_value</c> bytes so a forward-compatible MXAccess deployment
/// doesn't lose data on the wire — the consumer can opt to deserialise the bytes.
/// </summary>
/// <remarks>
/// ⚠️ <b>Every method here must be total — it must never throw.</b> The only caller is
/// <see cref="EventPump"/>'s dispatch loop, and an exception escaping into that loop
/// terminates it permanently: the pump keeps reading the gateway stream while nothing
/// is ever dispatched again. So a malformed payload returns <c>false</c> from
/// <see cref="TryDecode"/> rather than raising, and every bound/shape check below is a
/// guard rather than an assertion.
/// </remarks>
internal static class MxValueDecoder
{
/// <summary>Decodes a gateway MxValue into a boxed CLR object.</summary>
/// <param name="value">The MxValue to decode, or null.</param>
/// <returns>The decoded boxed CLR value, or null when <paramref name="value"/> is null or carries a null MxValue.</returns>
/// <returns>
/// The decoded boxed CLR value, or null when <paramref name="value"/> is null, carries a
/// null MxValue, or cannot be represented. Prefer <see cref="TryDecode"/> when the caller
/// needs to tell a genuine null apart from an unrepresentable value.
/// </returns>
public static object? Decode(MxValue? value)
{
if (value is null) return null;
if (value.IsNull) return null;
TryDecode(value, out var decoded);
return decoded;
}
return value.KindCase switch
/// <summary>
/// Decodes a gateway MxValue, reporting whether it was representable at all.
/// </summary>
/// <param name="value">The MxValue to decode, or null.</param>
/// <param name="decoded">
/// The decoded boxed CLR value. Null both for a genuine null and for a value this driver
/// cannot represent — <paramref name="decoded"/> alone cannot distinguish the two.
/// </param>
/// <returns>
/// <c>true</c> when the value was decoded, including the genuine-null cases (a null
/// reference or <see cref="MxValue.IsNull"/>). <c>false</c> when the payload carries a
/// kind this driver has no CLR representation for — a null published under a
/// <c>Good</c> quality would otherwise be indistinguishable from a real null, which is
/// how a new wire type would go silently missing.
/// </returns>
public static bool TryDecode(MxValue? value, out object? decoded)
{
decoded = null;
if (value is null) return true;
if (value.IsNull) return true;
switch (value.KindCase)
{
MxValue.KindOneofCase.BoolValue => value.BoolValue,
MxValue.KindOneofCase.Int32Value => value.Int32Value,
MxValue.KindOneofCase.Int64Value => value.Int64Value,
MxValue.KindOneofCase.FloatValue => value.FloatValue,
MxValue.KindOneofCase.DoubleValue => value.DoubleValue,
MxValue.KindOneofCase.StringValue => value.StringValue,
MxValue.KindOneofCase.TimestampValue => DecodeTimestamp(value.TimestampValue),
MxValue.KindOneofCase.ArrayValue => DecodeArray(value.ArrayValue),
MxValue.KindOneofCase.RawValue => value.RawValue.ToByteArray(),
_ => null,
};
case MxValue.KindOneofCase.BoolValue: decoded = value.BoolValue; return true;
case MxValue.KindOneofCase.Int32Value: decoded = value.Int32Value; return true;
case MxValue.KindOneofCase.Int64Value: decoded = value.Int64Value; return true;
case MxValue.KindOneofCase.FloatValue: decoded = value.FloatValue; return true;
case MxValue.KindOneofCase.DoubleValue: decoded = value.DoubleValue; return true;
case MxValue.KindOneofCase.StringValue: decoded = value.StringValue; return true;
case MxValue.KindOneofCase.TimestampValue: decoded = DecodeTimestamp(value.TimestampValue); return true;
case MxValue.KindOneofCase.RawValue: decoded = value.RawValue.ToByteArray(); return true;
case MxValue.KindOneofCase.ArrayValue: return TryDecodeArray(value.ArrayValue, out decoded);
case MxValue.KindOneofCase.SparseArrayValue: return TryDecodeSparseArray(value.SparseArrayValue, out decoded);
default: return false;
}
}
private static DateTime? DecodeTimestamp(Timestamp? ts) => ts?.ToDateTime();
private static object? DecodeArray(MxArray? array)
private static bool TryDecodeArray(MxArray? array, out object? decoded)
{
if (array is null) return null;
decoded = null;
if (array is null) return false;
return array.ValuesCase switch
switch (array.ValuesCase)
{
MxArray.ValuesOneofCase.BoolValues => array.BoolValues.Values.ToArray(),
MxArray.ValuesOneofCase.Int32Values => array.Int32Values.Values.ToArray(),
MxArray.ValuesOneofCase.Int64Values => array.Int64Values.Values.ToArray(),
MxArray.ValuesOneofCase.FloatValues => array.FloatValues.Values.ToArray(),
MxArray.ValuesOneofCase.DoubleValues => array.DoubleValues.Values.ToArray(),
MxArray.ValuesOneofCase.StringValues => array.StringValues.Values.ToArray(),
MxArray.ValuesOneofCase.TimestampValues => array.TimestampValues.Values.Select(t => t.ToDateTime()).ToArray(),
_ => null,
};
case MxArray.ValuesOneofCase.BoolValues: decoded = array.BoolValues.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.Int32Values: decoded = array.Int32Values.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.Int64Values: decoded = array.Int64Values.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.FloatValues: decoded = array.FloatValues.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.DoubleValues: decoded = array.DoubleValues.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.StringValues: decoded = array.StringValues.Values.ToArray(); return true;
case MxArray.ValuesOneofCase.TimestampValues:
decoded = array.TimestampValues.Values.Select(t => t.ToDateTime()).ToArray();
return true;
default: return false;
}
}
/// <summary>
/// Expands a sparse array into the dense CLR array it denotes: every index the payload
/// names carries its value, and every index it does not carries the element type's
/// default.
/// </summary>
/// <remarks>
/// <para>
/// ⚠️ <b>Per the gateway contract this cannot arrive inbound.</b> <c>MxSparseArray</c> is
/// documented write-only — the gateway expands it into a full <c>MxArray</c> before
/// forwarding, and "the worker never receives or produces it". This branch therefore
/// exists as contract defence, not as an expected path: if a future gateway ever emits
/// one, the alternative is a silent null published under the event's own (likely Good)
/// quality, which loses the reading with nothing to show for it.
/// </para>
/// <para>
/// The fill semantics deliberately mirror the gateway's own <c>SparseArrayExpander</c>
/// rather than inventing a reading: unmentioned indices are <b>reset to the element
/// default, not preserved</b> (the gateway cannot read-modify-write without racing the
/// provider), <c>Time</c> defaults to the Unix epoch because the expander fills
/// <c>Timestamp{0,0}</c>, and <c>Integer</c> widens to <c>long[]</c> if any element
/// carries an <c>int64</c> — matching the expander's own Int32/Int64 sub-array choice.
/// </para>
/// <para>
/// Malformed payloads the gateway would have rejected outright (zero/oversized length,
/// out-of-range index) are tolerated here rather than thrown, because this side is a
/// consumer: an out-of-range index is skipped, a duplicate index is last-wins.
/// </para>
/// </remarks>
private static bool TryDecodeSparseArray(MxSparseArray? sparse, out object? decoded)
{
decoded = null;
if (sparse is null) return false;
if (sparse.TotalLength == 0 || sparse.TotalLength > (uint)Array.MaxLength) return false;
var length = (int)sparse.TotalLength;
var elements = sparse.Elements;
switch (sparse.ElementDataType)
{
case MxDataType.Boolean:
return Fill(new bool[length], elements, v => v.BoolValue, out decoded);
// The expander picks its Integer sub-array width from the element kinds, since a
// sparse payload carries no CLR array to infer it from. Mirror that exactly, or a
// round-trip through the gateway would change the published CLR element type.
case MxDataType.Integer when UsesInt64(elements):
return Fill(new long[length], elements, ReadInt64, out decoded);
case MxDataType.Integer:
return Fill(new int[length], elements, v => v.Int32Value, out decoded);
case MxDataType.Float:
return Fill(new float[length], elements, v => v.FloatValue, out decoded);
case MxDataType.Double:
return Fill(new double[length], elements, v => v.DoubleValue, out decoded);
case MxDataType.String:
var strings = new string[length];
Array.Fill(strings, string.Empty);
return Fill(strings, elements, v => v.StringValue ?? string.Empty, out decoded);
case MxDataType.Time:
var times = new DateTime[length];
Array.Fill(times, DateTime.UnixEpoch);
return Fill(times, elements, v => v.TimestampValue?.ToDateTime() ?? DateTime.UnixEpoch, out decoded);
default:
// Structs, enums, references and the rest are not scalar element types the
// expander supports either — there is nothing meaningful to build.
return false;
}
}
private static bool Fill<T>(
T[] target,
IReadOnlyList<MxSparseElement> elements,
Func<MxValue, T> read,
out object? decoded)
{
foreach (var element in elements)
{
if (element.Index >= (uint)target.Length) continue; // out of range — skip, never throw
if (element.Value is null) continue; // leave the default in place
target[(int)element.Index] = read(element.Value);
}
decoded = target;
return true;
}
private static bool UsesInt64(IReadOnlyList<MxSparseElement> elements)
{
foreach (var element in elements)
{
if (element.Value?.KindCase == MxValue.KindOneofCase.Int64Value) return true;
}
return false;
}
private static long ReadInt64(MxValue value) => value.KindCase switch
{
MxValue.KindOneofCase.Int64Value => value.Int64Value,
MxValue.KindOneofCase.Int32Value => value.Int32Value,
_ => 0L,
};
}