using System.Security.Cryptography; using System.Text.Json; using Shouldly; using Xunit; 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; /// /// 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. /// [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? folders = null, IReadOnlyList? drivers = null, IReadOnlyList? devices = null, IReadOnlyList? groups = null, IReadOnlyList? tags = null, IReadOnlyList? equipment = null, IReadOnlyList? references = null, IReadOnlyList? scripted = null, IReadOnlyList? 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(); } /// 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. [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 Warnings { get; } = []; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception? exception, Func 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(() => keys.Derive("a\0b", AddressSpaceRealm.Raw, "c")); Should.Throw(() => 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(() => 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(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), compiled.Nodes, [], conditionPlacements: [bad])); Should.Throw(() => new LocalExportCatalog("cluster", fixture.Serving, fixture.Activation.CaptureAuthority(), compiled.Nodes, [], conditionPlacements: [uns, uns])); } /// /// #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. /// [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 } 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 { 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(); var devices = new List(); var groups = new List(); var tags = new List(); var rawPaths = new List(); 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(); var references = new List(); var scripted = new List(); 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 value) => JsonSerializer.Serialize(value); }