b7ca71f188
#916: Metadata.stable_source_id carried the internal acquisition key (<len>:<driverInstanceId><RawPath>) on every export, so a UNS-only peer learned driver ids and RawPaths. No consumer uses the field beyond byte accounting; it is optional on the wire and absent decodes as null. It is now never sent; the internal BackingSourceKey is unchanged. #917: alarm-bearing raw tags never get a value but were exported as Variables. They are now the existing explicit UnsupportedVariable kind (browsable, Unsupported on every value op). The node is kept so exports rooted at it still compile and A1 condition placements are unaffected. The real-origin v1 goldens are not re-recorded: GrpcDataV1RealOriginCorrections applies exactly these two edits to the parsed goldens, pinned by a test. Evidence: docs/plans/evidence/grpc-data-ext/V1-916-917.md
451 lines
31 KiB
C#
451 lines
31 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// A1 (§5.2): realm-local condition placements per export, the condition listing and the m-T6 key properties. The
|
|
/// v1 catalog (nodes, metadata, stable source ids) must be byte-identical with and without the enumeration.
|
|
/// </summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")]
|
|
public sealed class GrpcDataConditionPlacementTests
|
|
{
|
|
private const string AlarmConfig = "{\"alarm\":{\"alarmType\":\"AlarmCondition\",\"severity\":700}}";
|
|
private static readonly string Secret = Convert.ToBase64String(RandomNumberGenerator.GetBytes(48));
|
|
private const DataOperations Ops = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe;
|
|
|
|
private static DraftSnapshot Fixed(bool withAlarms = true) => With(Base(withAlarms));
|
|
|
|
private static DraftSnapshot With(DraftSnapshot b, IReadOnlyList<RawFolder>? folders = null, IReadOnlyList<DriverInstance>? drivers = null,
|
|
IReadOnlyList<Device>? devices = null, IReadOnlyList<TagGroup>? groups = null, IReadOnlyList<Tag>? tags = null,
|
|
IReadOnlyList<Equipment>? equipment = null, IReadOnlyList<UnsTagReference>? references = null,
|
|
IReadOnlyList<ScriptedAlarm>? scripted = null, IReadOnlyList<DataExport>? exports = null) => new()
|
|
{
|
|
GenerationId = b.GenerationId, ClusterId = b.ClusterId, ServerClusters = b.ServerClusters,
|
|
RawFolders = [.. folders ?? b.RawFolders], DriverInstances = [.. drivers ?? b.DriverInstances], Devices = [.. devices ?? b.Devices],
|
|
TagGroups = [.. groups ?? b.TagGroups], Tags = [.. tags ?? b.Tags], UnsAreas = b.UnsAreas, UnsLines = b.UnsLines,
|
|
Equipment = [.. equipment ?? b.Equipment], UnsTagReferences = [.. references ?? b.UnsTagReferences], Scripts = b.Scripts,
|
|
ScriptedAlarms = [.. scripted ?? b.ScriptedAlarms], DataExports = [.. exports ?? b.DataExports]
|
|
};
|
|
|
|
private static DraftSnapshot Base(bool withAlarms) => new()
|
|
{
|
|
GenerationId = 1, ClusterId = "cluster",
|
|
ServerClusters = [new() { ClusterId = "cluster", Name = "Cluster", Enterprise = "Enterprise", Site = "Site", CreatedBy = "test", RedundancyMode = RedundancyMode.None }],
|
|
RawFolders = [new() { RawFolderId = "folder", ClusterId = "cluster", Name = "Plant" }],
|
|
DriverInstances = [new() { DriverInstanceId = "driver-id-7f3", ClusterId = "cluster", RawFolderId = "folder", Name = "Driver", DriverType = "ModbusTcp", DriverConfig = "{}" }],
|
|
Devices = [new() { DeviceId = "device", DriverInstanceId = "driver-id-7f3", Name = "Device", DeviceConfig = "{}" }],
|
|
TagGroups = [new() { TagGroupId = "group", DeviceId = "device", Name = "Group" }],
|
|
Tags = [new() { TagId = "tag", DeviceId = "device", Name = "Speed", DataType = "Int32", AccessLevel = TagAccessLevel.ReadWrite, TagConfig = "{}" },
|
|
new() { TagId = "alarm-tag", DeviceId = "device", TagGroupId = "group", Name = "OverTemp", DataType = "Boolean", AccessLevel = TagAccessLevel.Read,
|
|
TagConfig = withAlarms ? AlarmConfig : "{}" }],
|
|
UnsAreas = [new() { UnsAreaId = "area-id", ClusterId = "cluster", Name = "Area" }],
|
|
UnsLines = [new() { UnsLineId = "line-id", UnsAreaId = "area-id", Name = "Line" }],
|
|
Equipment = [new() { EquipmentId = "eq-1", UnsLineId = "line-id", Name = "Filler", MachineCode = "E1" },
|
|
new() { EquipmentId = "eq-2", UnsLineId = "line-id", Name = "Capper", MachineCode = "E2" }],
|
|
UnsTagReferences = [new() { UnsTagReferenceId = "ref-speed", EquipmentId = "eq-1", TagId = "tag" },
|
|
new() { UnsTagReferenceId = "ref-alarm-1", EquipmentId = "eq-1", TagId = "alarm-tag" },
|
|
new() { UnsTagReferenceId = "ref-alarm-2", EquipmentId = "eq-2", TagId = "alarm-tag", DisplayNameOverride = "HeadTemp" }],
|
|
Scripts = [new() { ScriptId = "script", Name = "Predicate", SourceCode = "return false;", SourceHash = "h" }],
|
|
ScriptedAlarms = withAlarms
|
|
? [new() { ScriptedAlarmId = "sa-1", EquipmentId = "eq-2", Name = "Jam", AlarmType = "AlarmCondition", MessageTemplate = "jam", PredicateScriptId = "script" },
|
|
new() { ScriptedAlarmId = "sa-off", EquipmentId = "eq-2", Name = "Off", AlarmType = "AlarmCondition", MessageTemplate = "x", PredicateScriptId = "script", Enabled = false }]
|
|
: [],
|
|
DataExports = [Export("raw", DataRealm.Raw, "raw-peer"), Export("uns", DataRealm.Uns, "uns-peer"),
|
|
Export("uns-2", DataRealm.Uns, "uns-peer-2"),
|
|
Export("eq", DataRealm.Uns, "eq-peer", rootKind: "Equipment", rootId: "eq-2")]
|
|
};
|
|
|
|
private static DataExport Export(string id, DataRealm realm, string principal, string rootKind = "Cluster", string rootId = "cluster") =>
|
|
new() { DataExportId = id, ClusterId = "cluster", Enabled = true, Realm = realm, RootKind = rootKind, RootEntityId = rootId,
|
|
PrincipalId = principal, AllowedOperations = Ops };
|
|
|
|
[Fact]
|
|
public void Placements_are_realm_local_RawPath_in_Raw_and_reserved_reference_ids_or_ScriptedAlarmId_in_Uns()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var native = new OriginConditionRef(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp");
|
|
var placements = catalog.PlacementsOf(native);
|
|
placements.Select(p => (p.View.Realm, p.View.Address.Identifier)).ShouldBe([
|
|
(DataRealm.Raw, "Plant/Driver/Device/Group/OverTemp"),
|
|
(DataRealm.Uns, "Area/Line/Capper/HeadTemp"),
|
|
(DataRealm.Uns, "Area/Line/Filler/OverTemp")]);
|
|
placements[0].Parent.Address.Identifier.ShouldBe("Plant/Driver/Device/Group"); // its group folder
|
|
placements[1].Parent.Address.Identifier.ShouldBe("eq-2"); // the equipment
|
|
placements[2].Parent.Address.Identifier.ShouldBe("eq-1");
|
|
placements.ShouldAllBe(p => p.SourceKind == ConditionSourceKind.Native);
|
|
|
|
var scripted = catalog.PlacementsOf(new(AddressSpaceRealm.Uns, "sa-1")).ShouldHaveSingleItem();
|
|
scripted.View.Realm.ShouldBe(DataRealm.Uns);
|
|
scripted.View.Address.Identifier.ShouldBe("sa-1");
|
|
scripted.Parent.Address.Identifier.ShouldBe("eq-2");
|
|
scripted.SourceKind.ShouldBe(ConditionSourceKind.Scripted);
|
|
catalog.PlacementsOf(new(AddressSpaceRealm.Uns, "sa-off")).ShouldBeEmpty(); // the node manager materialises enabled only
|
|
catalog.ConditionPlacements.Count.ShouldBe(4);
|
|
catalog.ConditionPlacements.ShouldNotContain(p => p.View.Realm == DataRealm.Raw && p.SourceKind == ConditionSourceKind.Scripted);
|
|
|
|
// No UNS node exists at a reserved id (#896), and the placement does not create one.
|
|
catalog.Nodes.ShouldNotContain(n => n.Metadata.View.Address.Identifier == "Area/Line/Filler/OverTemp");
|
|
catalog.TryResolveConditionPlacement(placements[2].View with { Subject = "claimed" }, out var resolved).ShouldBeTrue();
|
|
resolved.Condition.ShouldBe(native);
|
|
catalog.TryResolveConditionPlacement(placements[2].View with { Realm = DataRealm.Raw }, out _).ShouldBeFalse();
|
|
catalog.TryResolveConditionPlacement(placements[2].View with { MappingId = "m", MappingRevision = 1 }, out _).ShouldBeFalse();
|
|
}
|
|
|
|
/// <summary>Review nit: an address claimed by two placements drops both (fail closed) and says so at Warning in the
|
|
/// LOCAL log; the listing simply does not carry them.</summary>
|
|
[Fact]
|
|
public void Colliding_placements_are_dropped_and_logged_at_Warning()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var b = Fixed();
|
|
var clash = new ScriptedAlarm
|
|
{
|
|
ScriptedAlarmId = "Area/Line/Filler/OverTemp", EquipmentId = "eq-1", Name = "Clash", AlarmType = "AlarmCondition",
|
|
MessageTemplate = "x", PredicateScriptId = "script",
|
|
};
|
|
var log = new CapturingLogger();
|
|
|
|
var catalog = LocalExportCatalog.Compile(With(b, scripted: [.. b.ScriptedAlarms, clash]), fixture.Serving,
|
|
fixture.Activation.CaptureAuthority(), logger: log);
|
|
|
|
catalog.ConditionPlacements.ShouldNotContain(p => p.View.Address.Identifier == "Area/Line/Filler/OverTemp");
|
|
catalog.ConditionPlacements.Count.ShouldBe(3);
|
|
log.Warnings.ShouldHaveSingleItem().ShouldContain("Area/Line/Filler/OverTemp");
|
|
}
|
|
|
|
private sealed class CapturingLogger : Microsoft.Extensions.Logging.ILogger
|
|
{
|
|
public List<string> Warnings { get; } = [];
|
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
|
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
|
|
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
|
|
Exception? exception, Func<TState, Exception?, string> formatter)
|
|
{
|
|
if (logLevel == Microsoft.Extensions.Logging.LogLevel.Warning) Warnings.Add(formatter(state, exception));
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void The_v1_catalog_is_unchanged_by_the_enumeration()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var withAlarms = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
// Same topology, placements stripped: the v1 node set (metadata, source ids, scopes, parents) is identical.
|
|
var stripped = new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), withAlarms.Nodes, Fixed().DataExports);
|
|
stripped.ConditionPlacements.ShouldBeEmpty();
|
|
Json(withAlarms.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)).ShouldBe(Json(stripped.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)));
|
|
// And the scripted alarms now passed to the composer change no v1 node.
|
|
var noScripted = With(Fixed(), scripted: []);
|
|
var v1 = LocalExportCatalog.Compile(noScripted, fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
Json(v1.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)).ShouldBe(Json(withAlarms.Nodes.OrderBy(n => n.EntityKind).ThenBy(n => n.EntityId)));
|
|
// A role-only serving refresh keeps the placements.
|
|
withAlarms.WithServingRole(fixture.Serving with { Role = "Secondary" }).ConditionPlacements.Count.ShouldBe(4);
|
|
}
|
|
|
|
[Fact]
|
|
public void Listing_is_scoped_to_the_export_root_and_realm_and_fails_closed()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var keys = ConditionKeys.FromSecret(Secret);
|
|
var unsRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns);
|
|
var rawRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw);
|
|
|
|
var raw = catalog.ListConditions("raw-peer", rawRoot, DataOperations.Subscribe, keys);
|
|
raw.ShouldHaveSingleItem().Placements.ShouldHaveSingleItem().View.Address.Identifier.ShouldBe("Plant/Driver/Device/Group/OverTemp");
|
|
|
|
var uns = catalog.ListConditions("uns-peer", unsRoot, DataOperations.Subscribe, keys);
|
|
uns.Count.ShouldBe(2);
|
|
uns.Single(c => c.SourceKind == ConditionSourceKind.Native).Placements.Select(p => p.View.Address.Identifier)
|
|
.ShouldBe(["Area/Line/Capper/HeadTemp", "Area/Line/Filler/OverTemp"]);
|
|
uns.SelectMany(c => c.Placements).ShouldAllBe(p => p.View.Realm == DataRealm.Uns);
|
|
|
|
// Equipment-rooted export: only the placements under eq-2.
|
|
var equipmentRoot = catalog.Nodes.Single(n => n.EntityKind == "Equipment" && n.EntityId == "eq-2").Metadata.View;
|
|
var eq = catalog.ListConditions("eq-peer", equipmentRoot, DataOperations.Subscribe, keys);
|
|
eq.SelectMany(c => c.Placements).Select(p => p.View.Address.Identifier).Order(StringComparer.Ordinal).ShouldBe(["Area/Line/Capper/HeadTemp", "sa-1"]);
|
|
catalog.ListConditions("eq-peer", unsRoot, DataOperations.Subscribe, keys).Count.ShouldBe(2); // same principal, export root still bounds it
|
|
|
|
// Fail closed: wrong realm / principal / an ungranted bit / no secret / unknown root.
|
|
catalog.ListConditions("raw-peer", unsRoot, DataOperations.Subscribe, keys).ShouldBeEmpty();
|
|
catalog.ListConditions("uns-peer", rawRoot, DataOperations.Subscribe, keys).ShouldBeEmpty();
|
|
catalog.ListConditions("nobody", unsRoot, DataOperations.Subscribe, keys).ShouldBeEmpty();
|
|
catalog.ListConditions("uns-peer", unsRoot, DataOperations.AlarmSubscribe, keys).ShouldBeEmpty(); // not understood until A2
|
|
catalog.ListConditions("uns-peer", unsRoot, DataOperations.Write, keys).ShouldBeEmpty();
|
|
catalog.ListConditions("uns-peer", unsRoot, DataOperations.Subscribe, ConditionKeys.Unavailable).ShouldBeEmpty();
|
|
catalog.ListConditions("uns-peer", unsRoot with { Address = unsRoot.Address with { Identifier = "elsewhere" } }, DataOperations.Subscribe, keys).ShouldBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public void Condition_key_is_equal_across_listings_principals_restart_and_pair_members_m_T6()
|
|
{
|
|
using var nodeA = new LocalDataFixture();
|
|
using var nodeB = new LocalDataFixture(servingNode: "node-b", servingIncarnation: "serving-9");
|
|
using var restarted = new LocalDataFixture(servingIncarnation: "serving-2");
|
|
var unsRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns);
|
|
var rawRoot = LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw);
|
|
string NativeKey(LocalDataFixture f, string principal, DataView root, ConditionKeys keys) =>
|
|
LocalExportCatalog.Compile(Fixed(), f.Serving, f.Activation.CaptureAuthority())
|
|
.ListConditions(principal, root, DataOperations.Subscribe, keys).Single(c => c.SourceKind == ConditionSourceKind.Native).ConditionKey;
|
|
|
|
var keys = ConditionKeys.FromSecret(Secret);
|
|
var raw = NativeKey(nodeA, "raw-peer", rawRoot, keys);
|
|
ImportedConditionIds.IsWellFormedConditionKey(raw).ShouldBeTrue();
|
|
NativeKey(nodeA, "uns-peer", unsRoot, keys).ShouldBe(raw); // Raw and UNS listings
|
|
NativeKey(nodeA, "uns-peer-2", unsRoot, keys).ShouldBe(raw); // another principal
|
|
NativeKey(restarted, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret)).ShouldBe(raw); // a restart (new process, new deriver)
|
|
NativeKey(nodeB, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret)).ShouldBe(raw); // the pair member
|
|
|
|
// Only a rotated secret or another origin cluster changes it.
|
|
NativeKey(nodeA, "uns-peer", unsRoot, ConditionKeys.FromSecret(Secret + "-rotated")).ShouldNotBe(raw);
|
|
keys.Derive("CLUSTER", AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp").ShouldBe(raw); // cluster ids are case-insensitive
|
|
keys.Derive("other-cluster", AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp").ShouldNotBe(raw);
|
|
}
|
|
|
|
[Fact]
|
|
public void Condition_key_is_keyed_realm_separated_and_reveals_no_input()
|
|
{
|
|
var keys = ConditionKeys.FromSecret(Secret);
|
|
var a = keys.Derive("cluster", AddressSpaceRealm.Raw, "same-id");
|
|
var b = keys.Derive("cluster", AddressSpaceRealm.Uns, "same-id");
|
|
a.ShouldNotBe(b); // a RawPath and a ScriptedAlarmId spelled alike are two conditions
|
|
a.Length.ShouldBe(ImportedConditionIds.ConditionKeyLength);
|
|
a.ShouldNotContain("same-id");
|
|
// Cluster/condition boundary is unambiguous.
|
|
keys.Derive("ab", AddressSpaceRealm.Raw, "c").ShouldNotBe(keys.Derive("a", AddressSpaceRealm.Raw, "bc"));
|
|
Should.Throw<ArgumentException>(() => keys.Derive("a\0b", AddressSpaceRealm.Raw, "c"));
|
|
Should.Throw<InvalidOperationException>(() => ConditionKeys.Unavailable.Derive("cluster", AddressSpaceRealm.Raw, "x"))
|
|
.Message.ShouldContain("DataConnections:ConditionKeySecret");
|
|
}
|
|
|
|
[Fact]
|
|
public void Secret_absent_is_fail_closed_and_a_weak_secret_is_refused_without_echoing_it()
|
|
{
|
|
ConditionKeys.FromSecret(null).IsAvailable.ShouldBeFalse();
|
|
ConditionKeys.FromSecret("").IsAvailable.ShouldBeFalse();
|
|
ConditionKeys.FromSecret(null).UnavailableReason.ShouldBe(ConditionKeys.NotProvisionedReason);
|
|
ConditionKeys.SecretProblem(null).ShouldBeNull();
|
|
ConditionKeys.SecretProblem(Secret).ShouldBeNull();
|
|
foreach (var weak in new[] { "short-secret", new string(' ', 40), "${secret:otopcua/condition-key}-padding-padding-padding", "abc\u0001" + new string('x', 40) })
|
|
{
|
|
var problem = ConditionKeys.SecretProblem(weak).ShouldNotBeNull();
|
|
problem.ShouldContain("DataConnections:ConditionKeySecret");
|
|
if (weak.Trim().Length > 0) problem.ShouldNotContain(weak);
|
|
Should.Throw<ArgumentException>(() => ConditionKeys.FromSecret(weak)).Message.ShouldNotContain("short-secret");
|
|
}
|
|
// 32 bytes is the floor, counted in UTF-8 bytes.
|
|
ConditionKeys.SecretProblem(new string('k', 31)).ShouldNotBeNull();
|
|
ConditionKeys.SecretProblem(new string('k', 32)).ShouldBeNull();
|
|
ConditionKeys.SecretProblem(new string('é', 16)).ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public void Catalog_refuses_a_cross_realm_or_unparented_placement()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var compiled = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var uns = compiled.ConditionPlacements.First(p => p.View.Realm == DataRealm.Uns && p.SourceKind == ConditionSourceKind.Native);
|
|
var raw = compiled.ConditionPlacements.Single(p => p.View.Realm == DataRealm.Raw);
|
|
LocalConditionPlacement[] invalid =
|
|
[
|
|
uns with { Parent = raw.Parent }, // UNS placement under a raw folder
|
|
raw with { Condition = new(AddressSpaceRealm.Raw, "Other/Path") }, // raw address ≠ its ConditionId
|
|
uns with { SourceKind = ConditionSourceKind.Scripted }, // scripted with a raw condition
|
|
uns with { View = uns.View with { MappingId = "m", MappingRevision = 1 } },
|
|
uns with { View = uns.View with { Address = uns.View.Address with { OriginClusterId = "foreign" } } },
|
|
uns with { Parent = uns.Parent with { Address = uns.Parent.Address with { Identifier = "missing" } } },
|
|
];
|
|
foreach (var bad in invalid)
|
|
Should.Throw<ArgumentException>(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(),
|
|
compiled.Nodes, [], conditionPlacements: [bad]));
|
|
Should.Throw<ArgumentException>(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(),
|
|
compiled.Nodes, [], conditionPlacements: [uns, uns]));
|
|
}
|
|
|
|
/// <summary>
|
|
/// #916 class: a UNS-only principal must never see a RawPath or a driver id. Property test over generated topologies
|
|
/// (folders, drivers, devices, nested groups, alarm-bearing and plain tags, references with and without display
|
|
/// overrides, scripted alarms); the whole serialized listing record is searched. A Raw listing of the same topology is
|
|
/// the positive control: the same search finds the RawPaths there.
|
|
/// </summary>
|
|
[Fact]
|
|
public void A_Uns_only_export_lists_no_RawPath_or_driver_id_anywhere_in_the_record_property()
|
|
{
|
|
var keys = ConditionKeys.FromSecret(Secret);
|
|
var listedNative = 0;
|
|
for (var seed = 1; seed <= 60; seed++)
|
|
{
|
|
var (snapshot, rawPaths, driverIds, expectedUnsNative) = Generate(seed);
|
|
using var fixture = new LocalDataFixture();
|
|
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var unsListing = catalog.ListConditions("uns-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Uns), DataOperations.Subscribe, keys);
|
|
var text = Json(unsListing);
|
|
foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}");
|
|
foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}");
|
|
text.ShouldNotContain(V3NodeIds.RawNamespaceUri, Case.Sensitive, $"seed {seed}");
|
|
unsListing.SelectMany(c => c.Placements).ShouldAllBe(p => p.View.Realm == DataRealm.Uns && p.Parent.Realm == DataRealm.Uns);
|
|
var native = unsListing.Where(c => c.SourceKind == ConditionSourceKind.Native).Sum(c => c.Placements.Count);
|
|
native.ShouldBe(expectedUnsNative, $"seed {seed}");
|
|
listedNative += native;
|
|
|
|
// Positive control: the Raw listing does carry the alarm-bearing RawPaths, so the search above can see one.
|
|
var rawText = Json(catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe, keys));
|
|
foreach (var alarmPath in catalog.ConditionPlacements.Where(p => p.View.Realm == DataRealm.Raw).Select(p => p.View.Address.Identifier))
|
|
rawText.ShouldContain(alarmPath);
|
|
}
|
|
listedNative.ShouldBeGreaterThan(20); // the generator really exercised native UNS placements
|
|
}
|
|
|
|
/// <summary>
|
|
/// #916: no exported metadata carries <c>stable_source_id</c> — a driver source's internal key is
|
|
/// <c><len>:<driverInstanceId><RawPath></c>, so sending it told a UNS-only peer the origin's driver ids and
|
|
/// RawPaths. The internal <see cref="BackingSourceKey"/> is unchanged (positive control: it still holds both, so the
|
|
/// search below would see a leak). Checked on the encoded wire bytes of every node, every realm, 60 seeds.
|
|
/// </summary>
|
|
[Fact]
|
|
public void No_exported_metadata_carries_the_internal_source_key_916()
|
|
{
|
|
var checkedSources = 0;
|
|
for (var seed = 1; seed <= 60; seed++)
|
|
{
|
|
var (snapshot, rawPaths, driverIds, _) = Generate(seed);
|
|
using var fixture = new LocalDataFixture();
|
|
var catalog = LocalExportCatalog.Compile(snapshot, fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
foreach (var node in catalog.Nodes)
|
|
{
|
|
node.Metadata.StableSourceId.ShouldBeNull($"seed {seed} {node.EntityKind} {node.EntityId}");
|
|
var wire = DataProtoMapper.EncodeMetadata(node.Metadata);
|
|
wire.HasStableSourceId.ShouldBeFalse();
|
|
if (node.Metadata.View.Realm != DataRealm.Uns) continue;
|
|
var text = wire.ToString();
|
|
foreach (var rawPath in rawPaths) text.ShouldNotContain(rawPath, Case.Sensitive, $"seed {seed}");
|
|
foreach (var driverId in driverIds) text.ShouldNotContain(driverId, Case.Sensitive, $"seed {seed}");
|
|
// Positive control: the internal key of a driver-backed UNS reference still names its driver and RawPath.
|
|
if (node.Source is { SourceKind: "driver" } source)
|
|
{
|
|
driverIds.ShouldContain(d => source.StableSourceId.Contains(d, StringComparison.Ordinal));
|
|
rawPaths.ShouldContain(r => source.StableSourceId.EndsWith(r, StringComparison.Ordinal));
|
|
checkedSources++;
|
|
}
|
|
}
|
|
}
|
|
checkedSources.ShouldBeGreaterThan(20); // the generator really produced driver-backed UNS references
|
|
}
|
|
|
|
/// <summary>
|
|
/// #917: an alarm-bearing raw tag gets no value (DriverHostActor keeps it out of the value fan-out, and #896 gives it
|
|
/// no UNS variable), so v1 exports it as the pre-existing explicit <c>UnsupportedVariable</c> kind: browsable, with
|
|
/// no Read/Subscribe/Write/HistoryRead bit, and Unsupported on every value operation — never a Variable that waits
|
|
/// forever. Its condition placements (A1) are untouched, and an export rooted at it still compiles.
|
|
/// </summary>
|
|
[Fact]
|
|
public void An_alarm_bearing_raw_tag_is_an_UnsupportedVariable_and_keeps_its_condition_placements_917()
|
|
{
|
|
using var fixture = new LocalDataFixture();
|
|
var catalog = LocalExportCatalog.Compile(Fixed(), fixture.Serving, fixture.Activation.CaptureAuthority());
|
|
var alarm = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
|
|
alarm.Supported.ShouldBeFalse();
|
|
alarm.Metadata.NodeKind.ShouldBe("UnsupportedVariable");
|
|
alarm.Metadata.ValueKind.ShouldBe(DataValueKind.Null);
|
|
alarm.Metadata.Writable.ShouldBeFalse();
|
|
// (Every value gate keys on Supported; the operations a caller sees are masked to Browse by LocalDataServices —
|
|
// pinned on the wire by GrpcDataV1RealOriginCompatibilityTests.)
|
|
// Positive controls: a plain tag is still a Variable, and the same tag without its alarm config is one too.
|
|
var speed = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
|
|
speed.Supported.ShouldBeTrue();
|
|
speed.Metadata.NodeKind.ShouldBe("Variable");
|
|
var plain = LocalExportCatalog.Compile(Fixed(withAlarms: false), fixture.Serving, fixture.Activation.CaptureAuthority())
|
|
.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "alarm-tag");
|
|
plain.Supported.ShouldBeTrue();
|
|
plain.Metadata.NodeKind.ShouldBe("Variable");
|
|
plain.Metadata.ValueKind.ShouldBe(DataValueKind.Boolean);
|
|
|
|
// Condition forwarding is unaffected: the Raw placement at its RawPath and both UNS placements remain.
|
|
catalog.PlacementsOf(new(AddressSpaceRealm.Raw, "Plant/Driver/Device/Group/OverTemp")).Count.ShouldBe(3);
|
|
catalog.ListConditions("raw-peer", LocalExportCatalog.RealmRoot("cluster", DataRealm.Raw), DataOperations.Subscribe,
|
|
ConditionKeys.FromSecret(Secret)).ShouldHaveSingleItem();
|
|
|
|
// A deployable export rooted at the alarm-bearing tag still compiles (the node is kept, not removed).
|
|
var b = Fixed();
|
|
Should.NotThrow(() => LocalExportCatalog.Compile(With(b, exports: [.. b.DataExports,
|
|
Export("tag-root", DataRealm.Raw, "tag-peer", rootKind: "RawTag", rootId: "alarm-tag")]), fixture.Serving, fixture.Activation.CaptureAuthority()));
|
|
}
|
|
|
|
private static (DraftSnapshot Snapshot, string[] RawPaths, string[] DriverIds, int ExpectedUnsNative) Generate(int seed)
|
|
{
|
|
var random = new Random(seed);
|
|
var snapshot = Fixed(withAlarms: false);
|
|
var folders = new List<RawFolder> { new() { RawFolderId = "f0", ClusterId = "cluster", Name = "Site" + seed } };
|
|
if (random.Next(2) == 0) folders.Add(new() { RawFolderId = "f1", ClusterId = "cluster", ParentRawFolderId = "f0", Name = "Cell" + seed });
|
|
var drivers = new List<DriverInstance>(); var devices = new List<Device>(); var groups = new List<TagGroup>(); var tags = new List<Tag>();
|
|
var rawPaths = new List<string>();
|
|
for (var d = 0; d < 1 + random.Next(3); d++)
|
|
{
|
|
var folder = folders[random.Next(folders.Count)];
|
|
var folderPath = folder.ParentRawFolderId is null ? folder.Name : folders[0].Name + "/" + folder.Name;
|
|
var driverId = $"drvid-{seed}-{d}-{random.Next(1000, 9999)}";
|
|
drivers.Add(new() { DriverInstanceId = driverId, ClusterId = "cluster", RawFolderId = folder.RawFolderId, Name = $"Drv{d}", DriverType = "ModbusTcp", DriverConfig = "{}" });
|
|
for (var v = 0; v < 1 + random.Next(2); v++)
|
|
{
|
|
var deviceId = $"{driverId}-dev{v}";
|
|
devices.Add(new() { DeviceId = deviceId, DriverInstanceId = driverId, Name = $"Dev{v}", DeviceConfig = "{}" });
|
|
string? groupId = null; var prefix = $"{folderPath}/Drv{d}/Dev{v}";
|
|
if (random.Next(2) == 0)
|
|
{
|
|
groupId = deviceId + "-g"; groups.Add(new() { TagGroupId = groupId, DeviceId = deviceId, Name = "Grp" });
|
|
if (random.Next(2) == 0)
|
|
{
|
|
var inner = groupId + "2"; groups.Add(new() { TagGroupId = inner, DeviceId = deviceId, ParentTagGroupId = groupId, Name = "Sub" });
|
|
groupId = inner; prefix += "/Grp/Sub";
|
|
}
|
|
else prefix += "/Grp";
|
|
}
|
|
for (var t = 0; t < 1 + random.Next(4); t++)
|
|
{
|
|
var alarm = random.Next(2) == 0;
|
|
var name = $"Pt{t}{(alarm ? "Alm" : "Val")}";
|
|
tags.Add(new() { TagId = $"{deviceId}-t{t}", DeviceId = deviceId, TagGroupId = groupId, Name = name, DataType = alarm ? "Boolean" : "Double",
|
|
AccessLevel = TagAccessLevel.Read, TagConfig = alarm ? AlarmConfig : "{}" });
|
|
rawPaths.Add($"{prefix}/{name}");
|
|
}
|
|
}
|
|
}
|
|
var equipment = new List<Equipment>(); var references = new List<UnsTagReference>(); var scripted = new List<ScriptedAlarm>();
|
|
var expected = 0;
|
|
for (var e = 0; e < 1 + random.Next(4); e++)
|
|
{
|
|
var equipmentId = $"eq-{seed}-{e}";
|
|
equipment.Add(new() { EquipmentId = equipmentId, UnsLineId = "line-id", Name = $"Mach{e}", MachineCode = $"M{e}" });
|
|
var picked = tags.OrderBy(_ => random.Next()).Take(random.Next(tags.Count + 1)).ToArray();
|
|
for (var r = 0; r < picked.Length; r++)
|
|
{
|
|
// Overrides are unique per equipment; without one the effective name is the tag name (a RawPath's last
|
|
// segment — legitimately visible, the whole RawPath is not).
|
|
var useOverride = random.Next(2) == 0 || picked.Take(r).Any(x => x.Name == picked[r].Name);
|
|
references.Add(new() { UnsTagReferenceId = $"{equipmentId}-r{r}", EquipmentId = equipmentId, TagId = picked[r].TagId,
|
|
DisplayNameOverride = useOverride ? $"Ref{r}" : null });
|
|
if (picked[r].TagConfig == AlarmConfig) expected++;
|
|
}
|
|
if (random.Next(2) == 0)
|
|
scripted.Add(new() { ScriptedAlarmId = $"sa-{seed}-{e}", EquipmentId = equipmentId, Name = $"Scr{e}", AlarmType = "AlarmCondition",
|
|
MessageTemplate = "m", PredicateScriptId = "script" });
|
|
}
|
|
snapshot = With(snapshot, folders, drivers, devices, groups, tags, equipment, references, scripted,
|
|
[Export("raw", DataRealm.Raw, "raw-peer"), Export("uns", DataRealm.Uns, "uns-peer")]);
|
|
return (snapshot, rawPaths.ToArray(), drivers.Select(x => x.DriverInstanceId).ToArray(), expected);
|
|
}
|
|
|
|
private static string Json<T>(T value) => JsonSerializer.Serialize(value);
|
|
}
|