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);
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var configured = Environment.GetEnvironmentVariable("GRPC_DATA_NODE_PROBE_DIR");
if (string.IsNullOrWhiteSpace(configured) || !Path.IsPathFullyQualified(configured))
throw new InvalidOperationException("Fixture command directory required.");
var folder = new DirectoryInfo(configured);
folder.Create();
if (folder.LinkTarget is not null) throw new InvalidOperationException("Fixture command directory cannot be linked.");
while (!stoppingToken.IsCancellationRequested)
{
foreach (var input in folder.EnumerateFiles("*.request.json").OrderBy(file => file.Name).Take(16))
{
if (input.LinkTarget is not null || input.Length is <= 0 or > 16384) continue;
var id = input.Name[..^".request.json".Length];
if (!SafeId().IsMatch(id)) continue;
var resultPath = Path.Combine(folder.FullName, id + ".result.json");
if (File.Exists(resultPath)) { input.Delete(); continue; }
var claimed = input.FullName + ".running";
try { File.Move(input.FullName, claimed, overwrite: false); }
catch (IOException) { continue; }
ProbeResult result;
try
{
var command = JsonSerializer.Deserialize(await File.ReadAllTextAsync(claimed, stoppingToken), ProbeEngine.Json)
?? throw new InvalidOperationException();
if (command.Id != id || command.TimeoutSeconds is < 1 or > 120) throw new InvalidOperationException();
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
timeout.CancelAfter(TimeSpan.FromSeconds(command.TimeoutSeconds));
if (command.Operation == "topology")
{
var cluster = Akka.Cluster.Cluster.Get(services.GetRequiredService());
var members = cluster.State.Members.Select(member => new
{
host = member.Address.Host, port = member.Address.Port,
status = member.Status.ToString(), roles = member.Roles.ToArray()
}).ToArray();
result = new(id, "topology", members.Length == 2 && members.All(member => member.status == "Up"), 2,
new() { ["members"] = members, ["self"] = cluster.SelfAddress.ToString(), ["processId"] = Environment.ProcessId });
var cache = services.GetService();
var artifact = cache is null ? null : await cache.GetCurrentUnkeyedAsync(timeout.Token);
result.Observations["artifactRevision"] = artifact?.RevisionHash;
result.Observations["deploymentId"] = artifact?.DeploymentId;
result.Observations["connections"] = services.GetService()?.CaptureDiagnostics();
result.Observations["originAccounting"] = CaptureOriginAccounting();
result.Observations["process"] = WorkloadEngine.CaptureProcess();
result.Observations["inboundDataRequests"] = services.GetRequiredService().Requests;
result.Observations["inboundDataRequestObserverId"] = services.GetRequiredService().InstanceId;
}
else if (command.Operation == "warm-state")
{
var settings = services.GetService() ?? WarmRedundancySettings.Unset;
var warm = services.GetRequiredService().Snapshot;
var serving = services.GetRequiredService().Serving;
using var process = System.Diagnostics.Process.GetCurrentProcess();
result = new(id, command.Operation, true, 1, new()
{
["nodeId"] = serving.NodeId, ["mode"] = settings.Mode.ToString(), ["isWarm"] = settings.IsWarm,
["warmRole"] = new { role = warm.Role?.ToString(), generation = warm.Generation },
["serving"] = serving,
["process"] = new { id = Environment.ProcessId, startedUtc = process.StartTime.ToUniversalTime().ToString("O") }
});
}
else if (command.Operation == "bundle-commit")
{
var observer = services.GetRequiredService();
var state = await observer.ObserveAsync(command.ConnectionId, timeout.Token);
result = new(id, command.Operation, true, 1, new()
{
["credentialScopeVersion"] = state.CredentialScopeVersion,
["credentialVersion"] = state.CredentialVersion,
["credentialDeleted"] = state.CredentialDeleted,
["trustScopeVersion"] = state.TrustScopeVersion,
["trustVersion"] = state.TrustVersion,
["trustRetired"] = state.TrustRetired
});
}
else if (command.Operation == "projection-diagnostics")
{
result = CaptureProjectionDiagnostics(command);
}
else if (command.Operation == "legacy-telemetry")
{
// Feature-disable validation must bypass DataConnection acquisition.
result = await LegacyTelemetryAsync(command, timeout.Token);
var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService());
result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME");
result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}";
result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..];
}
else
{
var runtime = services.GetRequiredService();
var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService());
if (!runtime.TryAcquire(command.ConnectionId, out var lease) || lease is null)
result = new(id, command.Operation, command.ExpectedState == "Unavailable", 1,
new() { ["readiness"] = "Unavailable", ["caller"] = Environment.GetEnvironmentVariable("HOSTNAME") });
else
{
await using (lease)
{
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, lease.CancellationToken);
result = command.Operation == "workload"
? await WorkloadEngine.RunAsync(lease.Connection, command, linked.Token,
() => new { connections = runtime.CaptureDiagnostics(), originAccounting = CaptureOriginAccounting() })
: await ProbeEngine.RunAsync(lease.Connection, command, linked.Token);
result.Observations["caller"] = Environment.GetEnvironmentVariable("HOSTNAME");
var target = lease.Connection.Target;
result.Observations["target"] = new { mode = target.Mode.ToString(), target.ExpectedClusterId,
target.ExpectedNodeId, consistency = target.Consistency.ToString() };
result.Observations["realm"] = command.Realm;
result.Observations["namespaceUri"] = command.NamespaceUri;
result.Observations["path"] = command.Path;
}
}
result.Observations["callerNodeId"] = $"{callerCluster.SelfAddress.Host}:{callerCluster.SelfAddress.Port}";
result.Observations["callerClusterId"] = callerCluster.SelfRoles.Single(role => role.StartsWith("cluster-", StringComparison.Ordinal))["cluster-".Length..];
}
}
catch (Exception error) when (error is not OutOfMemoryException)
{
var failure = ProbeFailureClassifier.Capture(error, ProbeFailurePhase.NodeProbe);
result = new(id, "invalid", false, 0,
new() { ["failurePhase"] = failure.Phase, ["failureEvidence"] = failure }, failure.Category);
}
var temporary = resultPath + ".tmp";
await File.WriteAllTextAsync(temporary, JsonSerializer.Serialize(result, ProbeEngine.Json), stoppingToken);
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(temporary, UnixFileMode.UserRead | UnixFileMode.UserWrite);
File.Move(temporary, resultPath, overwrite: false);
File.Delete(claimed);
}
await Task.Delay(100, stoppingToken);
}
}
}