560 lines
47 KiB
C#
560 lines
47 KiB
C#
// Disposable local fixture only. No plaintext key or SQL diagnostic is printed.
|
|
using System.Text.Json;
|
|
using System.IO.Compression;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
using Opc.Ua;
|
|
using ZB.MOM.WW.OtOpcUa.Client.Shared;
|
|
using ZB.MOM.WW.OtOpcUa.Client.Shared.Models;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration;
|
|
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.Core.Authorization;
|
|
using GrpcDataSeed;
|
|
|
|
var output = Environment.GetEnvironmentVariable("GRPC_DATA_OUTPUT") ?? "/output";
|
|
var connection = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_CONNECTION") ?? throw new InvalidOperationException("local SQL configuration required");
|
|
var pepper = Environment.GetEnvironmentVariable("GRPC_DATA_PEPPER") ?? throw new InvalidOperationException("local API pepper required");
|
|
// Never accept an arbitrary DB host. The helper runs only on this run's network.
|
|
var sql = new Microsoft.Data.SqlClient.SqlConnectionStringBuilder(connection);
|
|
if (sql.DataSource != "sql,1433") throw new InvalidOperationException("fixture SQL must use owned service DNS");
|
|
var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(connection).Options;
|
|
IDbContextFactory<OtOpcUaConfigDbContext> factory = new PooledDbContextFactory<OtOpcUaConfigDbContext>(options);
|
|
string[] nodes = ["control-1", "control-2", "source-1", "source-2", "consumer-1", "consumer-2"];
|
|
const DataOperations operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
|
// H2 smoke profile (opt-in, `rig.py up --history`): SOURCE historizes `counter`, the consumer's connection and
|
|
// exports gain HistoryRead, and a second principal's export lacks it. Unset ⇒ the v1 fixture, unchanged.
|
|
var history = Environment.GetEnvironmentVariable("GRPC_DATA_HISTORY") == "1";
|
|
var grantedOperations = history ? operations | DataOperations.HistoryRead : operations;
|
|
// A2a smoke profile (opt-in, `rig.py up --conditions`): SOURCE exports gain AlarmSubscribe and the SOURCE equipment gets
|
|
// one scripted alarm, ScalarHigh (scalar > 100), so a condition stream sees a snapshot and a delta. Unset ⇒ v1 fixture.
|
|
var conditions = Environment.GetEnvironmentVariable("GRPC_DATA_CONDITIONS") == "1";
|
|
try
|
|
{
|
|
if (args.Length == 0) return 2;
|
|
if (args[0] == "scope")
|
|
{
|
|
var id = Guid.Parse(args[1]);
|
|
await using var db = await factory.CreateDbContextAsync();
|
|
var deployment = await db.Deployments.AsNoTracking().SingleAsync(x => x.DeploymentId == id);
|
|
if (deployment.RevisionHash != args[2] || deployment.ArtifactBlob.Length == 0) throw new InvalidOperationException();
|
|
using var compressed = new MemoryStream(deployment.ArtifactBlob);
|
|
using var stream = new GZipStream(compressed, CompressionMode.Decompress);
|
|
using var artifact = await JsonDocument.ParseAsync(stream);
|
|
var version = artifact.RootElement.GetProperty("DataConnectionScopeVersion").GetInt64();
|
|
if (version <= 0) throw new InvalidOperationException();
|
|
await Save("scope.json", new { deployment_id = id, revision_hash = deployment.RevisionHash, scope_version = version,
|
|
required_node_ids = artifact.RootElement.GetProperty("Nodes").EnumerateArray()
|
|
.Where(x => x.GetProperty("Enabled").GetBoolean() && !x.GetProperty("MaintenanceMode").GetBoolean())
|
|
.Select(x => x.GetProperty("NodeId").GetString()).ToArray(),
|
|
connections = artifact.RootElement.GetProperty("DataConnections").EnumerateArray()
|
|
.Where(x => x.GetProperty("Enabled").GetBoolean()).Select(x => new {
|
|
connection_id = x.GetProperty("DataConnectionId").GetString(),
|
|
owner = x.GetProperty("ClusterId").GetString(),
|
|
secret_reference = x.GetProperty("SecretReference").GetString(),
|
|
consumer_node_ids = x.GetProperty("ConsumerNodeIds").EnumerateArray().Select(y => y.GetString()).ToArray() }).ToArray() });
|
|
return 0;
|
|
}
|
|
if (args[0] == "resolve")
|
|
{
|
|
var resolved = new Dictionary<string, object>();
|
|
await using var config = await factory.CreateDbContextAsync();
|
|
var activeConnections = await config.DataConnections.Where(x => x.Enabled).Select(x => x.DataConnectionId).ToListAsync();
|
|
var activeMappings = await config.RemoteNamespaceMappings.Where(x => x.Enabled && activeConnections.Contains(x.DataConnectionId)).ToListAsync();
|
|
foreach (var node in nodes)
|
|
{
|
|
var client = new OpcUaClientServiceFactory().Create();
|
|
try
|
|
{
|
|
await client.ConnectAsync(new ConnectionSettings { EndpointUrl = $"opc.tcp://{node}:4840", SecurityMode = SecurityMode.None,
|
|
Username = "apikey", Password = (await File.ReadAllTextAsync(Path.Combine(output, "cli.key"))).Trim(),
|
|
AutoAcceptCertificates = true, CertificateStorePath = "/output/pki", SessionTimeoutSeconds = 30 });
|
|
var ns = await client.ReadValueAsync(VariableIds.Server_NamespaceArray);
|
|
if (StatusCode.IsBad(ns.StatusCode) || ns.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy) is not string[] uris) throw new InvalidOperationException();
|
|
var servers = await client.ReadValueAsync(VariableIds.Server_ServerArray);
|
|
if (servers.WrappedValue.AsBoxedObject(Variant.BoxingBehavior.Legacy) is not string[] applications || !applications.Contains("urn:OtOpcUa:grpc-data:" + node, StringComparer.Ordinal)) throw new InvalidOperationException("unexpected application identity");
|
|
var rawIndex = Array.IndexOf(uris, V3NodeIds.RawNamespaceUri);
|
|
if (rawIndex > 0)
|
|
{
|
|
var pending = new Queue<(NodeId Node, int Depth)>();
|
|
var seen = new HashSet<string>(StringComparer.Ordinal);
|
|
pending.Enqueue((new NodeId(V3NodeIds.SharedRootFolderId, checked((ushort)rawIndex)), 0));
|
|
while (pending.TryDequeue(out var parent))
|
|
{
|
|
if (!seen.Add(parent.Node.ToString()) || parent.Depth > 8 || seen.Count > 256) continue;
|
|
foreach (var child in await client.BrowseAsync(parent.Node))
|
|
if (child.HasChildren) pending.Enqueue((NodeId.Parse(child.NodeId), parent.Depth + 1));
|
|
}
|
|
}
|
|
var aliases = new Dictionary<string, string>();
|
|
var expected = new List<(string Name, string Uri, string Identifier)>();
|
|
if (node.StartsWith("source-", StringComparison.Ordinal))
|
|
{
|
|
expected.Add(("raw", V3NodeIds.RawNamespaceUri, "modbus/plc/scalar"));
|
|
expected.Add(("uns", V3NodeIds.UnsNamespaceUri, "area/line/plc/scalar"));
|
|
}
|
|
if (node.StartsWith("consumer-", StringComparison.Ordinal))
|
|
{
|
|
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
|
|
{
|
|
if (!activeMappings.Any(x => x.RemoteNamespaceMappingId == "map-" + realm.ToString().ToLowerInvariant() && x.ConsumerNodeIds.Contains(node + ":4053"))) continue;
|
|
var uri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri;
|
|
var path = realm == DataRealm.Raw ? "modbus/plc/scalar" : "area/line/plc/scalar";
|
|
expected.Add((realm.ToString().ToLowerInvariant(), ProjectedDataIds.NamespaceUri(realm),
|
|
ProjectedDataIds.Identifier("map-" + realm.ToString().ToLowerInvariant(), new("SOURCE", uri, "string", path))));
|
|
}
|
|
}
|
|
foreach (var item in expected)
|
|
{
|
|
var index = Array.IndexOf(uris, item.Uri);
|
|
if (index < 1) throw new InvalidOperationException("namespace absent");
|
|
var id = new NodeId(item.Identifier, checked((ushort)index));
|
|
Opc.Ua.DataValue value;
|
|
var readDeadline = DateTime.UtcNow.AddSeconds(5);
|
|
while (true)
|
|
{
|
|
try { value = await client.ReadValueAsync(id, TimeSpan.FromSeconds(5)); break; }
|
|
catch (ServiceResultException error) when (error.StatusCode == StatusCodes.BadWaitingForInitialData && DateTime.UtcNow < readDeadline)
|
|
{ await Task.Delay(100); }
|
|
}
|
|
if (StatusCode.IsBad(value.StatusCode)) throw new InvalidOperationException("fixture leaf not ready");
|
|
aliases[item.Name] = id.ToString();
|
|
}
|
|
resolved[node] = new { namespace_uris = uris, aliases };
|
|
}
|
|
finally { await client.DisconnectAsync(); }
|
|
}
|
|
await Save("resolved.json", resolved);
|
|
return 0;
|
|
}
|
|
if (args[0] == "snapshot")
|
|
{
|
|
await using var db = await factory.CreateDbContextAsync();
|
|
await Save("baseline.json", new {
|
|
Connections = await db.DataConnections.AsNoTracking().ToListAsync(), Mappings = await db.RemoteNamespaceMappings.AsNoTracking().ToListAsync(),
|
|
Exports = await db.DataExports.AsNoTracking().ToListAsync(), Tags = await db.Tags.AsNoTracking().ToListAsync(),
|
|
References = await db.UnsTagReferences.AsNoTracking().ToListAsync(),
|
|
Clusters = await db.ServerClusters.AsNoTracking().ToListAsync(), Nodes = await db.ClusterNodes.AsNoTracking().ToListAsync(),
|
|
Acls = await db.NodeAcls.AsNoTracking().ToListAsync(),
|
|
Keys = await db.ApiKeys.AsNoTracking().Select(x => new { x.ApiKeyId, x.Enabled }).ToListAsync() });
|
|
await SaveText("baseline-source.key", await File.ReadAllTextAsync(Path.Combine(output, "source.key")));
|
|
return 0;
|
|
}
|
|
if (args[0] == "restore")
|
|
{
|
|
using var baseline = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "baseline.json")));
|
|
var root = baseline.RootElement;
|
|
await using var db = await factory.CreateDbContextAsync();
|
|
await using var transaction = await db.Database.BeginTransactionAsync();
|
|
await RestoreRows(db, db.DataConnections, root.GetProperty("Connections").Deserialize<List<DataConnection>>()!, x => x.DataConnectionId);
|
|
await RestoreRows(db, db.RemoteNamespaceMappings, root.GetProperty("Mappings").Deserialize<List<RemoteNamespaceMapping>>()!, x => x.RemoteNamespaceMappingId);
|
|
await RestoreRows(db, db.DataExports, root.GetProperty("Exports").Deserialize<List<DataExport>>()!, x => x.DataExportId);
|
|
await RestoreRows(db, db.Tags, root.GetProperty("Tags").Deserialize<List<Tag>>()!, x => x.TagId);
|
|
await RestoreRows(db, db.UnsTagReferences, root.GetProperty("References").Deserialize<List<UnsTagReference>>()!, x => x.UnsTagReferenceId);
|
|
await RestoreRows(db, db.ServerClusters, root.GetProperty("Clusters").Deserialize<List<ServerCluster>>()!, x => x.ClusterId);
|
|
await RestoreRows(db, db.ClusterNodes, root.GetProperty("Nodes").Deserialize<List<ClusterNode>>()!, x => x.NodeId);
|
|
await RestoreRows(db, db.NodeAcls, root.GetProperty("Acls").Deserialize<List<NodeAcl>>()!, x => x.NodeAclId);
|
|
await db.SaveChangesAsync();
|
|
if (DraftValidator.Validate(await DraftSnapshotFactory.FromConfigDbAsync(db)).Count != 0) throw new InvalidOperationException();
|
|
await transaction.CommitAsync();
|
|
var admin = new ApiKeyAdminService(factory, pepper);
|
|
var baselineKeys = root.GetProperty("Keys").EnumerateArray().Select(x => x.GetProperty("ApiKeyId").GetString()).ToHashSet(StringComparer.Ordinal);
|
|
foreach (var extra in (await admin.ListAsync(default)).Where(x => !baselineKeys.Contains(x.ApiKeyId)))
|
|
await admin.SetEnabledAsync(extra.ApiKeyId, false, default);
|
|
foreach (var key in root.GetProperty("Keys").EnumerateArray())
|
|
await admin.SetEnabledAsync(key.GetProperty("ApiKeyId").GetString()!, key.GetProperty("Enabled").GetBoolean(), default);
|
|
await SaveText("source.key", await File.ReadAllTextAsync(Path.Combine(output, "baseline-source.key")));
|
|
return 0;
|
|
}
|
|
if (args[0] == "mutate")
|
|
{
|
|
using var mutation = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(output, "mutation.json")));
|
|
var root = mutation.RootElement;
|
|
string[] allowedFields = ["connection_id", "target_mode", "target_node_id", "consistency", "consumer_node_ids", "connection_enabled", "connection_allowed_operations",
|
|
"mapping_enabled", "write_through", "allowed_operations", "export_id", "export_enabled", "export_allowed_operations", "source_redundancy_mode", "consumer_redundancy_mode",
|
|
"control_redundancy_mode", "rename_tag", "upsert_tag", "upsert_reference", "remove_tag_id", "disable_feature", "key_action", "key_expiry_seconds", "upsert_connection", "upsert_mapping", "upsert_export", "remove_mapping_id", "maintenance_mode", "acl_permissions", "bump_mapping_revision"];
|
|
if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Any(property => !allowedFields.Contains(property.Name, StringComparer.Ordinal)))
|
|
throw new InvalidOperationException("unknown fixture mutation field");
|
|
await using var db = await factory.CreateDbContextAsync();
|
|
await using var transaction = await db.Database.BeginTransactionAsync();
|
|
var rejectionPath = Path.Combine(output, "rejection.json");
|
|
if (File.Exists(rejectionPath)) File.Delete(rejectionPath);
|
|
var revisionReceiptPath = Path.Combine(output, "mutation-revisions.json");
|
|
if (File.Exists(revisionReceiptPath)) File.Delete(revisionReceiptPath);
|
|
if (root.TryGetProperty("key_action", out var keyAction) && keyAction.GetString() is not ("rotate" or "rotate_staged" or "expire" or "retire_old" or "revoke"))
|
|
throw new InvalidOperationException("unknown key mutation");
|
|
if (root.TryGetProperty("maintenance_mode", out var maintenance))
|
|
{
|
|
if (maintenance.ValueKind != JsonValueKind.Object
|
|
|| maintenance.EnumerateObject().Select(x => x.Name).Order().SequenceEqual(new[] { "enabled", "node_id" }) is false
|
|
|| maintenance.GetProperty("node_id").GetString() is not { } maintenanceNodeId
|
|
|| !nodes.Select(node => node + ":4053").Contains(maintenanceNodeId, StringComparer.Ordinal)
|
|
|| maintenance.GetProperty("enabled").ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
|
throw new InvalidOperationException("owned maintenance node and boolean required");
|
|
var maintenanceNode = await db.ClusterNodes.SingleAsync(x => x.NodeId == maintenanceNodeId);
|
|
maintenanceNode.MaintenanceMode = maintenance.GetProperty("enabled").GetBoolean();
|
|
}
|
|
if (root.TryGetProperty("upsert_connection", out var newConnection))
|
|
{
|
|
var candidate = JsonSerializer.Deserialize<DataConnection>(newConnection.GetRawText()) ?? throw new InvalidOperationException();
|
|
if (candidate.Endpoints.Any(endpoint => !Uri.TryCreate(endpoint, UriKind.Absolute, out var url) || url.Scheme != "https" || !nodes.Contains(url.Host, StringComparer.Ordinal) || url.Port != 4057)) throw new InvalidOperationException("owned endpoint required");
|
|
candidate.DataConnectionRowId = Guid.NewGuid();
|
|
var existing = await db.DataConnections.SingleOrDefaultAsync(x => x.DataConnectionId == candidate.DataConnectionId);
|
|
if (existing is null) db.DataConnections.Add(candidate);
|
|
else { candidate.DataConnectionRowId = existing.DataConnectionRowId; db.Entry(existing).CurrentValues.SetValues(candidate); }
|
|
await db.SaveChangesAsync();
|
|
}
|
|
if (root.TryGetProperty("upsert_mapping", out var newMapping))
|
|
{
|
|
var candidate = JsonSerializer.Deserialize<RemoteNamespaceMapping>(newMapping.GetRawText()) ?? throw new InvalidOperationException();
|
|
candidate.RemoteNamespaceMappingRowId = Guid.NewGuid();
|
|
var existing = await db.RemoteNamespaceMappings.SingleOrDefaultAsync(x => x.RemoteNamespaceMappingId == candidate.RemoteNamespaceMappingId);
|
|
if (existing is null) db.RemoteNamespaceMappings.Add(candidate);
|
|
else { candidate.RemoteNamespaceMappingRowId = existing.RemoteNamespaceMappingRowId; db.Entry(existing).CurrentValues.SetValues(candidate); }
|
|
}
|
|
if (root.TryGetProperty("upsert_export", out var newExport))
|
|
{
|
|
var candidate = newExport.Deserialize<DataExport>() ?? throw new InvalidOperationException();
|
|
candidate.DataExportRowId = Guid.NewGuid();
|
|
var existing = await db.DataExports.SingleOrDefaultAsync(x => x.DataExportId == candidate.DataExportId);
|
|
if (existing is null) db.DataExports.Add(candidate);
|
|
else { candidate.DataExportRowId = existing.DataExportRowId; db.Entry(existing).CurrentValues.SetValues(candidate); }
|
|
}
|
|
if (root.TryGetProperty("bump_mapping_revision", out var bumpMapping))
|
|
{
|
|
// A03: a consumer condition-stream reset against the SAME origin incarnation — a changed mapping revision restarts the
|
|
// connection's condition runner (new stream + complete snapshot, materialised conditions handed over).
|
|
var bumped = await db.RemoteNamespaceMappings.SingleAsync(x => x.RemoteNamespaceMappingId == bumpMapping.GetString());
|
|
bumped.Revision++;
|
|
}
|
|
if (root.TryGetProperty("remove_mapping_id", out var removeMapping))
|
|
await db.RemoteNamespaceMappings.Where(x => x.RemoteNamespaceMappingId == removeMapping.GetString()).ExecuteDeleteAsync();
|
|
var connectionId = root.TryGetProperty("connection_id", out var selected) ? selected.GetString() : "consumer-source";
|
|
var item = await db.DataConnections.SingleAsync(x => x.DataConnectionId == connectionId);
|
|
if (root.TryGetProperty("target_mode", out var mode))
|
|
{
|
|
item.TargetMode = Enum.Parse<DataTargetMode>(mode.GetString()!);
|
|
item.ExpectedNodeId = item.TargetMode == DataTargetMode.Node ? (root.TryGetProperty("target_node_id", out var target) ? target.GetString() : "source-1:4053") : null;
|
|
item.EligibleTargetNodeIds = item.TargetMode == DataTargetMode.Node ? [] : ["source-1:4053", "source-2:4053"];
|
|
item.Endpoints = item.TargetMode == DataTargetMode.Node ? ["https://" + item.ExpectedNodeId!.Split(':')[0] + ":4057"] : ["https://source-1:4057", "https://source-2:4057"];
|
|
}
|
|
if (root.TryGetProperty("consistency", out var consistency)) item.Consistency = Enum.Parse<DataConsistency>(consistency.GetString()!);
|
|
if (root.TryGetProperty("connection_allowed_operations", out var connectionOps)) item.AllowedOperations = (DataOperations)connectionOps.GetInt32();
|
|
if (root.TryGetProperty("connection_enabled", out var enabled)) item.Enabled = enabled.GetBoolean();
|
|
if (root.TryGetProperty("consumer_node_ids", out var consumers)) item.ConsumerNodeIds = consumers.EnumerateArray().Select(x => x.GetString()!).ToList();
|
|
var mutationMappings = await db.RemoteNamespaceMappings.Where(x => x.DataConnectionId == connectionId).ToListAsync();
|
|
foreach (var mapping in mutationMappings)
|
|
{
|
|
FixtureMutationRevisions.InheritConsumerPlacement(root, item, mapping);
|
|
if (root.TryGetProperty("mapping_enabled", out var mappingEnabled)) mapping.Enabled = mappingEnabled.GetBoolean();
|
|
if (root.TryGetProperty("write_through", out var write)) mapping.WriteThrough = write.GetBoolean();
|
|
if (root.TryGetProperty("allowed_operations", out var ops)) mapping.AllowedOperations = (DataOperations)ops.GetInt32();
|
|
}
|
|
var selectedExport = root.TryGetProperty("export_id", out var exportId) ? exportId.GetString() : null;
|
|
var mutationExports = await db.DataExports.Where(x => selectedExport == null || x.DataExportId == selectedExport).ToListAsync();
|
|
foreach (var export in mutationExports)
|
|
{
|
|
if (root.TryGetProperty("export_enabled", out var exportEnabled)) export.Enabled = exportEnabled.GetBoolean();
|
|
if (root.TryGetProperty("export_allowed_operations", out var ops)) export.AllowedOperations = (DataOperations)ops.GetInt32();
|
|
}
|
|
var revisionReceipt = FixtureMutationRevisions.Advance(root, item, mutationMappings, mutationExports);
|
|
foreach (var cluster in await db.ServerClusters.ToListAsync())
|
|
{
|
|
var field = cluster.ClusterId.ToLowerInvariant() + "_redundancy_mode";
|
|
if (root.TryGetProperty(field, out var redundancy)) cluster.RedundancyMode = Enum.Parse<RedundancyMode>(redundancy.GetString()!);
|
|
}
|
|
if (root.TryGetProperty("rename_tag", out var rename))
|
|
{
|
|
var tag = await db.Tags.SingleAsync(x => x.TagId == rename.GetProperty("tag_id").GetString());
|
|
tag.Name = rename.GetProperty("name").GetString()!;
|
|
}
|
|
if (root.TryGetProperty("upsert_tag", out var newTag))
|
|
{
|
|
var candidate = newTag.Deserialize<Tag>() ?? throw new InvalidOperationException();
|
|
candidate.TagRowId = Guid.NewGuid();
|
|
db.Tags.Add(candidate);
|
|
}
|
|
if (root.TryGetProperty("upsert_reference", out var newReference))
|
|
{
|
|
var candidate = newReference.Deserialize<UnsTagReference>() ?? throw new InvalidOperationException();
|
|
if (!root.TryGetProperty("upsert_tag", out var pairedTag)
|
|
|| candidate.TagId != pairedTag.GetProperty("TagId").GetString()
|
|
|| candidate.UnsTagReferenceId != "ref-" + candidate.TagId
|
|
|| !await db.Equipment.AnyAsync(x => x.EquipmentId == candidate.EquipmentId))
|
|
throw new InvalidOperationException("new fixture reference must accompany its local tag");
|
|
candidate.UnsTagReferenceRowId = Guid.NewGuid();
|
|
db.UnsTagReferences.Add(candidate);
|
|
}
|
|
if (root.TryGetProperty("remove_tag_id", out var removeTag))
|
|
{
|
|
await db.UnsTagReferences.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync();
|
|
await db.Tags.Where(x => x.TagId == removeTag.GetString()).ExecuteDeleteAsync();
|
|
}
|
|
if (root.TryGetProperty("acl_permissions", out var aclPermissions))
|
|
{
|
|
// H3: {"node_acl_id": "...", "permission_flags": <int>} — one existing row's flags (baseline restore reverts it).
|
|
var acl = await db.NodeAcls.SingleAsync(x => x.NodeAclId == aclPermissions.GetProperty("node_acl_id").GetString());
|
|
acl.PermissionFlags = (NodePermissions)aclPermissions.GetProperty("permission_flags").GetInt32();
|
|
}
|
|
if (root.TryGetProperty("disable_feature", out var disable) && disable.GetBoolean())
|
|
{
|
|
foreach (var row in await db.DataConnections.ToListAsync()) { row.Enabled = false; row.Revision++; }
|
|
foreach (var row in await db.RemoteNamespaceMappings.ToListAsync()) { row.Enabled = false; row.Revision++; }
|
|
foreach (var row in await db.DataExports.ToListAsync()) { row.Enabled = false; row.Revision++; }
|
|
}
|
|
await db.SaveChangesAsync();
|
|
var errors = DraftValidator.Validate(await DraftSnapshotFactory.FromConfigDbAsync(db));
|
|
if (errors.Count != 0)
|
|
{
|
|
await Save("rejection.json", new { validator = "DraftValidator", codes = errors.Select(error => error.Code).Distinct().ToArray() });
|
|
throw new InvalidOperationException("production mutation validation failed");
|
|
}
|
|
await transaction.CommitAsync();
|
|
if (revisionReceipt.CredentialOnly)
|
|
await Save("mutation-revisions.json", new { keyAction = root.GetProperty("key_action").GetString(), revisions = revisionReceipt });
|
|
if (root.TryGetProperty("key_action", out var action))
|
|
{
|
|
var admin = new ApiKeyAdminService(factory, pepper);
|
|
var old = (await File.ReadAllTextAsync(Path.Combine(output, "source.key"))).Trim();
|
|
if (action.GetString() is "rotate" or "rotate_staged" or "expire")
|
|
{
|
|
await SaveText("source-previous.key", old);
|
|
await SaveText("source.key", await admin.CreateAsync("source-issued-rotated", "fixture-consumer",
|
|
action.GetString() == "expire" ? DateTime.UtcNow.AddSeconds(root.TryGetProperty("key_expiry_seconds", out var seconds) ? seconds.GetInt32() : 10) : null, "local rotation", default));
|
|
if (action.GetString() != "rotate_staged") await admin.SetEnabledAsync(old.Split('_')[1], false, default);
|
|
}
|
|
else if (action.GetString() == "retire_old")
|
|
await admin.SetEnabledAsync((await File.ReadAllTextAsync(Path.Combine(output, "source-previous.key"))).Trim().Split('_')[1], false, default);
|
|
else if (action.GetString() == "revoke") await admin.SetEnabledAsync(old.Split('_')[1], false, default);
|
|
else throw new InvalidOperationException("unknown key mutation");
|
|
}
|
|
return 0;
|
|
}
|
|
if (args[0] != "seed") return 2;
|
|
var pumpEquipment = new Dictionary<string, string>(StringComparer.Ordinal); // A4: pump equipment name → EquipmentId
|
|
await using (var db = await factory.CreateDbContextAsync())
|
|
{
|
|
if (await db.ServerClusters.AnyAsync()) throw new InvalidOperationException("fixture seed requires empty owned database");
|
|
foreach (var cluster in new[] { "CONTROL", "SOURCE", "CONSUMER" })
|
|
{
|
|
db.ServerClusters.Add(new() { ClusterId = cluster, Name = cluster, Enterprise = "zb", Site = "local", NodeCount = 2,
|
|
RedundancyMode = RedundancyMode.Hot, CreatedBy = "grpc-data-local-gate" });
|
|
foreach (var node in nodes.Where(x => x.StartsWith(cluster.ToLowerInvariant() + "-", StringComparison.Ordinal)))
|
|
db.ClusterNodes.Add(new() { NodeId = node + ":4053", ClusterId = cluster, Host = node, OpcUaPort = 4840, DashboardPort = 9000,
|
|
GrpcPort = 4056, ApplicationUri = "urn:OtOpcUa:grpc-data:" + node, CreatedBy = "grpc-data-local-gate" });
|
|
// H3 (history profile): on CONSUMER the CLI principal's HistoryRead comes ONLY from the mapping-scoped grants below,
|
|
// so a scenario can take it away per mapping (plan §6: mapped history needs HistoryRead on the mapping scope).
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-" + cluster, ClusterId = cluster,
|
|
Principal = "fixture-cli", ScopeKind = NodeAclScopeKind.Cluster,
|
|
PermissionFlags = history && cluster == "CONSUMER" ? NodePermissions.Admin & ~NodePermissions.HistoryRead : NodePermissions.Admin });
|
|
}
|
|
db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-modbus", ClusterId = "SOURCE", Name = "modbus", DriverType = "Modbus",
|
|
DriverConfig = """{"TimeoutMs":2000,"AutoReconnect":true,"Probe":{"Enabled":true,"ProbeAddress":0}}""" });
|
|
db.Devices.Add(new() { DeviceRowId = Guid.NewGuid(), DeviceId = "source-device", DriverInstanceId = "source-modbus", Name = "plc",
|
|
DeviceConfig = """{"Host":"device","Port":5020,"UnitId":1}""" });
|
|
db.PollGroups.Add(new() { PollGroupRowId = Guid.NewGuid(), PollGroupId = "source-fast", DriverInstanceId = "source-modbus", Name = "fast", IntervalMs = 200 });
|
|
foreach (var (name, address, writable) in new[] { ("counter", 0, false), ("scalar", 20, true), ("array0", 10, false), ("array1", 11, false), ("array2", 12, false) })
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-" + name, DeviceId = "source-device", Name = name, DataType = "UInt16",
|
|
AccessLevel = writable ? TagAccessLevel.ReadWrite : TagAccessLevel.Read, WriteIdempotent = false, PollGroupId = "source-fast",
|
|
TagConfig = history && name == "counter"
|
|
? JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable, isHistorized = true })
|
|
: JsonSerializer.Serialize(new { region = "HoldingRegisters", address, dataType = "UInt16", writable }) });
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-vector", DeviceId = "source-device", Name = "vector", DataType = "UInt16",
|
|
AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast",
|
|
TagConfig = """{"region":"HoldingRegisters","address":24,"dataType":"UInt16","isArray":true,"arrayLength":3,"writable":true}""" });
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-text", DeviceId = "source-device", Name = "text", DataType = "String",
|
|
AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast",
|
|
TagConfig = history
|
|
? """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true,"isHistorized":true}"""
|
|
: """{"region":"HoldingRegisters","address":40,"dataType":"String","stringLength":16,"writable":true}""" });
|
|
if (history)
|
|
// H3 review: a historized Float32 (two registers 30..31, big-endian), so the gate proves a backend that stores Double
|
|
// still reads Good Singles through the projection.
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-flt", DeviceId = "source-device", Name = "flt", DataType = "Float",
|
|
AccessLevel = TagAccessLevel.ReadWrite, WriteIdempotent = false, PollGroupId = "source-fast",
|
|
TagConfig = """{"region":"HoldingRegisters","address":30,"dataType":"Float32","writable":true,"isHistorized":true}""" });
|
|
db.UnsAreas.Add(new() { UnsAreaRowId = Guid.NewGuid(), UnsAreaId = "source-area", ClusterId = "SOURCE", Name = "area" });
|
|
db.UnsLines.Add(new() { UnsLineRowId = Guid.NewGuid(), UnsLineId = "source-line", UnsAreaId = "source-area", Name = "line" });
|
|
var uuid = Guid.NewGuid();
|
|
var equipment = DraftValidator.DeriveEquipmentId(uuid);
|
|
db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = equipment, EquipmentUuid = uuid, UnsLineId = "source-line", Name = "plc", MachineCode = "fixture-plc" });
|
|
foreach (var name in new[] { "counter", "scalar", "array0", "array1", "array2", "vector", "text" }.Concat(history ? ["flt"] : []))
|
|
db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + name, EquipmentId = equipment, TagId = "source-" + name });
|
|
if (conditions)
|
|
{
|
|
const string predicate = "return Convert.ToInt32(ctx.GetTag(\"modbus/plc/scalar\").Value) > 100;";
|
|
db.Scripts.Add(new() { ScriptRowId = Guid.NewGuid(), ScriptId = "source-scalar-high", Name = "scalar-high", SourceCode = predicate,
|
|
SourceHash = Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(predicate))) });
|
|
db.ScriptedAlarms.Add(new() { ScriptedAlarmRowId = Guid.NewGuid(), ScriptedAlarmId = "source-scalar-high", EquipmentId = equipment,
|
|
Name = "ScalarHigh", AlarmType = "AlarmCondition", MessageTemplate = "scalar high", PredicateScriptId = "source-scalar-high" });
|
|
// A4 live scenarios (A02/A04): an OpcUaClient driver against the run-owned opc-plc `--alm` container (compose.conditions.yml),
|
|
// one native alarm tag bound 1:1 to the upstream CONDITION node EastTank?Yellow (several conditions share the EastTank source,
|
|
// so the source node would fold them; docs/drivers/OpcUaClient.md "Native alarms"), and a value control tag. Yellow, not Red:
|
|
// opc-plc's Yellow cycles Active (~40 s) / Inactive (~8 s) on its own, so the origin re-reports it live; Red never leaves
|
|
// Active and its heartbeats repeat the last-told state, so once acked it goes silent (live run a4s-1). The alarm tag is
|
|
// referenced by two NEW equipment (pumpa, pumpb) so the A2a/A3 smokes' `plc` equipment view is unchanged.
|
|
db.DriverInstances.Add(new() { DriverInstanceRowId = Guid.NewGuid(), DriverInstanceId = "source-opcua", ClusterId = "SOURCE", Name = "opcua", DriverType = "OpcUaClient",
|
|
DriverConfig = """{"SecurityPolicy":"None","SecurityMode":"None","AuthType":"Anonymous","AutoAcceptCertificates":true}""" });
|
|
db.Devices.Add(new() { DeviceRowId = Guid.NewGuid(), DeviceId = "source-opcplc", DriverInstanceId = "source-opcua", Name = "opcplc",
|
|
DeviceConfig = """{"EndpointUrl":"opc.tcp://opcplc:50000"}""" });
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-fast", DeviceId = "source-opcplc", Name = "FastUInt1", DataType = "UInt32",
|
|
AccessLevel = TagAccessLevel.Read, WriteIdempotent = false, TagConfig = """{"nodeId":"ns=3;s=FastUInt1"}""" });
|
|
db.Tags.Add(new() { TagRowId = Guid.NewGuid(), TagId = "source-opcua-yellow", DeviceId = "source-opcplc", Name = "EastTankYellow", DataType = "Boolean",
|
|
AccessLevel = TagAccessLevel.Read, WriteIdempotent = false,
|
|
TagConfig = """{"nodeId":"ns=6;s=1:Colours/EastTank?Yellow","alarm":{"alarmType":"AlarmCondition","severity":500}}""" });
|
|
foreach (var pump in new[] { "pumpa", "pumpb" })
|
|
{
|
|
var pumpUuid = Guid.NewGuid();
|
|
var pumpId = DraftValidator.DeriveEquipmentId(pumpUuid);
|
|
pumpEquipment[pump] = pumpId;
|
|
db.Equipment.Add(new() { EquipmentRowId = Guid.NewGuid(), EquipmentId = pumpId, EquipmentUuid = pumpUuid, UnsLineId = "source-line", Name = pump, MachineCode = "fixture-" + pump });
|
|
db.UnsTagReferences.Add(new() { UnsTagReferenceRowId = Guid.NewGuid(), UnsTagReferenceId = "ref-" + pump + "-yellow", EquipmentId = pumpId, TagId = "source-opcua-yellow" });
|
|
}
|
|
}
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer", ClusterId = "SOURCE", Principal = "fixture-consumer",
|
|
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
|
|
db.DataConnections.Add(new() { DataConnectionRowId = Guid.NewGuid(), DataConnectionId = "consumer-source", ClusterId = "CONSUMER", Enabled = true,
|
|
ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"], TargetMode = DataTargetMode.Cluster, ExpectedClusterId = "SOURCE",
|
|
EligibleTargetNodeIds = ["source-1:4053", "source-2:4053"], Endpoints = ["https://source-1:4057", "https://source-2:4057"],
|
|
// A3: the conditions profile makes the CONSUMER condition-bearing too (connection + mappings carry AlarmSubscribe and
|
|
// the method bits), so a consumer Server-object subscription imports ScalarHigh and can acknowledge it remotely.
|
|
SecretReference = "secret:data/source", SecretScopeClusterId = "CONSUMER",
|
|
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None),
|
|
TimeoutMilliseconds = 30000 });
|
|
foreach (var realm in new[] { DataRealm.Raw, DataRealm.Uns })
|
|
{
|
|
var name = realm.ToString().ToLowerInvariant();
|
|
var rootKind = realm == DataRealm.Raw ? "RawDevice" : "Equipment";
|
|
var entity = realm == DataRealm.Raw ? "source-device" : equipment;
|
|
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name, ClusterId = "SOURCE", Enabled = true,
|
|
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer",
|
|
// A2b: the conditions profile also grants the remote condition methods (Acknowledge/AddComment, Confirm).
|
|
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None) });
|
|
if (history)
|
|
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + name + "-nohistory", ClusterId = "SOURCE", Enabled = true,
|
|
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-nohistory", AllowedOperations = operations });
|
|
db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-" + name,
|
|
ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"],
|
|
Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-source",
|
|
RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
|
|
RemoteIdentifierKind = "string", RemoteIdentifier = realm == DataRealm.Raw ? "modbus/plc" : equipment,
|
|
AllowedOperations = grantedOperations | (conditions ? DataOperationSets.ConditionGrants : DataOperations.None), WriteThrough = true });
|
|
if (history)
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-history-map-" + name, ClusterId = "CONSUMER", Principal = "fixture-cli",
|
|
ScopeKind = NodeAclScopeKind.RemoteNamespaceMapping, ScopeId = "map-" + name, PermissionFlags = NodePermissions.Browse | NodePermissions.HistoryRead });
|
|
}
|
|
if (conditions)
|
|
{
|
|
// A4: exports + CONSUMER mappings for the native alarm's three placements — the Raw opc-plc device and the two
|
|
// UNS equipment that reference it (A04: one consumer condition, three notifiers). Distinct branch names.
|
|
var conditionOps = operations | DataOperationSets.ConditionGrants;
|
|
foreach (var (id, realm, rootKind, entity, identifier) in new[] {
|
|
("opc", DataRealm.Raw, "RawDevice", "source-opcplc", "opcua/opcplc"),
|
|
("pumpa", DataRealm.Uns, "Equipment", pumpEquipment["pumpa"], pumpEquipment["pumpa"]),
|
|
("pumpb", DataRealm.Uns, "Equipment", pumpEquipment["pumpb"], pumpEquipment["pumpb"]) })
|
|
{
|
|
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-" + id, ClusterId = "SOURCE", Enabled = true,
|
|
Realm = realm, RootKind = rootKind, RootEntityId = entity, PrincipalId = "fixture-consumer", AllowedOperations = conditionOps });
|
|
db.RemoteNamespaceMappings.Add(new() { RemoteNamespaceMappingRowId = Guid.NewGuid(), RemoteNamespaceMappingId = "map-" + id,
|
|
ClusterId = "CONSUMER", DataConnectionId = "consumer-source", Enabled = true, ConsumerNodeIds = ["consumer-1:4053", "consumer-2:4053"],
|
|
Realm = realm, RemoteRealm = realm, LocalParentKind = "Cluster", LocalParentId = "CONSUMER", BranchName = "remote-" + id,
|
|
RemoteRootEntityId = entity, RemoteNamespaceUri = realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri,
|
|
RemoteIdentifierKind = "string", RemoteIdentifier = identifier, AllowedOperations = conditionOps, WriteThrough = true });
|
|
}
|
|
// A04: a UNS-ONLY origin principal (one UNS export, no Raw export) — its condition records must carry no RawPath.
|
|
db.DataExports.Add(new() { DataExportRowId = Guid.NewGuid(), DataExportId = "export-pumpa-unsonly", ClusterId = "SOURCE", Enabled = true,
|
|
Realm = DataRealm.Uns, RootKind = "Equipment", RootEntityId = pumpEquipment["pumpa"], PrincipalId = "fixture-unsonly", AllowedOperations = conditionOps });
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-unsonly", ClusterId = "SOURCE", Principal = "fixture-unsonly",
|
|
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
|
|
// A05: the CONSUMER-local principal `fixture-cli-nogrant` deliberately has NO NodeAcl row (no mapping grant).
|
|
// A06: a SECOND granted CONSUMER principal, so the two consumer pair members can be watched under different
|
|
// principals (the imported ConditionId must not depend on who asks).
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "cli-alt-CONSUMER", ClusterId = "CONSUMER", Principal = "fixture-cli-alt",
|
|
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Admin });
|
|
}
|
|
if (history)
|
|
// The second principal's origin ACL also lacks HistoryRead: with its export's HistoryRead off the RPC is refused
|
|
// (PermissionDenied, like v1 Read); granting the export bit then leaves the per-node ACL denial (BadHistoryOperationUnsupported).
|
|
db.NodeAcls.Add(new() { NodeAclRowId = Guid.NewGuid(), NodeAclId = "source-peer-nohistory", ClusterId = "SOURCE", Principal = "fixture-nohistory",
|
|
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly & ~NodePermissions.HistoryRead });
|
|
await db.SaveChangesAsync();
|
|
}
|
|
var seedAdmin = new ApiKeyAdminService(factory, pepper);
|
|
await SaveText("cli.key", await seedAdmin.CreateAsync("fixture-cli", "fixture-cli", null, "owned local fixture", default));
|
|
await SaveText("source.key", await seedAdmin.CreateAsync("source-issued-consumer", "fixture-consumer", null, "SOURCE grants for CONSUMER", default));
|
|
if (conditions)
|
|
{
|
|
await SaveText("source-unsonly.key", await seedAdmin.CreateAsync("source-issued-unsonly", "fixture-unsonly", null, "SOURCE UNS-only export (A04)", default));
|
|
await SaveText("cli-nogrant.key", await seedAdmin.CreateAsync("fixture-cli-nogrant", "fixture-cli-nogrant", null, "CONSUMER principal without a mapping grant (A05)", default));
|
|
await SaveText("cli-alt.key", await seedAdmin.CreateAsync("fixture-cli-alt", "fixture-cli-alt", null, "second granted CONSUMER principal (A06)", default));
|
|
}
|
|
if (history)
|
|
await SaveText("source-nohistory.key", await seedAdmin.CreateAsync("source-issued-nohistory", "fixture-nohistory", null, "SOURCE export without HistoryRead", default));
|
|
string unsBrowseRoot;
|
|
await using (var db = await factory.CreateDbContextAsync())
|
|
{
|
|
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db);
|
|
var errors = DraftValidator.Validate(snapshot).Concat(snapshot.ServerClusters.SelectMany(cluster => DraftValidator.ValidateClusterTopology(cluster, snapshot.ClusterNodes.Where(node => node.ClusterId == cluster.ClusterId).ToList()))).ToList();
|
|
if (errors.Count != 0) throw new InvalidOperationException("production validator rejected fixture");
|
|
unsBrowseRoot = await db.Equipment.Where(item => item.Name == "plc").Select(item => item.EquipmentId).SingleAsync();
|
|
}
|
|
await Save("fixture.json", new { connection_id = "consumer-source", mapping_ids = new[] { "map-raw", "map-uns" },
|
|
namespace_uris = new { raw = V3NodeIds.RawNamespaceUri, uns = V3NodeIds.UnsNamespaceUri, mapped_raw = ProjectedDataIds.RawNamespaceUri, mapped_uns = ProjectedDataIds.UnsNamespaceUri },
|
|
browse_roots = new { raw = "modbus/plc", uns = unsBrowseRoot },
|
|
browse_subjects = new { raw = "modbus/plc", uns = "area/line/plc" },
|
|
origin_paths = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar", raw_array = "modbus/plc/vector", uns_array = "area/line/plc/vector", raw_string = "modbus/plc/text", uns_string = "area/line/plc/text" }, aliases = new[] { "raw", "uns" },
|
|
history = history ? new { historized = new { raw = "modbus/plc/counter", uns = "area/line/plc/counter" }, unhistorized = new { raw = "modbus/plc/scalar", uns = "area/line/plc/scalar" },
|
|
historized_string = new { raw = "modbus/plc/text", uns = "area/line/plc/text" } } : null,
|
|
// A4 live scenarios: where the native alarm lives (origin RawPath + equipment) and which consumer mappings place it.
|
|
conditions = conditions ? new { scripted = new { condition = "ScalarHigh", origin_id = "source-scalar-high", mapping = "map-uns", branch = "remote-source" },
|
|
native = new { condition = "EastTankYellow", raw_path = "opcua/opcplc/EastTankYellow", upstream = "ns=6;s=1:Colours/EastTank?Yellow",
|
|
equipment = pumpEquipment, subjects = new { pumpa = "area/line/pumpa", pumpb = "area/line/pumpb" }, raw_root = "opcua/opcplc",
|
|
mappings = new { raw = "map-opc", pumpa = "map-pumpa", pumpb = "map-pumpb" },
|
|
branches = new { raw = "remote-opc", pumpa = "remote-pumpa", pumpb = "remote-pumpb" } } } : null });
|
|
return 0;
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
// Only the restricted run-owned output receives diagnostics. Console output
|
|
// remains safe for Docker orchestration, which can contain credential args.
|
|
try { await SaveText("last-error.txt", error.ToString()[..Math.Min(error.ToString().Length, 16384)]); }
|
|
catch (Exception) { /* Preserve the original failure and redacted console. */ }
|
|
Console.Error.WriteLine("grpc-data fixture helper failed; secret-bearing diagnostics withheld");
|
|
return 1;
|
|
}
|
|
|
|
async Task Save(string name, object body) => await SaveText(name, JsonSerializer.Serialize(body));
|
|
async Task SaveText(string name, string text)
|
|
{
|
|
Directory.CreateDirectory(output);
|
|
var path = Path.Combine(output, name);
|
|
var temporary = Path.Combine(output, "." + name + "." + Guid.NewGuid().ToString("N"));
|
|
var fileOptions = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
|
|
if (!OperatingSystem.IsWindows()) fileOptions.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
|
|
await using (var file = new FileStream(temporary, fileOptions))
|
|
await using (var writer = new StreamWriter(file)) { await writer.WriteAsync(text); }
|
|
File.Move(temporary, path, true);
|
|
}
|
|
|
|
async Task RestoreRows<T>(OtOpcUaConfigDbContext db, DbSet<T> set, List<T> baseline, Func<T, string> identity) where T : class
|
|
{
|
|
var rows = await set.ToListAsync();
|
|
foreach (var row in rows.Where(row => !baseline.Any(candidate => identity(candidate) == identity(row)))) set.Remove(row);
|
|
foreach (var candidate in baseline)
|
|
{
|
|
var current = rows.SingleOrDefault(row => identity(row) == identity(candidate));
|
|
if (current is null) { set.Add(candidate); continue; }
|
|
var entry = db.Entry(current);
|
|
var previousRevision = entry.Metadata.FindProperty("Revision") is not null ? (long)entry.Property("Revision").CurrentValue! : 0;
|
|
var preserved = entry.Metadata.FindPrimaryKey()!.Properties.Select(property => property.Name).Append("RowVersion")
|
|
.Where(name => entry.Metadata.FindProperty(name) is not null).ToDictionary(name => name, name => entry.Property(name).CurrentValue);
|
|
entry.CurrentValues.SetValues(candidate);
|
|
if (entry.Metadata.FindProperty("Revision") is not null)
|
|
entry.Property("Revision").CurrentValue = checked(Math.Max(previousRevision, (long)entry.Property("Revision").CurrentValue!) + 1);
|
|
foreach (var property in preserved) entry.Property(property.Key).CurrentValue = property.Value;
|
|
}
|
|
}
|