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.
This commit is contained in:
Joseph Doherty
2026-08-15 03:39:59 -04:00
parent 2b74851f96
commit 9b5cb3dd9d
16 changed files with 2150 additions and 131 deletions
@@ -199,19 +199,25 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable
var request = new InstanceStreamRequest
{
CorrelationId = correlationId,
InstanceUniqueName = instanceUniqueName
InstanceUniqueName = instanceUniqueName,
// R2 batch negotiation. Declaring support is safe against ANY site: one that
// predates batching ignores the unknown field and keeps sending per-event
// frames, which ForEachEvent handles as the single-event case.
BatchingSupported = true
};
void Deliver(SiteStreamEvent single)
{
var domainEvent = ConvertToDomainEvent(single);
if (domainEvent != null)
onEvent(domainEvent);
}
await ConsumeStreamAsync(
correlationId,
cts,
() => _client.SubscribeInstance(request, cancellationToken: cts.Token),
evt =>
{
var domainEvent = ConvertToDomainEvent(evt);
if (domainEvent != null)
onEvent(domainEvent);
},
frame => ForEachEvent(frame, Deliver),
onError,
onCompleted);
}
@@ -270,19 +276,23 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable
var request = new SiteStreamRequest
{
CorrelationId = correlationId
CorrelationId = correlationId,
// R2 batch negotiation — see SubscribeAsync.
BatchingSupported = true
};
void Deliver(SiteStreamEvent single)
{
// Site-wide stream is alarm-only by contract; defensively ignore anything else.
if (ConvertToAlarmEvent(single) is { } alarm)
onAlarmEvent(alarm);
}
await ConsumeStreamAsync(
correlationId,
cts,
() => _client.SubscribeSite(request, cancellationToken: cts.Token),
evt =>
{
// Site-wide stream is alarm-only by contract; defensively ignore anything else.
if (ConvertToAlarmEvent(evt) is { } alarm)
onAlarmEvent(alarm);
},
frame => ForEachEvent(frame, Deliver),
onError,
onCompleted,
onConnected);
@@ -451,6 +461,39 @@ public class SiteStreamGrpcClient : IAsyncDisposable, IDisposable
}
}
/// <summary>
/// Unpacks one wire frame into the per-event pipeline (R2 — gRPC event batching).
/// A plain <c>attribute_changed</c>/<c>alarm_changed</c> frame is delivered as-is; a
/// <see cref="SiteStreamEventBatch"/> frame is unpacked <b>in order</b> into the same
/// callback, so every downstream consumer (<c>SiteAlarmAggregatorActor</c>,
/// <c>DebugStreamBridgeActor</c>, the consumer-keepalive/orphan logic, per-event
/// <c>Timestamp</c> fidelity) sees no difference between a batched and an unbatched site.
/// <para>
/// Unpacking is deliberately NON-RECURSIVE: the server never nests a batch inside a
/// batch, and a nested or unknown inner case from a malformed peer is skipped rather
/// than followed. Internal for testability.
/// </para>
/// </summary>
/// <param name="frame">The wire frame received from the site.</param>
/// <param name="handler">Invoked once per contained event, in arrival order.</param>
internal static void ForEachEvent(SiteStreamEvent frame, Action<SiteStreamEvent> handler)
{
if (frame.EventCase != SiteStreamEvent.EventOneofCase.Batch)
{
handler(frame);
return;
}
foreach (var inner in frame.Batch.Events)
{
if (inner.EventCase is SiteStreamEvent.EventOneofCase.AttributeChanged
or SiteStreamEvent.EventOneofCase.AlarmChanged)
{
handler(inner);
}
}
}
/// <summary>
/// Converts a proto SiteStreamEvent to the corresponding domain message.
/// Internal for testability.