Merge A1 keys/placements/ids into A1 core

This commit is contained in:
Joseph Doherty
2026-11-24 10:02:34 -05:00
14 changed files with 1158 additions and 9 deletions
@@ -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>&lt;identifier&gt;/&lt;browse path&gt;</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>&lt;identifier&gt;/&lt;browse path&gt;</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,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);
}
}