feat: deploy scoped grpc data connection configuration

This commit is contained in:
Joseph Doherty
2026-11-15 22:46:12 -05:00
parent a323373a45
commit d5b3653012
20 changed files with 4190 additions and 6 deletions
@@ -52,6 +52,14 @@ public static class ConfigComposer
public static ConfigArtifact Compose(DraftSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
foreach (var connection in snapshot.DataConnections)
{
if (connection.Endpoints is null || connection.Endpoints.Any(endpoint =>
!string.IsNullOrWhiteSpace(endpoint) &&
(!Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || uri.Scheme != Uri.UriSchemeHttps ||
!string.IsNullOrEmpty(uri.UserInfo) || !string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment))))
throw new InvalidDataException($"Invalid endpoint in data connection '{connection.DataConnectionId}'.");
}
// v3 greenfield snapshot: the Raw tree (RawFolders → DriverInstances(+RawFolderId) → Devices(+DeviceConfig)
// → TagGroups → Tags(DeviceId/TagGroupId, no EquipmentId/FolderPath/DriverInstanceId)) plus the UNS
@@ -87,6 +95,20 @@ public static class ConfigComposer
Scripts = snapshot.Scripts,
VirtualTags = snapshot.VirtualTags,
ScriptedAlarms = snapshot.ScriptedAlarms,
DataConnections = snapshot.DataConnections.OrderBy(x => x.DataConnectionId, StringComparer.Ordinal).Select(connection =>
{
var copy = JsonSerializer.Deserialize<ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection>(JsonSerializer.SerializeToUtf8Bytes(connection, JsonOptions), JsonOptions)!;
copy.ConsumerNodeIds = copy.ConsumerNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
copy.EligibleTargetNodeIds = copy.EligibleTargetNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
return copy;
}).ToArray(),
DataExports = snapshot.DataExports.OrderBy(x => x.DataExportId, StringComparer.Ordinal).ToArray(),
RemoteNamespaceMappings = snapshot.RemoteNamespaceMappings.OrderBy(x => x.RemoteNamespaceMappingId, StringComparer.Ordinal).Select(mapping =>
{
var copy = JsonSerializer.Deserialize<ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping>(JsonSerializer.SerializeToUtf8Bytes(mapping, JsonOptions), JsonOptions)!;
copy.ConsumerNodeIds = copy.ConsumerNodeIds.OrderBy(x => x, StringComparer.Ordinal).ToList();
return copy;
}).ToArray(),
};
return Pack(JsonSerializer.SerializeToUtf8Bytes(ordered, JsonOptions));
@@ -0,0 +1,313 @@
using System.Text.Json;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
public static partial class DeploymentArtifact
{
/// <summary>Read the node-effective data connections from an artifact.</summary>
public static IReadOnlyList<DataConnection> ParseDataConnections(
ReadOnlySpan<byte> blob,
string nodeId
)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseDataConnections(nodeId);
}
/// <summary>Read the node-effective data exports from an artifact.</summary>
public static IReadOnlyList<DataExport> ParseDataExports(ReadOnlySpan<byte> blob, string nodeId)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseDataExports(nodeId);
}
/// <summary>Read the node-effective remote namespace mappings from an artifact.</summary>
public static IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(
ReadOnlySpan<byte> blob,
string nodeId
)
{
using var parsed = Open(blob.ToArray());
return parsed.ParseRemoteNamespaceMappings(nodeId);
}
}
internal sealed partial class ParsedDeploymentArtifact
{
private static readonly JsonSerializerOptions DataJsonOptions = new()
{
PropertyNameCaseInsensitive = true,
};
private static readonly StringComparer DataIds = StringComparer.OrdinalIgnoreCase;
public IReadOnlyList<DataConnection> ParseDataConnections(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
ValidateRows(
projection.Value.Snapshot,
projection.Value.Snapshot.DataConnections.Select(x => x.DataConnectionId)
);
return projection
.Value.Snapshot.DataConnections.Where(x => x.ConsumerNodeIds.Contains(nodeId, DataIds))
.ToArray();
}
public IReadOnlyList<DataExport> ParseDataExports(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
ValidateRows(
projection.Value.Snapshot,
projection.Value.Snapshot.DataExports.Select(x => x.DataExportId)
);
return projection.Value.Snapshot.DataExports.ToArray();
}
public IReadOnlyList<RemoteNamespaceMapping> ParseRemoteNamespaceMappings(string nodeId)
{
var projection = ReadDataProjection(nodeId);
if (projection is null)
return [];
var snapshot = projection.Value.Snapshot;
ValidateRows(
snapshot,
snapshot
.RemoteNamespaceMappings.Where(x =>
DataIds.Equals(x.ClusterId, projection.Value.ClusterId)
)
.Select(x => x.RemoteNamespaceMappingId)
.Concat(snapshot.DataConnections.Select(x => x.DataConnectionId))
);
return snapshot
.RemoteNamespaceMappings.Where(x =>
DataIds.Equals(x.ClusterId, projection.Value.ClusterId)
&& x.ConsumerNodeIds.Contains(nodeId, DataIds)
)
.ToArray();
}
private (DraftSnapshot Snapshot, string ClusterId)? ReadDataProjection(string nodeId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(nodeId);
var root = Root;
if (root.ValueKind != JsonValueKind.Object)
return null;
if (
!root.TryGetProperty("DataConnections", out _)
&& !root.TryGetProperty("DataExports", out _)
&& !root.TryGetProperty("RemoteNamespaceMappings", out _)
)
return null;
var node = EnumerateArray(root, "Nodes")
.Where(x => DataIds.Equals(ReadDataString(x, "NodeId"), nodeId))
.ToArray();
if (
node.Length != 1
|| !IsExplicitTrue(node[0], "Enabled")
|| IsExplicitTrue(node[0], "MaintenanceMode")
)
return null;
var clusterId = ReadDataString(node[0], "ClusterId");
if (string.IsNullOrWhiteSpace(clusterId))
return null;
var cluster = EnumerateArray(root, "Clusters")
.Where(x => DataIds.Equals(ReadDataString(x, "ClusterId"), clusterId))
.ToArray();
if (cluster.Length != 1 || !IsExplicitTrue(cluster[0], "Enabled"))
return null;
var connections = ReadDataRows<DataConnection>(
root,
"DataConnections",
"DataConnectionId",
clusterId
);
var exports = ReadDataRows<DataExport>(root, "DataExports", "DataExportId", clusterId);
var mappings = ReadDataRows<RemoteNamespaceMapping>(
root,
"RemoteNamespaceMappings",
"RemoteNamespaceMappingId",
clusterId
);
// Only foreign mapping identity is needed to detect a projected root. Do not import
// foreign configuration or validate it as a local execution graph.
foreach (var foreign in EnumerateArray(root, "RemoteNamespaceMappings"))
{
var owner = ReadDataString(foreign, "ClusterId");
var id = ReadDataString(foreign, "RemoteNamespaceMappingId");
if (
!string.IsNullOrWhiteSpace(owner)
&& !DataIds.Equals(owner, clusterId)
&& !string.IsNullOrWhiteSpace(id)
)
mappings.Add(
new RemoteNamespaceMapping { ClusterId = owner, RemoteNamespaceMappingId = id }
);
}
foreach (var c in connections)
if (c.ConsumerNodeIds is null || c.EligibleTargetNodeIds is null || c.Endpoints is null)
throw InvalidRow(c.DataConnectionId);
foreach (var m in mappings)
if (m.ConsumerNodeIds is null)
throw InvalidRow(m.RemoteNamespaceMappingId);
var snapshot = new DraftSnapshot
{
GenerationId = 0,
ClusterId = clusterId,
ServerClusters = ReadTopology<ServerCluster>(root, "Clusters"),
ClusterNodes = ReadTopology<ClusterNode>(root, "Nodes"),
RawFolders = ReadTopology<RawFolder>(root, "RawFolders"),
DriverInstances = ReadTopology<DriverInstance>(root, "DriverInstances"),
Devices = ReadTopology<Device>(root, "Devices"),
TagGroups = ReadTopology<TagGroup>(root, "TagGroups"),
Tags = ReadTopology<Tag>(root, "Tags"),
UnsAreas = ReadTopology<UnsArea>(root, "UnsAreas"),
UnsLines = ReadTopology<UnsLine>(root, "UnsLines"),
Equipment = ReadTopology<Equipment>(root, "Equipment"),
UnsTagReferences = ReadTopology<UnsTagReference>(root, "UnsTagReferences"),
VirtualTags = ReadTopology<VirtualTag>(root, "VirtualTags"),
ScriptedAlarms = ReadTopology<ScriptedAlarm>(root, "ScriptedAlarms"),
DataConnections = connections,
DataExports = exports,
RemoteNamespaceMappings = mappings,
};
return (snapshot, clusterId);
}
private static JsonElement? DataProperty(JsonElement element, string property)
{
JsonElement? found = null;
foreach (var entry in element.EnumerateObject())
{
if (!DataIds.Equals(entry.Name, property))
continue;
if (found is not null)
throw InvalidRow(null);
found = entry.Value;
}
return found;
}
private static string? ReadDataString(JsonElement element, string property)
{
var value = DataProperty(element, property);
return value is { ValueKind: JsonValueKind.String } ? value.Value.GetString() : null;
}
private static bool IsExplicitTrue(JsonElement element, string property) =>
DataProperty(element, property) is { ValueKind: JsonValueKind.True };
private static void RejectDuplicateDataProperties(JsonElement element)
{
var names = new HashSet<string>(DataIds);
foreach (var property in element.EnumerateObject())
if (!names.Add(property.Name))
throw InvalidRow(null);
}
private static InvalidDataException InvalidRow(string? id) =>
new(
$"Invalid data configuration row '{(string.IsNullOrWhiteSpace(id) ? "<unknown>" : id)}'."
);
private static List<T> ReadDataRows<T>(
JsonElement root,
string name,
string idName,
string clusterId
)
{
if (!root.TryGetProperty(name, out var array))
return [];
if (array.ValueKind != JsonValueKind.Array)
throw new InvalidDataException($"Invalid {name} collection.");
var result = new List<T>();
foreach (var element in array.EnumerateArray())
{
if (element.ValueKind != JsonValueKind.Object)
throw InvalidRow(null);
RejectDuplicateDataProperties(element);
var owner = ReadDataString(element, "ClusterId");
var id = ReadDataString(element, idName);
if (string.IsNullOrWhiteSpace(owner))
{
if (IsExplicitTrue(element, "Enabled"))
throw InvalidRow(id);
continue;
}
if (!DataIds.Equals(owner, clusterId))
continue;
if (IsExplicitTrue(element, "Enabled") && string.IsNullOrWhiteSpace(id))
throw InvalidRow(null);
try
{
var row = element.Deserialize<T>(DataJsonOptions);
if (row is null)
throw InvalidRow(id);
var identity = row switch
{
DataConnection c => (c.Enabled, c.DataConnectionId, c.ClusterId),
DataExport e => (e.Enabled, e.DataExportId, e.ClusterId),
RemoteNamespaceMapping m => (
m.Enabled,
m.RemoteNamespaceMappingId,
m.ClusterId
),
_ => throw new InvalidOperationException("Unsupported data row type."),
};
if (
!DataIds.Equals(identity.Item3, clusterId)
|| (identity.Item1 && string.IsNullOrWhiteSpace(identity.Item2))
)
throw InvalidRow(identity.Item2);
result.Add(row);
}
catch (JsonException)
{
throw InvalidRow(id);
}
catch (NotSupportedException)
{
throw InvalidRow(id);
}
}
return result;
}
private static List<T> ReadTopology<T>(JsonElement root, string name)
{
if (!root.TryGetProperty(name, out var array))
return [];
if (array.ValueKind != JsonValueKind.Array)
throw new InvalidDataException($"Invalid {name} topology.");
try
{
if (array.EnumerateArray().Any(element => element.ValueKind != JsonValueKind.Object))
throw new InvalidDataException($"Invalid {name} topology.");
var rows = array.Deserialize<List<T>>(DataJsonOptions)
?? throw new InvalidDataException($"Invalid {name} topology.");
if (rows.Any(row => row is null))
throw new InvalidDataException($"Invalid {name} topology.");
return rows;
}
catch (JsonException)
{
throw new InvalidDataException($"Invalid {name} topology.");
}
}
private static void ValidateRows(DraftSnapshot snapshot, IEnumerable<string> ids)
{
var requested = ids.ToHashSet(DataIds);
var error = DataConnectionValidator
.Validate(snapshot)
.FirstOrDefault(x => x.Context is not null && requested.Contains(x.Context));
if (error is not null)
throw InvalidRow(error.Context);
}
}
@@ -124,7 +124,7 @@ public readonly record struct ClusterScope(ClusterFilterMode Mode, string? Clust
/// exist so the one-shot call sites (and every existing test) keep their exact shape and their lenient
/// empty/malformed contract.
/// </summary>
public static class DeploymentArtifact
public static partial class DeploymentArtifact
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
@@ -442,7 +442,7 @@ public static class DeploymentArtifact
/// "results survive disposal" contract enforceable rather than merely documented.
/// </para>
/// </remarks>
internal sealed class ParsedDeploymentArtifact : IDisposable
internal sealed partial class ParsedDeploymentArtifact : IDisposable
{
private readonly JsonDocument _document;