test: validate grpc data connections with local docker and opcua cli

This commit is contained in:
Joseph Doherty
2026-11-17 22:01:26 -05:00
parent 1df29a3124
commit 29fec57fac
194 changed files with 23327 additions and 740 deletions
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><AssemblyName>GrpcDataNodeProbe</AssemblyName><IsPackable>false</IsPackable></PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<ProjectReference Include="../../../../src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ZB.MOM.WW.OtOpcUa.Runtime.csproj" />
<Compile Include="../probe/ProbeEngine.cs" Link="ProbeEngine.cs" />
<Compile Include="../probe/ProbeFailureClassifier.cs" Link="ProbeFailureClassifier.cs" />
<Compile Include="../probe/WorkloadEngine.cs" Link="WorkloadEngine.cs" />
</ItemGroup>
</Project>
@@ -0,0 +1,272 @@
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;
/// <summary>Loaded only by the isolated Docker fixture's explicit hosting-startup assembly.</summary>
public sealed class NodeProbeStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder.ConfigureServices(services =>
{
services.AddSingleton<InboundDataRequestCounter>();
services.AddSingleton<IStartupFilter, FixtureDataRequestStartupFilter>();
services.AddHostedService<NodeProbeWorker>();
});
}
/// <summary>Fixture-only process counter; retains no request identity or payload.</summary>
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);
}
/// <summary>Observes HTTP arrivals before the fixture Host's authentication and gRPC pipeline.</summary>
public sealed class FixtureDataRequestStartupFilter(InboundDataRequestCounter counter) : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) => app =>
{
app.Use(nextMiddleware => async context =>
{
if (context.Connection.LocalPort == 4057) counter.Record();
await nextMiddleware(context);
});
next(app);
};
}
/// <summary>Bounded, one-shot file requests through the caller's deployed DI registry; no listener.</summary>
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<PartitionedSampleHub>();
var acquisition = services.GetService<ZB.MOM.WW.OtOpcUa.Runtime.Drivers.SubscriptionAcquisitionCapacity>();
var composition = services.GetService<LocalDataRuntimeComposition>();
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(),
definition = "actual origin hub resource charges and physical driver reservation owners; driver count is not source count"
};
}
private static async Task<ProbeResult> LegacyTelemetryAsync(ProbeCommand command, CancellationToken cancellationToken)
{
var observations = new Dictionary<string, object?>();
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<ProbeCommand>(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<Akka.Actor.ActorSystem>());
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<ZB.MOM.WW.OtOpcUa.Runtime.DeploymentCache.IDeploymentArtifactCache>();
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<DataConnectionDeploymentRuntime>()?.CaptureDiagnostics();
result.Observations["originAccounting"] = CaptureOriginAccounting();
result.Observations["process"] = WorkloadEngine.CaptureProcess();
result.Observations["inboundDataRequests"] = services.GetRequiredService<InboundDataRequestCounter>().Requests;
result.Observations["inboundDataRequestObserverId"] = services.GetRequiredService<InboundDataRequestCounter>().InstanceId;
}
else if (command.Operation == "warm-state")
{
var settings = services.GetService<WarmRedundancySettings>() ?? WarmRedundancySettings.Unset;
var warm = services.GetRequiredService<DataConnectionWarmRoleView>().Snapshot;
var serving = services.GetRequiredService<LocalCatalogCoordinator>().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<IDataConnectionBundleCommitObserver>();
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<Akka.Actor.ActorSystem>());
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<DataConnectionDeploymentRuntime>();
var callerCluster = Akka.Cluster.Cluster.Get(services.GetRequiredService<Akka.Actor.ActorSystem>());
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);
}
}
}
@@ -0,0 +1,81 @@
using GrpcDataProbe;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace GrpcDataNodeProbe;
public sealed partial class NodeProbeWorker
{
// Fixture-only, read-only inspection. Retained validity and item observations
// are bounded diagnostics, not an atomic authorization decision.
private ProbeResult CaptureProjectionDiagnostics(ProbeCommand command)
{
if (!Enum.TryParse<DataRealm>(command.Realm, true, out var realm) ||
realm is not (DataRealm.Raw or DataRealm.Uns) ||
string.IsNullOrWhiteSpace(command.OriginCluster) || command.OriginCluster.Length > 128 ||
string.IsNullOrWhiteSpace(command.NamespaceUri) || command.NamespaceUri.Length > 1024 ||
string.IsNullOrWhiteSpace(command.Path) || command.Path.Length > 4096)
throw new ArgumentException("Invalid fixture projection target.");
var mapping = command.OperationId ?? (realm == DataRealm.Raw ? "map-raw" : "map-uns");
if (string.IsNullOrWhiteSpace(mapping) || mapping.Length > 128)
throw new ArgumentException("Invalid fixture mapping.");
var identifier = ProjectedDataIds.Identifier(mapping,
new DataAddress(command.OriginCluster, command.NamespaceUri, "string", command.Path));
var nodes = services.GetRequiredService<IProjectedNodeLookup>();
var catalog = services.GetRequiredService<IFederatedProjectionCatalog>();
var mappings = services.GetRequiredService<ProjectedMappingDeploymentRuntime>();
var access = services.GetService<ProjectedDataAccess>();
var accessPresent = access is not null;
var nodeIdResolvable = nodes.TryGetNodeId(ProjectedDataIds.NamespaceUri(realm), identifier, out var nodeId);
ProjectedVariableDefinition? definition = null;
var definitionResolvable = nodeIdResolvable && nodeId is { } actual && nodes.TryResolve(actual, out definition);
var proofResolvable = catalog.TryResolveProjected(realm, identifier, out var proof);
var connectionPresent = mappings.TryGetConnectionId(mapping, out var connectionId);
var cache = services.GetRequiredService<ProjectedCatalogCache>();
var capture = typeof(ProjectedCatalogCache).GetMethod("CaptureRetainedDiagnostics",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var retained = capture?.Invoke(cache, [realm, identifier]);
var retainedFlags = new Dictionary<string, object?>();
foreach (var name in new[] { "Retained", "Retired", "Generation", "RouteAlive", "LocalAuthorityActive",
"RemoteLeaseValid", "MappingBindingCurrent", "CacheGenerationCurrent" })
retainedFlags[name] = retained?.GetType().GetProperty(name)?.GetValue(retained);
var metadataMatches = definition is not null && proof is not null &&
proof.Metadata.Dimensions.SequenceEqual(definition.Metadata.Dimensions) &&
(proof.Metadata with { Dimensions = definition.Metadata.Dimensions }) == definition.Metadata;
var deferred = services.GetService<DeferredAddressSpaceSink>();
var sdk = deferred?.GetCapability<SdkAddressSpaceSink>();
var manager = sdk?.GetType().GetField("_nodeManager",
System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)?.GetValue(sdk);
var sdkItems = SdkItemDiagnostics.Capture(manager, nodeId);
var observations = new Dictionary<string, object?>
{
["nodeIdResolvable"] = nodeIdResolvable,
["definitionResolvable"] = definitionResolvable,
["definitionAuthorityCurrent"] = definition?.AuthorityIsCurrent(),
["definitionLifetimeActive"] = definition?.Lifetime.IsActive,
["definitionGeneration"] = definition?.ProjectionGeneration,
["proofResolvable"] = proofResolvable,
["proofGeneration"] = proof?.Generation,
["generationMatches"] = definition is not null && proof is not null && definition.ProjectionGeneration == proof.Generation,
["metadataMatches"] = metadataMatches,
["leaseValid"] = proof?.Lease.IsValid,
["leaseRemainingMilliseconds"] = null, // IDataAuthorizationLease does not expose a remaining duration.
["retainedValidity"] = retainedFlags,
["maximumSampleAgeMilliseconds"] = proof?.MaximumSampleAge.TotalMilliseconds,
["servingGeneration"] = proof?.Lease.Serving.ServingGeneration,
["allowedOperations"] = proof?.Subject.AllowedOperations.ToString(),
["connectionMappingPresent"] = connectionPresent && !string.IsNullOrWhiteSpace(connectionId),
["projectedAccessPresent"] = accessPresent,
["streamCounters"] = ProjectedStreamDiagnostics.Capture(),
["deliveryCounters"] = ProjectedDeliveryDiagnostics.Capture(),
["sdkItems"] = sdkItems,
["runtimeCohorts"] = RuntimeCohortDiagnostics.Capture(access, catalog, realm, identifier, proof),
["callerAuthorization"] = "unknown: no caller identity is supplied to this fixture diagnostic"
};
return new(command.Id, command.Operation, true, 1, observations);
}
}
@@ -0,0 +1,138 @@
using System.Collections;
using System.Reflection;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace GrpcDataNodeProbe;
// Fixture-only read-only snapshots. References are copied under their owning
// locks; validity callbacks run after releasing those locks. Results are not an
// atomic authorization decision and never include values, callers or secrets.
internal static class RuntimeCohortDiagnostics
{
private const BindingFlags Members = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const int ScanLimit = 16384;
private const int ItemLimit = 16;
internal sealed record Serving(string NodeId, string Incarnation, string Role, long CatalogEpoch,
long AuthorityEpoch, long ServingGeneration);
internal sealed record Proof(bool? LeaseValid, bool? LocalAuthorityActive, bool? CacheUsable, bool? IsCurrentCacheProof,
long? Generation, long? MappingRevision, double? RemainingMilliseconds, Serving? Serving);
internal sealed record Cohort(Serving? Serving, double? IntervalMilliseconds, int? Started, int? Closing,
int? HealthyBaseline, int? ServingMismatch, long? AttemptEpoch);
internal sealed record Demand(bool? Disposed, bool? Valid, string? Operation, bool? NodePinValid,
bool? DefinitionLifetimeActive, bool? DefinitionAuthorityCurrent, long? DefinitionGeneration,
Proof? Proof, Cohort? Cohort);
internal sealed record Source(bool? ReadOwned, bool? NodePinValid, bool? DefinitionLifetimeActive,
bool? DefinitionAuthorityCurrent, int? ActiveAttempts, long? AttemptEra, long? AuthorityGeneration,
long? LastVersion, bool? CachedSamplePresent, Proof? Current, Proof? Previous);
internal sealed record Snapshot(bool Available, bool Truncated, int DemandsScanned, int SourcesScanned,
int? UnaryCount, long? UnaryBytes, IReadOnlyList<Demand> Demands, IReadOnlyList<Source> Sources);
private sealed record DemandRefs(IProjectedDemandLease Demand, object? Binding, object? Cohort, object? CohortKey);
private sealed record SourceRefs(object Source, object? Key);
internal static Snapshot Capture(ProjectedDataAccess? access, IFederatedProjectionCatalog catalog,
DataRealm realm, string identifier, ProjectedNodeProof? currentCacheProof)
{
if (access is null) return new(false, false, 0, 0, null, null, [], []);
try
{
var sync = Field(access, "_sync");
var demands = Field(access, "_demands") as IEnumerable;
var memberships = Field(access, "_demandCohorts") as IDictionary;
var sources = Field(access, "_sources") as IDictionary;
if (sync is null || demands is null || memberships is null || sources is null)
return new(false, false, 0, 0, null, null, [], []);
var selectedDemands = new List<DemandRefs>(); var selectedSources = new List<SourceRefs>();
var demandsScanned = 0; var sourcesScanned = 0; var truncated = false;
int? unaryCount; long? unaryBytes;
lock (sync)
{
unaryCount = Field(access, "_unaryCount") as int?;
unaryBytes = Field(access, "_unaryBytes") as long?;
foreach (var item in demands)
{
if (++demandsScanned > ScanLimit) { truncated = true; break; }
if (item is not IProjectedDemandLease demand || demand.Realm != realm || demand.LocalIdentifier != identifier) continue;
if (selectedDemands.Count == ItemLimit) { truncated = true; break; }
var cohort = memberships.Contains(item) ? memberships[item] : null;
selectedDemands.Add(new(demand, Property(item, "CurrentBinding"), cohort, Field(cohort, "_key")));
}
foreach (DictionaryEntry entry in sources)
{
if (++sourcesScanned > ScanLimit) { truncated = true; break; }
var key = entry.Key;
if (Property(key, "Realm") is not DataRealm sourceRealm || sourceRealm != realm ||
Property(key, "LocalIdentifier") as string != identifier) continue;
if (selectedSources.Count == ItemLimit) { truncated = true; break; }
if (entry.Value is { } source) selectedSources.Add(new(source, key));
}
}
var describedDemands = selectedDemands.Select(item => DescribeDemand(item, catalog, currentCacheProof)).ToArray();
var describedSources = selectedSources.Select(item => DescribeSource(item, catalog, currentCacheProof)).ToArray();
return new(true, truncated, Math.Min(demandsScanned, ScanLimit), Math.Min(sourcesScanned, ScanLimit),
unaryCount, unaryBytes, describedDemands, describedSources);
}
catch (Exception error) when (error is not OutOfMemoryException)
{ return new(false, false, 0, 0, null, null, [], []); }
}
private static Demand DescribeDemand(DemandRefs item, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof)
{
var definition = Property(item.Binding, "Definition") as ProjectedVariableDefinition;
var proof = Property(item.Binding, "Proof") as ProjectedNodeProof;
var nodePin = Property(item.Binding, "NodePin") as IProjectedNodePin;
var operation = Property(item.Demand, "RequestedOperation") is DataOperations value ? value.ToString() : null;
var cohort = item.Cohort is null ? null : new Cohort(
DescribeServing(Property(item.CohortKey, "Serving") as ServingIdentity),
(Property(item.CohortKey, "Interval") as TimeSpan?)?.TotalMilliseconds,
Field(item.Cohort, "_started") as int?, Field(item.Cohort, "_closing") as int?,
Field(item.Cohort, "_healthyBaseline") as int?, Field(item.Cohort, "_servingMismatch") as int?,
Field(item.Cohort, "_epoch") as long?);
return new(SafeBool(() => Property(item.Demand, "Disposed") as bool?), SafeBool(() => item.Demand.IsValid), operation,
SafeBool(() => nodePin?.IsValid), SafeBool(() => definition?.Lifetime.IsActive),
SafeBool(() => definition?.AuthorityIsCurrent()), definition?.ProjectionGeneration,
DescribeProof(proof, catalog, currentCacheProof), cohort);
}
private static Source DescribeSource(SourceRefs item, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof)
{
var gate = Field(item.Source, "Gate") ?? throw new InvalidOperationException("Source gate missing.");
ProjectedNodeProof? current, previous; ProjectedVariableDefinition? definition; IProjectedNodePin? pin;
int? active; long? era, generation, version; bool? readOwned, cached;
lock (gate)
{
current = Field(item.Source, "_proof") as ProjectedNodeProof;
previous = Field(item.Source, "_previousProof") as ProjectedNodeProof;
definition = Field(item.Source, "_definition") as ProjectedVariableDefinition;
pin = Field(item.Source, "_nodePin") as IProjectedNodePin;
active = Field(item.Source, "_activeAttempts") as int?; era = Field(item.Source, "_attemptEra") as long?;
generation = Field(item.Source, "_authorityGeneration") as long?; version = Field(item.Source, "LastVersion") as long?;
readOwned = Field(item.Source, "ReadOwned") as bool?; cached = Field(item.Source, "_cachedSample") is not null;
}
return new(readOwned, SafeBool(() => pin?.IsValid), SafeBool(() => definition?.Lifetime.IsActive),
SafeBool(() => definition?.AuthorityIsCurrent()), active, era, generation, version, cached,
DescribeProof(current, catalog, currentCacheProof), DescribeProof(previous, catalog, currentCacheProof));
}
private static Proof? DescribeProof(ProjectedNodeProof? proof, IFederatedProjectionCatalog catalog, ProjectedNodeProof? currentCacheProof)
{
if (proof is null) return null;
return new(SafeBool(() => proof.Lease.IsValid), SafeBool(() => proof.Resolver.LocalAuthority.IsActive),
SafeBool(() => catalog.IsUsableProof(proof)), ReferenceEquals(proof, currentCacheProof), proof.Generation,
proof.Metadata.View.MappingRevision, SafeDouble(() => (Property(proof.Lease, "Remaining") as TimeSpan?)?.TotalMilliseconds),
DescribeServing(proof.Lease.Serving));
}
private static Serving? DescribeServing(ServingIdentity? serving) => serving is null ? null :
new(Bounded(serving.NodeId, 512), Bounded(serving.Incarnation, 256), Bounded(serving.Role, 32),
serving.CatalogEpoch, serving.AuthorityEpoch, serving.ServingGeneration);
private static string Bounded(string value, int length) => value.Length <= length ? value : value[..length];
private static object? Field(object? target, string name) => target?.GetType().GetField(name, Members)?.GetValue(target);
private static object? Property(object? target, string name) => target?.GetType().GetProperty(name, Members)?.GetValue(target);
private static bool? SafeBool(Func<bool?> read)
{ try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } }
private static double? SafeDouble(Func<double?> read)
{ try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } }
}
@@ -0,0 +1,103 @@
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
namespace GrpcDataNodeProbe;
// Fixture-only inspection. All returned fields are bounded, fixed-shape state;
// no item, proof, principal, identifier, payload or exception text escapes.
internal static class SdkItemDiagnostics
{
private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.NonPublic;
private const BindingFlags Properties = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private const int ScanLimit = 16384;
private const int ItemLimit = 16;
internal sealed record Item(bool? Retired, bool? Suppressed, bool? HealthTracked, bool? DemandPresent,
bool? DemandValid, long? DefinitionGeneration, bool? DefinitionLifetimeActive, bool? DefinitionAuthorityCurrent,
bool? SourceBindingValid, bool? LatestProofValid, int? CandidateCount, int? MonitoringMode);
internal sealed record Snapshot(long ProcessTimestamp, long ProcessFrequency, bool Available, bool Truncated,
int LiveScanned, int HealthScanned, IReadOnlyList<Item> Items);
internal static Snapshot Capture(object? manager, NodeId? target)
{
var timestamp = Stopwatch.GetTimestamp();
if (manager is null || target is not { } actualTarget) return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []);
try
{
var type = manager.GetType();
var live = type.GetField("_liveItems", Fields)?.GetValue(manager) as IEnumerable;
var health = type.GetField("_projectedHealthIndex", Fields)?.GetValue(manager) as IDictionary;
var healthGate = type.GetField("_projectedHealthGate", Fields)?.GetValue(manager);
if (live is null || health is null || healthGate is null)
return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []);
var found = new Dictionary<object, (bool? Suppressed, bool Health)>(System.Collections.Generic.ReferenceEqualityComparer.Instance);
var liveScanned = 0; var healthScanned = 0; var truncated = false;
foreach (var pair in live)
{
if (++liveScanned > ScanLimit) { truncated = true; break; }
var item = pair?.GetType().GetProperty("Key")?.GetValue(pair);
if (!Matches(item, actualTarget)) continue;
if (found.Count == ItemLimit) { truncated = true; break; }
var tracked = pair!.GetType().GetProperty("Value")?.GetValue(pair);
found[item!] = (ReadBool(tracked, "Suppressed"), false);
}
// Copy only references under the index lock. Authority and proof checks
// happen after releasing it, avoiding health-index/manager lock inversion.
var healthItems = new List<object>();
lock (healthGate)
{
foreach (var key in health.Keys)
{
if (++healthScanned > ScanLimit) { truncated = true; break; }
if (key is not null) healthItems.Add(key);
}
}
foreach (var item in healthItems)
{
if (!Matches(item, actualTarget)) continue;
if (found.TryGetValue(item, out var current)) found[item] = (current.Suppressed, true);
else if (found.Count < ItemLimit) found[item] = (null, true);
else truncated = true;
}
var items = found.Select(pair => Describe(pair.Key, pair.Value.Suppressed,
pair.Value.Health ? true : truncated ? null : false)).ToArray();
return new(timestamp, Stopwatch.Frequency, true, truncated, Math.Min(liveScanned, ScanLimit),
Math.Min(healthScanned, ScanLimit), items);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{ return new(timestamp, Stopwatch.Frequency, false, false, 0, 0, []); }
}
private static bool Matches(object? item, NodeId target) =>
item?.GetType().GetProperty("ProjectedNodeId", Properties)?.GetValue(item) is NodeId id && id == target;
private static Item Describe(object item, bool? suppressed, bool? healthTracked)
{
var type = item.GetType();
object? demand, binding, evidence; ProjectedVariableDefinition? definition; int? candidateCount;
var sync = type.GetField("_bindingSync", Fields)!.GetValue(item)!;
lock (sync)
{
demand = type.GetField("_demand", Fields)?.GetValue(item);
binding = type.GetField("_binding", Fields)?.GetValue(item);
evidence = type.GetField("_latestEvidence", Fields)?.GetValue(item);
definition = type.GetField("_definition", Fields)?.GetValue(item) as ProjectedVariableDefinition;
candidateCount = (type.GetField("_candidates", Fields)?.GetValue(item) as ICollection)?.Count;
}
var proof = evidence?.GetType().GetProperty("Proof", Properties)?.GetValue(evidence);
return new(ReadBool(item, "HealthRetired"), suppressed, healthTracked, demand is not null,
Safe(() => (demand as IProjectedDemandLease)?.IsValid), definition?.ProjectionGeneration, Safe(() => definition?.Lifetime.IsActive),
Safe(() => definition?.AuthorityIsCurrent()), ReadBool(binding, "IsValid"), ReadBool(proof, "IsValid"),
candidateCount, SafeInt(() => type.GetProperty("MonitoringMode", Properties)?.GetValue(item) is { } mode
? Convert.ToInt32(mode) : null));
}
private static bool? ReadBool(object? target, string property) =>
Safe(() => target?.GetType().GetProperty(property, Properties)?.GetValue(target) as bool?);
private static bool? Safe(Func<bool?> read)
{ try { return read(); } catch (Exception ex) when (ex is not OutOfMemoryException) { return null; } }
private static int? SafeInt(Func<int?> read)
{ try { return read(); } catch (Exception ex) when (ex is not OutOfMemoryException) { return null; } }
}