using System.Text.Json;
using System.Text.RegularExpressions;
using Grpc.Core;
using Grpc.Net.Client;
using GrpcDataProbe;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using T = ZB.MOM.WW.OtOpcUa.Commons.Protos.Telemetry.V1;
[assembly: HostingStartup(typeof(GrpcDataNodeProbe.NodeProbeStartup))]
namespace GrpcDataNodeProbe;
/// Loaded only by the isolated Docker fixture's explicit hosting-startup assembly.
public sealed class NodeProbeStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder.ConfigureServices(services =>
{
services.AddSingleton();
services.AddSingleton();
services.AddHostedService();
});
}
/// Fixture-only process counter; retains no request identity or payload.
public sealed class InboundDataRequestCounter
{
private long _requests;
public string InstanceId { get; } = Guid.NewGuid().ToString("N");
public long Requests => Interlocked.Read(ref _requests);
public void Record() => Interlocked.Increment(ref _requests);
}
/// Observes HTTP arrivals before the fixture Host's authentication and gRPC pipeline.
public sealed class FixtureDataRequestStartupFilter(InboundDataRequestCounter counter) : IStartupFilter
{
public Action Configure(Action next) => app =>
{
app.Use(nextMiddleware => async context =>
{
if (context.Connection.LocalPort == 4057) counter.Record();
await nextMiddleware(context);
});
next(app);
};
}
/// Bounded, one-shot file requests through the caller's deployed DI registry; no listener.
public sealed partial class NodeProbeWorker(IServiceProvider services) : BackgroundService
{
[GeneratedRegex("^[a-zA-Z0-9][a-zA-Z0-9-]{0,95}$")]
private static partial Regex SafeId();
private object CaptureOriginAccounting()
{
var hub = services.GetService();
var acquisition = services.GetService();
var composition = services.GetService();
return new
{
retainedBytes = hub?.Resources.RetainedBytes, maximumRetainedBytes = hub?.Resources.MaximumBytes,
reservedDrivers = acquisition?.ReservedDriverCount, maximumReservedDrivers = acquisition?.MaxReservations,
acquisitionOwnerSerial = acquisition?.CurrentOwnerSerial, acquisitionControlGeneration = acquisition?.ControlGeneration,
workload = composition?.CaptureWorkloadAccounting(),
sourceIngressCounters = SourceIngressDiagnostics.Capture(),
historyOpenContinuations = composition?.Services.HistoryOpenContinuations,
definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count"
};
}
private static async Task LegacyTelemetryAsync(ProbeCommand command, CancellationToken cancellationToken)
{
var observations = new Dictionary();
var assertions = 0;
void Check(bool condition)
{
if (!condition) throw new InvalidOperationException();
assertions++;
}
try
{
// These are the two run-owned SOURCE nodes, never a caller-supplied URL.
var address = command.ExpectedNodeId switch
{
"source-1:4053" => "http://source-1:4056",
"source-2:4053" => "http://source-2:4056",
_ => throw new InvalidOperationException()
};
Check(command.TimeoutSeconds is >= 1 and <= 20);
var key = Environment.GetEnvironmentVariable("Telemetry__ApiKey");
Check(!string.IsNullOrWhiteSpace(key));
observations["protocol"] = "authenticated gRPC over HTTP/2";
observations["service"] = "telemetry.v1.TelemetryStreamService/Subscribe";
observations["eventClass"] = "DriverHealth";
observations["target"] = new { mode = "Node", expectedClusterId = "SOURCE", expectedNodeId = command.ExpectedNodeId };
using var handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
UseProxy = false,
ConnectTimeout = TimeSpan.FromSeconds(Math.Min(command.TimeoutSeconds, 5))
};
using var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
{
HttpHandler = handler,
MaxReceiveMessageSize = 64 * 1024
});
var client = new T.TelemetryStreamService.TelemetryStreamServiceClient(channel);
var headers = new Metadata { { "authorization", "Bearer " + key } };
using var call = client.Subscribe(new T.TelemetryStreamRequest { CorrelationId = command.Id }, headers,
deadline: DateTime.UtcNow.AddSeconds(command.TimeoutSeconds), cancellationToken: cancellationToken);
while (await call.ResponseStream.MoveNext(cancellationToken))
{
var envelope = call.ResponseStream.Current;
// The production local telemetry hub primes new subscribers with its
// actual driver-health snapshot. Other telemetry is not a substitute.
if (envelope.DriverHealth is not { DriverInstanceId: "source-modbus" } health) continue;
Check(envelope.CorrelationId == command.Id);
Check(health.DriverInstanceId == "source-modbus");
Check(health.HasReportingNodeId);
Check(health.ReportingNodeId == command.ExpectedNodeId);
Check(health.ClusterId == "SOURCE");
observations["driverInstanceId"] = health.DriverInstanceId;
observations["servingNodeId"] = health.ReportingNodeId;
observations["reportingNodeId"] = health.ReportingNodeId;
observations["clusterId"] = health.ClusterId;
observations["authenticatedSnapshotReceived"] = true;
return new(command.Id, command.Operation, true, assertions, observations);
}
return new(command.Id, command.Operation, false, assertions, observations, "SnapshotUnavailable");
}
catch (Exception error) when (error is not OutOfMemoryException)
{
// Headers, credentials and remote exception detail stay out of evidence.
return new(command.Id, command.Operation, false, assertions, observations, error.GetType().Name);
}
}
///
/// A4 (A08/§5.7): listen to THIS node's own authenticated telemetry stream for the command's window and return every
/// alerts transition it carries — the exact feed central's /alerts page and the alarm-history adapter
/// consume. A consumer node must publish none for imported conditions; the SOURCE Primary's list is the positive control.
///
private static async Task AlertTransitionsAsync(ProbeCommand command, CancellationToken cancellationToken)
{
var observations = new Dictionary();
var transitions = new List