Merge A1 keys/placements/ids into A1 core
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
# A1 (placements / keys / ids) — progress log and evidence
|
||||
|
||||
Phase A1 of `docs/plans/2026-11-23-grpc-data-connections-history-alarms-plan.md` (rev. 7), the **placements / keys / ids**
|
||||
slice only, 2026-11-24. The condition-state machinery (NM snapshot, `state_known`, signals, `ConditionStateHub`) is a parallel
|
||||
branch and is not touched here (no NM, `OpcUaPublishActor`, driver or scripted-alarm-engine edits).
|
||||
|
||||
## Progress log
|
||||
|
||||
- [x] `ImportedConditionIds` (`c1.` identifier, child ids, condition namespace) + tests
|
||||
- [x] `ConditionKeys` derivation + `DataConnections:ConditionKeySecret` option/validation/registration + tests
|
||||
- [x] Realm-local condition placement enumeration in `LocalExportCatalog` (+ coordinator listing) + tests (UNS-only property test,
|
||||
with a red control: leaking `plan.NodeId` into a UNS placement's Subject turns the property test red)
|
||||
- [x] `A1` manifest key (Abstractions, Runtime, Host); gates below
|
||||
- Next (not this slice): A2 consumes `TryListConditions` with `DataOperations.AlarmSubscribe` once that bit is understood, puts
|
||||
`condition_key` + `ConditionInfo.placements` on the wire, and resolves method placements through
|
||||
`TryResolveConditionPlacement`; the core branch's `ConditionStateHub` maps a condition to its placements via `PlacementsOf`.
|
||||
|
||||
## Public API (for the core agent and A2)
|
||||
|
||||
| Where | API |
|
||||
|---|---|
|
||||
| `Core.Abstractions/DataConnections/ImportedConditionIds.cs` | `NamespaceUri` (`https://zb.com/otopcua/mapped/conditions`), `IsConditionNamespace(uri)`, `Identifier(connectionId, conditionKey)` ⇒ `c1.`+base64url(JSON{ConnectionId,ConditionKey}), `TryDecodeIdentifier(id, out connectionId, out conditionKey)` (bare condition, canonical only), `ChildIdentifier(conditionId, browsePath)`, `TryParse(id, out conditionIdentifier, out connectionId, out conditionKey, out browsePath?)` (splits at the first `/`), `IsValidBrowsePath`, `IsWellFormedConditionKey` (43 base64url chars = 32 bytes), `ConditionKeyLength`, `ChildSeparator` |
|
||||
| `Runtime/DataConnections/ConditionKeys.cs` | `ConditionKeys.FromSecret(secret)` (absent ⇒ `Unavailable`; weak ⇒ `ArgumentException`), `Unavailable`, `IsAvailable`, `UnavailableReason`, `Derive(originClusterId, AddressSpaceRealm, conditionId)`, `SecretProblem(secret)`, `IsProvisioned`, `MinimumSecretBytes` (32), `DerivationInfo` |
|
||||
| `Runtime/DataConnections/ConditionPlacements.cs` | `ConditionSourceKind {Native=1, Scripted=2}`, `OriginConditionRef(AddressSpaceRealm Realm, string ConditionId)` (origin-internal; the NM realm key), `LocalConditionPlacement(View, Parent, Scope, BrowseName, SourceKind, Condition, EntityKind, EntityId)` (origin-internal) + `ToView()`, `ConditionPlacementView(View, Parent, BrowseName)` and `ExportedCondition(ConditionKey, SourceKind, Placements)` (peer-safe) |
|
||||
| `LocalExportCatalog` | `ConditionPlacements`, `TryResolveConditionPlacement(view, out placement)` (unmapped address+realm; Subject ignored), `PlacementsOf(OriginConditionRef)`, `ListConditions(principal, root, operation, keys)`, internal `AllowsConditionPlacement(principal, placement, operation)`; ctor gained optional `conditionPlacements` |
|
||||
| `LocalCatalogCoordinator` | `ConditionKeys { get; init; }` (default `Unavailable`; the host wires the configured one), `TryListConditions(principal, root, operation, out conditions)` (false while no catalog is served or no secret) |
|
||||
| Host | `DataConnectionOptions.ConditionKeySecret`; `ConditionKeys` singleton; one Information log of the fail-closed diagnostic when absent |
|
||||
|
||||
## Placements (§5.2)
|
||||
|
||||
- **Raw**: every alarm-bearing raw tag (`RawTagPlan.Alarm != null`): View = raw ns at the RawPath, Parent = its device/group
|
||||
folder, Scope = the raw tag's ACL subject, Condition = `(Raw, RawPath)`.
|
||||
- **UNS native**: every `UnsTagReference` (in the cluster) to an alarm-bearing tag: View = uns ns at the reserved id
|
||||
`V3NodeIds.UnsChild(V3NodeIds.Uns(area, line, equipment), effectiveName)` — the same derivation the composer skips for #896;
|
||||
Subject = that id; Parent = the equipment's catalog view (identifier = EquipmentId); Scope = `DataScopeSubjects.Owned(equipment
|
||||
scope)`; Condition = `(Raw, RawPath)` (internal only).
|
||||
- **UNS scripted**: every **enabled** `EquipmentScriptedAlarmPlan` (the producer the NM materialises from): View = uns ns at the
|
||||
ScriptedAlarmId, Subject = equipment path + alarm name, Parent = equipment, Scope = equipment-owned, Condition = `(Uns, ScriptedAlarmId)`.
|
||||
- Listing (`ListConditions`): placements in the root's realm whose parent is under the root and that pass the principal's export
|
||||
rule for the operation, grouped by condition, keyed with `condition_key`; ordered by key, placements by identifier.
|
||||
|
||||
## Decisions / deviations
|
||||
|
||||
1. **Realm byte in the key input.** The plan's formula is `HMAC(K, originClusterId ‖ 0x00 ‖ ConditionId)`. Implemented as
|
||||
`HMAC(K, upper(originClusterId) ‖ 0x00 ‖ realm(1=Raw|2=Uns) ‖ ConditionId)`: a native ConditionId (RawPath) and a scripted one
|
||||
(ScriptedAlarmId) live in the NM's realm-keyed map and nothing prevents equal strings, so the realm keeps two conditions from
|
||||
sharing a key. Cluster ids are upper-cased (they compare OrdinalIgnoreCase everywhere). HKDF uses an empty salt; output 32 bytes.
|
||||
2. **Missing secret is not a startup error** (§5.2 "fail closed, with a diagnostic"): `ConditionKeys.Unavailable` + one Information
|
||||
log line. A **provisioned** secret that is < 32 UTF-8 bytes, blank, contains control characters or still holds an unexpanded
|
||||
`${secret:` is a `DataConnectionOptionsValidator` error (startup), only while `DataConnections:Enabled`. Messages never echo
|
||||
the value. No dev literal added to docker-dev / grpc-data rig (A1 is invisible; A2/A3 will need one on the rig's origins).
|
||||
3. **Operation-parameterised listing.** `ListConditions` takes the required export bit. A2 passes `AlarmSubscribe`; today
|
||||
`DataOperationSets.Understood` masks it out of every export rule, so production listings are empty until A2 — tests use
|
||||
`Subscribe`. No wire, proto or v1-listing change.
|
||||
4. **Placements are a separate index, not catalog nodes.** A Raw placement shares its address with the v1 raw tag node (#917);
|
||||
UNS placements have no node (#896). They are not counted in `maximumNodes` (a v1 catalog that compiled before still compiles).
|
||||
An address claimed by two placements is dropped (fail closed for conditions) rather than failing the compile.
|
||||
5. **Composer now gets the cluster's scripted alarms** (`LocalExportCatalog.Compile` passed `[]` before) so scripted placements
|
||||
come from the same `EquipmentScriptedAlarms` the NM materialises; a test pins that the v1 node set is identical with and
|
||||
without them.
|
||||
6. **UNS native placement scope** = equipment-owned subject (§5.2 "authorized against that placement's origin ACL subject (the
|
||||
equipment scope)"), not the reference's tag-level path.
|
||||
7. `ImportedConditionIds` is **not** added to `ProjectedDataIds.IsMappedNamespace` (that would change v1 classifiers/NM); the core
|
||||
branch must dispatch `IsConditionNamespace` before `RealmOf` (guard test is theirs/A3's).
|
||||
|
||||
## Questions (tracked, not asked)
|
||||
|
||||
- Q-A1k-1: should the plan text adopt the realm byte (deviation 1)? A2 golden tests should pin the exact derivation.
|
||||
- Q-A1k-2: rig provisioning — A2 needs `DataConnections__ConditionKeySecret` on both `source-*` services in
|
||||
`scripts/validation/grpc-data/compose.yml` (a dev literal, identical on the pair).
|
||||
|
||||
## Gates
|
||||
|
||||
| Gate | Result |
|
||||
|---|---|
|
||||
| `dotnet build ZB.MOM.WW.OtOpcUa.slnx` | 0 errors / 0 warnings |
|
||||
| `run-unit-phase.py A1` (Abstractions 7 + Runtime 8 + `GrpcDataLocalExportCatalogTests` + Host 7 + `GrpcDataV1RealOriginCompatibilityTests`) | passed |
|
||||
| `run-unit-phase.py X0`, `H2` | passed |
|
||||
| `test_unit_phase_runner.py` | 30 passed |
|
||||
| Runtime.Tests (`Category!=E2E&Category!=LiveIntegration`) | 1923 passed, 3 skipped, 0 failed |
|
||||
| Core.Abstractions.Tests (full) | 860 passed |
|
||||
| Host.Tests `.DataConnections.` | 196 passed |
|
||||
| Red control | UNS placement Subject = RawPath ⇒ the property test fails (reverted) |
|
||||
@@ -925,7 +925,8 @@
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=H4)|FullyQualifiedName~.GrpcDataProjectedHistoryCursorTests.|FullyQualifiedName~.GrpcDataOriginHistorySessionTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataHistoryMetricsTests", "GrpcDataDiagnosticsSerializationTests"
|
||||
"GrpcDataHistoryMetricsTests",
|
||||
"GrpcDataDiagnosticsSerializationTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"GrpcDataConfiguredDiscoveryWireTests",
|
||||
@@ -967,18 +968,20 @@
|
||||
},
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/ZB.MOM.WW.OtOpcUa.Runtime.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=A1)|FullyQualifiedName~.OpcUaPublishActorDeferredWriteTests.|FullyQualifiedName~.DriverInstanceActorNativeAlarmTests.|FullyQualifiedName~.DriverHostActorNativeAlarmTests.|FullyQualifiedName~.ScriptedAlarmHostActorTests.",
|
||||
"filter": "(Feature=GrpcData&Phase=A1)|FullyQualifiedName~.OpcUaPublishActorDeferredWriteTests.|FullyQualifiedName~.DriverInstanceActorNativeAlarmTests.|FullyQualifiedName~.DriverHostActorNativeAlarmTests.|FullyQualifiedName~.ScriptedAlarmHostActorTests.|FullyQualifiedName~.GrpcDataLocalExportCatalogTests.",
|
||||
"new_classes": [
|
||||
"ConditionStateHubTests",
|
||||
"OpcUaPublishActorConditionKnownTests",
|
||||
"NativeAlarmInitialStateSignalTests",
|
||||
"ScriptedAlarmHostInputsEstablishedTests"
|
||||
"ScriptedAlarmHostInputsEstablishedTests",
|
||||
"GrpcDataConditionPlacementTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"OpcUaPublishActorDeferredWriteTests",
|
||||
"DriverInstanceActorNativeAlarmTests",
|
||||
"DriverHostActorNativeAlarmTests",
|
||||
"ScriptedAlarmHostActorTests"
|
||||
"ScriptedAlarmHostActorTests",
|
||||
"GrpcDataLocalExportCatalogTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -999,6 +1002,24 @@
|
||||
"DeferredSinkForwardingReflectionTests",
|
||||
"DeferredAddressSpaceSinkTests"
|
||||
]
|
||||
},
|
||||
{
|
||||
"project": "tests/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests/ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=A1)",
|
||||
"new_classes": [
|
||||
"GrpcDataImportedConditionIdsTests"
|
||||
],
|
||||
"existing_classes": []
|
||||
},
|
||||
{
|
||||
"project": "tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/ZB.MOM.WW.OtOpcUa.Host.Tests.csproj",
|
||||
"filter": "(Feature=GrpcData&Phase=A1)|FullyQualifiedName~.GrpcDataV1RealOriginCompatibilityTests.",
|
||||
"new_classes": [
|
||||
"GrpcDataConditionKeySecretTests"
|
||||
],
|
||||
"existing_classes": [
|
||||
"GrpcDataV1RealOriginCompatibilityTests"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A1 (§5.2 "Imported condition NodeId", N4): the consumer-local identifier of an imported condition, in a third mapped
|
||||
/// namespace beside <see cref="ProjectedDataIds.RawNamespaceUri"/> / <see cref="ProjectedDataIds.UnsNamespaceUri"/>.
|
||||
/// <para>
|
||||
/// The identifier is keyed on <c>(DataConnectionId, condition_key)</c> only — never the mapping, the home placement
|
||||
/// or stream order — so disabling, adding or re-ordering mappings never changes it. It is
|
||||
/// <c>c1.</c> + base64url(JSON{ConnectionId, ConditionKey}); a condition child (#629) is
|
||||
/// <c><identifier>/<browse path></c>, split at the FIRST <c>/</c> (base64url has none).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// ⚠️ This namespace is NOT one of <see cref="ProjectedDataIds.IsMappedNamespace"/>'s and has no
|
||||
/// <see cref="DataRealm"/>: anything that classifies a NodeId (authorizer, history, read, call) must dispatch
|
||||
/// <see cref="IsConditionNamespace"/> BEFORE folding a namespace into a realm (the node manager's <c>RealmOf</c> folds
|
||||
/// every index other than 0/2 into Uns). Decoding never establishes authorization.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public static class ImportedConditionIds
|
||||
{
|
||||
/// <summary>The imported-condition namespace (registered by the consumer beside the two mapped namespaces).</summary>
|
||||
public const string NamespaceUri = "https://zb.com/otopcua/mapped/conditions";
|
||||
|
||||
/// <summary>Separates a condition identifier from a child browse path.</summary>
|
||||
public const char ChildSeparator = '/';
|
||||
|
||||
/// <summary>A well-formed <c>condition_key</c> is base64url (unpadded) of a 32-byte HMAC-SHA256: 43 characters.</summary>
|
||||
public const int ConditionKeyLength = 43;
|
||||
|
||||
/// <summary>Upper bound of a connection id inside the identifier (the ConfigDb key is far shorter).</summary>
|
||||
public const int MaximumConnectionIdLength = 256;
|
||||
|
||||
/// <summary>Upper bound of a whole identifier, child path included.</summary>
|
||||
public const int MaximumIdentifierLength = 4_096;
|
||||
|
||||
private const string Prefix = "c1.";
|
||||
private sealed record Identity(string ConnectionId, string ConditionKey);
|
||||
|
||||
public static bool IsConditionNamespace(string? namespaceUri) =>
|
||||
string.Equals(namespaceUri, NamespaceUri, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>True for an opaque key of the shape the origin mints (43 base64url characters decoding to 32 bytes).</summary>
|
||||
public static bool IsWellFormedConditionKey(string? conditionKey)
|
||||
{
|
||||
if (conditionKey is null || conditionKey.Length != ConditionKeyLength || !IsBase64Url(conditionKey)) return false;
|
||||
// 43 chars carry 258 bits; the last character's low 2 bits must be zero for a canonical 32-byte encoding.
|
||||
return (Base64UrlValue(conditionKey[^1]) & 0b11) == 0;
|
||||
}
|
||||
|
||||
/// <summary>The condition identifier for <paramref name="connectionId"/> and an origin <paramref name="conditionKey"/>.</summary>
|
||||
public static string Identifier(string connectionId, string conditionKey)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(connectionId);
|
||||
if (connectionId.Length > MaximumConnectionIdLength || connectionId.Any(char.IsControl))
|
||||
throw new ArgumentOutOfRangeException(nameof(connectionId));
|
||||
if (!IsWellFormedConditionKey(conditionKey))
|
||||
throw new ArgumentException("A condition key is 43 base64url characters.", nameof(conditionKey));
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(new Identity(connectionId, conditionKey));
|
||||
return Prefix + Convert.ToBase64String(payload).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
|
||||
/// <summary>A child (#629) of a condition: <c><identifier>/<browse path></c>.</summary>
|
||||
public static string ChildIdentifier(string conditionIdentifier, string browsePath)
|
||||
{
|
||||
if (!TryDecodeIdentifier(conditionIdentifier, out _, out _))
|
||||
throw new ArgumentException("Invalid imported condition identifier.", nameof(conditionIdentifier));
|
||||
if (!IsValidBrowsePath(browsePath)) throw new ArgumentException("Invalid child browse path.", nameof(browsePath));
|
||||
var child = conditionIdentifier + ChildSeparator + browsePath;
|
||||
if (child.Length > MaximumIdentifierLength) throw new ArgumentOutOfRangeException(nameof(browsePath));
|
||||
return child;
|
||||
}
|
||||
|
||||
/// <summary>Decodes a bare condition identifier (no child path). Canonical encodings only.</summary>
|
||||
public static bool TryDecodeIdentifier(string? identifier, out string connectionId, out string conditionKey)
|
||||
{
|
||||
connectionId = string.Empty; conditionKey = string.Empty;
|
||||
if (identifier is null || identifier.Length > MaximumIdentifierLength || !identifier.StartsWith(Prefix, StringComparison.Ordinal))
|
||||
return false;
|
||||
var encoded = identifier[Prefix.Length..];
|
||||
if (encoded.Length == 0 || !IsBase64Url(encoded)) return false;
|
||||
try
|
||||
{
|
||||
var padded = encoded.Replace('-', '+').Replace('_', '/');
|
||||
padded = padded.PadRight((padded.Length + 3) / 4 * 4, '=');
|
||||
var parsed = JsonSerializer.Deserialize<Identity>(Convert.FromBase64String(padded));
|
||||
if (parsed?.ConnectionId is null || parsed.ConditionKey is null
|
||||
|| !string.Equals(Identifier(parsed.ConnectionId, parsed.ConditionKey), identifier, StringComparison.Ordinal))
|
||||
return false;
|
||||
connectionId = parsed.ConnectionId; conditionKey = parsed.ConditionKey;
|
||||
return true;
|
||||
}
|
||||
catch (Exception error) when (error is JsonException or FormatException or ArgumentException)
|
||||
{ return false; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a condition identifier or a child of one. <paramref name="conditionIdentifier"/> is the bare condition part,
|
||||
/// <paramref name="browsePath"/> null for the condition itself.
|
||||
/// </summary>
|
||||
public static bool TryParse(string? identifier, out string conditionIdentifier, out string connectionId,
|
||||
out string conditionKey, out string? browsePath)
|
||||
{
|
||||
conditionIdentifier = string.Empty; connectionId = string.Empty; conditionKey = string.Empty; browsePath = null;
|
||||
if (identifier is null || identifier.Length > MaximumIdentifierLength) return false;
|
||||
var split = identifier.IndexOf(ChildSeparator);
|
||||
var head = split < 0 ? identifier : identifier[..split];
|
||||
string? tail = split < 0 ? null : identifier[(split + 1)..];
|
||||
if (tail is not null && !IsValidBrowsePath(tail)) return false;
|
||||
if (!TryDecodeIdentifier(head, out connectionId, out conditionKey)) return false;
|
||||
conditionIdentifier = head; browsePath = tail;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A non-empty <c>/</c>-joined path of non-empty segments with no control characters.</summary>
|
||||
public static bool IsValidBrowsePath(string? browsePath) =>
|
||||
!string.IsNullOrEmpty(browsePath) && browsePath.Length < MaximumIdentifierLength
|
||||
&& !browsePath.Split(ChildSeparator).Any(string.IsNullOrEmpty) && !browsePath.Any(char.IsControl);
|
||||
|
||||
private static bool IsBase64Url(string value) => value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_');
|
||||
|
||||
private static int Base64UrlValue(char c) => c switch
|
||||
{
|
||||
>= 'A' and <= 'Z' => c - 'A',
|
||||
>= 'a' and <= 'z' => c - 'a' + 26,
|
||||
>= '0' and <= '9' => c - '0' + 52,
|
||||
'-' => 62,
|
||||
_ => 63
|
||||
};
|
||||
}
|
||||
@@ -27,4 +27,12 @@ public sealed class DataConnectionOptions
|
||||
public string? CredentialBundlePath { get; set; }
|
||||
public string? TrustBundlePath { get; set; }
|
||||
public TimeSpan BundleRefreshInterval { get; set; } = TimeSpan.FromSeconds(1);
|
||||
/// <summary>
|
||||
/// A1 (§5.2/§6): the per-origin-cluster secret the <c>condition_key</c> is derived from. Supply it as a
|
||||
/// <c>${secret:…}</c> reference or the <c>DataConnections__ConditionKeySecret</c> environment variable, identical on
|
||||
/// both pair members — never a committed literal. Absent ⇒ the origin advertises no conditions capability (fail
|
||||
/// closed, with a diagnostic); present but shorter than 32 bytes ⇒ a startup error. Rotating it changes every
|
||||
/// imported condition's NodeId on the consumers (a planned operation).
|
||||
/// </summary>
|
||||
public string? ConditionKeySecret { get; set; }
|
||||
}
|
||||
|
||||
@@ -39,6 +39,10 @@ public sealed class DataConnectionOptionsValidator(IHostEnvironment environment)
|
||||
if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5)
|
||||
|| options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1))
|
||||
errors.Add("Unary and stream-command timeouts must be finite and within supported limits.");
|
||||
// A1: an absent condition-key secret is NOT an error (the origin just never advertises conditions); a provisioned
|
||||
// one that is too short, blank or still an unexpanded ${secret:} reference is.
|
||||
if (ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionKeys.SecretProblem(options.ConditionKeySecret) is { } secretProblem)
|
||||
errors.Add(secretProblem);
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,8 @@ public static class DataConnectionRegistration
|
||||
return new DataConnectionProcessIdentity(role.ClusterId, role.LocalNode.Value, Guid.NewGuid().ToString("N"));
|
||||
});
|
||||
services.AddSingleton(sp => new CatalogActivation(sp.GetRequiredService<DataWriteDispatchFence>()));
|
||||
// A1: the condition-key deriver (validated above; absent secret ⇒ Unavailable, conditions never advertised).
|
||||
services.AddSingleton(_ => ConditionKeys.FromSecret(options.ConditionKeySecret));
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var identity = sp.GetRequiredService<DataConnectionProcessIdentity>();
|
||||
@@ -58,7 +60,11 @@ public static class DataConnectionRegistration
|
||||
var state = CaptureReadRole(role, warm);
|
||||
var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role;
|
||||
return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation);
|
||||
}) { Logger = LoggerFor<LocalCatalogCoordinator>(sp) };
|
||||
})
|
||||
{
|
||||
Logger = LoggerFor<LocalCatalogCoordinator>(sp),
|
||||
ConditionKeys = ReportConditionKeys(sp.GetRequiredService<ConditionKeys>(), LoggerFor<LocalCatalogCoordinator>(sp))
|
||||
};
|
||||
});
|
||||
services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService<TimeProvider>()));
|
||||
services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService<PartitionedSampleHub>(),
|
||||
@@ -261,6 +267,13 @@ public static class DataConnectionRegistration
|
||||
return options;
|
||||
}
|
||||
|
||||
/// <summary>A1 fail-closed diagnostic: an origin without a condition-key secret says so once, when its catalog starts.</summary>
|
||||
private static ConditionKeys ReportConditionKeys(ConditionKeys keys, Microsoft.Extensions.Logging.ILogger logger)
|
||||
{
|
||||
if (!keys.IsAvailable)
|
||||
Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(logger, "{Reason}", keys.UnavailableReason);
|
||||
return keys;
|
||||
}
|
||||
private static Microsoft.Extensions.Logging.ILogger LoggerFor<T>(IServiceProvider sp) =>
|
||||
(Microsoft.Extensions.Logging.ILogger?)sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<T>()
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A1 (§5.2 "Dedupe key", N3, m-T6): mints the opaque <c>condition_key</c> an origin puts on every condition record.
|
||||
/// <para>
|
||||
/// <c>condition_key = base64url(HMAC-SHA256(K, upper(originClusterId) ‖ 0x00 ‖ realm ‖ ConditionId))</c>, with
|
||||
/// <c>K = HKDF-SHA256(DataConnections:ConditionKeySecret, info = "otopcua/condition-key/v1")</c>. The realm byte
|
||||
/// (1 = Raw, 2 = Uns — the node manager's condition realm key) is an A1 addition to the plan's formula: a native
|
||||
/// ConditionId is a RawPath and a scripted one a ScriptedAlarmId, and nothing stops the two spaces from sharing a
|
||||
/// string, so the realm keeps two distinct conditions from sharing a key.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The key depends only on the secret, the origin cluster and the condition: it is stable across restarts,
|
||||
/// failover and re-deploys, identical on both pair members (the secret is a per-cluster <c>${secret:}</c>), and
|
||||
/// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements.
|
||||
/// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id
|
||||
/// (unlike <c>Metadata.stable_source_id</c>, #916).
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Without a secret the origin advertises no <c>conditions</c> capability (fail closed): <see cref="IsAvailable"/>
|
||||
/// is false and <see cref="UnavailableReason"/> is the diagnostic. A present but unusable secret is a configuration
|
||||
/// error (<see cref="SecretProblem"/>, enforced by the host's DataConnections options validator).
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class ConditionKeys
|
||||
{
|
||||
/// <summary>The configuration key, for diagnostics.</summary>
|
||||
public const string ConfigurationKey = "DataConnections:ConditionKeySecret";
|
||||
|
||||
/// <summary>Minimum secret length in UTF-8 bytes (256 bits of input keying material).</summary>
|
||||
public const int MinimumSecretBytes = 32;
|
||||
|
||||
/// <summary>HKDF <c>info</c>: versions the derivation, so a future scheme cannot collide with this one.</summary>
|
||||
public const string DerivationInfo = "otopcua/condition-key/v1";
|
||||
|
||||
/// <summary>The fail-closed diagnostic when no secret is provisioned.</summary>
|
||||
public const string NotProvisionedReason =
|
||||
ConfigurationKey + " is not provisioned; this origin does not advertise the conditions capability.";
|
||||
|
||||
private readonly byte[]? _key;
|
||||
|
||||
private ConditionKeys(byte[]? key, string? unavailableReason)
|
||||
{
|
||||
_key = key;
|
||||
UnavailableReason = unavailableReason;
|
||||
}
|
||||
|
||||
/// <summary>An instance that never derives (no secret).</summary>
|
||||
public static ConditionKeys Unavailable { get; } = new(null, NotProvisionedReason);
|
||||
|
||||
/// <summary>Whether a secret is provisioned and keys can be derived.</summary>
|
||||
public bool IsAvailable => _key is not null;
|
||||
|
||||
/// <summary>Why <see cref="IsAvailable"/> is false; null when available.</summary>
|
||||
public string? UnavailableReason { get; }
|
||||
|
||||
/// <summary>True when a secret value is configured at all (null/empty means "not provisioned", never an error).</summary>
|
||||
public static bool IsProvisioned(string? secret) => !string.IsNullOrEmpty(secret);
|
||||
|
||||
/// <summary>
|
||||
/// The configuration error for a PROVISIONED but unusable secret, or null (absent or valid). Never echoes the value.
|
||||
/// </summary>
|
||||
public static string? SecretProblem(string? secret)
|
||||
{
|
||||
if (!IsProvisioned(secret)) return null;
|
||||
if (secret!.Contains("${secret:", StringComparison.OrdinalIgnoreCase))
|
||||
return ConfigurationKey + " still holds an unexpanded ${secret:} reference.";
|
||||
if (string.IsNullOrWhiteSpace(secret) || secret.Any(char.IsControl))
|
||||
return ConfigurationKey + " must not be blank or contain control characters.";
|
||||
if (Encoding.UTF8.GetByteCount(secret) < MinimumSecretBytes)
|
||||
return $"{ConfigurationKey} must be at least {MinimumSecretBytes} bytes; generate a random per-cluster secret.";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the deriver from the configured secret: <see cref="Unavailable"/> when absent; throws
|
||||
/// <see cref="ArgumentException"/> (without the value) when provisioned but unusable.
|
||||
/// </summary>
|
||||
public static ConditionKeys FromSecret(string? secret)
|
||||
{
|
||||
if (!IsProvisioned(secret)) return Unavailable;
|
||||
if (SecretProblem(secret) is { } problem) throw new ArgumentException(problem, nameof(secret));
|
||||
var material = Encoding.UTF8.GetBytes(secret!);
|
||||
try
|
||||
{
|
||||
return new(HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 32, salt: [],
|
||||
info: Encoding.UTF8.GetBytes(DerivationInfo)), null);
|
||||
}
|
||||
finally { CryptographicOperations.ZeroMemory(material); }
|
||||
}
|
||||
|
||||
/// <summary>The key for one origin condition; throws when <see cref="IsAvailable"/> is false.</summary>
|
||||
public string Derive(string originClusterId, AddressSpaceRealm realm, string conditionId)
|
||||
{
|
||||
if (_key is null) throw new InvalidOperationException(UnavailableReason);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(originClusterId);
|
||||
ArgumentException.ThrowIfNullOrEmpty(conditionId);
|
||||
if (originClusterId.Contains('\0')) throw new ArgumentException("Cluster ids cannot contain NUL.", nameof(originClusterId));
|
||||
if (realm is not (AddressSpaceRealm.Raw or AddressSpaceRealm.Uns)) throw new ArgumentOutOfRangeException(nameof(realm));
|
||||
var cluster = Encoding.UTF8.GetBytes(originClusterId.ToUpperInvariant());
|
||||
var condition = Encoding.UTF8.GetBytes(conditionId);
|
||||
var message = new byte[cluster.Length + 2 + condition.Length];
|
||||
cluster.CopyTo(message, 0);
|
||||
message[cluster.Length] = 0;
|
||||
message[cluster.Length + 1] = realm == AddressSpaceRealm.Raw ? (byte)1 : (byte)2;
|
||||
condition.CopyTo(message, cluster.Length + 2);
|
||||
var key = Convert.ToBase64String(HMACSHA256.HashData(_key, message)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
System.Diagnostics.Debug.Assert(ImportedConditionIds.IsWellFormedConditionKey(key));
|
||||
return key;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>A1: where an origin condition comes from (wire <c>ConditionInfo.source_kind</c> NATIVE / SCRIPTED).</summary>
|
||||
public enum ConditionSourceKind { Unspecified = 0, Native = 1, Scripted = 2 }
|
||||
|
||||
/// <summary>
|
||||
/// A1: an origin condition's identity in the node manager — the realm key its condition is registered under
|
||||
/// (<c>(Raw, RawPath)</c> for a native condition, <c>(Uns, ScriptedAlarmId)</c> for a scripted one).
|
||||
/// ⚠️ ORIGIN-INTERNAL: a native <see cref="ConditionId"/> IS a RawPath; it never goes on the wire (the wire carries
|
||||
/// the keyed <c>condition_key</c> instead, <see cref="ConditionKeys"/>).
|
||||
/// </summary>
|
||||
public readonly record struct OriginConditionRef(AddressSpaceRealm Realm, string ConditionId);
|
||||
|
||||
/// <summary>
|
||||
/// A1 (§5.2 "Addressing within the listing export's realm"): one realm-local placement of an origin condition, as the
|
||||
/// origin's catalog knows it.
|
||||
/// <list type="bullet">
|
||||
/// <item>Raw: <see cref="View"/> = the raw namespace at the RawPath; <see cref="Parent"/> = its device/group folder;
|
||||
/// <see cref="Scope"/> = the raw tag's ACL subject.</item>
|
||||
/// <item>UNS native: <see cref="View"/> = the uns namespace at the RESERVED reference id
|
||||
/// <c>Area/Line/Equipment/EffectiveName</c> of each <c>UnsTagReference</c> to the alarm-bearing tag (no UNS node
|
||||
/// exists there, #896; the effective-name guard reserves it); <see cref="Parent"/> = that equipment;
|
||||
/// <see cref="Scope"/> = the equipment-owned subject.</item>
|
||||
/// <item>UNS scripted: <see cref="View"/> = the uns namespace at the ScriptedAlarmId; <see cref="Parent"/> = its
|
||||
/// equipment; <see cref="Scope"/> = the equipment-owned subject. Scripted conditions have no Raw placement.</item>
|
||||
/// </list>
|
||||
/// ⚠️ ORIGIN-INTERNAL (carries <see cref="Condition"/>). What may reach a peer is
|
||||
/// <see cref="ConditionPlacementView"/>, via <see cref="LocalExportCatalog.ListConditions"/>.
|
||||
/// </summary>
|
||||
public sealed record LocalConditionPlacement(DataView View, DataView Parent, NodeScope Scope, string BrowseName,
|
||||
ConditionSourceKind SourceKind, OriginConditionRef Condition, string EntityKind, string EntityId)
|
||||
{
|
||||
/// <summary>The peer-safe projection: address, parent and name, in the placement's own realm.</summary>
|
||||
public ConditionPlacementView ToView() => new(View, Parent, BrowseName);
|
||||
}
|
||||
|
||||
/// <summary>A1: a placement as a listing may carry it (no origin condition id, no backing source).</summary>
|
||||
public sealed record ConditionPlacementView(DataView View, DataView Parent, string BrowseName);
|
||||
|
||||
/// <summary>
|
||||
/// A1: one condition as an export listing presents it — the opaque <see cref="ConditionKey"/> (equal across every
|
||||
/// listing, principal, restart and pair member) and its placements INSIDE the listed export root, all in that root's
|
||||
/// realm. Nothing here names a RawPath unless the listing is itself a Raw listing.
|
||||
/// </summary>
|
||||
public sealed record ExportedCondition(string ConditionKey, ConditionSourceKind SourceKind,
|
||||
IReadOnlyList<ConditionPlacementView> Placements);
|
||||
@@ -50,6 +50,25 @@ public sealed class LocalCatalogCoordinator
|
||||
/// <summary>Diagnostics sink for the X0 dropped export-operation warning.</summary>
|
||||
public Microsoft.Extensions.Logging.ILogger Logger { private get; init; } = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
/// <summary>
|
||||
/// A1: the origin's condition-key deriver (<c>DataConnections:ConditionKeySecret</c>). Unavailable by default, so an
|
||||
/// origin without a secret lists no conditions (fail closed).
|
||||
/// </summary>
|
||||
public ConditionKeys ConditionKeys { get; init; } = ConditionKeys.Unavailable;
|
||||
|
||||
/// <summary>
|
||||
/// A1: the served catalog's condition listing for one export root (<see cref="LocalExportCatalog.ListConditions"/>).
|
||||
/// False — nothing listed — while no catalog is served or no condition-key secret is provisioned.
|
||||
/// </summary>
|
||||
public bool TryListConditions(string principal, DataView root, DataOperations operation,
|
||||
out IReadOnlyList<ExportedCondition> conditions)
|
||||
{
|
||||
conditions = [];
|
||||
if (!ConditionKeys.IsAvailable || Current is not { } catalog) return false;
|
||||
conditions = catalog.ListConditions(principal, root, operation, ConditionKeys);
|
||||
return true;
|
||||
}
|
||||
|
||||
public LocalCatalogCoordinator(CatalogActivation activation, DataPlaneAuthorityState authority, Func<ServingIdentity> serving)
|
||||
{
|
||||
_activation = activation ?? throw new ArgumentNullException(nameof(activation));
|
||||
|
||||
+62
-3
@@ -62,9 +62,13 @@ public sealed partial class LocalExportCatalog
|
||||
areas.ToDictionary(x => x.UnsAreaId, x => x.Name, ids),
|
||||
lines.ToDictionary(x => x.UnsLineId, x => (x.UnsAreaId, x.Name), ids),
|
||||
equipment.ToDictionary(x => x.EquipmentId, x => (x.UnsLineId, x.Name), ids), referenceNames);
|
||||
var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, [], virtuals,
|
||||
// A1: the cluster's scripted alarms ride the same composition so their placements come from the producer the node
|
||||
// manager materialises (EquipmentScriptedAlarms); nothing the v1 catalog reads depends on them.
|
||||
var scriptedAlarms = snapshot.ScriptedAlarms.Where(x => equipmentIds.Contains(x.EquipmentId)).ToArray();
|
||||
var composition = AddressSpaceComposer.Compose(areas, lines, equipment, drivers, scriptedAlarms, virtuals,
|
||||
snapshot.Scripts, references, tags, folders, devices, groups);
|
||||
var nodes = new List<LocalDataNode>((int)count);
|
||||
var conditionPlacements = new List<LocalConditionPlacement>();
|
||||
var views = new Dictionary<(DataRealm Realm, string Kind, string Id), DataView>();
|
||||
var rawViewsByPath = new Dictionary<string, DataView>(StringComparer.Ordinal);
|
||||
const DataOperations navigation = DataOperations.Browse | DataOperations.Metadata;
|
||||
@@ -127,9 +131,14 @@ public sealed partial class LocalExportCatalog
|
||||
rawSources.Add(plan.NodeId, (source, enabled));
|
||||
var kind = ValueKind(plan.DataType);
|
||||
var supported = kind != DataValueKind.Unspecified && (!plan.IsArray || DataValue.IsSupportedArrayElementKind(kind));
|
||||
Add("RawTag", plan.TagId, plan.Name, View(DataRealm.Raw, plan.NodeId, scope), scope, RawParent(scope), source,
|
||||
var rawView = View(DataRealm.Raw, plan.NodeId, scope);
|
||||
Add("RawTag", plan.TagId, plan.Name, rawView, scope, RawParent(scope), source,
|
||||
supported ? kind : DataValueKind.Null, plan.Writable && (!plan.IsArray || plan.ArrayWritable),
|
||||
plan.IsArray, plan.ArrayLength, supported, enabled);
|
||||
// A1: a native condition's Raw placement is its RawPath (ConditionId = RawPath), under its device/group folder.
|
||||
if (plan.Alarm is not null)
|
||||
conditionPlacements.Add(new(rawView, RawParent(scope), scope, plan.Name, ConditionSourceKind.Native,
|
||||
new(AddressSpaceRealm.Raw, plan.NodeId), "RawTag", plan.TagId));
|
||||
}
|
||||
foreach (var area in areas)
|
||||
{
|
||||
@@ -141,9 +150,11 @@ public sealed partial class LocalExportCatalog
|
||||
var scope = Scope(NodeAclScopeKind.UnsLine, line.UnsLineId, DataRealm.Uns);
|
||||
Add("UnsLine", line.UnsLineId, line.Name, View(DataRealm.Uns, line.UnsLineId, scope), scope, views[(DataRealm.Uns, "UnsArea", line.UnsAreaId.ToUpperInvariant())]);
|
||||
}
|
||||
var equipmentScopes = new Dictionary<string, NodeScope>(ids);
|
||||
foreach (var item in equipment)
|
||||
{
|
||||
var scope = Scope(NodeAclScopeKind.Equipment, item.EquipmentId, DataRealm.Uns);
|
||||
equipmentScopes[item.EquipmentId] = scope;
|
||||
Add("Equipment", item.EquipmentId, item.Name, View(DataRealm.Uns, item.EquipmentId, scope), scope,
|
||||
views[(DataRealm.Uns, "UnsLine", item.UnsLineId.ToUpperInvariant())]);
|
||||
}
|
||||
@@ -172,9 +183,57 @@ public sealed partial class LocalExportCatalog
|
||||
SourceKey.ForVirtual(cluster, value.VirtualTagId, serving.NodeId, serving.Incarnation),
|
||||
kind == DataValueKind.Unspecified ? DataValueKind.Null : kind, supported: kind != DataValueKind.Unspecified, enabled: value.Enabled);
|
||||
}
|
||||
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes);
|
||||
AddConditionPlacements();
|
||||
return new(cluster, serving, activation, nodes, snapshot.DataExports, maximumNodes, DistinctPlacements(conditionPlacements));
|
||||
|
||||
// A1 (§5.2): the UNS placements. Native: the RESERVED reference id Area/Line/Equipment/EffectiveName of every
|
||||
// reference to an alarm-bearing tag — the same derivation as AddressSpaceComposer.BuildUnsReferenceVariables, which
|
||||
// skips exactly these references (#896), so no UNS node exists there and the guard keeps the id unique. Scripted:
|
||||
// the ScriptedAlarmId the node manager registers the condition under. Both are authorized against the
|
||||
// equipment-owned subject and parented at the equipment. Nothing here carries a RawPath except the internal
|
||||
// OriginConditionRef of a native condition.
|
||||
void AddConditionPlacements()
|
||||
{
|
||||
var alarmPlans = composition.RawTags.Where(x => x.Alarm is not null).ToDictionary(x => x.TagId, ids);
|
||||
var areaById = areas.ToDictionary(x => x.UnsAreaId, ids);
|
||||
var lineById = lines.ToDictionary(x => x.UnsLineId, ids);
|
||||
var equipmentById = equipment.ToDictionary(x => x.EquipmentId, ids);
|
||||
foreach (var reference in references.OrderBy(x => x.UnsTagReferenceId, StringComparer.Ordinal))
|
||||
{
|
||||
if (!alarmPlans.TryGetValue(reference.TagId, out var plan)
|
||||
|| !equipmentById.TryGetValue(reference.EquipmentId, out var owner)
|
||||
|| !lineById.TryGetValue(owner.UnsLineId, out var line) || !areaById.TryGetValue(line.UnsAreaId, out var area))
|
||||
continue;
|
||||
var effectiveName = string.IsNullOrEmpty(reference.DisplayNameOverride) ? tagById[reference.TagId].Name
|
||||
: reference.DisplayNameOverride!;
|
||||
string reserved;
|
||||
try { reserved = V3NodeIds.UnsChild(V3NodeIds.Uns(area.Name, line.Name, owner.Name), effectiveName); }
|
||||
catch (ArgumentException) { continue; } // an invalid name segment: the deploy gate rejects it; never listed
|
||||
var view = new DataView(new(cluster, V3NodeIds.UnsNamespaceUri, "string", reserved), DataRealm.Uns, null, 0, reserved);
|
||||
conditionPlacements.Add(new(view, views[(DataRealm.Uns, "Equipment", owner.EquipmentId.ToUpperInvariant())],
|
||||
DataScopeSubjects.Owned(equipmentScopes[owner.EquipmentId]), effectiveName, ConditionSourceKind.Native,
|
||||
new(AddressSpaceRealm.Raw, plan.NodeId), "UnsTagReference", reference.UnsTagReferenceId));
|
||||
}
|
||||
foreach (var alarm in composition.EquipmentScriptedAlarms)
|
||||
{
|
||||
// The node manager materialises only enabled scripted alarms (AddressSpaceApplier).
|
||||
if (!alarm.Enabled || !equipmentScopes.TryGetValue(alarm.EquipmentId, out var owner)) continue;
|
||||
var view = new DataView(new(cluster, V3NodeIds.UnsNamespaceUri, "string", alarm.ScriptedAlarmId), DataRealm.Uns,
|
||||
null, 0, string.Join('/', owner.Segments.Append(alarm.Name)));
|
||||
conditionPlacements.Add(new(view, views[(DataRealm.Uns, "Equipment", alarm.EquipmentId.ToUpperInvariant())],
|
||||
DataScopeSubjects.Owned(owner), alarm.Name, ConditionSourceKind.Scripted,
|
||||
new(AddressSpaceRealm.Uns, alarm.ScriptedAlarmId), "ScriptedAlarm", alarm.ScriptedAlarmId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An address claimed by two placements is ambiguous: neither is listed (fail closed for conditions), and the v1
|
||||
/// catalog compiles exactly as before.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<LocalConditionPlacement> DistinctPlacements(IEnumerable<LocalConditionPlacement> placements) =>
|
||||
placements.GroupBy(x => (x.View.Realm, x.View.Address.Identifier)).Where(x => x.Count() == 1).Select(x => x.Single()).ToArray();
|
||||
|
||||
private static DataValueKind ValueKind(string type) => type switch
|
||||
{
|
||||
"Boolean" => DataValueKind.Boolean, "SByte" => DataValueKind.Int8, "Byte" => DataValueKind.UInt8,
|
||||
|
||||
@@ -17,12 +17,15 @@ public sealed partial class LocalExportCatalog
|
||||
private readonly Dictionary<DataView, LocalDataNode[]> _children;
|
||||
private readonly ExportRule[] _exports;
|
||||
private readonly IDataMappedCatalogAuthority _activation;
|
||||
private readonly Dictionary<(DataRealm Realm, string Identifier), LocalConditionPlacement> _placements;
|
||||
private readonly Dictionary<OriginConditionRef, LocalConditionPlacement[]> _placementsByCondition;
|
||||
private sealed record ExportRule(string Identity, string Principal, DataRealm Realm, DataView? Root, bool WholeRealm,
|
||||
DataOperations Operations, int Batch, int Page, int Items, int Streams,
|
||||
int HistoryReads = 4, int HistoryValuesPerPage = 10_000, int HistoryResponseBytes = 4 * 1024 * 1024);
|
||||
|
||||
public LocalExportCatalog(string clusterId, ServingIdentity serving, IDataMappedCatalogAuthority activation,
|
||||
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000)
|
||||
IEnumerable<LocalDataNode> nodes, IEnumerable<DataExport> exports, int maximumNodes = 100_000,
|
||||
IEnumerable<LocalConditionPlacement>? conditionPlacements = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(clusterId);
|
||||
ArgumentNullException.ThrowIfNull(serving);
|
||||
@@ -101,6 +104,8 @@ public sealed partial class LocalExportCatalog
|
||||
_exports = rules.ToArray();
|
||||
DroppedUnknownOperations = dropped;
|
||||
Nodes = new ReadOnlyCollection<LocalDataNode>(_nodes.Values.ToArray());
|
||||
(_placements, _placementsByCondition) = IndexPlacements(conditionPlacements ?? []);
|
||||
ConditionPlacements = new ReadOnlyCollection<LocalConditionPlacement>(_placements.Values.ToArray());
|
||||
}
|
||||
|
||||
public string ClusterId { get; }
|
||||
@@ -122,6 +127,8 @@ public sealed partial class LocalExportCatalog
|
||||
ClusterId = current.ClusterId; Serving = serving; _activation = current._activation;
|
||||
_nodes = current._nodes; _children = current._children; _exports = current._exports; Nodes = current.Nodes;
|
||||
DroppedUnknownOperations = current.DroppedUnknownOperations;
|
||||
_placements = current._placements; _placementsByCondition = current._placementsByCondition;
|
||||
ConditionPlacements = current.ConditionPlacements;
|
||||
}
|
||||
|
||||
/// <summary>A role-only transition changes serving provenance without freshening source acquisitions.</summary>
|
||||
@@ -213,4 +220,107 @@ public sealed partial class LocalExportCatalog
|
||||
internal DataOperations ExportOperations(string principal) => _exports
|
||||
.Where(x => string.Equals(x.Principal, principal, StringComparison.OrdinalIgnoreCase))
|
||||
.Aggregate(DataOperations.None, (operations, rule) => operations | rule.Operations);
|
||||
|
||||
// ---- A1: realm-local condition placements (§5.2). The v1 node set, listing and wire bytes are untouched. ----
|
||||
|
||||
/// <summary>A1: every condition placement of this origin, in every realm (origin-internal; see <see cref="ListConditions"/>).</summary>
|
||||
public IReadOnlyList<LocalConditionPlacement> ConditionPlacements { get; }
|
||||
|
||||
/// <summary>A1: the placement at an (unmapped) origin address in its realm; the claimed Subject is ignored.</summary>
|
||||
public bool TryResolveConditionPlacement(DataView view, out LocalConditionPlacement placement)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(view);
|
||||
if (view.MappingId is null && view.MappingRevision == 0 && view.Address is { } address
|
||||
&& string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
&& address.IdentifierKind == "string" && address.NamespaceUri == RealmNamespace(view.Realm)
|
||||
&& _placements.TryGetValue((view.Realm, address.Identifier), out var found))
|
||||
{ placement = found; return true; }
|
||||
placement = null!; return false;
|
||||
}
|
||||
|
||||
/// <summary>A1: every placement of one origin condition (Raw and UNS), ordered by realm then identifier.</summary>
|
||||
public IReadOnlyList<LocalConditionPlacement> PlacementsOf(OriginConditionRef condition) =>
|
||||
_placementsByCondition.TryGetValue(condition, out var found) ? Array.AsReadOnly(found) : [];
|
||||
|
||||
/// <summary>
|
||||
/// A1: whether <paramref name="principal"/> holds an export of the placement's realm granting
|
||||
/// <paramref name="operation"/> whose root contains the placement (whole realm, or an ancestor of its parent).
|
||||
/// </summary>
|
||||
internal bool AllowsConditionPlacement(string principal, LocalConditionPlacement placement, DataOperations operation)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(placement);
|
||||
if (operation == DataOperations.None) return false;
|
||||
foreach (var rule in _exports)
|
||||
{
|
||||
if (!string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase)
|
||||
|| rule.Realm != placement.View.Realm || (rule.Operations & operation) != operation) continue;
|
||||
if (rule.WholeRealm || IsAncestor(rule.Root!, placement.Parent)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A1: the conditions under one export root as a listing presents them to <paramref name="principal"/> — each with
|
||||
/// its <c>condition_key</c> and only the placements inside <paramref name="root"/>, all in the root's realm and each
|
||||
/// passing the principal's export check for <paramref name="operation"/> (A2 passes
|
||||
/// <see cref="DataOperations.AlarmSubscribe"/>; until A2 makes that bit understood, no export grants it and the
|
||||
/// listing is empty). Fails closed (empty) when the root is not an origin node or no condition-key secret is
|
||||
/// provisioned. A UNS listing never names a RawPath: native UNS placements are the reserved reference ids.
|
||||
/// </summary>
|
||||
public IReadOnlyList<ExportedCondition> ListConditions(string principal, DataView root, DataOperations operation, ConditionKeys keys)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
|
||||
ArgumentNullException.ThrowIfNull(root);
|
||||
ArgumentNullException.ThrowIfNull(keys);
|
||||
if (!keys.IsAvailable || operation == DataOperations.None || !TryResolve(root, out var rootNode)) return [];
|
||||
var rootView = rootNode.Metadata.View;
|
||||
return _placements.Values
|
||||
.Where(p => p.View.Realm == rootView.Realm && IsAncestor(rootView, p.Parent) && AllowsConditionPlacement(principal, p, operation))
|
||||
.GroupBy(p => p.Condition)
|
||||
.Select(g => new ExportedCondition(keys.Derive(ClusterId, g.Key.Realm, g.Key.ConditionId), g.First().SourceKind,
|
||||
Array.AsReadOnly(g.OrderBy(p => p.View.Address.Identifier, StringComparer.Ordinal).Select(p => p.ToView()).ToArray())))
|
||||
.OrderBy(x => x.ConditionKey, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
private static string RealmNamespace(DataRealm realm) =>
|
||||
realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : realm == DataRealm.Uns ? V3NodeIds.UnsNamespaceUri : string.Empty;
|
||||
|
||||
private (Dictionary<(DataRealm, string), LocalConditionPlacement>, Dictionary<OriginConditionRef, LocalConditionPlacement[]>)
|
||||
IndexPlacements(IEnumerable<LocalConditionPlacement> placements)
|
||||
{
|
||||
var byAddress = new Dictionary<(DataRealm, string), LocalConditionPlacement>();
|
||||
foreach (var input in placements)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(input);
|
||||
input.View.Validate();
|
||||
var view = input.View;
|
||||
var address = view.Address;
|
||||
var nativeRawPlacement = view.Realm == DataRealm.Raw && input.SourceKind == ConditionSourceKind.Native
|
||||
&& input.Condition.Realm == AddressSpaceRealm.Raw && input.Condition.ConditionId == address.Identifier;
|
||||
var nativeUnsPlacement = view.Realm == DataRealm.Uns && input.SourceKind == ConditionSourceKind.Native
|
||||
&& input.Condition.Realm == AddressSpaceRealm.Raw;
|
||||
var scriptedPlacement = view.Realm == DataRealm.Uns && input.SourceKind == ConditionSourceKind.Scripted
|
||||
&& input.Condition.Realm == AddressSpaceRealm.Uns && input.Condition.ConditionId == address.Identifier;
|
||||
if (view.MappingId is not null || !string.Equals(address.OriginClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| address.IdentifierKind != "string" || address.NamespaceUri != RealmNamespace(view.Realm)
|
||||
|| string.IsNullOrEmpty(input.Condition.ConditionId) || string.IsNullOrWhiteSpace(input.BrowseName)
|
||||
|| !(nativeRawPlacement || nativeUnsPlacement || scriptedPlacement)
|
||||
|| !string.Equals(input.Scope.ClusterId, ClusterId, StringComparison.OrdinalIgnoreCase)
|
||||
|| input.Scope.Kind != (view.Realm == DataRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns)
|
||||
|| !TryResolve(input.Parent, out var parent) || parent.Metadata.View.Realm != view.Realm)
|
||||
throw new ArgumentException("Condition placement is nonlocal, cross-realm or not parented in this catalog.", nameof(placements));
|
||||
var placement = input with
|
||||
{
|
||||
View = view with { Address = address with { OriginClusterId = ClusterId } },
|
||||
Parent = parent.Metadata.View,
|
||||
Scope = input.Scope with { Segments = Array.AsReadOnly(input.Scope.Segments.ToArray()) }
|
||||
};
|
||||
if (!byAddress.TryAdd((view.Realm, address.Identifier), placement))
|
||||
throw new ArgumentException("Catalog contains duplicate condition placements.", nameof(placements));
|
||||
}
|
||||
var byCondition = byAddress.Values.GroupBy(x => x.Condition).ToDictionary(x => x.Key,
|
||||
x => x.OrderBy(p => p.View.Realm).ThenBy(p => p.View.Address.Identifier, StringComparer.Ordinal).ToArray());
|
||||
return (byAddress, byCondition);
|
||||
}
|
||||
}
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
using System.Text;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests.DataConnections;
|
||||
|
||||
/// <summary>A1 (§5.2, N4): the imported-condition identifier, its children and the condition namespace.</summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")]
|
||||
public sealed class GrpcDataImportedConditionIdsTests
|
||||
{
|
||||
// 43 base64url chars of a 32-byte value (last char low bits zero).
|
||||
private static readonly string Key = Convert.ToBase64String(Enumerable.Range(1, 32).Select(x => (byte)(x * 7)).ToArray())
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
private static readonly string OtherKey = Convert.ToBase64String(Enumerable.Repeat((byte)0xFB, 32).ToArray())
|
||||
.TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
|
||||
[Fact]
|
||||
public void Condition_namespace_is_a_third_mapped_namespace_and_not_a_realm_namespace()
|
||||
{
|
||||
ImportedConditionIds.NamespaceUri.ShouldBe("https://zb.com/otopcua/mapped/conditions");
|
||||
ImportedConditionIds.IsConditionNamespace(ImportedConditionIds.NamespaceUri).ShouldBeTrue();
|
||||
ImportedConditionIds.IsConditionNamespace(ProjectedDataIds.RawNamespaceUri).ShouldBeFalse();
|
||||
ImportedConditionIds.IsConditionNamespace(ProjectedDataIds.UnsNamespaceUri).ShouldBeFalse();
|
||||
ImportedConditionIds.IsConditionNamespace(null).ShouldBeFalse();
|
||||
// The variable classifier must not claim it: a caller dispatches the condition namespace first (RealmOf trap).
|
||||
ProjectedDataIds.IsMappedNamespace(ImportedConditionIds.NamespaceUri).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Identifier_round_trips_and_is_keyed_on_connection_and_key_only()
|
||||
{
|
||||
Key.Length.ShouldBe(43);
|
||||
var id = ImportedConditionIds.Identifier("conn-1", Key);
|
||||
id.ShouldStartWith("c1.");
|
||||
id.ShouldNotContain('/');
|
||||
ImportedConditionIds.TryDecodeIdentifier(id, out var connection, out var key).ShouldBeTrue();
|
||||
connection.ShouldBe("conn-1");
|
||||
key.ShouldBe(Key);
|
||||
ImportedConditionIds.Identifier("conn-1", Key).ShouldBe(id); // deterministic
|
||||
ImportedConditionIds.Identifier("conn-2", Key).ShouldNotBe(id);
|
||||
ImportedConditionIds.Identifier("conn-1", OtherKey).ShouldNotBe(id);
|
||||
// Disjoint from the variable scheme.
|
||||
ProjectedDataIds.TryDecodeIdentifier(id, out _, out _).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("EnabledState")]
|
||||
[InlineData("EnabledState/Id")]
|
||||
[InlineData("ShelvingState/UnshelveTime")]
|
||||
public void Child_round_trips_and_splits_at_the_first_separator(string browsePath)
|
||||
{
|
||||
var id = ImportedConditionIds.Identifier("conn/with/slash", Key);
|
||||
var child = ImportedConditionIds.ChildIdentifier(id, browsePath);
|
||||
child.ShouldBe(id + "/" + browsePath);
|
||||
ImportedConditionIds.TryParse(child, out var condition, out var connection, out var key, out var path).ShouldBeTrue();
|
||||
condition.ShouldBe(id);
|
||||
connection.ShouldBe("conn/with/slash"); // a slash inside the JSON payload never reaches the identifier text
|
||||
key.ShouldBe(Key);
|
||||
path.ShouldBe(browsePath);
|
||||
ImportedConditionIds.TryParse(id, out condition, out _, out _, out path).ShouldBeTrue();
|
||||
condition.ShouldBe(id);
|
||||
path.ShouldBeNull();
|
||||
ImportedConditionIds.TryDecodeIdentifier(child, out _, out _).ShouldBeFalse(); // a child is not a condition
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Malformed_identifiers_are_rejected()
|
||||
{
|
||||
var id = ImportedConditionIds.Identifier("conn-1", Key);
|
||||
static string B64(string json) => Convert.ToBase64String(Encoding.UTF8.GetBytes(json)).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
string?[] bad =
|
||||
[
|
||||
null, "", "c1.", "c1", "p1." + id[3..], "C1." + id[3..], id + "=", id[..^1] + "*", id + "/", id + "//X",
|
||||
id + "/A//B", id + "/A/", id + "/\u0001", "c1." + B64("{}"), "c1." + B64("[1]"), "c1.!!!!",
|
||||
"c1." + B64($"{{\"ConnectionId\":\"conn-1\",\"ConditionKey\":\"short\"}}"),
|
||||
"c1." + B64($"{{\"ConnectionId\":\" \",\"ConditionKey\":\"{Key}\"}}"),
|
||||
// non-canonical: same values, different JSON spelling (whitespace)
|
||||
"c1." + B64($"{{ \"ConnectionId\":\"conn-1\",\"ConditionKey\":\"{Key}\"}}"),
|
||||
"c1." + new string('A', ImportedConditionIds.MaximumIdentifierLength)
|
||||
];
|
||||
foreach (var candidate in bad)
|
||||
{
|
||||
ImportedConditionIds.TryDecodeIdentifier(candidate, out _, out _).ShouldBeFalse(candidate);
|
||||
ImportedConditionIds.TryParse(candidate, out _, out _, out _, out _).ShouldBeFalse(candidate);
|
||||
}
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.ChildIdentifier("c1.bogus", "X"));
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.ChildIdentifier(id, ""));
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.ChildIdentifier(id, "/X"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Construction_refuses_a_malformed_key_or_connection()
|
||||
{
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.Identifier("conn", "not-a-key"));
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.Identifier("conn", Key + "A"));
|
||||
// 43 chars whose trailing bits are non-zero is not a canonical 32-byte encoding.
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.Identifier("conn", Key[..^1] + "B"));
|
||||
Should.Throw<ArgumentException>(() => ImportedConditionIds.Identifier(" ", Key));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => ImportedConditionIds.Identifier(new string('c', 257), Key));
|
||||
Should.Throw<ArgumentOutOfRangeException>(() => ImportedConditionIds.Identifier("a\nb", Key));
|
||||
ImportedConditionIds.IsWellFormedConditionKey(Key).ShouldBeTrue();
|
||||
ImportedConditionIds.IsWellFormedConditionKey(OtherKey).ShouldBeTrue();
|
||||
ImportedConditionIds.IsWellFormedConditionKey(Key.Replace(Key[0], '+')).ShouldBeFalse();
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// A1 (§5.2, §6): <c>DataConnections:ConditionKeySecret</c>. Absent ⇒ fail closed (no error, conditions never advertised);
|
||||
/// provisioned but weak ⇒ a startup validation error that never echoes the value; disabled data connections ⇒ not
|
||||
/// checked at all. Never a committed literal.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A1")]
|
||||
public sealed class GrpcDataConditionKeySecretTests
|
||||
{
|
||||
private static DataConnectionOptions Enabled(string? secret) => new()
|
||||
{
|
||||
Enabled = true, ListenPort = 9443, CertificatePath = "server.pem", AllowedHosts = ["source.local"], ConditionKeySecret = secret
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Absent_secret_is_not_an_error_and_a_valid_one_passes()
|
||||
{
|
||||
DataConnectionOptionsValidator.Validate(Enabled(null), development: false).ShouldBeEmpty();
|
||||
DataConnectionOptionsValidator.Validate(Enabled(""), development: false).ShouldBeEmpty();
|
||||
DataConnectionOptionsValidator.Validate(Enabled(new string('k', 32)), development: false).ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("too-short-secret")]
|
||||
[InlineData(" ")]
|
||||
[InlineData("${secret:otopcua/dataconnections/condition-key}")]
|
||||
public void A_weak_or_unexpanded_secret_fails_startup_validation_without_echoing_it(string secret)
|
||||
{
|
||||
var errors = DataConnectionOptionsValidator.Validate(Enabled(secret), development: false);
|
||||
var error = errors.ShouldHaveSingleItem();
|
||||
error.ShouldContain("DataConnections:ConditionKeySecret");
|
||||
if (secret.Trim().Length > 0) error.ShouldNotContain(secret);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_data_connections_do_not_validate_the_secret()
|
||||
{
|
||||
var options = Enabled("short");
|
||||
options.Enabled = false;
|
||||
DataConnectionOptionsValidator.Validate(options, development: false).ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Secret_binds_from_the_DataConnections_section_like_an_env_var_override()
|
||||
{
|
||||
// DataConnections__ConditionKeySecret (env) and ${secret:} both land on this key before binding.
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["DataConnections:ConditionKeySecret"] = new string('s', 40)
|
||||
}).Build();
|
||||
var options = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>()!;
|
||||
options.ConditionKeySecret.ShouldBe(new string('s', 40));
|
||||
ConditionKeys.FromSecret(options.ConditionKeySecret).IsAvailable.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void No_committed_appsettings_carries_a_condition_key_secret_literal()
|
||||
{
|
||||
var root = FindRepoRoot();
|
||||
var files = Directory.EnumerateFiles(Path.Combine(root, "src"), "appsettings*.json", SearchOption.AllDirectories)
|
||||
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}")
|
||||
&& !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}"))
|
||||
.ToArray();
|
||||
files.ShouldNotBeEmpty();
|
||||
foreach (var file in files)
|
||||
{
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(file),
|
||||
new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
|
||||
if (document.RootElement.TryGetProperty("DataConnections", out var section)
|
||||
&& section.TryGetProperty("ConditionKeySecret", out var value) && value.ValueKind == JsonValueKind.String)
|
||||
(value.GetString() ?? string.Empty).ShouldStartWith("${secret:", customMessage: file);
|
||||
}
|
||||
}
|
||||
|
||||
private static string FindRepoRoot()
|
||||
{
|
||||
var directory = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (directory is not null && !Directory.Exists(Path.Combine(directory.FullName, "src", "Server"))) directory = directory.Parent;
|
||||
return directory?.FullName ?? throw new DirectoryNotFoundException("Repository root not found.");
|
||||
}
|
||||
}
|
||||
+340
@@ -0,0 +1,340 @@
|
||||
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;
|
||||
|
||||
/// <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();
|
||||
}
|
||||
|
||||
[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
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
Reference in New Issue
Block a user