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 Demands, IReadOnlyList 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(); var selectedSources = new List(); 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 read) { try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } } private static double? SafeDouble(Func read) { try { return read(); } catch (Exception error) when (error is not OutOfMemoryException) { return null; } } }