feat(grpc-data): A1 — ImportedConditionIds: c1. condition identifier, child ids, mapped/conditions namespace
This commit is contained in:
@@ -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
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user