Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Communication.Tests/Grpc/ProtoContractTests.cs
T
Joseph Doherty 9b5cb3dd9d feat(comm): batch site→central stream events over gRPC (R2)
Every AttributeValueChanged/AlarmStateChanged rode its own gRPC message on
SiteStreamService; at target scale that is ~37.5k messages/s/site of pure
framing overhead. Coalesce them, additively, with no new RPC.

Wire (sitestream.proto, regenerated via docker/regen-proto.sh sitestream):
  InstanceStreamRequest.batching_supported = 3
  SiteStreamRequest.batching_supported     = 2
  SiteStreamEvent.batch                    = 4  (new oneof case)
  SiteStreamEventBatch { repeated SiteStreamEvent events = 1 }

The proto3 default of batching_supported IS the negotiation, and it is
load-bearing: a batch frame reaches a pre-R2 central as EventOneofCase.None,
whose ConvertToDomainEvent returns null — the whole batch would vanish with
no error anywhere. An old central cannot set the flag so it never receives
one; an old site ignores the unknown request field and keeps sending
per-event frames, which the new client's ForEachEvent handles as the
single-event case. Both skew directions are covered by tests that go through
a real proto serialize/parse round-trip.

Server: SiteStreamEventBatcher, a per-subscriber pump replacing the handler's
await-foreach/WriteAsync loop and byte-identical to it at a cap of 1. It
never delays a lone event — it drains the already-queued backlog for free and
lingers only once a backlog is proven — emits a single-event buffer as a
plain frame, preserves order and per-event Timestamps exactly, and flushes
what is buffered when the send channel's writer completes. It sits DOWNSTREAM
of StreamRelayActor's bounded DropOldest channel, so it changes framing only
and does not move the burst ceiling (deferred register row 31, which lives in
the shared publish stage upstream of the BroadcastHub).

Client: sets the flag on both subscriptions and unpacks in order into the
existing per-event pipeline, so SiteAlarmAggregatorActor,
DebugStreamBridgeActor, consumer-keepalive/orphan logic,
reconnect-on-graceful-completion, generation fencing, the (siteId, endpoint)
factory key and IsLive semantics are untouched.

Options (validated): GrpcStreamBatchMaxEvents 100 (1 disables),
GrpcStreamBatchWindow 25 ms — validated strictly under 250 ms, the load
test's end-to-end P99 threshold. Measured worst case (trickle-with-backlog,
window-bound rather than cap-bound): P50 13.8 ms, P99 25.4 ms, max 25.8 ms;
cap-bound case sent 600 queued events in 6 frames.

Telemetry: histogram scadabridge.site.stream.batch_size tagged by stream
kind, recorded only on negotiated streams (per-event otherwise). It rides
ScadaBridgeTelemetry.MeterName, already in the ObservedMeters allowlist.

Docs: Component-Communication.md gains an Event Batching section; CLAUDE.md's
gRPC streaming bullet records the wire shape and the negotiation rationale.
2026-08-15 03:39:59 -04:00

119 lines
4.5 KiB
C#

using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.ScadaBridge.Communication.Grpc;
namespace ZB.MOM.WW.ScadaBridge.Communication.Tests.Grpc;
/// <summary>
/// Guardrail tests that verify all oneof variants in SiteStreamEvent have
/// corresponding conversion handlers. Adding a new proto field without
/// implementing the conversion will cause these tests to fail.
/// </summary>
public class ProtoContractTests
{
/// <summary>
/// The set of EventOneofCase values we handle in ConvertToDomainEvent.
/// Update this array when adding a new oneof variant.
/// </summary>
private static readonly SiteStreamEvent.EventOneofCase[] HandledCases =
[
SiteStreamEvent.EventOneofCase.AttributeChanged,
SiteStreamEvent.EventOneofCase.AlarmChanged
];
/// <summary>
/// Oneof variants that are NOT per-event payloads and so are deliberately absent from
/// <see cref="HandledCases"/>. <c>Batch</c> (R2) is a framing envelope: it is unpacked
/// by <see cref="SiteStreamGrpcClient.ForEachEvent"/> into the per-event cases above
/// BEFORE conversion, and never reaches <c>ConvertToDomainEvent</c> as a whole frame.
/// </summary>
private static readonly SiteStreamEvent.EventOneofCase[] FramingCases =
[
SiteStreamEvent.EventOneofCase.Batch
];
[Fact]
public void AllOneofVariants_HaveConversionHandlers()
{
var allCases = System.Enum.GetValues<SiteStreamEvent.EventOneofCase>()
.Where(c => c != SiteStreamEvent.EventOneofCase.None)
.ToArray();
var accountedFor = HandledCases.Concat(FramingCases).ToArray();
Assert.Equal(allCases.Length, accountedFor.Length);
foreach (var c in allCases)
Assert.Contains(c, accountedFor);
}
[Fact]
public void BatchFrame_IsUnpackedIntoPerEventCases_NotConvertedWhole()
{
// The framing case's contract: ForEachEvent hands the per-event cases to the
// handler in order, and ConvertToDomainEvent is never asked to make sense of the
// envelope itself (it would return null, silently dropping the whole batch).
var inner = new[]
{
CreateTestEvent(SiteStreamEvent.EventOneofCase.AttributeChanged),
CreateTestEvent(SiteStreamEvent.EventOneofCase.AlarmChanged)
};
var frame = new SiteStreamEvent
{
CorrelationId = "test",
Batch = new SiteStreamEventBatch { Events = { inner } }
};
Assert.Null(SiteStreamGrpcClient.ConvertToDomainEvent(frame));
var seen = new List<SiteStreamEvent.EventOneofCase>();
SiteStreamGrpcClient.ForEachEvent(frame, e => seen.Add(e.EventCase));
Assert.Equal(
[SiteStreamEvent.EventOneofCase.AttributeChanged, SiteStreamEvent.EventOneofCase.AlarmChanged],
seen);
}
[Theory]
[InlineData(SiteStreamEvent.EventOneofCase.AttributeChanged)]
[InlineData(SiteStreamEvent.EventOneofCase.AlarmChanged)]
public void ConvertToDomainEvent_HandlesAllOneofVariants(SiteStreamEvent.EventOneofCase eventCase)
{
var evt = CreateTestEvent(eventCase);
var result = SiteStreamGrpcClient.ConvertToDomainEvent(evt);
Assert.NotNull(result);
}
private static SiteStreamEvent CreateTestEvent(SiteStreamEvent.EventOneofCase eventCase)
{
var ts = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow);
return eventCase switch
{
SiteStreamEvent.EventOneofCase.AttributeChanged => new SiteStreamEvent
{
CorrelationId = "test",
AttributeChanged = new AttributeValueUpdate
{
InstanceUniqueName = "Site1.Inst1",
AttributePath = "Path",
AttributeName = "Attr",
Value = "42",
Quality = Quality.Good,
Timestamp = ts
}
},
SiteStreamEvent.EventOneofCase.AlarmChanged => new SiteStreamEvent
{
CorrelationId = "test",
AlarmChanged = new AlarmStateUpdate
{
InstanceUniqueName = "Site1.Inst1",
AlarmName = "HighTemp",
State = AlarmStateEnum.AlarmStateActive,
Priority = 1,
Timestamp = ts
}
},
_ => throw new ArgumentOutOfRangeException(nameof(eventCase), eventCase, "Unhandled event case")
};
}
}