Merge branch 'review/wp2' into review/integration

This commit is contained in:
Joseph Doherty
2026-12-03 10:41:17 -05:00
46 changed files with 5166 additions and 284 deletions
@@ -0,0 +1,20 @@
-- WidenSystemArtifactPerSiteStatus (2026-12-03, DEP-3 / code-review WP2 task 2.9). Widens
-- SystemArtifactDeploymentRecords.PerSiteStatus from nvarchar(4000) to nvarchar(max): one serialized
-- per-site result per site overflowed 4000 chars at ~25 sites, failing Deploy Artifacts after every
-- site had applied. The table holds one small row per Deploy Artifacts run. Not yet applied to QA/DEV.
BEGIN TRANSACTION;
DECLARE @var nvarchar(max);
SELECT @var = QUOTENAME([d].[name])
FROM [sys].[default_constraints] [d]
INNER JOIN [sys].[columns] [c] ON [d].[parent_column_id] = [c].[column_id] AND [d].[parent_object_id] = [c].[object_id]
WHERE ([d].[parent_object_id] = OBJECT_ID(N'[SystemArtifactDeploymentRecords]') AND [c].[name] = N'PerSiteStatus');
IF @var IS NOT NULL EXEC(N'ALTER TABLE [SystemArtifactDeploymentRecords] DROP CONSTRAINT ' + @var + ';');
ALTER TABLE [SystemArtifactDeploymentRecords] ALTER COLUMN [PerSiteStatus] nvarchar(max) NULL;
INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N'20261203151127_WidenSystemArtifactPerSiteStatus', N'10.0.13');
COMMIT;
GO
+4 -2
View File
@@ -171,6 +171,8 @@ scadabridge site area delete --id <id>
scadabridge site deploy-artifacts [--site-id <id>]
```
`site update`, `data-connection update` and `api-method update` are **partial** updates (CLI-2, 2026-12-03): only the options passed are sent; an omitted option travels as null and the server keeps the stored value (preserve-if-null in the `ManagementActor` handler), and an empty string (`""`) clears an optional field. Previously every omitted option was sent as null or a default (`--failover-retry-count` 3, `--timeout` 30) and overwrote the stored value — `site update --id 3 --name X` nulled both gRPC addresses. An older CLI that always sends every field still deserializes unchanged.
### Deployment Commands
```
scadabridge deploy instance --id <id>
@@ -185,7 +187,7 @@ scadabridge deploy status [--instance-id <id>] [--status <status>] [--page <n>]
scadabridge data-connection list [--site-id <id>]
scadabridge data-connection get --id <id>
scadabridge data-connection create --site-id <id> --name <name> --protocol <protocol> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> --name <name> --protocol <protocol> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection update --id <id> [--name <name>] [--protocol <protocol>] [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <n>]
scadabridge data-connection delete --id <id>
scadabridge data-connection move --id <id> --site-id <destination-site-id>
```
@@ -423,7 +425,7 @@ scadabridge db-connection delete --id <id>
scadabridge api-method list
scadabridge api-method get --id <id>
scadabridge api-method create --name <name> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> --script <code> [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method update --id <id> [--script <code>] [--timeout <seconds>] [--parameters <json>] [--return-def <json>]
scadabridge api-method delete --id <id>
scadabridge api-method validate --id <id>
scadabridge api-method recompile --id <id>
@@ -156,6 +156,8 @@ When an instance is deployed, the Template Engine resolves the full configuratio
5. Resolve data connection bindings — replace connection name references with concrete connection details from the site.
6. Output a flat structure: list of attributes with resolved values and data source addresses, list of alarms with resolved trigger definitions, list of scripts with resolved code and triggers.
**Alarm on-trigger script resolution (2026-12-03, TPL-1/TPL-2/TPL-5).** An alarm's `OnTriggerScriptId` is resolved **by name within the alarm's own chain**: the id is looked up among the script rows of every template in that alarm's inheritance chain (base rows, derived overrides and `IsInherited` placeholders), and the row's *name* is path-qualified with the alarm's composition prefix (`Pump1.HighTemp` → `Pump1.OnHigh`). It used to go through one flatten-wide `script id → canonical name` map, which (a) made every slot of a module composed twice run the **last** slot's script, since all slots share the base script row id; (b) dropped the link (null on-trigger script) when a derived template overrode the script, since the override row has a different id; and (c) let the second visit of a nested slot overwrite a slot-level on-trigger override. The value is decided by the pass that actually adds the alarm (first wins, same as the alarm itself). An id that is not a script row of the alarm's own chain keeps the old flatten-wide fallback, and a reference that names no resolved script is still left null. **This changes the revision hash** of any instance whose flattened alarms were affected — such instances read *Out of date* once and redeploy with the corrected script link.
### Flatten-session caching and the graph watermark (WP2.5)
The flatten above is driven per instance, so an unmemoised implementation re-walks
+6 -4
View File
@@ -22,7 +22,7 @@ As of M8 (T18), Transport is no longer limited to central-only configuration: it
- Move **site-scoped configuration** (T18): `Site` definitions, site-scoped `DataConnection`s (protocol connections — distinct from External-System `DatabaseConnection`s), and `Instance`s along with their `InstanceAttributeOverride` / `InstanceAlarmOverride` / `InstanceNativeAlarmSourceOverride` / `InstanceConnectionBinding` children and `Area` membership (carried by name).
- Reconcile cross-environment site identifiers and connection names through the **name-mapping subsystem** (`BundleNameMap`): auto-match by identifier/name, operator override via the import-wizard Map step or CLI flags, and per-conflict create-or-bind resolution (see "Name Mapping").
- Compute a **per-line (Myers) diff** for code fields on Modified artifacts (T20) via the pure `LineDiffer`, embedding a size-capped structured line diff in each `ArtifactDiff`. Two independent caps guard the diff: a 400-line **output** cap on the emitted hunk list, and — as of arch-review 05 (Task 22) — a `MaxInputLines` **input** cap (4000 combined lines) that short-circuits the O((N+M)²) Myers trace to a summary-only result (`Truncated = true`, add/remove totals only) so a bloated or crafted bundle cannot OOM the active central node from the import preview.
- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature). Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack.
- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature) plus, since 2026-12-03 (TRN-8), the additive `AreaPath` (root→leaf names): the importer resolves the area level by level and creates any missing level under its real parent, since the same leaf name may sit under two parents. A pre-TRN-8 bundle carries only the leaf; an ambiguous leaf then resolves deterministically (a root-level area, else the lowest id) with an `ImportResult.Warnings` entry instead of taking whichever row came back first. Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack.
- Encrypt content with AES-256-GCM + PBKDF2-SHA256 (600 000 iterations) when a passphrase is supplied; leave content plaintext with a UI warning and an `UnencryptedBundleExport` audit event when none is given.
- Validate `manifest.json` on upload: format version gating, SHA-256 content hash verification.
- **Optionally sign** exported bundles (ECDSA P-256 detached signature in `manifest.sig`) and enforce an import-side signature policy against a trust store — off by default (ScadaBridge#45; see "Bundle Signing").
@@ -97,7 +97,7 @@ The manifest is plaintext so the import wizard can preview bundle contents and s
### `content.json` / `content.enc`
- One top-level array per entity type, POCO shapes serialized via `System.Text.Json`. As of schema 1.1 (T18) this includes `sites`, `dataConnections`, and `instances` arrays (`SiteDto`, `DataConnectionDto`, `InstanceDto` + its override-child and connection-binding DTOs) alongside the existing central-config arrays.
- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs as presence-only and are never echoed in plaintext. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields.
- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs presence-only and are never echoed in plaintext. **Secret values are still compared (2026-12-03, TRN-2):** the preview hashes both sides (SHA-256) and, when a value present on both sides differs, reports the value-free marker `<present>` → `<changed>`, so the row classifies **Modified**. Before, only a presence flip counted, so a changed OPC UA endpoint (or DB connection string, external-system auth, SMTP credentials, SMS token) read *Identical* and was force-skipped, and an Overwrite driven by an unrelated field replaced the value unseen. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields.
- The whole `content` blob is AES-256-GCM encrypted with a key derived via PBKDF2-SHA256 (600 000 iterations) from the user's passphrase, with per-bundle random salt and per-encryption random IV.
- Unencrypted bundles are allowed but the UI warns and audit-tags them `UnencryptedBundleExport`.
@@ -234,7 +234,7 @@ Upload → Passphrase → Diff → Confirm → Result. The **Map** step is not a
**Step 4 — Diff & resolve conflicts.** For each artifact in the bundle, compare to existing by name:
- **Identical** (field-by-field) → marked, auto-skipped, cannot be selected.
- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename.
- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename — **Rename is not offered for a Site, DataConnection, SmtpConfiguration or SmsConfiguration (TRN-9, 2026-12-03)**: it was silently treated as Skip for sites/connections and wrote a junk second SMTP/SMS row (mangled Host / AccountSid) that delivery never used. `ApplyAsync` rejects such a resolution (`ImportRenameSupport`), and the CLI's `--on-conflict rename` falls back to Skip for those types with a result warning.
- **New** → marked `+ Add`. User can opt to skip individually.
Bulk "Apply to all" at the top (Overwrite / Skip / Rename), overridable per row. Summary line at the bottom: "5 add · 2 overwrite · 1 skip · 0 rename".
@@ -302,7 +302,7 @@ Site identifiers and connection names are environment-specific, so a bundle expo
**Identity keys.** Sites are matched by `SiteIdentifier`; connections by the **site-qualified** key `{SiteIdentifier}/{Name}`; instances by `UniqueName`.
**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply.
**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. **The preview honours the name map (2026-12-03, TRN-3):** `PreviewAsync` takes an optional `BundleNameMap`; under a MapToExisting redirect, the connection / instance diffs, the connection auto-match and the unresolved-connection blocker run against the **mapped** target site and connection. The CLI import passes its explicit `--map-site` / `--map-connection` redirects to the preview before the blocker gate (a connection present only on the mapped site used to be a blocker no mapping could clear), and the Central UI re-runs the preview under the Map-step choices when Confirm is pressed. On apply, a Create-new for a site identifier or a `(site, connection)` name the target already holds binds to that existing row (its own Skip/Overwrite resolution then applies) instead of inserting a duplicate the unique index rejects. **Site-scoped and template-reference lookups are case-insensitive (TRN-7)** — connections, instances, the instance's template, and the composition / inheritance rewire fallbacks match exact spelling first, then case-insensitively, the way the database collation and its unique indexes do. **Instance diff (TRN-6):** a binding's bound connection is compared by name (the existing FK is resolved per site), and `State` is no longer compared — the import never carries a live state, so a State-only difference read Modified and an Overwrite reset a live instance to `NotDeployed` for nothing. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply.
**Template library reads (review 2026-10-21 04/P4 + 08/P1).** A preview and each apply attempt read the target template library **once**, through body-free projections (`GetTemplateStubsAsync` for id/name maps, `GetAllTemplatesForAnalysisAsync` — untracked, members and lock flags but no script bodies — where members or edges are needed), held on a per-session `TemplateLibrary` and threaded to every consumer: preview diff names, blocker and locked-override scans, apply-time validation, the composition/inheritance rewire fallbacks (formerly a full library reload *inside* the per-template loop), the instance pass's name→id map (overlaid with the change tracker's just-flushed templates), the acyclicity guard and the stale-instance expansion. The full tracked graph is loaded only for the templates the bundle **Overwrites** (`GetTemplatesWithChildrenAsync` by name), since their child syncs mutate it. The acyclicity guard reads the change tracker's staged templates overlaid on that snapshot — the untouched part of the graph has not changed during the apply. Instance lookups are batched by name set (`ITemplateEngineRepository.GetInstancesByUniqueNamesAsync`, one tracked + hydrated read for preview and one for the instance pass, Rename targets included), and the preview resolves an existing instance's template / site / area names from the library, one site list and one area list per site, and reads shared scripts and external systems once each.
@@ -315,6 +315,8 @@ Site identifiers and connection names are environment-specific, so a bundle expo
- `InstanceConnectionBinding.DataConnectionId` is resolved via the connection map, with a **Pass-2** that also binds connections which already exist in the target but were not carried in the bundle.
- `InstanceNativeAlarmSourceOverride.ConnectionNameOverride` is rewritten to the **mapped target** connection name.
**Composition Overwrite (2026-12-03, TRN-4/TRN-5).** An Overwrite of a template whose bundle copy has **no** compositions still runs the composition clear — it used to skip the template entirely, so the target's slots survived an Overwrite the preview said would remove them. A slot the bundle **removes** (its instance name is not among the bundle owner's compositions, and no bundle composition names its composed template) is deleted through `TemplateService.DeleteCompositionAsync`, which also deletes its slot-owned derived template (and that template's nested slots); before, only the row was deleted, leaving a derived template with a dangling `OwnerCompositionId` and a live `ParentTemplateId` that then blocked deleting its base. A slot the bundle re-composes keeps the plain row delete-and-re-add, so a pre-#118 bundle that re-composes a slot onto its derived template by name still resolves.
### Derived (composition-slot) templates (ScadaBridge#118)
Composing a template into a slot creates a slot-owned **derived** template (`IsDerived`, `ParentTemplateId` = the base, `OwnerCompositionId` = the slot) named after the slot. Before #118 the bundle did not say so, and the importer re-created every such template as a **base** template named after its slot. Owner decision (2026-11-10): carry the relationship and rebuild the slot through the normal compose flow.
@@ -123,21 +123,27 @@ public static class ApiMethodCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "API method ID", Required = true };
var scriptOption = new Option<string>("--script") { Description = "Script code", Required = true };
var timeoutOption = new Option<int>("--timeout") { Description = "Timeout in seconds" };
timeoutOption.DefaultValueFactory = _ => 30;
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON" };
var returnDefOption = new Option<string?>("--return-def") { Description = "Return type definition" };
var scriptOption = new Option<string?>("--script") { Description = "Script code (omitted = unchanged)" };
var timeoutOption = new Option<int?>("--timeout") { Description = "Timeout in seconds (omitted = unchanged)" };
var parametersOption = new Option<string?>("--parameters") { Description = "Parameter definitions JSON (omitted = unchanged; \"\" clears)" };
var returnDefOption = new Option<string?>("--return-def") { Description = "Return type definition (omitted = unchanged; \"\" clears)" };
// bool? so an update that omits the flag leaves the stored value unchanged.
var traceAllCallsOption = new Option<bool?>("--trace-all-calls")
{
Description = "Trace every production call to this method for the Flow Debugger (true/false; omitted = unchanged; adds 7-10 audit rows per call)"
};
var cmd = new Command("update") { Description = "Update an API method" };
var cmd = new Command("update") { Description = "Update an API method (partial: only the options passed are changed)" };
cmd.Add(idOption);
cmd.Add(scriptOption);
cmd.Add(timeoutOption);
@@ -147,14 +153,16 @@ public static class ApiMethodCommands
cmd.SetAction(async (ParseResult result) =>
{
var id = result.GetValue(idOption);
var script = result.GetValue(scriptOption)!;
var script = result.GetValue(scriptOption);
var timeout = result.GetValue(timeoutOption);
var parameters = result.GetValue(parametersOption);
var returnDef = result.GetValue(returnDefOption);
var traceAllCalls = result.GetValue(traceAllCallsOption);
var command = new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls);
if (commandInterceptor is not null)
return commandInterceptor(command);
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateApiMethodCommand(id, script, timeout, parameters, returnDef, traceAllCalls));
result, urlOption, formatOption, usernameOption, passwordOption, command);
});
return cmd;
}
@@ -58,18 +58,25 @@ public static class DataConnectionCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "Data connection ID", Required = true };
var nameOption = new Option<string>("--name") { Description = "Connection name", Required = true };
var protocolOption = new Option<string>("--protocol") { Description = "Protocol", Required = true };
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON" };
var backupConfigOption = new Option<string?>("--backup-config") { Description = "Backup configuration JSON" };
var nameOption = new Option<string?>("--name") { Description = "Connection name (omitted = unchanged)" };
var protocolOption = new Option<string?>("--protocol") { Description = "Protocol (omitted = unchanged)" };
var configOption = new Option<string?>("--primary-config", "--configuration") { Description = "Primary configuration JSON (omitted = unchanged)" };
var backupConfigOption = new Option<string?>("--backup-config") { Description = "Backup configuration JSON (omitted = unchanged; \"\" removes the backup)" };
var configFileOption = ValueSourceOptions.CreateFileOption(configOption, "the primary configuration JSON");
var backupConfigFileOption = ValueSourceOptions.CreateFileOption(backupConfigOption, "the backup configuration JSON");
var failoverRetryOption = new Option<int>("--failover-retry-count") { Description = "Number of retries before failover to backup", DefaultValueFactory = _ => 3 };
var failoverRetryOption = new Option<int?>("--failover-retry-count") { Description = "Number of retries before failover to backup (omitted = unchanged)" };
var cmd = new Command("update") { Description = "Update a data connection" };
var cmd = new Command("update") { Description = "Update a data connection (partial: only the options passed are changed)" };
cmd.Add(idOption);
cmd.Add(nameOption);
cmd.Add(protocolOption);
@@ -80,14 +87,16 @@ public static class DataConnectionCommands
cmd.SetAction(async (ParseResult result) =>
{
var id = result.GetValue(idOption);
var name = result.GetValue(nameOption)!;
var protocol = result.GetValue(protocolOption)!;
var name = result.GetValue(nameOption);
var protocol = result.GetValue(protocolOption);
var config = ValueSourceOptions.GetValue(result, configOption, configFileOption);
var backupConfig = ValueSourceOptions.GetValue(result, backupConfigOption, backupConfigFileOption);
var failoverRetryCount = result.GetValue(failoverRetryOption);
var command = new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount);
if (commandInterceptor is not null)
return commandInterceptor(command);
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateDataConnectionCommand(id, name, protocol, config, backupConfig, failoverRetryCount));
result, urlOption, formatOption, usernameOption, passwordOption, command);
});
return cmd;
}
@@ -88,17 +88,24 @@ public static class SiteCommands
return cmd;
}
private static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption)
/// <summary>
/// Builds the partial <c>update</c> subcommand (CLI-2): only the options actually
/// passed are sent; an omitted option travels as <c>null</c> and the server keeps
/// the stored value. <paramref name="commandInterceptor"/> is a test seam that
/// receives the built command record instead of sending it.
/// </summary>
internal static Command BuildUpdate(Option<string> urlOption, Option<string> formatOption, Option<string> usernameOption, Option<string> passwordOption,
Func<object, int>? commandInterceptor = null)
{
var idOption = new Option<int>("--id") { Description = "Site ID", Required = true };
var nameOption = new Option<string>("--name") { Description = "Site name", Required = true };
var descOption = new Option<string?>("--description") { Description = "Site description" };
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A" };
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B" };
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A" };
var grpcNodeBOption = new Option<string?>("--grpc-node-b-address") { Description = "gRPC address for Node B" };
var nameOption = new Option<string?>("--name") { Description = "Site name (omitted = unchanged)" };
var descOption = new Option<string?>("--description") { Description = "Site description (omitted = unchanged; \"\" clears)" };
var nodeAOption = new Option<string?>("--node-a-address") { Description = "Akka address for Node A (omitted = unchanged; \"\" clears)" };
var nodeBOption = new Option<string?>("--node-b-address") { Description = "Akka address for Node B (omitted = unchanged; \"\" clears)" };
var grpcNodeAOption = new Option<string?>("--grpc-node-a-address") { Description = "gRPC address for Node A (omitted = unchanged; \"\" clears)" };
var grpcNodeBOption = new Option<string?>("--grpc-node-b-address") { Description = "gRPC address for Node B (omitted = unchanged; \"\" clears)" };
var cmd = new Command("update") { Description = "Update an existing site" };
var cmd = new Command("update") { Description = "Update an existing site (partial: only the options passed are changed)" };
cmd.Add(idOption);
cmd.Add(nameOption);
cmd.Add(descOption);
@@ -109,15 +116,17 @@ public static class SiteCommands
cmd.SetAction(async (ParseResult result) =>
{
var id = result.GetValue(idOption);
var name = result.GetValue(nameOption)!;
var name = result.GetValue(nameOption);
var desc = result.GetValue(descOption);
var nodeA = result.GetValue(nodeAOption);
var nodeB = result.GetValue(nodeBOption);
var grpcNodeA = result.GetValue(grpcNodeAOption);
var grpcNodeB = result.GetValue(grpcNodeBOption);
var command = new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB);
if (commandInterceptor is not null)
return commandInterceptor(command);
return await CommandHelpers.ExecuteCommandAsync(
result, urlOption, formatOption, usernameOption, passwordOption,
new UpdateSiteCommand(id, name, desc, nodeA, nodeB, grpcNodeA, grpcNodeB));
result, urlOption, formatOption, usernameOption, passwordOption, command);
});
return cmd;
}
+22 -25
View File
@@ -976,22 +976,21 @@ scadabridge --url <url> site create --name <string> --identifier <string> [--des
#### `site update`
Update an existing site. An update **replaces** the whole entity — every required field
below must be supplied with its post-update value, even if unchanged.
Update an existing site. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field.
```sh
scadabridge --url <url> site update --id <int> --name <string> [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
scadabridge --url <url> site update --id <int> [--name <string>] [--description <string>] [--node-a-address <string>] [--node-b-address <string>] [--grpc-node-a-address <string>] [--grpc-node-b-address <string>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Site ID |
| `--name` | yes | Human-readable site name |
| `--description` | no | Site description |
| `--node-a-address` | no | Akka.NET cluster address for Node A |
| `--node-b-address` | no | Akka.NET cluster address for Node B |
| `--grpc-node-a-address` | no | gRPC streaming address for Node A |
| `--grpc-node-b-address` | no | gRPC streaming address for Node B |
| `--name` | no | Human-readable site name (omitted = unchanged) |
| `--description` | no | Site description (omitted = unchanged; `""` clears) |
| `--node-a-address` | no | Akka.NET cluster address for Node A (omitted = unchanged; `""` clears) |
| `--node-b-address` | no | Akka.NET cluster address for Node B (omitted = unchanged; `""` clears) |
| `--grpc-node-a-address` | no | gRPC streaming address for Node A (omitted = unchanged; `""` clears) |
| `--grpc-node-b-address` | no | gRPC streaming address for Node B (omitted = unchanged; `""` clears) |
#### `site delete`
@@ -1263,23 +1262,22 @@ scadabridge --url <url> data-connection create --site-id <int> --name <string> -
#### `data-connection update`
Update a data connection definition. An update **replaces** the whole entity — every
required field below must be supplied, even if unchanged.
Update a data connection definition. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field.
```sh
scadabridge --url <url> data-connection update --id <int> --name <string> --protocol <string> [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
scadabridge --url <url> data-connection update --id <int> [--name <string>] [--protocol <string>] [--primary-config <json> | --primary-config-file <path|->] [--backup-config <json> | --backup-config-file <path|->] [--failover-retry-count <int>]
```
| Option | Required | Description |
|--------|----------|-------------|
| `--id` | yes | Data connection ID |
| `--name` | yes | Connection name |
| `--protocol` | yes | Protocol identifier |
| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`) |
| `--name` | no | Connection name (omitted = unchanged) |
| `--protocol` | no | Protocol identifier (omitted = unchanged) |
| `--primary-config` | no | Primary protocol-specific configuration as a JSON string (alias `--configuration`; omitted = unchanged) |
| `--primary-config-file` | no | Read the primary configuration from a file, or stdin with `-` — use it when the config carries a secret (MxGateway `apiKey`, OPC UA password). Not together with `--primary-config`. |
| `--backup-config` | no | Backup protocol-specific configuration as a JSON string |
| `--backup-config` | no | Backup protocol-specific configuration as a JSON string (omitted = unchanged; `""` removes the backup) |
| `--backup-config-file` | no | Read the backup configuration from a file, or stdin with `-`. Not together with `--backup-config`. |
| `--failover-retry-count` | no | Retries before failover to the backup configuration (default: `3`) |
| `--failover-retry-count` | no | Retries before failover to the backup configuration (omitted = unchanged) |
#### `data-connection move`
@@ -2497,21 +2495,20 @@ scadabridge --url <url> api-method create --name <string> --script <string> [--t
#### `api-method update`
Update an inbound API method. An update **replaces** the whole entity — every required
field below must be supplied, even if unchanged.
Update an inbound API method. This is a **partial** update: only the options you pass are changed. An omitted option leaves the stored value as it is; pass an empty string (`""`) to clear an optional field.
```sh
scadabridge --url <url> api-method update --id <int> --script <string> [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
scadabridge --url <url> api-method update --id <int> [--script <string>] [--timeout <int>] [--parameters <json>] [--return-def <json>] [--trace-all-calls <true|false>]
```
| Option | Required | Default | Description |
|--------|----------|---------|-------------|
| `--id` | yes | — | API method ID |
| `--script` | yes | — | Script source code implementing the method |
| `--timeout` | no | `30` | Timeout in seconds |
| `--parameters` | no | — | Parameter definitions JSON |
| `--return-def` | no | — | Return type definition JSON |
| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only). Omitted = the stored value is left as-is (the one field the replace-all rule does not apply to) |
| `--script` | no | unchanged | Script source code implementing the method |
| `--timeout` | no | unchanged | Timeout in seconds |
| `--parameters` | no | unchanged | Parameter definitions JSON (`""` clears) |
| `--return-def` | no | unchanged | Return type definition JSON (`""` clears) |
| `--trace-all-calls` | no | unchanged | `true`/`false` — trace every production call for the Flow Debugger. **Adds 7–10 audit rows per call** (3 of them trace-only) |
Script changes take effect immediately — the updated code is recompiled in-memory on the active central node. No restart is required.
@@ -168,8 +168,11 @@
return;
}
await MutationServices.ExecuteConfigurationAsync(_editingSite is not null
? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim(),
_formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim())
// Update is preserve-if-null (CLI-2): this full-entity form sends "" for a
// field the operator cleared so the server clears it rather than keeping it.
? new UpdateSiteCommand(_editingSite.Id, _formName.Trim(), _formDescription?.Trim() ?? "",
_formNodeAAddress?.Trim() ?? "", _formNodeBAddress?.Trim() ?? "",
_formGrpcNodeAAddress?.Trim() ?? "", _formGrpcNodeBAddress?.Trim() ?? "")
: new CreateSiteCommand(_formName.Trim(), _formIdentifier.Trim(), _formDescription?.Trim(),
_formNodeAAddress?.Trim(), _formNodeBAddress?.Trim(), _formGrpcNodeAAddress?.Trim(), _formGrpcNodeBAddress?.Trim()));
CommunicationService.RefreshSiteAddresses();
@@ -399,7 +399,8 @@
{
var methodName = _existing?.Name ?? _name.Trim();
await MutationServices.ExecuteConfigurationAsync(_existing is not null
? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)
// Update is preserve-if-null (CLI-2): "" clears a removed definition.
? new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? "", _returns?.Trim() ?? "", _traceAllCalls)
: new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls));
// Reconcile per-key method-scopes for the affected keys (added/removed vs. load time).
@@ -382,7 +382,8 @@
try
{
await MutationServices.ExecuteConfigurationAsync(_editingConnection is not null
? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3)
// Update is preserve-if-null (CLI-2): "" clears a removed backup endpoint.
? new UpdateDataConnectionCommand(_editingConnection.Id, _formName.Trim(), _protocol, primaryJson, backupJson ?? "", _showBackup ? _formFailoverRetryCount : 3)
: new CreateDataConnectionCommand(_formSiteId, _formName.Trim(), _protocol, primaryJson, backupJson, _showBackup ? _formFailoverRetryCount : 3));
NavigationManager.NavigateTo("/design/connections");
}
@@ -482,7 +482,10 @@
var key = (item.EntityType, item.Name);
<div class="d-flex flex-wrap gap-2 align-items-center">
@foreach (var action in new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename })
@* TRN-9: Rename is not offered where it has no meaning (site, data connection, SMTP/SMS). *@
@foreach (var action in ImportRenameSupport.IsSupported(item.EntityType)
? new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename }
: new[] { ResolutionAction.Overwrite, ResolutionAction.Skip })
{
var inputId = $"res-{item.EntityType}-{item.Name}-{action}";
<div class="form-check form-check-inline mb-0">
@@ -823,9 +823,10 @@ public partial class TransportImport : ComponentBase, IDisposable
return (adds, overs, skips, renames, blockers);
}
private void GoToConfirm()
private async Task GoToConfirm()
{
if (_preview is null) return;
await RefreshPreviewUnderMappingAsync();
if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker))
{
_errorMessage = "Cannot proceed while blockers exist — resolve or remove blocker rows first.";
@@ -835,6 +836,58 @@ public partial class TransportImport : ComponentBase, IDisposable
_step = ImportWizardStep.Confirm;
}
/// <summary>
/// TRN-3: when the Map step redirects a source site or connection to a differently
/// named target, the diff rows, auto-matches and unresolved-connection blockers of
/// the first preview were computed against the SOURCE identity. Re-run the preview
/// under the current name map so the blocker gate (and the diff table) reflect the
/// mapped targets. The Map step's required-mapping lists are kept (they are keyed
/// by source reference); resolutions the operator already chose are kept unless the
/// row's conflict kind changed, in which case that row gets its new default.
/// </summary>
private async Task RefreshPreviewUnderMappingAsync()
{
if (_session is null || _preview is null || _resolutions is null) return;
var map = BuildNameMap();
var redirects = map.Sites.Any(m => m.Action == MappingAction.MapToExisting
&& !string.Equals(m.TargetSiteIdentifier, m.SourceSiteIdentifier, StringComparison.Ordinal))
|| map.Connections.Any(m => m.Action == MappingAction.MapToExisting
&& !string.Equals(m.TargetConnectionName, m.SourceConnectionName, StringComparison.Ordinal));
if (!redirects) return;
ImportPreview? refreshed;
try
{
refreshed = await BundleImporter.PreviewAsync(_session.SessionId, CancellationToken.None, map);
}
catch (Exception ex)
{
_errorMessage = $"Failed to refresh the import preview for the chosen mappings: {ex.Message}";
return;
}
if (refreshed is null) return;
var previousKinds = new Dictionary<(string, string), ConflictKind>();
foreach (var item in _preview.Items) previousKinds[(item.EntityType, item.Name)] = item.Kind;
var defaults = BuildDefaultResolutions(refreshed);
foreach (var item in refreshed.Items)
{
var key = (item.EntityType, item.Name);
if (!_resolutions.ContainsKey(key)
|| !previousKinds.TryGetValue(key, out var previousKind)
|| previousKind != item.Kind)
{
_resolutions[key] = defaults[key];
}
}
_preview = refreshed with
{
RequiredSiteMappings = _preview.RequiredSiteMappings,
RequiredConnectionMappings = _preview.RequiredConnectionMappings,
};
}
private void BackToDiff()
{
_step = ImportWizardStep.Diff;
@@ -30,8 +30,15 @@ public interface IBundleImporter
/// </summary>
/// <param name="sessionId">Session id returned by <see cref="LoadAsync"/>.</param>
/// <param name="ct">Cancellation token.</param>
/// <param name="nameMap">
/// TRN-3: optional operator site/connection mapping. When supplied, every site-scoped
/// preview lookup (connection and instance diffs, the required-mapping auto-match and
/// the unresolved-connection blocker) runs against the MAPPED target site and connection
/// names instead of the source identity, so a preview reflects what the apply with the
/// same map will do. <c>null</c> (the default) keeps the identity auto-match.
/// </param>
/// <returns>A task that resolves to a per-artifact import preview with conflict details.</returns>
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default);
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null);
/// <summary>
/// Applies the chosen conflict resolutions and commits the import transaction.
@@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
public record ListDataConnectionsCommand(int? SiteId = null);
public record GetDataConnectionCommand(int DataConnectionId);
public record CreateDataConnectionCommand(int SiteId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3);
public record UpdateDataConnectionCommand(int DataConnectionId, string Name, string Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int FailoverRetryCount = 3);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> leaves the
/// stored value unchanged; an empty string clears an optional field. Older clients that always
/// send every field keep deserializing unchanged (the fields only became nullable).
/// </summary>
public record UpdateDataConnectionCommand(int DataConnectionId, string? Name, string? Protocol, string? PrimaryConfiguration, string? BackupConfiguration = null, int? FailoverRetryCount = null);
public record DeleteDataConnectionCommand(int DataConnectionId);
/// <summary>
@@ -4,8 +4,13 @@ public record ListApiMethodsCommand;
public record GetApiMethodCommand(int ApiMethodId);
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): trace every production call to this method. Additive; defaults to off.</param>
public record CreateApiMethodCommand(string Name, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool TraceAllCalls = false);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> leaves the
/// stored value unchanged; an empty string clears an optional field. Older clients that always
/// send every field keep deserializing unchanged (the fields only became nullable).
/// </summary>
/// <param name="TraceAllCalls">Flow Debugger (design 2026-09-05 §5.2): <c>null</c> leaves the stored value unchanged so an older CLI never resets it.</param>
public record UpdateApiMethodCommand(int ApiMethodId, string Script, int TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null);
public record UpdateApiMethodCommand(int ApiMethodId, string? Script, int? TimeoutSeconds, string? ParameterDefinitions, string? ReturnDefinition, bool? TraceAllCalls = null);
public record DeleteApiMethodCommand(int ApiMethodId);
/// <summary>
/// Compiles the method's stored script on the receiving central node and returns the
@@ -3,7 +3,12 @@ namespace ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
public record ListSitesCommand;
public record GetSiteCommand(int SiteId);
public record CreateSiteCommand(string Name, string SiteIdentifier, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null);
public record UpdateSiteCommand(int SiteId, string Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null);
/// <summary>
/// Partial update (CLI-2): every field except the id is preserve-if-null — <c>null</c> leaves the
/// stored value unchanged; an empty string clears an optional field. Older clients that always
/// send every field keep deserializing unchanged (the fields only became nullable).
/// </summary>
public record UpdateSiteCommand(int SiteId, string? Name, string? Description, string? NodeAAddress = null, string? NodeBAddress = null, string? GrpcNodeAAddress = null, string? GrpcNodeBAddress = null);
public record DeleteSiteCommand(int SiteId);
public record ListAreasCommand(int SiteId);
public record CreateAreaCommand(int SiteId, string Name, int? ParentAreaId);
@@ -7,3 +7,25 @@ public sealed record ImportResolution(
string Name,
ResolutionAction Action,
string? RenameTo);
/// <summary>
/// TRN-9: which preview entity types a <see cref="ResolutionAction.Rename"/> resolution
/// is meaningful for. A Site, a site-scoped DataConnection, an SMTP configuration and
/// an SMS configuration have no renameable identity: a renamed site/connection was
/// silently treated as Skip, and a renamed SMTP/SMS row mangled the Host / AccountSid
/// into a junk second row that delivery (lowest-id wins) never used. The importer
/// rejects Rename for these types, the Central UI does not offer it, and the CLI's
/// <c>--conflict-policy rename</c> falls back to Skip for them with a warning.
/// </summary>
public static class ImportRenameSupport
{
private static readonly HashSet<string> Unsupported = new(StringComparer.Ordinal)
{
"Site", "DataConnection", "SmtpConfiguration", "SmsConfiguration",
};
/// <summary>True when a Rename resolution is supported for <paramref name="entityType"/>.</summary>
/// <param name="entityType">The preview item / resolution entity type.</param>
/// <returns><c>false</c> for Site, DataConnection, SmtpConfiguration and SmsConfiguration.</returns>
public static bool IsSupported(string entityType) => !Unsupported.Contains(entityType);
}
@@ -113,8 +113,11 @@ public class SystemArtifactDeploymentRecordConfiguration : IEntityTypeConfigurat
.IsRequired()
.HasMaxLength(200);
builder.Property(d => d.PerSiteStatus)
.HasMaxLength(4000);
// DEP-3: unbounded. One serialized SiteArtifactResult per site (identifier, name,
// error text, removed secret names) is ~155 chars for a clean site, so 4000 ran
// out at ~25 sites (fewer with long errors) — and that save runs AFTER every site
// has applied the artifacts, so the run failed with nothing stamped.
builder.Property(d => d.PerSiteStatus);
builder.HasIndex(d => d.DeployedAt);
}
@@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
{
/// <inheritdoc />
public partial class WidenSystemArtifactPerSiteStatus : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "PerSiteStatus",
table: "SystemArtifactDeploymentRecords",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(4000)",
oldMaxLength: 4000,
oldNullable: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<string>(
name: "PerSiteStatus",
table: "SystemArtifactDeploymentRecords",
type: "nvarchar(4000)",
maxLength: 4000,
nullable: true,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
}
}
}
@@ -381,8 +381,7 @@ namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Migrations
.HasColumnType("nvarchar(200)");
b.Property<string>("PerSiteStatus")
.HasMaxLength(4000)
.HasColumnType("nvarchar(4000)");
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
@@ -30,7 +30,13 @@ public class NotificationRepository : INotificationRepository
/// <inheritdoc />
public async Task<NotificationList?> GetListByNameAsync(string name, CancellationToken cancellationToken = default)
=> await _context.Set<NotificationList>().FirstOrDefaultAsync(l => l.Name == name, cancellationToken);
// Eager-load Recipients (TRN-1): the Transport importer's Overwrite clears and
// re-adds the recipient collection. Without the Include the Clear() ran on an
// unloaded collection, deleted nothing, and the bundle's recipients were appended
// to the target's — duplicates plus recipients the source had removed.
=> await _context.Set<NotificationList>()
.Include(n => n.Recipients)
.FirstOrDefaultAsync(l => l.Name == name, cancellationToken);
/// <inheritdoc />
public async Task AddNotificationListAsync(NotificationList list, CancellationToken cancellationToken = default)
@@ -2088,16 +2088,25 @@ public class ManagementActor : ReceiveActor
private static async Task<object?> HandleUpdateSite(IServiceProvider sp, UpdateSiteCommand cmd, string user)
{
ValidateSiteGrpcAddresses(cmd.GrpcNodeAAddress, cmd.GrpcNodeBAddress);
var repo = sp.GetRequiredService<ISiteRepository>();
var site = await repo.GetSiteByIdAsync(cmd.SiteId)
?? throw new ManagementCommandException($"Site with ID {cmd.SiteId} not found.");
site.Name = cmd.Name;
site.Description = cmd.Description;
site.NodeAAddress = cmd.NodeAAddress;
site.NodeBAddress = cmd.NodeBAddress;
site.GrpcNodeAAddress = cmd.GrpcNodeAAddress;
site.GrpcNodeBAddress = cmd.GrpcNodeBAddress;
// CLI-2: preserve-if-null partial update. Validate the EFFECTIVE addresses
// (the merge of the command and the stored row) before anything is written.
var grpcNodeA = PartialUpdate.Optional(cmd.GrpcNodeAAddress, site.GrpcNodeAAddress);
var grpcNodeB = PartialUpdate.Optional(cmd.GrpcNodeBAddress, site.GrpcNodeBAddress);
ValidateSiteGrpcAddresses(grpcNodeA, grpcNodeB);
if (cmd.Name is not null)
{
if (string.IsNullOrWhiteSpace(cmd.Name))
throw new ManagementCommandException("Site name must not be empty.");
site.Name = cmd.Name;
}
site.Description = PartialUpdate.Optional(cmd.Description, site.Description);
site.NodeAAddress = PartialUpdate.Optional(cmd.NodeAAddress, site.NodeAAddress);
site.NodeBAddress = PartialUpdate.Optional(cmd.NodeBAddress, site.NodeBAddress);
site.GrpcNodeAAddress = grpcNodeA;
site.GrpcNodeBAddress = grpcNodeB;
await repo.UpdateSiteAsync(site);
await repo.SaveChangesAsync();
var commService = sp.GetService<CommunicationService>();
@@ -2260,14 +2269,33 @@ public class ManagementActor : ReceiveActor
var repo = sp.GetRequiredService<ISiteRepository>();
var conn = await repo.GetDataConnectionByIdAsync(cmd.DataConnectionId)
?? throw new ManagementCommandException($"DataConnection with ID {cmd.DataConnectionId} not found.");
conn.Name = cmd.Name;
conn.Protocol = cmd.Protocol;
// CLI-2: preserve-if-null partial update — an omitted field keeps the stored
// value; an empty string clears an optional configuration.
if (cmd.Name is not null)
{
if (string.IsNullOrWhiteSpace(cmd.Name))
throw new ManagementCommandException("Data connection name must not be empty.");
conn.Name = cmd.Name;
}
if (cmd.Protocol is not null)
{
if (string.IsNullOrWhiteSpace(cmd.Protocol))
throw new ManagementCommandException("Data connection protocol must not be empty.");
conn.Protocol = cmd.Protocol;
}
// Sentinel-preserving merge: a client that round-trips a scrubbed config
// (secrets replaced with the redaction sentinel) keeps the stored secret
// rather than wiping it. Non-sentinel values overwrite as usual.
conn.PrimaryConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration);
conn.BackupConfiguration = ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration);
conn.FailoverRetryCount = cmd.FailoverRetryCount;
if (cmd.PrimaryConfiguration is not null)
conn.PrimaryConfiguration = string.IsNullOrWhiteSpace(cmd.PrimaryConfiguration)
? null
: ConfigSecretScrubber.MergeSentinels(cmd.PrimaryConfiguration, conn.PrimaryConfiguration);
if (cmd.BackupConfiguration is not null)
conn.BackupConfiguration = string.IsNullOrWhiteSpace(cmd.BackupConfiguration)
? null
: ConfigSecretScrubber.MergeSentinels(cmd.BackupConfiguration, conn.BackupConfiguration);
if (cmd.FailoverRetryCount is { } failoverRetryCount)
conn.FailoverRetryCount = failoverRetryCount;
await repo.UpdateDataConnectionAsync(conn);
await repo.SaveChangesAsync();
var publicShape = DataConnectionPublicShape(conn);
@@ -4006,10 +4034,19 @@ public class ManagementActor : ReceiveActor
var repo = sp.GetRequiredService<IInboundApiRepository>();
var method = await repo.GetApiMethodByIdAsync(cmd.ApiMethodId)
?? throw new ManagementCommandException($"ApiMethod with ID {cmd.ApiMethodId} not found.");
method.Script = cmd.Script;
method.TimeoutSeconds = cmd.TimeoutSeconds;
method.ParameterDefinitions = cmd.ParameterDefinitions;
method.ReturnDefinition = cmd.ReturnDefinition;
// CLI-2: preserve-if-null partial update — an omitted field keeps the stored
// value (an omitted --timeout used to reset it to 30 and drop both
// definitions); an empty string clears an optional definition.
if (cmd.Script is not null)
{
if (string.IsNullOrWhiteSpace(cmd.Script))
throw new ManagementCommandException("API method script must not be empty.");
method.Script = cmd.Script;
}
if (cmd.TimeoutSeconds is { } timeoutSeconds)
method.TimeoutSeconds = timeoutSeconds;
method.ParameterDefinitions = PartialUpdate.Optional(cmd.ParameterDefinitions, method.ParameterDefinitions);
method.ReturnDefinition = PartialUpdate.Optional(cmd.ReturnDefinition, method.ReturnDefinition);
if (cmd.TraceAllCalls is { } traceAllCalls)
method.TraceAllCalls = traceAllCalls;
await repo.UpdateApiMethodAsync(method);
@@ -4676,7 +4713,13 @@ public class ManagementActor : ReceiveActor
// is safe even when ApplyAsync already released the same id.
try
{
var preview = await importer.PreviewAsync(session.SessionId);
// TRN-3: an explicit --map-site / --map-connection redirect changes what
// the site-scoped preview rows resolve against, so the preview (and its
// unresolved-connection blockers and auto-matches) runs under those
// redirects — otherwise a connection present only on the MAPPED site was
// a blocker no mapping could clear.
var preview = await importer.PreviewAsync(
session.SessionId, nameMap: BuildExplicitRedirectMap(cmd));
var blockers = preview.Items.Where(i => i.Kind == ConflictKind.Blocker).ToList();
if (blockers.Count > 0)
@@ -4702,6 +4745,7 @@ public class ManagementActor : ReceiveActor
// automatically correct — no bare-connection-name special case needed.
var renameStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
var resolutionsMap = new Dictionary<(string, string), ImportResolution>();
var renameFallbacks = new SortedSet<string>(StringComparer.Ordinal);
foreach (var item in preview.Items)
{
var action = item.Kind switch
@@ -4711,15 +4755,31 @@ public class ManagementActor : ReceiveActor
ConflictKind.Modified => policy,
_ => ResolutionAction.Skip,
};
var renameTo = (item.Kind == ConflictKind.Modified && policy == ResolutionAction.Rename)
// TRN-9: --conflict-policy rename has no meaning for a site, data
// connection or SMTP/SMS configuration (the importer rejects it);
// fall back to Skip for those and say so in the result.
if (action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(item.EntityType))
{
action = ResolutionAction.Skip;
renameFallbacks.Add($"{item.EntityType} '{item.Name}'");
}
var renameTo = (item.Kind == ConflictKind.Modified && action == ResolutionAction.Rename)
? $"{item.Name}-imported-{renameStamp}"
: null;
resolutionsMap[(item.EntityType, item.Name)] = new ImportResolution(
item.EntityType, item.Name, action, renameTo);
}
return await importer.ApplyAsync(
var importResult = await importer.ApplyAsync(
session.SessionId, resolutionsMap.Values.ToList(), username, nameMap: nameMap);
if (renameFallbacks.Count == 0) return importResult;
return importResult with
{
Warnings = importResult.Warnings
.Concat(renameFallbacks.Select(f =>
$"{f} was skipped: Rename is not supported for sites, data connections, SMTP or SMS configurations."))
.ToList(),
};
}
finally
{
@@ -4732,6 +4792,27 @@ public class ManagementActor : ReceiveActor
}
}
/// <summary>
/// TRN-3: the operator's explicit MapToExisting redirects (a <c>--map-site</c> /
/// <c>--map-connection</c> with a target) as a <see cref="BundleNameMap"/> for the
/// preview, or <c>null</c> when there are none (the preview then keeps its identity
/// auto-match). Create-new specs are not redirects and are left to
/// <see cref="BuildNameMap"/>.
/// </summary>
private static BundleNameMap? BuildExplicitRedirectMap(ImportBundleCommand cmd)
{
var sites = (cmd.SiteMappings ?? Array.Empty<SiteMappingSpec>())
.Where(s => !string.IsNullOrWhiteSpace(s.TargetSiteIdentifier))
.Select(s => new SiteMapping(s.SourceSiteIdentifier, MappingAction.MapToExisting, s.TargetSiteIdentifier))
.ToList();
var connections = (cmd.ConnectionMappings ?? Array.Empty<ConnectionMappingSpec>())
.Where(c => !string.IsNullOrWhiteSpace(c.TargetConnectionName))
.Select(c => new ConnectionMapping(
c.SourceSiteIdentifier, c.SourceConnectionName, MappingAction.MapToExisting, c.TargetConnectionName))
.ToList();
return sites.Count == 0 && connections.Count == 0 ? null : new BundleNameMap(sites, connections);
}
/// <summary>
/// Merges the operator-supplied <see cref="SiteMappingSpec"/> /
/// <see cref="ConnectionMappingSpec"/> lists with the preview's auto-matches
@@ -0,0 +1,19 @@
namespace ZB.MOM.WW.ScadaBridge.ManagementService;
/// <summary>
/// Preserve-if-null merge rules for the partial update commands (CLI-2):
/// <c>UpdateSiteCommand</c>, <c>UpdateDataConnectionCommand</c> and
/// <c>UpdateApiMethodCommand</c>. A <c>null</c> field means "not supplied — keep the
/// stored value"; an empty (or whitespace-only) string means "clear this optional
/// field". The CLI sends only the options that were actually passed, and the Central
/// UI's full-entity forms send an empty string for a field the operator cleared.
/// </summary>
internal static class PartialUpdate
{
/// <summary>Merges an optional (nullable) string field.</summary>
/// <param name="incoming">The value carried by the command, or <c>null</c> when not supplied.</param>
/// <param name="stored">The value currently stored.</param>
/// <returns><paramref name="stored"/> when <paramref name="incoming"/> is null; null when it is blank; otherwise <paramref name="incoming"/>.</returns>
public static string? Optional(string? incoming, string? stored) =>
incoming is null ? stored : string.IsNullOrWhiteSpace(incoming) ? null : incoming;
}
@@ -78,11 +78,15 @@ public class FlatteningService
// Step 4: Apply connection bindings
ApplyConnectionBindings(instance.ConnectionBindings, attributes, dataConnections);
// Step 5: Resolve alarms from inheritance chain.
// alarmScriptIds maps a resolved alarm's canonical name to the
// TemplateScript.Id of its on-trigger script (if any).
// Step 5: Resolve alarms from inheritance chain. Each alarm's on-trigger
// script is resolved by NAME within the alarm's own chain and
// path-qualified with the alarm's prefix (TPL-1/TPL-2/TPL-5).
// alarmScriptIds only carries the legacy fallback: an on-trigger script
// id that is not a script row of the alarm's own chain.
var alarmScriptIds = new Dictionary<string, int>(StringComparer.Ordinal);
var alarms = ResolveInheritedAlarms(templateChain, prefix: null, alarmScriptIds);
var alarms = ResolveInheritedAlarms(templateChain, prefix: null, out var rootUnresolvedScriptIds);
foreach (var (alarmName, scriptId) in rootUnresolvedScriptIds)
alarmScriptIds[alarmName] = scriptId;
ResolveComposedAlarms(templateChain, compositionMap, composedTemplateChains, alarms, alarmScriptIds);
ApplyInstanceAlarmOverrides(instance.AlarmOverrides, alarms);
@@ -94,7 +98,7 @@ public class FlatteningService
ResolveComposedScripts(templateChain, compositionMap, composedTemplateChains, scripts, scriptCanonicalById);
// Step 7: Resolve alarm on-trigger script references to canonical names
ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById);
ResolveAlarmScriptReferences(alarms, alarmScriptIds, scriptCanonicalById, scripts);
// Step 7b: Resolve native alarm source bindings (connection + source
// reference). Conditions under each source are discovered at runtime;
@@ -405,19 +409,39 @@ public class FlatteningService
/// Resolves alarms from an inheritance chain. When <paramref name="prefix"/>
/// is non-null the alarm names are returned bare (caller path-qualifies);
/// the keys of the returned dictionary are always bare alarm names.
/// <paramref name="alarmScriptIds"/> is populated with the on-trigger
/// script id of each resolved alarm keyed by the canonical name the alarm
/// will ultimately carry (bare name when <paramref name="prefix"/> is null,
/// otherwise <c>prefix.name</c>).
/// <para>
/// Each alarm's on-trigger script is resolved <b>within this chain</b>: the
/// <c>OnTriggerScriptId</c> is looked up among the script rows of every
/// template in <paramref name="templateChain"/> and translated to that row's
/// NAME, which is then path-qualified with <paramref name="prefix"/> and set
/// as <see cref="ResolvedAlarm.OnTriggerScriptCanonicalName"/>. Resolving by
/// name per chain (not through a flatten-wide id map) is what keeps two
/// slots of the same module apart (TPL-1: both slots share the base script
/// row id, so a global map made every slot's alarm run the LAST slot's
/// script) and keeps the link when a derived template overrides the script
/// with a row of a different id (TPL-2). The value travels on the alarm, so
/// only the pass that actually adds the alarm decides it (TPL-5).
/// </para>
/// <paramref name="unresolvedScriptIds"/> receives, keyed by bare alarm name,
/// any on-trigger script id that is NOT a script row of this chain; the
/// caller records it for the legacy flatten-wide id fallback.
/// </summary>
private static Dictionary<string, ResolvedAlarm> ResolveInheritedAlarms(
IReadOnlyList<Template> templateChain,
string? prefix,
Dictionary<string, int> alarmScriptIds)
out Dictionary<string, int> unresolvedScriptIds)
{
var result = new Dictionary<string, ResolvedAlarm>(StringComparer.Ordinal);
var scriptIdByName = new Dictionary<string, int>(StringComparer.Ordinal);
// Script row id -> script name, over every template of this chain
// (base rows, derived overrides and IsInherited placeholders alike).
var chainScriptNameById = new Dictionary<int, string>();
foreach (var t in templateChain)
foreach (var script in t.Scripts)
if (script.Id != 0)
chainScriptNameById.TryAdd(script.Id, script.Name);
for (int i = templateChain.Count - 1; i >= 0; i--)
{
var template = templateChain[i];
@@ -468,10 +492,20 @@ public class FlatteningService
}
}
unresolvedScriptIds = new Dictionary<string, int>(StringComparer.Ordinal);
foreach (var (name, scriptId) in scriptIdByName)
{
var canonical = prefix == null ? name : $"{prefix}.{name}";
alarmScriptIds[canonical] = scriptId;
if (chainScriptNameById.TryGetValue(scriptId, out var scriptName))
{
result[name] = result[name] with
{
OnTriggerScriptCanonicalName = prefix == null ? scriptName : $"{prefix}.{scriptName}"
};
}
else
{
unresolvedScriptIds[name] = scriptId;
}
}
return result;
@@ -652,7 +686,7 @@ public class FlatteningService
if (!composedTemplateChains.TryGetValue(composition.ComposedTemplateId, out var composedChain))
return;
var composedAlarms = ResolveInheritedAlarms(composedChain, prefix, alarmScriptIds);
var composedAlarms = ResolveInheritedAlarms(composedChain, prefix, out var unresolvedScriptIds);
foreach (var (name, alarm) in composedAlarms)
{
var canonicalName = $"{prefix}.{name}";
@@ -664,6 +698,10 @@ public class FlatteningService
TriggerConfiguration = PrefixTriggerAttribute(alarm.TriggerConfiguration, prefix),
Source = "Composed"
};
// Only the pass that adds the alarm records its fallback script
// id (TPL-5: a nested slot is visited twice under one prefix).
if (unresolvedScriptIds.TryGetValue(name, out var scriptId))
alarmScriptIds[canonicalName] = scriptId;
}
}
@@ -1028,19 +1066,19 @@ public class FlatteningService
}
/// <summary>
/// Resolves alarm on-trigger script references from <see cref="TemplateScript.Id"/>
/// values to the canonical (path-qualified) names of the corresponding
/// resolved scripts. <paramref name="alarmScriptIds"/> maps an alarm's
/// canonical name to the id of its on-trigger script; <paramref name="scriptCanonicalById"/>
/// maps a script id to the canonical name it carries in the flattened
/// configuration. An alarm whose on-trigger script id has no matching
/// resolved script is left with a <c>null</c> reference — semantic
/// validation then reports the dangling reference.
/// Finalises alarm on-trigger script references. Most were resolved by name
/// within the alarm's own chain in <see cref="ResolveInheritedAlarms"/>; this
/// pass (1) resolves the legacy fallback — an on-trigger script id that is not
/// a script row of the alarm's chain — through the flatten-wide
/// <paramref name="scriptCanonicalById"/> map, and (2) clears any reference
/// whose canonical name is not a resolved script, so a dangling reference is
/// left <c>null</c> exactly as before.
/// </summary>
private static void ResolveAlarmScriptReferences(
Dictionary<string, ResolvedAlarm> alarms,
Dictionary<string, int> alarmScriptIds,
Dictionary<int, string> scriptCanonicalById)
Dictionary<int, string> scriptCanonicalById,
IReadOnlyDictionary<string, ResolvedScript> scripts)
{
foreach (var (alarmCanonicalName, scriptId) in alarmScriptIds)
{
@@ -1053,5 +1091,11 @@ public class FlatteningService
OnTriggerScriptCanonicalName = scriptCanonicalName
};
}
foreach (var (alarmCanonicalName, alarm) in alarms.ToList())
{
if (alarm.OnTriggerScriptCanonicalName is { } scriptName && !scripts.ContainsKey(scriptName))
alarms[alarmCanonicalName] = alarm with { OnTriggerScriptCanonicalName = null };
}
}
}
@@ -83,6 +83,19 @@ public sealed class BundleSecretEncryptor
throw new CryptographicException("Unsupported bundle encryption parameters.");
}
// TRN-10: the iteration count comes from the uploaded (untrusted) manifest.
// EncryptionMetadata's constructor range-checks it, but a record `with`
// expression or any other non-constructor path bypasses that, so re-check
// here — before PBKDF2 runs — or a hostile bundle declaring int.MaxValue
// pins a thread (and the single-flight transport gate) for tens of minutes.
if (metadata.Iterations < EncryptionMetadata.MinPbkdf2Iterations
|| metadata.Iterations > EncryptionMetadata.MaxPbkdf2Iterations)
{
throw new CryptographicException(
$"Bundle key-derivation iteration count {metadata.Iterations} is outside the supported range " +
$"[{EncryptionMetadata.MinPbkdf2Iterations}, {EncryptionMetadata.MaxPbkdf2Iterations}].");
}
var salt = Convert.FromBase64String(metadata.SaltB64);
var nonce = Convert.FromBase64String(metadata.IvB64);
var key = DeriveKey(passphrase, salt, metadata.Iterations);
@@ -106,6 +106,38 @@ public sealed class BundleExporter : IBundleExporter
.ToDictionaryAsync(a => a.Id, a => a.Name, cancellationToken)
.ConfigureAwait(false);
// TRN-8: the full root→leaf path of each referenced area — the same leaf name
// may exist under two parents. One read of the areas of the sites involved.
var areaPathById = new Dictionary<int, IReadOnlyList<string>>();
if (referencedAreaIds.Count > 0)
{
var areaSiteIds = await _dbContext.Areas
.Where(a => referencedAreaIds.Contains(a.Id))
.Select(a => a.SiteId)
.Distinct()
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var siteAreas = await _dbContext.Areas.AsNoTracking()
.Where(a => areaSiteIds.Contains(a.SiteId))
.Select(a => new { a.Id, a.Name, a.ParentAreaId })
.ToDictionaryAsync(a => a.Id, cancellationToken)
.ConfigureAwait(false);
foreach (var areaId in referencedAreaIds)
{
var path = new List<string>();
var seen = new HashSet<int>();
int? current = areaId;
while (current is { } id && siteAreas.TryGetValue(id, out var area) && seen.Add(id))
{
path.Add(area.Name);
current = area.ParentAreaId;
}
if (path.Count == 0 || current is not null) continue; // orphan/cyclic chain: leaf name only
path.Reverse();
areaPathById[areaId] = path;
}
}
// 2. Convert to the wire-shaped DTO (strips EF identity, refs-by-name).
// The resolver's site/dataConnection/instance closure is wired
// through via object-initializer — without this the aggregate would
@@ -134,6 +166,7 @@ public sealed class BundleExporter : IBundleExporter
// Area id→name lookup for the exported instances — feeds the serializer's
// AreaName projection so each instance's area travels by name.
AreaNameById = areaNameById,
AreaPathById = areaPathById,
};
var contentDto = _entitySerializer.ToBundleContent(aggregate);
@@ -237,15 +237,10 @@ public sealed class ArtifactDiff
// target's existing timeout untouched in that case.
AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds);
// Secrets: presence-only comparison (we never echo the value in the diff).
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthConfiguration);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthConfiguration");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.AuthConfiguration",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// Secrets: compared by hash, reported presence-only (TRN-2 — the value is never
// echoed in the diff, but a changed value is no longer read as Identical).
AddSecretChange(changes, "Secrets.AuthConfiguration",
existing.AuthConfiguration, SecretValue(incoming.Secrets, "AuthConfiguration"));
// Methods are name-keyed children.
var existingForCompare = existingMethods ?? Array.Empty<ExternalSystemMethod>();
@@ -276,15 +271,10 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
// ConnectionString lives in Secrets only — presence-only comparison.
var existingHasSecret = !string.IsNullOrEmpty(existing.ConnectionString);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("ConnectionString");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.ConnectionString",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// ConnectionString lives in Secrets only — compared by hash, reported
// presence-only (TRN-2).
AddSecretChange(changes, "Secrets.ConnectionString",
existing.ConnectionString, SecretValue(incoming.Secrets, "ConnectionString"));
return BuildItem("DatabaseConnection", incoming.Name, changes);
}
@@ -345,14 +335,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope);
AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport);
var existingHasSecret = !string.IsNullOrEmpty(existing.Credentials);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("Credentials");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.Credentials",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// TRN-2: compared by hash, reported presence-only.
AddSecretChange(changes, "Secrets.Credentials",
existing.Credentials, SecretValue(incoming.Secrets, "Credentials"));
return BuildItem("SmtpConfiguration", incoming.Host, changes);
}
@@ -379,14 +364,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthToken);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthToken");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.AuthToken",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// TRN-2: compared by hash, reported presence-only.
AddSecretChange(changes, "Secrets.AuthToken",
existing.AuthToken, SecretValue(incoming.Secrets, "AuthToken"));
return BuildItem("SmsConfiguration", incoming.AccountSid, changes);
}
@@ -481,13 +461,12 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount);
// Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration).
// Presence-only comparison — never echo the config value.
AddSecretPresenceChange(changes, "Secrets.PrimaryConfiguration",
!string.IsNullOrEmpty(existing.PrimaryConfiguration),
HasSecretKey(incoming.Secrets, "PrimaryConfiguration"));
AddSecretPresenceChange(changes, "Secrets.BackupConfiguration",
!string.IsNullOrEmpty(existing.BackupConfiguration),
HasSecretKey(incoming.Secrets, "BackupConfiguration"));
// Compared by hash, reported presence-only — never echo the config value
// (TRN-2: a changed endpoint URL used to read Identical and be force-skipped).
AddSecretChange(changes, "Secrets.PrimaryConfiguration",
existing.PrimaryConfiguration, SecretValue(incoming.Secrets, "PrimaryConfiguration"));
AddSecretChange(changes, "Secrets.BackupConfiguration",
existing.BackupConfiguration, SecretValue(incoming.Secrets, "BackupConfiguration"));
return BuildItem("DataConnection", incoming.Name, changes);
}
@@ -510,13 +489,19 @@ public sealed class ArtifactDiff
/// <param name="existingTemplateName">The existing instance's template name (the entity carries only a FK), or null if unknown.</param>
/// <param name="existingSiteIdentifier">The existing instance's site identifier (the entity carries only a FK), or null if unknown.</param>
/// <param name="existingAreaName">The existing instance's area name (the entity carries only a FK), or null if unknown / unset.</param>
/// <param name="existingConnectionNameById">TRN-6: id→name of the existing instance's site connections, so a
/// binding's bound connection (stored as a FK) is compared by name. Null skips the connection comparison.</param>
/// <param name="existingAreaPath">TRN-8: the existing instance's root→leaf area path; compared instead of the
/// leaf name when the incoming instance carries an <see cref="InstanceDto.AreaPath"/>.</param>
/// <returns>An import preview item describing the conflict type and differences.</returns>
public ImportPreviewItem CompareInstance(
InstanceDto incoming,
Instance? existing,
string? existingTemplateName = null,
string? existingSiteIdentifier = null,
string? existingAreaName = null)
string? existingAreaName = null,
IReadOnlyDictionary<int, string>? existingConnectionNameById = null,
IReadOnlyList<string>? existingAreaPath = null)
{
ArgumentNullException.ThrowIfNull(incoming);
if (existing is null) return New("Instance", incoming.UniqueName);
@@ -533,8 +518,21 @@ public sealed class ArtifactDiff
{
AddIfDifferent(changes, "SiteIdentifier", existingSiteIdentifier, incoming.SiteIdentifier);
}
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
AddIfDifferent(changes, "State", existing.State.ToString(), incoming.State.ToString());
if (incoming.AreaPath is { Count: > 0 } incomingPath && (existingAreaPath is not null || existing.AreaId is null))
{
// TRN-8: the same leaf name can sit under two parents — compare the full path.
AddIfDifferent(changes, "AreaPath",
existingAreaPath is null ? null : string.Join("/", existingAreaPath),
string.Join("/", incomingPath));
}
else
{
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
}
// TRN-6: State is not compared — an import always writes NotDeployed for a new
// instance and never carries a live state across environments, so a State-only
// difference used to read Modified and an Overwrite then reset a live instance
// to NotDeployed for no configuration change.
DiffChildren(
existing.AttributeOverrides,
@@ -573,10 +571,14 @@ public sealed class ArtifactDiff
incoming.ConnectionBindings,
e => e.AttributeName,
i => i.AttributeName,
// ConnectionName resolves to a FK on the entity (DataConnectionId) that
// can't be compared cross-environment, so the binding diff compares only
// the per-attribute DataSourceReference override.
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride,
// TRN-6: the entity binds by FK (DataConnectionId); the caller resolves it to
// the target connection's name, which is compared (case-insensitively, like
// the unique (SiteId, Name) index) together with the per-attribute
// DataSourceReference override. A rebind OPC1 -> OPC2 used to read Identical.
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride
&& (existingConnectionNameById is null
|| (existingConnectionNameById.TryGetValue(e.DataConnectionId, out var boundName)
&& string.Equals(boundName, i.ConnectionName, StringComparison.OrdinalIgnoreCase))),
"ConnectionBindings",
changes);
@@ -657,24 +659,37 @@ public sealed class ArtifactDiff
};
/// <summary>True if <paramref name="secrets"/> carries the named key.</summary>
private static bool HasSecretKey(SecretsBlock? secrets, string key) =>
secrets is not null && secrets.Values.ContainsKey(key);
private static string? SecretValue(SecretsBlock? secrets, string key) =>
secrets is not null && secrets.Values.TryGetValue(key, out var value) ? value : null;
/// <summary>
/// Records a presence-only secret change (a flip in whether a value is set on
/// each side) using the <c>&lt;present&gt;</c> / null marker convention. The
/// secret value itself is NEVER read into the diff — only its presence.
/// TRN-2: compares a secret-bearing value by SHA-256 hash and reports the result
/// presence-only. A flip in presence uses the <c>&lt;present&gt;</c> / null markers;
/// a value present on both sides that DIFFERS is reported as
/// <c>&lt;present&gt;</c> → <c>&lt;changed&gt;</c>, so the row classifies Modified
/// (it used to read Identical and be force-skipped) while the value itself never
/// reaches the diff.
/// </summary>
private static void AddSecretPresenceChange(List<FieldChange> changes, string field, bool existingHasSecret, bool incomingHasSecret)
private static void AddSecretChange(List<FieldChange> changes, string field, string? existingValue, string? incomingValue)
{
if (existingHasSecret != incomingHasSecret)
var existingHas = !string.IsNullOrEmpty(existingValue);
var incomingHas = !string.IsNullOrEmpty(incomingValue);
if (existingHas != incomingHas)
{
changes.Add(new FieldChange(field,
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
existingHas ? "<present>" : null,
incomingHas ? "<present>" : null));
return;
}
if (existingHas && !SecretHash(existingValue!).AsSpan().SequenceEqual(SecretHash(incomingValue!)))
{
changes.Add(new FieldChange(field, "<present>", "<changed>"));
}
}
private static byte[] SecretHash(string value) =>
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value));
private static void DiffChildren<TExisting, TIncoming>(
IEnumerable<TExisting> existing,
IEnumerable<TIncoming> incoming,
@@ -477,7 +477,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
/// <inheritdoc />
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
{
var session = _sessionStore.Get(sessionId)
?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired.");
@@ -628,10 +628,16 @@ public sealed partial class BundleImporter : IBundleImporter
var targetConnectionsBySiteIdentifier =
new Dictionary<string, IReadOnlyList<DataConnection>>(StringComparer.Ordinal);
// TRN-3: the preview honours the operator's name map, so the diffs, the
// connection auto-match and the unresolved-connection blocker are computed
// against the MAPPED target site / connection — not the source identity.
var previewMap = new PreviewNameMap(nameMap ?? BundleNameMap.Empty);
async Task<Site?> ResolveTargetSiteAsync(string siteIdentifier)
{
if (targetSiteByIdentifier.TryGetValue(siteIdentifier, out var cached)) return cached;
var site = await _siteRepo.GetSiteByIdentifierAsync(siteIdentifier, ct).ConfigureAwait(false);
var site = await _siteRepo.GetSiteByIdentifierAsync(
previewMap.TargetSiteIdentifier(siteIdentifier), ct).ConfigureAwait(false);
targetSiteByIdentifier[siteIdentifier] = site;
return site;
}
@@ -684,7 +690,10 @@ public sealed partial class BundleImporter : IBundleImporter
foreach (var dcDto in content.DataConnections)
{
var targetConns = await ResolveTargetConnectionsAsync(dcDto.SiteIdentifier).ConfigureAwait(false);
var existing = targetConns.FirstOrDefault(c => string.Equals(c.Name, dcDto.Name, StringComparison.Ordinal));
// TRN-7: names compare the way the database's case-insensitive collation
// (and its unique (SiteId, Name) index) does — exact spelling first.
var existing = FindByName(targetConns, c => c.Name,
previewMap.TargetConnectionName(dcDto.SiteIdentifier, dcDto.Name));
var item = _diff.CompareDataConnection(dcDto, existing);
items.Add(item with { Name = QualifiedConnectionName(dcDto.SiteIdentifier, dcDto.Name) });
}
@@ -698,14 +707,21 @@ public sealed partial class BundleImporter : IBundleImporter
// batched read for every bundled instance, and the template / site / area
// names come from the library projection, one site list and one area list
// per site — not four queries per instance.
// TRN-7: case-insensitive like the unique index on UniqueName (exact spelling wins).
var bundleInstanceNames = content.Instances.Select(i => i.UniqueName).ToHashSet(StringComparer.Ordinal);
var existingInstanceByName = content.Instances.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal)
: (await _templateRepo
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: ToNameLookup(
(await _templateRepo
.GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct)
.ConfigureAwait(false))
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
.OrderBy(i => bundleInstanceNames.Contains(i.UniqueName) ? 0 : 1),
i => i.UniqueName);
// TRN-6: an existing binding stores a DataConnectionId; resolve it to the
// connection's name (per site, one read) so the diff can compare it.
var connectionNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
Dictionary<int, string>? siteIdentifierById = null;
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, Area>>();
foreach (var instDto in content.Instances)
{
existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing);
@@ -713,8 +729,17 @@ public sealed partial class BundleImporter : IBundleImporter
string? existingTemplateName = null;
string? existingSiteIdentifier = null;
string? existingAreaName = null;
IReadOnlyList<string>? existingAreaPath = null;
IReadOnlyDictionary<int, string>? existingConnectionNames = null;
if (existing is not null)
{
if (!connectionNameByIdBySite.TryGetValue(existing.SiteId, out existingConnectionNames))
{
existingConnectionNames = (await _siteRepo.GetDataConnectionsBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(c => c.Id, c => c.Name);
connectionNameByIdBySite[existing.SiteId] = existingConnectionNames;
}
// The entity stores template/site/area as numeric FKs that can't be
// compared cross-environment, so resolve each to the same stable
// string identity the incoming DTO carries.
@@ -726,27 +751,39 @@ public sealed partial class BundleImporter : IBundleImporter
if (existing.AreaId is int areaId)
{
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areaNames))
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areasById))
{
areaNames = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(a => a.Id, a => a.Name);
areaNameByIdBySite[existing.SiteId] = areaNames;
areasById = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(a => a.Id, a => a);
areaNameByIdBySite[existing.SiteId] = areasById;
}
existingAreaName = areaNames.TryGetValue(areaId, out var an) ? an : null;
existingAreaName = areasById.TryGetValue(areaId, out var area) ? area.Name : null;
existingAreaPath = AreaPathOf(areaId, areasById);
}
}
// Compare against what the apply would write: the mapped target site and
// the mapped target connection names (TRN-3).
var mappedDto = instDto with
{
SiteIdentifier = previewMap.TargetSiteIdentifier(instDto.SiteIdentifier),
ConnectionBindings = instDto.ConnectionBindings
.Select(b => b with { ConnectionName = previewMap.TargetConnectionName(instDto.SiteIdentifier, b.ConnectionName) })
.ToList(),
};
items.Add(_diff.CompareInstance(
instDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName));
mappedDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName,
existingConnectionNames, existingAreaPath));
}
// ---- Required site/connection mappings ----
var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync(
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync).ConfigureAwait(false);
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName).ConfigureAwait(false);
// ---- Blocker detection ----
items.AddRange(await DetectBlockersAsync(
content, ResolveTargetConnectionsAsync, library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
content, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName,
library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
return new ImportPreview(sessionId, items, requiredSites, requiredConnections);
}
@@ -772,7 +809,8 @@ public sealed partial class BundleImporter : IBundleImporter
BuildRequiredMappingsAsync(
BundleContentDto content,
Func<string, Task<Site?>> resolveTargetSite,
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections)
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
Func<string, string, string> targetConnectionName)
{
// Distinct source-site identifiers, with a best-effort display name.
// SiteDto carries a Name; instances / data-connections only carry the
@@ -838,11 +876,11 @@ public sealed partial class BundleImporter : IBundleImporter
// Auto-match only WITHIN the auto-matched target site: a connection of
// the same name under a different site is not a valid match.
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
var matched = targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal));
var matched = FindByName(targetConns, c => c.Name, targetConnectionName(site, name));
connectionMappings.Add(new RequiredConnectionMapping(
SourceSiteIdentifier: site,
SourceConnectionName: name,
AutoMatchTargetName: matched ? name : null));
AutoMatchTargetName: matched?.Name));
}
return (siteMappings, connectionMappings);
@@ -860,6 +898,7 @@ public sealed partial class BundleImporter : IBundleImporter
private async Task<IReadOnlyList<ImportPreviewItem>> DetectBlockersAsync(
BundleContentDto content,
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
Func<string, string, string> targetConnectionName,
TemplateLibrary library,
IReadOnlyList<SharedScript> allSharedScripts,
IReadOnlyList<ExternalSystemDefinition> allExternalSystems,
@@ -871,7 +910,8 @@ public sealed partial class BundleImporter : IBundleImporter
// The set of template names the import can satisfy = (in-bundle templates)
// ∪ (templates already in the target DB). An instance whose TemplateName is
// in neither is unresolvable.
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
// TRN-7: instance template names resolve case-insensitively on apply.
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// A derived slot template is not something an instance is created from (#118).
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t))) bundleTemplateNames.Add(t.Name);
// ScadaBridge#118: a malformed or cyclic derivation fails the apply outright.
@@ -893,7 +933,7 @@ public sealed partial class BundleImporter : IBundleImporter
// Members + lock flags are needed below (CollectLockedOverrideWarnings) but
// never script bodies — the body-free, untracked analysis projection (04/P4).
var targetTemplates = await library.GetAnalysisAsync(ct).ConfigureAwait(false);
var targetTemplateNames = new HashSet<string>(StringComparer.Ordinal);
var targetTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var t in targetTemplates)
{
targetTemplateNames.Add(t.Name);
@@ -951,7 +991,7 @@ public sealed partial class BundleImporter : IBundleImporter
{
if (bundleConnections.Contains((site, name))) continue;
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
if (targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) continue;
if (FindByName(targetConns, c => c.Name, targetConnectionName(site, name)) is not null) continue;
// Site-qualify the blocker Name so two sites' same-named-but-missing
// connections surface as distinct blockers (a bare name would collide).
blockers.Add(new ImportPreviewItem(
@@ -1613,6 +1653,21 @@ public sealed partial class BundleImporter : IBundleImporter
ArgumentNullException.ThrowIfNull(resolutions);
ArgumentNullException.ThrowIfNull(user);
// TRN-9: Rename is meaningless for a site, a data connection and the SMTP /
// SMS configurations (it was silently Skipped, or wrote a mangled junk row
// delivery never uses). Reject it up front rather than report "Renamed: 1".
var unsupportedRenames = resolutions
.Where(r => r.Action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(r.EntityType))
.Select(r => $"{r.EntityType} '{r.Name}'")
.ToList();
if (unsupportedRenames.Count > 0)
{
throw new ArgumentException(
"Rename is not supported for sites, data connections, SMTP or SMS configurations; "
+ "choose Skip or Overwrite for: " + string.Join(", ", unsupportedRenames) + ".",
nameof(resolutions));
}
// Normalise null → Empty so the resolve-or-create logic always has a map
// to consult. An empty map means "no explicit operator mappings" — every
// referenced site/connection falls through to the identity auto-match.
@@ -1995,9 +2050,10 @@ public sealed partial class BundleImporter : IBundleImporter
// It writes the instance row + its four child collections (attribute /
// alarm / native-alarm-source overrides + connection bindings) and
// rewires every name-keyed FK to the target environment's ids.
var instanceWarnings = new List<string>();
await ApplyInstancesAsync(
content, resolutionMap, siteBySourceIdentifier, connectionMaps,
library, user, summary, ct).ConfigureAwait(false);
library, user, summary, instanceWarnings, ct).ConfigureAwait(false);
// ---- Pre-commit point: stale-instance computation ----
// Everything the import will write is staged on the change tracker at
@@ -2050,7 +2106,9 @@ public sealed partial class BundleImporter : IBundleImporter
StaleInstanceIds: staleInstanceIds,
AuditEventCorrelation: bundleImportId.ToString(),
ApiKeysIgnored: apiKeysIgnored,
Warnings: derivedWarnings.Count == 0 ? validationWarnings : validationWarnings.Concat(derivedWarnings).ToList());
Warnings: derivedWarnings.Count == 0 && instanceWarnings.Count == 0
? validationWarnings
: validationWarnings.Concat(derivedWarnings).Concat(instanceWarnings).ToList());
}
/// <summary>
@@ -2208,7 +2266,7 @@ public sealed partial class BundleImporter : IBundleImporter
{
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
if (resolution.Action != ResolutionAction.Overwrite) continue;
if (targetTemplateIdByName.TryGetValue(dto.Name, out var templateId))
if (TryGetIdByNameIgnoreCase(targetTemplateIdByName, dto.Name, out var templateId))
{
overwrittenTemplateIds.Add(templateId);
}
@@ -2418,6 +2476,96 @@ public sealed partial class BundleImporter : IBundleImporter
/// throw on a duplicate key: the first row for a name wins. Used wherever a
/// by-name DB result is re-keyed in memory (ScadaBridge#93).
/// </summary>
/// <summary>
/// TRN-7: finds the row named <paramref name="wanted"/> the way the database's
/// case-insensitive collation (and its unique indexes) would — the exact spelling
/// first, otherwise a case-insensitive match. Null when neither exists.
/// </summary>
internal static T? FindByName<T>(IEnumerable<T> rows, Func<T, string> name, string wanted)
where T : class
{
T? ignoreCase = null;
foreach (var row in rows)
{
var n = name(row);
if (string.Equals(n, wanted, StringComparison.Ordinal)) return row;
if (ignoreCase is null && string.Equals(n, wanted, StringComparison.OrdinalIgnoreCase)) ignoreCase = row;
}
return ignoreCase;
}
/// <summary>
/// TRN-8: the root→leaf name path of area <paramref name="areaId"/>, or null when the
/// parent chain is broken or cyclic.
/// </summary>
private static IReadOnlyList<string>? AreaPathOf(int areaId, IReadOnlyDictionary<int, Area> areasById)
{
var path = new List<string>();
var seen = new HashSet<int>();
int? current = areaId;
while (current is { } id)
{
if (!seen.Add(id) || !areasById.TryGetValue(id, out var area)) return null;
path.Add(area.Name);
current = area.ParentAreaId;
}
path.Reverse();
return path;
}
/// <summary>
/// TRN-7: looks <paramref name="name"/> up in an ordinal name→id map, falling back to a
/// case-insensitive match when exactly one key matches that way (two case variants are
/// ambiguous and resolve to nothing, as a missing name does).
/// </summary>
internal static bool TryGetIdByNameIgnoreCase(IReadOnlyDictionary<string, int> idByName, string name, out int id)
{
if (idByName.TryGetValue(name, out id)) return true;
var found = false;
foreach (var (key, value) in idByName)
{
if (!string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) continue;
if (found) { id = 0; return false; }
id = value;
found = true;
}
if (!found) id = 0;
return found;
}
/// <summary>
/// TRN-3: the operator's <see cref="BundleNameMap"/> as seen by the preview — the
/// target site identifier and target connection name a source reference resolves to.
/// Only a <see cref="MappingAction.MapToExisting"/> entry with an explicit target
/// redirects; every other reference keeps its source identity (the identity
/// auto-match the apply performs for it as well).
/// </summary>
private sealed class PreviewNameMap
{
private readonly Dictionary<string, string> _siteTargets = new(StringComparer.Ordinal);
private readonly Dictionary<(string Site, string Name), string> _connectionTargets = new();
public PreviewNameMap(BundleNameMap map)
{
foreach (var m in map.Sites)
{
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetSiteIdentifier))
_siteTargets.TryAdd(m.SourceSiteIdentifier, m.TargetSiteIdentifier);
}
foreach (var m in map.Connections)
{
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetConnectionName))
_connectionTargets.TryAdd((m.SourceSiteIdentifier, m.SourceConnectionName), m.TargetConnectionName);
}
}
public string TargetSiteIdentifier(string sourceSiteIdentifier) =>
_siteTargets.TryGetValue(sourceSiteIdentifier, out var t) ? t : sourceSiteIdentifier;
public string TargetConnectionName(string sourceSiteIdentifier, string sourceConnectionName) =>
_connectionTargets.TryGetValue((sourceSiteIdentifier, sourceConnectionName), out var t) ? t : sourceConnectionName;
}
internal static Dictionary<string, T> ToNameLookup<T>(IEnumerable<T> rows, Func<T, string> name)
{
var lookup = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
@@ -3346,7 +3494,11 @@ public sealed partial class BundleImporter : IBundleImporter
{
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
if (resolution.Action == ResolutionAction.Skip) continue;
if (dto.Compositions.Count == 0) continue;
// TRN-4: a bundle template with NO compositions must still run the
// clear below when it overwrites an existing target row — the source
// removed every slot, and the diff reports those removals. Only an
// Add/Rename (a brand-new row with nothing to clear) can be skipped.
if (dto.Compositions.Count == 0 && resolution.Action != ResolutionAction.Overwrite) continue;
var importedName = resolution.Action == ResolutionAction.Rename
? (resolution.RenameTo ?? dto.Name)
@@ -3378,9 +3530,42 @@ public sealed partial class BundleImporter : IBundleImporter
var existingComps = parent.Compositions
.Where(c => derivedSlots is null || !derivedSlots.Contains(c.InstanceName))
.ToList();
// TRN-5: a slot row owns its slot-derived template (OwnerCompositionId,
// no database relationship), so deleting the row alone orphaned the
// derived template with a live ParentTemplateId that then blocked
// deleting its base. A slot the bundle REMOVES (its instance name is
// not among the bundle's compositions for this owner, and no bundle
// composition names its composed template) is deleted through
// TemplateService.DeleteCompositionAsync, which cascades the slot-owned
// derived templates (it saves inside the import's transaction, as the
// derived-template pass already does). A slot the bundle re-composes
// keeps the row-only delete: a pre-#118 bundle re-composes the slot
// onto that very derived template by name, so it must survive.
var bundleSlotNames = dto.Compositions
.Select(c => c.InstanceName)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var bundleComposedNames = dto.Compositions
.Where(c => !string.IsNullOrEmpty(c.ComposedTemplateName))
.Select(c => c.ComposedTemplateName!)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
TemplateService? compositionService = null;
foreach (var existing in existingComps)
{
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
var removedSlot = !bundleSlotNames.Contains(existing.InstanceName)
&& await IsRemovableSlotDerivedAsync(existing, bundleComposedNames, ct).ConfigureAwait(false);
if (!removedSlot)
{
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
continue;
}
compositionService ??= new TemplateService(_templateRepo, _auditService);
var deleted = await compositionService.DeleteCompositionAsync(existing.Id, user, ct).ConfigureAwait(false);
if (!deleted.IsSuccess)
{
throw new InvalidOperationException(
$"Could not remove composition '{parent.Name}.{existing.InstanceName}': {deleted.Error}");
}
}
if (derivedSlots is null)
{
@@ -3421,11 +3606,13 @@ public sealed partial class BundleImporter : IBundleImporter
// The fallback is a dictionary lookup into the per-apply library
// snapshot (04/P4) — a name not in Local is a pre-existing target
// template this apply has not touched, so its pre-write id is current.
localByName.TryGetValue(compDto.ComposedTemplateName, out var composedStub);
// TRN-7: exact spelling first, then case-insensitive (the database's
// collation treats a case variant as the same template).
localByName.TryGetImported(compDto.ComposedTemplateName, out var composedStub);
int? composedId = composedStub?.Id;
if (composedId is null
&& (await library.GetIdByNameAsync(ct).ConfigureAwait(false))
.TryGetValue(compDto.ComposedTemplateName, out var libraryId))
&& TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false),
compDto.ComposedTemplateName, out var libraryId))
{
composedId = libraryId;
}
@@ -3514,10 +3701,13 @@ public sealed partial class BundleImporter : IBundleImporter
? (baseResolution.RenameTo ?? dto.BaseTemplateName)
: dto.BaseTemplateName;
localByName.TryGetValue(baseName, out var baseStub);
// TRN-7: exact spelling first, then case-insensitive — a bundle base
// 'PumpBase' overwriting target 'pumpbase' used to miss both lookups and
// null the child's ParentTemplateId.
localByName.TryGetImported(baseName, out var baseStub);
int? baseId = baseStub?.Id;
if (baseId is null
&& (await library.GetIdByNameAsync(ct).ConfigureAwait(false)).TryGetValue(baseName, out var libraryId))
&& TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false), baseName, out var libraryId))
{
baseId = libraryId;
}
@@ -3595,6 +3785,26 @@ public sealed partial class BundleImporter : IBundleImporter
_exact.TryGetValue(name, out template!) || _ignoreCase.TryGetValue(name, out template!);
}
/// <summary>
/// TRN-5: true when <paramref name="composition"/> owns a slot-derived template
/// (<c>IsDerived</c> with <c>OwnerCompositionId</c> pointing back at the row) that no
/// bundle composition of the same owner names — i.e. deleting the slot must cascade
/// the derived template. A slot that composes a base directly (pre-derived data) has
/// nothing to cascade and keeps the plain row delete.
/// </summary>
private async Task<bool> IsRemovableSlotDerivedAsync(
TemplateComposition composition, IReadOnlySet<string> bundleComposedNames, CancellationToken ct)
{
var composed = await _dbContext.Templates.AsNoTracking()
.Where(t => t.Id == composition.ComposedTemplateId)
.Select(t => new { t.Name, t.IsDerived, t.OwnerCompositionId })
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
return composed is not null
&& composed.IsDerived
&& composed.OwnerCompositionId == composition.Id
&& !bundleComposedNames.Contains(composed.Name);
}
/// <summary>
/// Loads the given tracked templates with their child collections in one batched
/// read (Gitea #47 — previously one <c>GetTemplateWithChildrenAsync</c> per
@@ -4581,7 +4791,11 @@ public sealed partial class BundleImporter : IBundleImporter
target = await _siteRepo.GetSiteByIdentifierAsync(targetId, ct).ConfigureAwait(false);
}
if (action == MappingAction.CreateNew || target is null)
// TRN-3: an explicit CreateNew for an identifier the target already holds
// would violate the unique SiteIdentifier index and roll the whole import
// back with a raw SQL error — treat it as a match to that existing site
// (the site's own Skip/Overwrite resolution then applies).
if (target is null)
{
var created = BuildSite(siteDto);
await _siteRepo.AddSiteAsync(created, ct).ConfigureAwait(false);
@@ -4756,13 +4970,14 @@ public sealed partial class BundleImporter : IBundleImporter
&& mapping.TargetConnectionName is { Length: > 0 } tn
? tn
: dcDto.Name;
var existing = targetConns.FirstOrDefault(c =>
string.Equals(c.Name, targetName, StringComparison.Ordinal));
// TRN-7: case-insensitive like the unique (SiteId, Name) index, exact first.
var existing = FindByName(targetConns, c => c.Name, targetName);
var action = mapping?.Action
?? (existing is not null ? MappingAction.MapToExisting : MappingAction.CreateNew);
if (action == MappingAction.CreateNew || existing is null)
// TRN-3: CreateNew against a connection the target site already holds
// (same name) would violate the unique (SiteId, Name) index and roll the
// import back with a raw SQL error — match the existing row instead (the
// connection's own Skip/Overwrite resolution then applies).
if (existing is null)
{
var created = BuildDataConnection(dcDto, targetSite.Id);
await _siteRepo.AddDataConnectionAsync(created, ct).ConfigureAwait(false);
@@ -4836,8 +5051,7 @@ public sealed partial class BundleImporter : IBundleImporter
: connName;
var targetConns = await TargetConnsAsync(targetSite.Id).ConfigureAwait(false);
var existing = targetConns.FirstOrDefault(c =>
string.Equals(c.Name, targetName, StringComparison.Ordinal));
var existing = FindByName(targetConns, c => c.Name, targetName);
if (existing is null)
{
// Should already be a preview blocker (present in neither bundle nor
@@ -4937,6 +5151,7 @@ public sealed partial class BundleImporter : IBundleImporter
TemplateLibrary library,
string user,
ImportSummary summary,
List<string> warnings,
CancellationToken ct)
{
if (content.Instances.Count == 0) return;
@@ -4945,8 +5160,13 @@ public sealed partial class BundleImporter : IBundleImporter
// for pre-existing templates, overlaid with the tracked (Local) templates —
// which include everything this apply added or renamed, flushed (so their ids
// are real) before this pass (review 2026-10-21 04/P4).
var templateIdByName = new Dictionary<string, int>(
await library.GetIdByNameAsync(ct).ConfigureAwait(false), StringComparer.Ordinal);
// TRN-7: case-insensitive like the template name index (exact spelling wins —
// the ordinal library map is copied first, so a case variant only fills a gap).
var templateIdByName = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, id) in await library.GetIdByNameAsync(ct).ConfigureAwait(false))
{
templateIdByName.TryAdd(name, id);
}
foreach (var local in _dbContext.Templates.Local)
{
// A tracked derived slot template never displaces a base of the same name
@@ -4966,14 +5186,19 @@ public sealed partial class BundleImporter : IBundleImporter
lookupNames.Add(dto.UniqueName);
if (r.Action == ResolutionAction.Rename && !string.IsNullOrEmpty(r.RenameTo)) lookupNames.Add(r.RenameTo);
}
// TRN-7: case-insensitive like the unique index on UniqueName; an exact-spelling
// row wins over a case variant.
var existingByName = lookupNames.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal)
: (await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: ToNameLookup(
(await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
.OrderBy(i => lookupNames.Contains(i.UniqueName) ? 0 : 1),
i => i.UniqueName);
// Memoise area resolution per (siteId, areaName) so two instances under the
// Memoise area resolution per (siteId, area key) so two instances under the
// same area don't each create a duplicate row.
var areaIdByKey = new Dictionary<(int SiteId, string Name), int>();
var areasBySite = new Dictionary<int, List<Area>>();
foreach (var dto in content.Instances)
{
@@ -5003,7 +5228,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
int? areaId = await ResolveOrCreateAreaIdAsync(
dto.AreaName, targetSite.Id, areaIdByKey, ct).ConfigureAwait(false);
dto, targetSite.Id, areaIdByKey, areasBySite, warnings, ct).ConfigureAwait(false);
switch (resolution.Action)
{
@@ -5075,37 +5300,96 @@ public sealed partial class BundleImporter : IBundleImporter
}
/// <summary>
/// Resolves an instance's area by name within the target site, creating the
/// area if it doesn't exist. Returns null when <paramref name="areaName"/> is
/// null/empty (the instance has no area). Memoised via
/// <paramref name="areaIdByKey"/> so repeated references resolve to one row.
/// Resolves an instance's area within the target site, creating what is missing.
/// Returns null when the instance has no area.
/// <para>
/// TRN-8: when the bundle carries <see cref="InstanceDto.AreaPath"/> the area is
/// resolved level by level from the site root (exact name first, then
/// case-insensitive, like the database collation), and any missing level is created
/// under its real parent — the same leaf name may exist under two parents, and a
/// missing nested area used to be recreated at the site root. A pre-TRN-8 bundle
/// carries only the leaf <see cref="InstanceDto.AreaName"/>: it is matched across the
/// site as before, but an ambiguous leaf (several areas with that name) is resolved
/// deterministically (a root-level area, else the lowest id) and reported as a
/// warning instead of silently taking whichever row came back first.
/// </para>
/// </summary>
private async Task<int?> ResolveOrCreateAreaIdAsync(
string? areaName,
InstanceDto dto,
int siteId,
Dictionary<(int SiteId, string Name), int> areaIdByKey,
Dictionary<int, List<Area>> areasBySite,
List<string> warnings,
CancellationToken ct)
{
if (string.IsNullOrEmpty(areaName)) return null;
IReadOnlyList<string>? path = dto.AreaPath is { Count: > 0 } p && p.All(segment => !string.IsNullOrEmpty(segment))
? p
: null;
if (path is null && string.IsNullOrEmpty(dto.AreaName)) return null;
var key = (siteId, areaName);
var key = (siteId, path is null ? "leaf:" + dto.AreaName : "path:" + string.Join("\u001f", path));
if (areaIdByKey.TryGetValue(key, out var cached)) return cached;
var existingAreas = await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false);
var match = existingAreas.FirstOrDefault(a => string.Equals(a.Name, areaName, StringComparison.Ordinal));
if (match is not null)
if (!areasBySite.TryGetValue(siteId, out var areas))
{
areaIdByKey[key] = match.Id;
return match.Id;
areas = (await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false)).ToList();
areasBySite[siteId] = areas;
}
var area = new Area(areaName) { SiteId = siteId };
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
// Flush so the area's surrogate id materialises before it's used as an
// instance FK (relational provider). Rides the outer transaction.
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areaIdByKey[key] = area.Id;
return area.Id;
int resolvedId;
if (path is not null)
{
int? parentId = null;
Area? current = null;
foreach (var segment in path)
{
var level = parentId;
current = FindByName(areas.Where(a => a.ParentAreaId == level), a => a.Name, segment);
if (current is null)
{
current = new Area(segment) { SiteId = siteId, ParentAreaId = parentId };
await _templateRepo.AddAreaAsync(current, ct).ConfigureAwait(false);
// Flush so the area's surrogate id materialises before it is used as a
// parent / instance FK (relational provider). Rides the outer transaction.
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areas.Add(current);
}
parentId = current.Id;
}
resolvedId = current!.Id;
}
else
{
var leaf = dto.AreaName!;
var exact = areas.Where(a => string.Equals(a.Name, leaf, StringComparison.Ordinal)).ToList();
var matches = exact.Count > 0
? exact
: areas.Where(a => string.Equals(a.Name, leaf, StringComparison.OrdinalIgnoreCase)).ToList();
if (matches.Count == 0)
{
var area = new Area(leaf) { SiteId = siteId };
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areas.Add(area);
resolvedId = area.Id;
}
else
{
var chosen = matches.Where(a => a.ParentAreaId is null).OrderBy(a => a.Id).FirstOrDefault()
?? matches.OrderBy(a => a.Id).First();
if (matches.Count > 1)
{
warnings.Add(
$"Instance '{dto.UniqueName}': area '{leaf}' matches {matches.Count} areas in the target site "
+ "and the bundle carries no area path (it predates area paths); it was assigned to area id "
+ $"{chosen.Id}. Check the instance's area after the import.");
}
resolvedId = chosen.Id;
}
}
areaIdByKey[key] = resolvedId;
return resolvedId;
}
/// <summary>
@@ -5380,7 +5664,7 @@ public sealed partial class BundleImporter : IBundleImporter
? tn
: name;
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
if (!conns.Any(c => string.Equals(c.Name, targetName, StringComparison.Ordinal)))
if (FindByName(conns, c => c.Name, targetName) is null)
{
errors.Add(
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
@@ -5389,7 +5673,8 @@ public sealed partial class BundleImporter : IBundleImporter
}
// ---- Instance template references ----
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
// TRN-7: instance template names resolve case-insensitively on apply.
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t)))
{
var resolution = ResolveOrDefault(resolutionMap, "Template", t.Name);
@@ -5400,7 +5685,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
var targetTemplateNames = new HashSet<string>(
(await library.GetIdByNameAsync(ct).ConfigureAwait(false)).Keys,
StringComparer.Ordinal);
StringComparer.OrdinalIgnoreCase);
foreach (var inst in content.Instances)
{
@@ -67,6 +67,14 @@ public sealed record EntityAggregate(
/// </summary>
public IReadOnlyDictionary<int, string> AreaNameById { get; init; } =
new Dictionary<int, string>();
/// <summary>
/// TRN-8: lookup from area ID to the area's full path from the site root (one
/// element per level) for the exported instances' <c>AreaId</c> FKs. Empty default:
/// the serializer then emits <c>AreaPath: null</c> and the importer uses the leaf name.
/// </summary>
public IReadOnlyDictionary<int, IReadOnlyList<string>> AreaPathById { get; init; } =
new Dictionary<int, IReadOnlyList<string>>();
}
/// <summary>
@@ -482,4 +490,16 @@ public sealed record InstanceDto(
IReadOnlyList<InstanceAttributeOverrideDto> AttributeOverrides,
IReadOnlyList<InstanceAlarmOverrideDto> AlarmOverrides,
IReadOnlyList<InstanceNativeAlarmSourceOverrideDto> NativeAlarmSourceOverrides,
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings);
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings)
{
/// <summary>
/// TRN-8 (additive, 2026-12-03): the instance's area as its full path from the site
/// root, one element per level (e.g. <c>["Line2", "Cell"]</c>; the last element equals
/// <see cref="AreaName"/>). The same leaf name may exist under two parents, so the
/// importer resolves (and creates missing levels of) the path instead of matching the
/// leaf name across the whole site. Null on a bundle written before the field existed
/// (the importer then falls back to the leaf <see cref="AreaName"/>) and when the
/// instance has no area. An older importer ignores the unknown property.
/// </summary>
public IReadOnlyList<string>? AreaPath { get; init; }
}
@@ -319,7 +319,14 @@ public sealed class EntitySerializer
ConnectionBindings: inst.ConnectionBindings.Select(b => new InstanceConnectionBindingDto(
AttributeName: b.AttributeName,
ConnectionName: connectionNameByConnectionId.TryGetValue(b.DataConnectionId, out var cn) ? cn : string.Empty,
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())).ToList(),
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())
{
// TRN-8: the full area path (root → leaf) so the importer can tell two
// same-named areas under different parents apart.
AreaPath = inst.AreaId is { } pathAreaId && aggregate.AreaPathById.TryGetValue(pathAreaId, out var ap)
? ap
: null,
}).ToList(),
};
}
@@ -0,0 +1,98 @@
using System.CommandLine;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// CLI-2 (WP2 task 2.8): <c>site update</c>, <c>data-connection update</c> and
/// <c>api-method update</c> send only the options actually passed. Before the fix an
/// omitted option was sent as null (or as a default: <c>--failover-retry-count</c> 3,
/// <c>--timeout</c> 30) and the server overwrote the stored value — e.g.
/// <c>site update --id 3 --name X</c> nulled both gRPC addresses. The server now treats
/// null as "keep"; these tests pin that the CLI sends null for every omitted option.
/// </summary>
public class PartialUpdateCommandTests
{
private static readonly Option<string> Url = new("--url") { Recursive = true };
private static readonly Option<string> Username = new("--username") { Recursive = true };
private static readonly Option<string> Password = new("--password") { Recursive = true };
private static readonly Option<string> Format = CliOptions.CreateFormatOption();
private static async Task<T> ParseAsync<T>(
Func<Option<string>, Option<string>, Option<string>, Option<string>, Func<object, int>, Command> build,
params string[] args)
{
var captured = new List<object>();
var root = new RootCommand { Url, Username, Password, Format };
root.Add(build(Url, Format, Username, Password, cmd => { captured.Add(cmd); return 0; }));
var exit = await root.Parse(args).InvokeAsync();
Assert.Equal(0, exit);
return Assert.IsType<T>(Assert.Single(captured));
}
/// <summary>A name-only site update leaves every other field null (= unchanged).</summary>
[Fact]
public async Task SiteUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--name", "Plant 3");
Assert.Equal(new UpdateSiteCommand(3, "Plant 3", null, null, null, null, null), cmd);
}
/// <summary>A site update can change one address without supplying the name.</summary>
[Fact]
public async Task SiteUpdate_AddressOnly_SendsNullName()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate,
"update", "--id", "3", "--grpc-node-a-address", "http://a:8083");
Assert.Null(cmd.Name);
Assert.Equal("http://a:8083", cmd.GrpcNodeAAddress);
Assert.Null(cmd.GrpcNodeBAddress);
}
/// <summary>An explicitly empty option is sent as "" (the server clears the field).</summary>
[Fact]
public async Task SiteUpdate_EmptyDescription_SendsEmptyStringToClear()
{
var cmd = await ParseAsync<UpdateSiteCommand>(SiteCommands.BuildUpdate, "update", "--id", "3", "--description", "");
Assert.Equal("", cmd.Description);
Assert.Null(cmd.Name);
}
/// <summary>A name-only data-connection update sends no protocol, configs or retry count.</summary>
[Fact]
public async Task DataConnectionUpdate_NameOnly_SendsNullForEveryOtherField()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--name", "X");
Assert.Equal(new UpdateDataConnectionCommand(7, "X", null, null, null, null), cmd);
}
/// <summary>A passed retry count and protocol are forwarded.</summary>
[Fact]
public async Task DataConnectionUpdate_PassedOptions_AreForwarded()
{
var cmd = await ParseAsync<UpdateDataConnectionCommand>(DataConnectionCommands.BuildUpdate,
"update", "--id", "7", "--protocol", "OpcUa", "--failover-retry-count", "5", "--backup-config", "");
Assert.Equal(new UpdateDataConnectionCommand(7, null, "OpcUa", null, "", 5), cmd);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[Fact]
public async Task ApiMethodUpdate_ScriptOnly_SendsNullTimeoutAndDefinitions()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--script", "return 1;");
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", null, null, null, null), cmd);
}
/// <summary>A timeout-only api-method update sends no script.</summary>
[Fact]
public async Task ApiMethodUpdate_TimeoutOnly_SendsNullScript()
{
var cmd = await ParseAsync<UpdateApiMethodCommand>(ApiMethodCommands.BuildUpdate,
"update", "--id", "5", "--timeout", "120");
Assert.Null(cmd.Script);
Assert.Equal(120, cmd.TimeoutSeconds);
}
}
@@ -4,7 +4,9 @@ using ZB.MOM.WW.ScadaBridge.CLI.Commands;
namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;
/// <summary>
/// Regression tests for the update commands. The <c>Update*Command</c> records in Commons carry
/// Regression tests for the update commands. Site, data-connection and api-method updates are
/// preserve-if-null partial updates (CLI-2, see <see cref="PartialUpdateCommandTests"/>); the
/// remaining <c>Update*Command</c> records in Commons carry
/// non-nullable "core" fields (e.g. <c>string Name</c>, <c>string Protocol</c>,
/// <c>string Script</c>) — an update is a <em>whole-entity replace</em>, not a sparse
/// patch. The CLI must therefore mark those core flags as <c>Required</c>: making them
@@ -57,15 +59,24 @@ public class UpdateCommandContractTests
public void TemplateScriptUpdate_CoreFieldsRequired()
=> AssertRequired(UpdateCommand(TemplateCommands.Build(Url, Format, Username, Password), "script", "update"), "--name", "--code");
/// <summary>Verifies that the site update command marks its core fields as required.</summary>
/// <summary>CLI-2: site update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[Fact]
public void SiteUpdate_CoreFieldsRequired()
=> AssertRequired(UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update"), "--name");
public void SiteUpdate_IsPartial_OnlyIdRequired()
{
var update = UpdateCommand(SiteCommands.Build(Url, Format, Username, Password), "update");
AssertRequired(update, "--id");
AssertOptional(update, "--name", "--description", "--node-a-address", "--node-b-address",
"--grpc-node-a-address", "--grpc-node-b-address");
}
/// <summary>Verifies that the data connection update command marks its core fields as required.</summary>
/// <summary>CLI-2: data-connection update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[Fact]
public void DataConnectionUpdate_CoreFieldsRequired()
=> AssertRequired(UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update"), "--name", "--protocol");
public void DataConnectionUpdate_IsPartial_OnlyIdRequired()
{
var update = UpdateCommand(DataConnectionCommands.Build(Url, Format, Username, Password), "update");
AssertRequired(update, "--id");
AssertOptional(update, "--name", "--protocol", "--primary-config", "--backup-config", "--failover-retry-count");
}
/// <summary>Verifies that the external system update command marks its core fields as required.</summary>
[Fact]
@@ -110,10 +121,25 @@ public class UpdateCommandContractTests
}
}
/// <summary>Verifies that the API method update command marks its script as required.</summary>
/// <summary>CLI-2: api-method update is a preserve-if-null partial update, so only <c>--id</c> is required.</summary>
[Fact]
public void ApiMethodUpdate_CoreFieldsRequired()
=> AssertRequired(UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update"), "--script");
public void ApiMethodUpdate_IsPartial_OnlyIdRequired()
{
var update = UpdateCommand(ApiMethodCommands.Build(Url, Format, Username, Password), "update");
AssertRequired(update, "--id");
AssertOptional(update, "--script", "--timeout", "--parameters", "--return-def", "--trace-all-calls");
}
private static void AssertOptional(Command command, params string[] optionNames)
{
foreach (var name in optionNames)
{
var option = command.Options.SingleOrDefault(o => o.Name == name);
Assert.True(option != null, $"'{command.Name}' is missing expected option '{name}'.");
Assert.False(option!.Required, $"'{command.Name}' option '{name}' must be optional (partial update).");
Assert.False(option.HasDefaultValue, $"'{command.Name}' option '{name}' must have no default — an omitted option must travel as null.");
}
}
/// <summary>Verifies that the external system method update command keeps all of its fields optional because it is a sparse update.</summary>
[Fact]
@@ -96,7 +96,7 @@ public class FlowDebuggerDrillinTests : BunitContext
Assert.Contains("7–10 audit rows per call", markup);
// Load, update and create paths all carry the flag.
Assert.Contains("_traceAllCalls = _existing.TraceAllCalls;", markup);
Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup);
Assert.Contains("new UpdateApiMethodCommand(_existing.Id, _script, _timeoutSeconds, _params?.Trim() ?? \"\", _returns?.Trim() ?? \"\", _traceAllCalls)", markup);
Assert.Contains("new CreateApiMethodCommand(methodName, _script, _timeoutSeconds, _params?.Trim(), _returns?.Trim(), _traceAllCalls)", markup);
}
}
@@ -434,6 +434,75 @@ public class TransportImportPageTests : BunitContext
Assert.Empty(cut.FindAll("[data-testid='map-section']"));
}
/// <summary>TRN-9: Rename is not offered for a data connection row, but still is for a template.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Rename_is_not_offered_for_unsupported_entity_types()
{
var session = BuildEncryptedSession(sourceEnv: "prod-cluster");
var preview = new ImportPreview(session.SessionId, new List<ImportPreviewItem>
{
new("DataConnection", "site-a/opc-a", null, null, ConflictKind.Modified, "{}", null),
new("Template", "Pump", null, null, ConflictKind.Modified, "{}", null),
});
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>()).Returns(preview);
var cut = Render<TransportImportPage>();
await cut.InvokeAsync(() => SetField(cut.Instance, "_session", session));
await cut.InvokeAsync(async () =>
await InvokeAsyncMethod(cut.Instance, "LoadPreviewAndAdvanceAsync"));
cut.Render();
Assert.Empty(cut.FindAll("input[id='res-DataConnection-site-a/opc-a-Rename']"));
Assert.NotEmpty(cut.FindAll("input[id='res-DataConnection-site-a/opc-a-Overwrite']"));
Assert.NotEmpty(cut.FindAll("input[id='res-Template-Pump-Rename']"));
}
/// <summary>
/// TRN-3: with the Map step redirecting site-a to site-b, the Confirm gate re-runs the
/// preview under that mapping, so a connection blocker the redirect resolves no longer
/// blocks the import.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Confirm_reruns_preview_under_redirect_mapping()
{
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(new List<Site> { new("Site B", "site-b") { Id = 7 } });
_siteRepo.GetDataConnectionsBySiteIdAsync(7, Arg.Any<CancellationToken>())
.Returns(new List<DataConnection> { new("opc-a", "OpcUa", 7) { Id = 11 } });
var session = BuildEncryptedSession(sourceEnv: "prod-cluster");
var blocked = new ImportPreview(
session.SessionId,
new List<ImportPreviewItem>
{
new("Instance", "site-a/opc-a", null, null, ConflictKind.Blocker, null, "Connection 'site-a/opc-a' unresolved"),
},
new List<RequiredSiteMapping> { new("site-a", "Site A", null) },
new List<RequiredConnectionMapping> { new("site-a", "opc-a", null) });
var resolved = new ImportPreview(
session.SessionId,
new List<ImportPreviewItem> { new("Instance", "Pump-01", null, null, ConflictKind.New, null, null) },
new List<RequiredSiteMapping> { new("site-a", "Site A", "site-b") },
new List<RequiredConnectionMapping> { new("site-a", "opc-a", "opc-a") });
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>()).Returns(blocked);
_importer.PreviewAsync(session.SessionId, Arg.Any<CancellationToken>(), Arg.Is<BundleNameMap?>(m => m != null))
.Returns(resolved);
var cut = Render<TransportImportPage>();
await cut.InvokeAsync(() => SetField(cut.Instance, "_session", session));
await cut.InvokeAsync(async () =>
await InvokeAsyncMethod(cut.Instance, "LoadPreviewAndAdvanceAsync"));
await cut.InvokeAsync(async () =>
await InvokeAsyncMethod(cut.Instance, "OnSiteChoiceChangedAsync", "site-a", "site-b"));
await cut.InvokeAsync(async () => await InvokeAsyncMethod(cut.Instance, "GoToConfirm"));
Assert.Equal(
TransportImportPage.ImportWizardStep.Confirm,
GetField<TransportImportPage.ImportWizardStep>(cut.Instance, "_step"));
}
// ─────────────────────────────────────────────────────────────────────
// Test 9: the operator's Map choices fold into the BundleNameMap
// passed to ApplyAsync — a chosen target → MapToExisting, "Create new" →
@@ -773,7 +842,7 @@ public class TransportImportPageTests : BunitContext
=> throw new NotSupportedException("These tests seed sessions via OpenSession().");
/// <inheritdoc />
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
=> Task.FromResult(new ImportPreview(sessionId, new List<ImportPreviewItem>()));
/// <inheritdoc />
@@ -1025,7 +1094,7 @@ public class TransportImportPageTests : BunitContext
return (T)field.GetValue(obj)!;
}
private static async Task InvokeAsyncMethod(object obj, string name)
private static async Task InvokeAsyncMethod(object obj, string name, params object?[] args)
{
var method = obj.GetType().GetMethod(
name,
@@ -1033,7 +1102,7 @@ public class TransportImportPageTests : BunitContext
| System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Public)
?? throw new InvalidOperationException($"Method '{name}' not found on {obj.GetType()}.");
var task = (Task)method.Invoke(obj, Array.Empty<object?>())!;
var task = (Task)method.Invoke(obj, args)!;
await task;
}
@@ -93,7 +93,7 @@ public class TransportImportSessionDisposeRaceTests : BunitContext
}
/// <inheritdoc />
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
public Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
=> throw new NotSupportedException("Not exercised by these tests.");
/// <inheritdoc />
@@ -0,0 +1,47 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Deployment;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests.Configurations;
/// <summary>
/// DEP-3 (WP2 task 2.9): <c>SystemArtifactDeploymentRecord.PerSiteStatus</c> holds one
/// serialized result per site (~155 chars for a clean site, far more with error text), so a
/// 4000-character cap made Deploy Artifacts over ~25 sites fail AFTER every site had applied,
/// with nothing stamped. The column is unbounded (<c>nvarchar(max)</c>).
/// </summary>
public class SystemArtifactDeploymentRecordConfigurationTests : IDisposable
{
private readonly ScadaBridgeDbContext _context = SqliteTestHelper.CreateInMemoryContext();
/// <summary>Releases the resources held by this test class.</summary>
public void Dispose()
{
_context.Database.CloseConnection();
_context.Dispose();
}
/// <summary>The PerSiteStatus property has no maximum length.</summary>
[Fact]
public void PerSiteStatus_IsUnbounded()
{
var property = _context.Model.FindEntityType(typeof(SystemArtifactDeploymentRecord))!
.FindProperty(nameof(SystemArtifactDeploymentRecord.PerSiteStatus))!;
Assert.Null(property.GetMaxLength());
}
/// <summary>A status payload well past the old 4000-character cap round-trips intact.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PerSiteStatus_LargePayload_RoundTrips()
{
var status = new string('x', 20_000);
var record = new SystemArtifactDeploymentRecord("Artifacts", "alice") { PerSiteStatus = status };
_context.SystemArtifactDeploymentRecords.Add(record);
await _context.SaveChangesAsync();
_context.ChangeTracker.Clear();
var loaded = await _context.SystemArtifactDeploymentRecords.FindAsync(record.Id);
Assert.Equal(status, loaded!.PerSiteStatus);
}
}
@@ -4499,7 +4499,8 @@ public class ManagementActorTests : TestKit, IDisposable
Manifest = null!,
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5),
});
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>())
// TRN-3: the preview may run under the operator's explicit redirects, so match any map.
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>(), Arg.Any<Commons.Types.Transport.BundleNameMap?>())
.Returns(new Commons.Types.Transport.ImportPreview(
sessionId,
Array.Empty<Commons.Types.Transport.ImportPreviewItem>(),
@@ -4522,6 +4523,87 @@ public class ManagementActorTests : TestKit, IDisposable
return (sessionId, () => captured);
}
/// <summary>
/// TRN-3: an explicit --map-site / --map-connection redirect reaches the PREVIEW, so its
/// unresolved-connection blockers and auto-matches are computed against the mapped target.
/// </summary>
[Fact]
public void ImportBundleCommand_ExplicitRedirects_ArePassedToThePreview()
{
var (_, importer) = AddBundleSubstitutes();
var (sessionId, _) = ConfigureImportForMapping(
importer,
new[] { new Commons.Types.Transport.RequiredSiteMapping("site-a", "Site A", AutoMatchTargetIdentifier: null) },
new[] { new Commons.Types.Transport.RequiredConnectionMapping("site-a", "OPC1", AutoMatchTargetName: null) });
Commons.Types.Transport.BundleNameMap? previewMap = null;
importer.When(i => i.PreviewAsync(sessionId, Arg.Any<CancellationToken>(),
Arg.Any<Commons.Types.Transport.BundleNameMap?>()))
.Do(ci => previewMap = ci.ArgAt<Commons.Types.Transport.BundleNameMap?>(2));
var cmd = new ImportBundleCommand(
Convert.ToBase64String(new byte[] { 0x01 }), null, "overwrite",
SiteMappings: new[] { new SiteMappingSpec("site-a", "site-x") },
ConnectionMappings: new[] { new ConnectionMappingSpec("site-a", "OPC1", "OPC1") });
CreateActor().Tell(Envelope(cmd, "Administrator"));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.NotNull(previewMap);
var site = Assert.Single(previewMap!.Sites);
Assert.Equal(("site-a", Commons.Types.Transport.MappingAction.MapToExisting, "site-x"),
(site.SourceSiteIdentifier, site.Action, site.TargetSiteIdentifier));
Assert.Equal("OPC1", Assert.Single(previewMap.Connections).TargetConnectionName);
}
/// <summary>
/// TRN-9: --conflict-policy rename falls back to Skip (with a warning) for a site, data
/// connection, SMTP or SMS configuration, and still renames a template.
/// </summary>
[Fact]
public void ImportBundleCommand_RenamePolicy_FallsBackToSkipForUnsupportedTypes()
{
var (_, importer) = AddBundleSubstitutes();
var sessionId = Guid.NewGuid();
importer.LoadAsync(Arg.Any<Stream>(), Arg.Any<string?>(), Arg.Any<CancellationToken>(), Arg.Any<string?>())
.Returns(new Commons.Types.Transport.BundleSession
{
SessionId = sessionId,
Manifest = null!,
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5),
});
Commons.Types.Transport.ImportPreviewItem Modified(string type, string name) =>
new(type, name, null, null, Commons.Types.Transport.ConflictKind.Modified, "{}", null);
importer.PreviewAsync(sessionId, Arg.Any<CancellationToken>(), Arg.Any<Commons.Types.Transport.BundleNameMap?>())
.Returns(new Commons.Types.Transport.ImportPreview(sessionId, new[]
{
Modified("SmtpConfiguration", "smtp.example.com"),
Modified("Template", "Pump"),
}));
IReadOnlyList<Commons.Types.Transport.ImportResolution>? captured = null;
importer.ApplyAsync(
Arg.Any<Guid>(),
Arg.Do<IReadOnlyList<Commons.Types.Transport.ImportResolution>>(r => captured = r),
Arg.Any<string>(),
Arg.Any<CancellationToken>(),
Arg.Any<Commons.Types.Transport.BundleNameMap?>())
.Returns(new Commons.Types.Transport.ImportResult(
BundleImportId: Guid.NewGuid(),
Added: 0, Overwritten: 0, Skipped: 1, Renamed: 1,
StaleInstanceIds: Array.Empty<int>(),
AuditEventCorrelation: "correlation"));
CreateActor().Tell(Envelope(
new ImportBundleCommand(Convert.ToBase64String(new byte[] { 0x01 }), null, "rename"), "Administrator"));
var success = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.NotNull(captured);
var smtp = captured!.Single(r => r.EntityType == "SmtpConfiguration");
Assert.Equal(Commons.Types.Transport.ResolutionAction.Skip, smtp.Action);
Assert.Null(smtp.RenameTo);
var template = captured.Single(r => r.EntityType == "Template");
Assert.Equal(Commons.Types.Transport.ResolutionAction.Rename, template.Action);
Assert.Contains("Rename is not supported", success.JsonData);
}
/// <summary>Verifies that import bundle command, when explicit spec, overrides auto match.</summary>
[Fact]
public void ImportBundleCommand_ExplicitSpec_OverridesAutoMatch()
@@ -0,0 +1,215 @@
using System.Text.Json;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// CLI-2 (WP2 task 2.8): the site, data-connection and api-method update handlers are
/// preserve-if-null. A null command field keeps the stored value; an empty string
/// clears an optional field. Before the fix every field was assigned unconditionally,
/// so <c>site update --id 3 --name X</c> nulled both gRPC addresses and
/// <c>api-method update --script …</c> reset the timeout to 30 and dropped both
/// definitions.
/// </summary>
public class PartialUpdateHandlerTests : TestKit, IDisposable
{
private readonly ServiceCollection _services = new ServiceCollection().AddTestConfigurationTransaction();
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
private readonly IInboundApiRepository _apiRepo = Substitute.For<IInboundApiRepository>();
/// <summary>Initializes the harness with stubbed repositories.</summary>
public PartialUpdateHandlerTests()
{
_services.AddScoped(_ => _siteRepo);
_services.AddScoped(_ => _apiRepo);
_services.AddScoped(_ => Substitute.For<IAuditService>());
_apiRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
}
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
private IActorRef CreateActor() =>
Sys.ActorOf(Props.Create(() => new ManagementActor(
_services.BuildServiceProvider(), NullLogger<ManagementActor>.Instance)));
private static ManagementEnvelope Admin(object command) =>
new(new AuthenticatedUser("admin", "Admin", new[] { "Administrator", "Designer" }, Array.Empty<string>()),
command, Guid.NewGuid().ToString("N"));
private static Site StoredSite() => new("Plant", "site-3")
{
Id = 3,
Description = "desc",
NodeAAddress = "akka.tcp://scadabridge@a:8081",
NodeBAddress = "akka.tcp://scadabridge@b:8081",
GrpcNodeAAddress = "http://a:8083",
GrpcNodeBAddress = "http://b:8083",
};
/// <summary>A name-only site update keeps the description and all four addresses.</summary>
[Fact]
public void UpdateSite_NameOnly_PreservesEveryOtherField()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, "Plant 3", null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("Plant 3", site.Name);
Assert.Equal("desc", site.Description);
Assert.Equal("akka.tcp://scadabridge@a:8081", site.NodeAAddress);
Assert.Equal("akka.tcp://scadabridge@b:8081", site.NodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
Assert.Equal("http://b:8083", site.GrpcNodeBAddress);
}
/// <summary>An address-only site update keeps the name; an empty string clears a field.</summary>
[Fact]
public void UpdateSite_EmptyString_ClearsField_NullNameKeepsName()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, "", GrpcNodeBAddress: "")));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("Plant", site.Name);
Assert.Null(site.Description);
Assert.Null(site.GrpcNodeBAddress);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A preserved address is still validated; a malformed incoming one is refused.</summary>
[Fact]
public void UpdateSite_MalformedIncomingAddress_IsRefused()
{
var site = StoredSite();
_siteRepo.GetSiteByIdAsync(3, Arg.Any<CancellationToken>()).Returns(site);
CreateActor().Tell(Admin(new UpdateSiteCommand(3, null, null, GrpcNodeAAddress: "a:8083")));
var error = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(10));
Assert.Contains("GrpcNodeAAddress", error.Error);
Assert.Equal("http://a:8083", site.GrpcNodeAAddress);
}
/// <summary>A name-only data-connection update keeps protocol, both configs and the retry count.</summary>
[Fact]
public void UpdateDataConnection_NameOnly_PreservesConfigsAndRetryCount()
{
var conn = new DataConnection("c1", "OpcUa", 1)
{
Id = 7,
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p","UserIdentity":{"Password":"pw"}}""",
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
FailoverRetryCount = 9,
};
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, "renamed", null, null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("renamed", conn.Name);
Assert.Equal("OpcUa", conn.Protocol);
Assert.Contains("\"pw\"", conn.PrimaryConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://b"}""", conn.BackupConfiguration);
Assert.Equal(9, conn.FailoverRetryCount);
}
/// <summary>An empty backup configuration removes the backup endpoint.</summary>
[Fact]
public void UpdateDataConnection_EmptyBackup_RemovesBackup()
{
var conn = new DataConnection("c1", "OpcUa", 1)
{
Id = 7,
PrimaryConfiguration = """{"Endpoint":"opc.tcp://p"}""",
BackupConfiguration = """{"Endpoint":"opc.tcp://b"}""",
};
_siteRepo.GetDataConnectionByIdAsync(7, Arg.Any<CancellationToken>()).Returns(conn);
CreateActor().Tell(Admin(new UpdateDataConnectionCommand(7, null, null, null, "", 3)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Null(conn.BackupConfiguration);
Assert.Equal("""{"Endpoint":"opc.tcp://p"}""", conn.PrimaryConfiguration);
Assert.Equal(3, conn.FailoverRetryCount);
}
/// <summary>A script-only api-method update keeps the timeout and both definitions.</summary>
[Fact]
public void UpdateApiMethod_ScriptOnly_PreservesTimeoutAndDefinitions()
{
var method = new ApiMethod("M", "return 1;")
{
Id = 5,
TimeoutSeconds = 120,
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
ReturnDefinition = """[{"name":"y","type":"Integer"}]""",
};
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, "return 2;", null, null, null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("return 2;", method.Script);
Assert.Equal(120, method.TimeoutSeconds);
Assert.Equal("""[{"name":"x","type":"Integer"}]""", method.ParameterDefinitions);
Assert.Equal("""[{"name":"y","type":"Integer"}]""", method.ReturnDefinition);
}
/// <summary>A timeout-only api-method update keeps the script; "" clears a definition.</summary>
[Fact]
public void UpdateApiMethod_TimeoutOnly_KeepsScript_EmptyClearsDefinition()
{
var method = new ApiMethod("M", "return 1;")
{
Id = 5,
TimeoutSeconds = 30,
ParameterDefinitions = """[{"name":"x","type":"Integer"}]""",
};
_apiRepo.GetApiMethodByIdAsync(5, Arg.Any<CancellationToken>()).Returns(method);
CreateActor().Tell(Admin(new UpdateApiMethodCommand(5, null, 90, "", null)));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(10));
Assert.Equal("return 1;", method.Script);
Assert.Equal(90, method.TimeoutSeconds);
Assert.Null(method.ParameterDefinitions);
}
/// <summary>
/// Wire compatibility: an older CLI always sends every field (non-null ints included);
/// that payload must still deserialize into the now-nullable records with its values.
/// </summary>
[Fact]
public void OlderClientPayloads_StillDeserialize()
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var dc = JsonSerializer.Deserialize<UpdateDataConnectionCommand>(
"""{"DataConnectionId":7,"Name":"X","Protocol":"OpcUa","PrimaryConfiguration":"{}","BackupConfiguration":null,"FailoverRetryCount":3}""",
options)!;
Assert.Equal(new UpdateDataConnectionCommand(7, "X", "OpcUa", "{}", null, 3), dc);
var api = JsonSerializer.Deserialize<UpdateApiMethodCommand>(
"""{"ApiMethodId":5,"Script":"return 1;","TimeoutSeconds":30,"ParameterDefinitions":null,"ReturnDefinition":null}""",
options)!;
Assert.Equal(new UpdateApiMethodCommand(5, "return 1;", 30, null, null), api);
var site = JsonSerializer.Deserialize<UpdateSiteCommand>(
"""{"SiteId":3,"Name":"S","Description":null}""", options)!;
Assert.Equal(new UpdateSiteCommand(3, "S", null), site);
}
}
@@ -0,0 +1,279 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.TemplateEngine.Flattening;
namespace ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests.Flattening;
/// <summary>
/// WP2 tasks 2.2/2.3 — alarm on-trigger script references are resolved by NAME within
/// the alarm's own composition chain, not through a flatten-wide script-id map.
/// TPL-1: two slots of one module share the base script row id, so the global map made
/// every slot's alarm run the LAST slot's script. TPL-2: a derived script override has
/// a different row id, so the base alarm lost its on-trigger script. TPL-5: a nested
/// slot visited twice under one prefix let the base pass overwrite a slot-level
/// override. The fixes change the revision hash of affected configurations by design.
/// </summary>
public class AlarmOnTriggerScriptResolutionTests
{
private readonly FlatteningService _sut = new();
private static Instance CreateInstance(int templateId = 1) =>
new("TestInstance") { Id = 1, TemplateId = templateId, SiteId = 1 };
private static Template CreateTemplate(int id, string name, int? parentId = null) =>
new(name) { Id = id, ParentTemplateId = parentId };
private static TemplateAlarm Alarm(string name, int? scriptId, bool inherited = false) => new(name)
{
TriggerType = AlarmTriggerType.RangeViolation,
TriggerConfiguration = "{\"attributeName\":\"Temp\",\"high\":100}",
PriorityLevel = 1,
OnTriggerScriptId = scriptId,
IsInherited = inherited,
};
/// <summary>
/// Builds the slot-derived template the composition service creates for a slot:
/// a child of <paramref name="baseTemplate"/> whose members are IsInherited
/// placeholders (placeholder alarms keep pointing at the BASE script id).
/// </summary>
private static Template SlotDerived(int id, Template baseTemplate, int scriptPlaceholderId)
{
var t = CreateTemplate(id, $"{baseTemplate.Name}_slot{id}", baseTemplate.Id);
foreach (var s in baseTemplate.Scripts)
t.Scripts.Add(new TemplateScript(s.Name, s.Code) { Id = scriptPlaceholderId++, IsInherited = true });
foreach (var a in baseTemplate.Alarms)
t.Alarms.Add(Alarm(a.Name, a.OnTriggerScriptId, inherited: true));
return t;
}
/// <summary>TPL-1: each slot's alarm runs its OWN slot's script.</summary>
[Fact]
public void TwoSlotsOfOneModule_EachAlarmResolvesItsOwnSlotScript()
{
var pump = CreateTemplate(10, "Pump");
pump.Scripts.Add(new TemplateScript("OnHigh", "// on high") { Id = 100 });
pump.Alarms.Add(Alarm("HighTemp", 100));
var pump1 = SlotDerived(11, pump, 110);
var pump2 = SlotDerived(12, pump, 120);
var skid = CreateTemplate(1, "Skid");
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition>
{
new("Pump1") { ComposedTemplateId = 11 },
new("Pump2") { ComposedTemplateId = 12 },
},
};
var chains = new Dictionary<int, IReadOnlyList<Template>>
{
[11] = [pump1, pump],
[12] = [pump2, pump],
};
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("Pump1.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.HighTemp").OnTriggerScriptCanonicalName);
Assert.Equal("Pump2.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "Pump2.HighTemp").OnTriggerScriptCanonicalName);
}
/// <summary>TPL-1 with the base template composed directly into two slots (one shared chain).</summary>
[Fact]
public void SameTemplateComposedDirectlyTwice_EachAlarmResolvesItsOwnSlotScript()
{
var pump = CreateTemplate(10, "Pump");
pump.Scripts.Add(new TemplateScript("OnHigh", "// on high") { Id = 100 });
pump.Alarms.Add(Alarm("HighTemp", 100));
var skid = CreateTemplate(1, "Skid");
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition>
{
new("A") { ComposedTemplateId = 10 },
new("B") { ComposedTemplateId = 10 },
},
};
var chains = new Dictionary<int, IReadOnlyList<Template>> { [10] = [pump] };
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("A.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "A.HighTemp").OnTriggerScriptCanonicalName);
Assert.Equal("B.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "B.HighTemp").OnTriggerScriptCanonicalName);
}
/// <summary>
/// TPL-5: a slot-level override that clears a nested alarm's on-trigger script is
/// not overwritten by the second (base) visit of the same nested slot.
/// </summary>
[Fact]
public void NestedSlotOverride_ClearingOnTriggerScript_IsNotOverwrittenByBasePass()
{
// Motor(5) has OnOverload(500) and alarm Overload -> 500.
var motor = CreateTemplate(5, "Motor");
motor.Scripts.Add(new TemplateScript("OnOverload", "// overload") { Id = 500 });
motor.Alarms.Add(Alarm("Overload", 500));
// Pump(3) composes Motor via its slot-derived Motor (6).
var pump = CreateTemplate(3, "Pump");
var pumpMotor = SlotDerived(6, motor, 600);
// Skid's slot Pump1 is a slot-derived Pump (2) with its own slot-derived Motor (7, child of 6),
// on which the operator overrode Overload to have NO on-trigger script.
var pump1 = CreateTemplate(2, "Pump_slot2", 3);
var pump1Motor = SlotDerived(7, pumpMotor, 700);
pump1Motor.ParentTemplateId = 6;
pump1Motor.Alarms.Clear();
pump1Motor.Alarms.Add(Alarm("Overload", scriptId: null, inherited: false));
var skid = CreateTemplate(1, "Skid");
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition> { new("Pump1") { ComposedTemplateId = 2 } },
[2] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 7 } },
[3] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 6 } },
};
var chains = new Dictionary<int, IReadOnlyList<Template>>
{
[2] = [pump1, pump],
[7] = [pump1Motor, pumpMotor, motor],
[6] = [pumpMotor, motor],
};
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
var alarm = result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.Motor.Overload");
Assert.Null(alarm.OnTriggerScriptCanonicalName);
}
/// <summary>TPL-5: a slot-level override that re-points the nested alarm keeps the new script.</summary>
[Fact]
public void NestedSlotOverride_RepointingOnTriggerScript_Wins()
{
var motor = CreateTemplate(5, "Motor");
motor.Scripts.Add(new TemplateScript("OnOverload", "// overload") { Id = 500 });
motor.Scripts.Add(new TemplateScript("OnOverloadAlt", "// alt") { Id = 501 });
motor.Alarms.Add(Alarm("Overload", 500));
var pump = CreateTemplate(3, "Pump");
var pumpMotor = SlotDerived(6, motor, 600);
var pump1 = CreateTemplate(2, "Pump_slot2", 3);
var pump1Motor = SlotDerived(7, pumpMotor, 700);
pump1Motor.ParentTemplateId = 6;
pump1Motor.Alarms.Clear();
pump1Motor.Alarms.Add(Alarm("Overload", scriptId: 501, inherited: false));
var skid = CreateTemplate(1, "Skid");
var compositions = new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition> { new("Pump1") { ComposedTemplateId = 2 } },
[2] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 7 } },
[3] = new List<TemplateComposition> { new("Motor") { ComposedTemplateId = 6 } },
};
var chains = new Dictionary<int, IReadOnlyList<Template>>
{
[2] = [pump1, pump],
[7] = [pump1Motor, pumpMotor, motor],
[6] = [pumpMotor, motor],
};
var result = _sut.Flatten(CreateInstance(), [skid], compositions, chains, new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("Pump1.Motor.OnOverloadAlt",
result.Value.Alarms.Single(a => a.CanonicalName == "Pump1.Motor.Overload").OnTriggerScriptCanonicalName);
}
/// <summary>
/// TPL-2: a derived template that overrides the on-trigger script (a new row with a
/// different id) keeps the base alarm's link, and the overridden code is what runs.
/// </summary>
[Fact]
public void DerivedScriptOverride_KeepsBaseAlarmOnTriggerLink()
{
var tank = CreateTemplate(1, "Tank");
tank.Scripts.Add(new TemplateScript("OnHighLevel", "// base") { Id = 10 });
tank.Alarms.Add(Alarm("HighLevel", 10));
var heater = CreateTemplate(2, "TankWithHeater", 1);
heater.Scripts.Add(new TemplateScript("OnHighLevel", "// derived") { Id = 20, IsInherited = false });
heater.Alarms.Add(Alarm("HighLevel", 10, inherited: true));
var result = _sut.Flatten(CreateInstance(templateId: 2), [heater, tank],
new Dictionary<int, IReadOnlyList<TemplateComposition>>(),
new Dictionary<int, IReadOnlyList<Template>>(),
new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("OnHighLevel", result.Value.Alarms.Single(a => a.CanonicalName == "HighLevel").OnTriggerScriptCanonicalName);
Assert.Equal("// derived", result.Value.Scripts.Single(s => s.CanonicalName == "OnHighLevel").Code);
}
/// <summary>TPL-2 for a composed module: a derived-module override keeps the slot alarm's link.</summary>
[Fact]
public void DerivedScriptOverride_InComposedModule_KeepsLink()
{
var pump = CreateTemplate(10, "Pump");
pump.Scripts.Add(new TemplateScript("OnHigh", "// base") { Id = 100 });
pump.Alarms.Add(Alarm("HighTemp", 100));
var slot = SlotDerived(11, pump, 110);
slot.Scripts.Clear();
slot.Scripts.Add(new TemplateScript("OnHigh", "// slot override") { Id = 111, IsInherited = false });
var skid = CreateTemplate(1, "Skid");
var result = _sut.Flatten(CreateInstance(), [skid],
new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition> { new("P") { ComposedTemplateId = 11 } },
},
new Dictionary<int, IReadOnlyList<Template>> { [11] = [slot, pump] },
new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("P.OnHigh", result.Value.Alarms.Single(a => a.CanonicalName == "P.HighTemp").OnTriggerScriptCanonicalName);
Assert.Equal("// slot override", result.Value.Scripts.Single(s => s.CanonicalName == "P.OnHigh").Code);
}
/// <summary>
/// Legacy fallback kept: an alarm whose on-trigger script id is not a script row of its
/// own chain (here a root alarm pointing at a composed module's script) still resolves
/// through the flatten-wide id map, as before.
/// </summary>
[Fact]
public void OutOfChainScriptId_StillResolvesThroughLegacyIdMap()
{
var pump = CreateTemplate(2, "Pump");
pump.Scripts.Add(new TemplateScript("Handler", "// h") { Id = 60 });
var station = CreateTemplate(1, "Station");
station.Alarms.Add(Alarm("StationAlarm", 60));
var result = _sut.Flatten(CreateInstance(), [station],
new Dictionary<int, IReadOnlyList<TemplateComposition>>
{
[1] = new List<TemplateComposition> { new("Main") { ComposedTemplateId = 2 } },
},
new Dictionary<int, IReadOnlyList<Template>> { [2] = [pump] },
new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Equal("Main.Handler", result.Value.Alarms.Single(a => a.CanonicalName == "StationAlarm").OnTriggerScriptCanonicalName);
}
/// <summary>A dangling on-trigger script id still resolves to null.</summary>
[Fact]
public void DanglingScriptId_ResolvesToNull()
{
var t = CreateTemplate(1, "T");
t.Alarms.Add(Alarm("A", 999));
var result = _sut.Flatten(CreateInstance(), [t],
new Dictionary<int, IReadOnlyList<TemplateComposition>>(),
new Dictionary<int, IReadOnlyList<Template>>(),
new Dictionary<int, DataConnection>());
Assert.True(result.IsSuccess);
Assert.Null(result.Value.Alarms.Single().OnTriggerScriptCanonicalName);
}
}
@@ -0,0 +1,182 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
/// <summary>
/// WP2 task 2.6 — template Overwrite and the composition rewire.
/// TRN-4: a bundle template with no compositions skipped the clear, so the target's
/// slots survived an Overwrite the preview said would remove them.
/// TRN-5: the rewire deleted a removed slot's row without its slot-owned derived
/// template, leaving an orphan with a dangling <c>OwnerCompositionId</c>.
/// </summary>
public sealed class CompositionOverwriteTests : IDisposable
{
private readonly ServiceProvider _provider;
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
public CompositionOverwriteTests()
{
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
var dbName = $"CompositionOverwriteTests_{Guid.NewGuid()}";
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
.UseInMemoryDatabase(dbName)
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
services.AddScoped<INotificationRepository, NotificationRepository>();
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
services.AddScoped<IAuditService, AuditService>();
services.AddTransport();
_provider = services.BuildServiceProvider();
}
/// <summary>Releases the resources held by this instance.</summary>
public void Dispose() => _provider.Dispose();
/// <summary>TRN-4: Overwrite with a composition-less bundle template removes the target's slots.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Overwrite_with_no_bundle_compositions_removes_target_compositions()
{
await SeedAsync(ctx =>
{
ctx.Templates.Add(new Template("B"));
ctx.Templates.Add(new Template("A"));
});
var bundle = await ExportAllTemplatesAsync();
// Target: A now composes B as b1.
await SeedAsync(ctx =>
{
var a = ctx.Templates.Single(t => t.Name == "A");
var b = ctx.Templates.Single(t => t.Name == "B");
ctx.TemplateCompositions.Add(new TemplateComposition("b1") { TemplateId = a.Id, ComposedTemplateId = b.Id });
});
await ImportOverwriteAsync(bundle, "A", "B");
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
Assert.False(await ctx.TemplateCompositions.AnyAsync(c => c.TemplateId == aId));
}
/// <summary>
/// TRN-5: target owner has slot S1 with a slot-owned derived template; the bundle
/// owner has only S2. Overwrite removes S1 AND its derived template.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Overwrite_removing_a_slot_deletes_its_slot_owned_derived_template()
{
// Source: A composes B directly as S2.
await SeedAsync(ctx =>
{
ctx.Templates.Add(new Template("B"));
ctx.Templates.Add(new Template("A"));
});
await SeedAsync(ctx =>
{
var a = ctx.Templates.Single(t => t.Name == "A");
var b = ctx.Templates.Single(t => t.Name == "B");
ctx.TemplateCompositions.Add(new TemplateComposition("S2") { TemplateId = a.Id, ComposedTemplateId = b.Id });
});
var bundle = await ExportAllTemplatesAsync();
// Target: drop S2; A instead owns slot S1 whose composed template is a
// slot-owned derived template of B.
await SeedAsync(ctx =>
{
ctx.TemplateCompositions.RemoveRange(ctx.TemplateCompositions);
});
int derivedId = 0;
await SeedAsync(ctx =>
{
var a = ctx.Templates.Single(t => t.Name == "A");
var b = ctx.Templates.Single(t => t.Name == "B");
var derived = new Template("A.S1") { ParentTemplateId = b.Id, IsDerived = true };
ctx.Templates.Add(derived);
ctx.SaveChanges();
var slot = new TemplateComposition("S1") { TemplateId = a.Id, ComposedTemplateId = derived.Id };
ctx.TemplateCompositions.Add(slot);
ctx.SaveChanges();
derived.OwnerCompositionId = slot.Id;
derivedId = derived.Id;
});
await ImportOverwriteAsync(bundle, "A", "B");
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
var slots = await ctx.TemplateCompositions.Where(c => c.TemplateId == aId).Select(c => c.InstanceName).ToListAsync();
Assert.Equal(new[] { "S2" }, slots);
Assert.False(await ctx.Templates.AnyAsync(t => t.Id == derivedId),
"the removed slot's derived template must be deleted with it");
}
private async Task SeedAsync(Action<ScadaBridgeDbContext> seed)
{
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
seed(ctx);
await ctx.SaveChangesAsync();
}
private async Task<byte[]> ExportAllTemplatesAsync()
{
await using var scope = _provider.CreateAsyncScope();
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var templateIds = await ctx.Templates.Select(t => t.Id).ToListAsync();
var selection = new ExportSelection(
TemplateIds: templateIds,
SharedScriptIds: Array.Empty<int>(),
ExternalSystemIds: Array.Empty<int>(),
DatabaseConnectionIds: Array.Empty<int>(),
NotificationListIds: Array.Empty<int>(),
SmtpConfigurationIds: Array.Empty<int>(),
ApiMethodIds: Array.Empty<int>(),
IncludeDependencies: false);
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
passphrase: null, cancellationToken: CancellationToken.None);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
return ms.ToArray();
}
private async Task ImportOverwriteAsync(byte[] bundle, params string[] templateNames)
{
Guid sessionId;
await using (var scope = _provider.CreateAsyncScope())
{
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
using var input = new MemoryStream(bundle, writable: false);
sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId;
}
await using (var scope = _provider.CreateAsyncScope())
{
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
await importer.ApplyAsync(sessionId,
templateNames.Select(n => new ImportResolution("Template", n, ResolutionAction.Overwrite, null)).ToList(),
user: "bob");
}
}
}
@@ -0,0 +1,520 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
using ZB.MOM.WW.ScadaBridge.Transport.Serialization;
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
/// <summary>
/// WP2 tasks 2.4 + 2.5 against the real importer and an EF context:
/// TRN-2 (a changed secret-bearing value reads Modified, value-free), TRN-6 (instance diff
/// compares the bound connection, not State), TRN-3 (preview honours the name map; CreateNew
/// against an existing same-name row maps to it), TRN-7 (site-scoped and template-reference
/// lookups are case-insensitive), TRN-8 (areas resolve by full path), TRN-9 (Rename is
/// rejected for sites / data connections / SMTP / SMS).
/// </summary>
public sealed class ImportMappingAndIdentityTests : IDisposable
{
private readonly ServiceProvider _provider;
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
public ImportMappingAndIdentityTests()
{
var services = new ServiceCollection();
services.AddSingleton<Microsoft.AspNetCore.DataProtection.IDataProtectionProvider>(
new Microsoft.AspNetCore.DataProtection.EphemeralDataProtectionProvider());
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
var dbName = $"ImportMappingAndIdentityTests_{Guid.NewGuid()}";
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
.UseInMemoryDatabase(dbName)
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
services.AddScoped<INotificationRepository, NotificationRepository>();
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
services.AddScoped<IAuditService, AuditService>();
services.AddTransport();
_provider = services.BuildServiceProvider();
}
/// <summary>Releases the resources held by this instance.</summary>
public void Dispose() => _provider.Dispose();
// ── TRN-2 / TRN-6 (task 2.4) ─────────────────────────────────────────────
/// <summary>TRN-2: a target whose connection endpoint changed previews Modified, never echoing the config.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Preview_changed_connection_configuration_is_Modified_without_echo()
{
await SeedSiteAsync("plant-1", ("OPC1", "{\"endpoint\":\"opc.tcp://source-host:4840\"}"));
var sessionId = await ExportSitesAndLoadAsync();
await MutateAsync(ctx => ctx.DataConnections.Single().PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://target-host:4840\"}");
var preview = await PreviewAsync(sessionId);
var item = preview.Items.Single(i => i.EntityType == "DataConnection");
Assert.Equal(ConflictKind.Modified, item.Kind);
using var diff = System.Text.Json.JsonDocument.Parse(item.FieldDiffJson!);
var change = diff.RootElement.GetProperty("changes").EnumerateArray()
.Single(c => c.GetProperty("field").GetString() == "Secrets.PrimaryConfiguration");
Assert.Equal("<changed>", change.GetProperty("newValue").GetString());
Assert.DoesNotContain("source-host", item.FieldDiffJson);
Assert.DoesNotContain("target-host", item.FieldDiffJson);
}
/// <summary>TRN-6: rebinding an attribute to another connection previews Modified; a State-only change is Identical.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Preview_instance_diff_covers_bound_connection_and_ignores_state()
{
await SeedSiteAsync("plant-1", ("OPC1", "{}"), ("OPC2", "{}"));
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1");
var sessionId = await ExportSitesAndLoadAsync();
// State only: Identical.
await MutateAsync(ctx => ctx.Instances.Single().State = InstanceState.Disabled);
var stateOnly = await PreviewAsync(sessionId);
Assert.Equal(ConflictKind.Identical, stateOnly.Items.Single(i => i.EntityType == "Instance").Kind);
// Rebind OPC1 -> OPC2 on the target: Modified.
await MutateAsync(ctx =>
{
var opc2 = ctx.DataConnections.Single(c => c.Name == "OPC2");
ctx.InstanceConnectionBindings.Single().DataConnectionId = opc2.Id;
});
var rebound = await PreviewAsync(sessionId);
var item = rebound.Items.Single(i => i.EntityType == "Instance");
Assert.Equal(ConflictKind.Modified, item.Kind);
Assert.Contains("ConnectionBindings", item.FieldDiffJson);
}
// ── TRN-3 (task 2.5) ─────────────────────────────────────────────────────
/// <summary>
/// TRN-3 scenario A: an instance-only bundle for site-a bound to OPC1, imported with
/// site-a mapped to site-x (which has OPC1). The unmapped preview blocks; the mapped
/// preview does not, auto-matches the connection on the mapped site, and the apply binds it.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Preview_with_site_map_resolves_connection_on_the_mapped_site()
{
await SeedTemplateAsync("Pump");
await SeedSiteAsync("site-x", ("OPC1", "{}"));
var sessionId = await PackAndLoadAsync(Content(instances:
[
Instance("Pump-01", "site-a", bindings: [new InstanceConnectionBindingDto("Flow", "OPC1", "ns=2;s=Flow")]),
]));
var unmapped = await PreviewAsync(sessionId);
Assert.Contains(unmapped.Items, i => i.Kind == ConflictKind.Blocker && i.Name == "site-a/OPC1");
var map = new BundleNameMap(
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
Array.Empty<ConnectionMapping>());
var mapped = await PreviewAsync(sessionId, map);
Assert.DoesNotContain(mapped.Items, i => i.Kind == ConflictKind.Blocker);
Assert.Equal("site-x", mapped.RequiredSiteMappings.Single().AutoMatchTargetIdentifier);
Assert.Equal("OPC1", mapped.RequiredConnectionMappings.Single().AutoMatchTargetName);
await ApplyAsync(sessionId,
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)],
map with
{
Connections = [new ConnectionMapping("site-a", "OPC1", MappingAction.MapToExisting, "OPC1")],
});
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var siteX = await ctx.Sites.SingleAsync(s => s.SiteIdentifier == "site-x");
var opc1 = await ctx.DataConnections.SingleAsync(c => c.SiteId == siteX.Id && c.Name == "OPC1");
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
Assert.Equal(siteX.Id, instance.SiteId);
Assert.Equal(opc1.Id, instance.ConnectionBindings.Single().DataConnectionId);
}
/// <summary>
/// TRN-3 scenario B: CreateNew for a carried connection whose name already exists on the
/// mapped target site maps to the existing row instead of inserting a duplicate.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CreateNew_connection_with_existing_name_on_mapped_site_maps_to_it()
{
await SeedSiteAsync("site-x", ("OPC1", "{\"endpoint\":\"target\"}"));
var sessionId = await PackAndLoadAsync(Content(connections:
[
new DataConnectionDto("site-a", "OPC1", "OpcUa", 3,
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{\"endpoint\":\"source\"}" })),
]));
await ApplyAsync(sessionId,
[new ImportResolution("DataConnection", "site-a/OPC1", ResolutionAction.Skip, null)],
new BundleNameMap(
[new SiteMapping("site-a", MappingAction.MapToExisting, "site-x")],
[new ConnectionMapping("site-a", "OPC1", MappingAction.CreateNew, null)]));
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var conn = await ctx.DataConnections.SingleAsync();
Assert.Equal("{\"endpoint\":\"target\"}", conn.PrimaryConfiguration);
}
// ── TRN-7 (task 2.5) ─────────────────────────────────────────────────────
/// <summary>
/// TRN-7: a bundle connection differing only in case matches the target row (preview is
/// not New, apply does not insert a duplicate the unique (SiteId, Name) index would reject),
/// and an instance binding naming it in a different case resolves to it. (The instance
/// UniqueName half of TRN-7 depends on the SQL Server collation returning the case
/// variant from the repository read, which the in-memory provider does not emulate; the
/// importer's own lookups over that read are case-insensitive.)
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Case_variant_connection_matches_existing_row()
{
await SeedTemplateAsync("Pump");
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
var sessionId = await PackAndLoadAsync(Content(
sites: [new SiteDto("plant-1", "plant-1", null, null, null, null, null)],
connections: [new DataConnectionDto("plant-1", "Opc1", "OpcUa", 3,
new SecretsBlock(new Dictionary<string, string> { ["PrimaryConfiguration"] = "{}" }))],
instances: [Instance("Pump-01", "plant-1", bindings: [new InstanceConnectionBindingDto("Flow", "opc1", null)])]));
var preview = await PreviewAsync(sessionId);
Assert.Equal(ConflictKind.Identical, preview.Items.Single(i => i.EntityType == "DataConnection").Kind);
Assert.DoesNotContain(preview.Items, i => i.Kind == ConflictKind.Blocker);
await ApplyAsync(sessionId,
[
new ImportResolution("DataConnection", "plant-1/Opc1", ResolutionAction.Overwrite, null),
new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null),
],
BundleNameMap.Empty);
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var conn = await ctx.DataConnections.SingleAsync();
var instance = await ctx.Instances.Include(i => i.ConnectionBindings).SingleAsync();
Assert.Equal(conn.Id, instance.ConnectionBindings.Single().DataConnectionId);
}
/// <summary>
/// TRN-7: a child whose bundle base is 'PumpBase' resolves its inheritance edge against
/// the target's 'pumpbase' (the base itself is not re-imported) instead of nulling it.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Case_variant_base_template_keeps_child_inheritance_edge()
{
await MutateAsync(ctx => ctx.Templates.Add(new Template("PumpBase")));
await MutateAsync(ctx => ctx.Templates.Add(new Template("Child") { ParentTemplateId = ctx.Templates.Single(t => t.Name == "PumpBase").Id }));
var bundle = await ExportTemplatesAsync();
await MutateAsync(ctx => ctx.Templates.Single(t => t.Name == "PumpBase").Name = "pumpbase");
var sessionId = await LoadAsync(bundle);
await ApplyAsync(sessionId,
[
new ImportResolution("Template", "PumpBase", ResolutionAction.Skip, null),
new ImportResolution("Template", "Child", ResolutionAction.Overwrite, null),
],
BundleNameMap.Empty);
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var baseId = await ctx.Templates.Where(t => t.Name == "pumpbase").Select(t => t.Id).SingleAsync();
var child = await ctx.Templates.SingleAsync(t => t.Name == "Child");
Assert.Equal(baseId, child.ParentTemplateId);
}
// ── TRN-8 (task 2.5) ─────────────────────────────────────────────────────
/// <summary>TRN-8: an instance in Line2/Cell lands in Line2/Cell, not whichever 'Cell' comes back first.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Area_resolves_by_full_path_when_leaf_name_is_shared()
{
await SeedSiteAsync("plant-1", ("OPC1", "{}"));
var (line1Cell, line2Cell) = await SeedTwoCellsAsync("plant-1");
await SeedInstanceAsync("plant-1", "Pump-01", boundTo: "OPC1", areaId: line2Cell);
var sessionId = await ExportSitesAndLoadAsync();
// Target: move the instance to Line1/Cell, then Overwrite from the bundle.
await MutateAsync(ctx => ctx.Instances.Single().AreaId = line1Cell);
var preview = await PreviewAsync(sessionId);
var item = preview.Items.Single(i => i.EntityType == "Instance");
Assert.Equal(ConflictKind.Modified, item.Kind);
Assert.Contains("AreaPath", item.FieldDiffJson);
await ApplyAsync(sessionId,
[new ImportResolution("Instance", "Pump-01", ResolutionAction.Overwrite, null)],
BundleNameMap.Empty);
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
Assert.Equal(line2Cell, (await ctx.Instances.SingleAsync()).AreaId);
Assert.Equal(4, await ctx.Areas.CountAsync()); // Line1, Line2 and both Cells — nothing created
}
/// <summary>TRN-8: a missing nested area is created under its real parent, not at the site root.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Missing_nested_area_is_created_under_its_parent()
{
await SeedTemplateAsync("Pump");
await SeedSiteAsync("plant-1");
var sessionId = await PackAndLoadAsync(Content(instances:
[
Instance("Pump-01", "plant-1") with { AreaName = "Cell", AreaPath = ["Line2", "Cell"] },
]));
await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var line2 = await ctx.Areas.SingleAsync(a => a.Name == "Line2");
var cell = await ctx.Areas.SingleAsync(a => a.Name == "Cell");
Assert.Null(line2.ParentAreaId);
Assert.Equal(line2.Id, cell.ParentAreaId);
Assert.Equal(cell.Id, (await ctx.Instances.SingleAsync()).AreaId);
}
/// <summary>TRN-8: a legacy (path-less) bundle with an ambiguous leaf name warns instead of guessing silently.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Legacy_ambiguous_leaf_area_name_warns()
{
await SeedTemplateAsync("Pump");
await SeedSiteAsync("plant-1");
await SeedTwoCellsAsync("plant-1");
var sessionId = await PackAndLoadAsync(Content(instances:
[
Instance("Pump-01", "plant-1") with { AreaName = "Cell" },
]));
var result = await ApplyAsync(sessionId, [new ImportResolution("Instance", "Pump-01", ResolutionAction.Add, null)], BundleNameMap.Empty);
Assert.Contains(result.Warnings, w => w.Contains("area 'Cell' matches 2 areas"));
}
// ── TRN-9 (task 2.5) ─────────────────────────────────────────────────────
/// <summary>TRN-9: Rename is rejected for sites, data connections, SMTP and SMS configurations.</summary>
/// <param name="entityType">The resolution's entity type.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData("Site")]
[InlineData("DataConnection")]
[InlineData("SmtpConfiguration")]
[InlineData("SmsConfiguration")]
public async Task Rename_is_rejected_for_unsupported_entity_types(string entityType)
{
var sessionId = await PackAndLoadAsync(Content());
var ex = await Assert.ThrowsAsync<ArgumentException>(() => ApplyAsync(sessionId,
[new ImportResolution(entityType, "x", ResolutionAction.Rename, "y")], BundleNameMap.Empty));
Assert.Contains("Rename is not supported", ex.Message);
}
// ── helpers ──────────────────────────────────────────────────────────────
private async Task MutateAsync(Action<ScadaBridgeDbContext> mutate)
{
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
mutate(ctx);
await ctx.SaveChangesAsync();
}
private Task SeedTemplateAsync(string name) => MutateAsync(ctx =>
{
var t = new Template(name);
t.Attributes.Add(new TemplateAttribute("Flow") { Value = "0" });
ctx.Templates.Add(t);
});
private async Task SeedSiteAsync(string identifier, params (string Name, string Config)[] connections)
{
await MutateAsync(ctx => ctx.Sites.Add(new Site(identifier, identifier)));
await MutateAsync(ctx =>
{
var site = ctx.Sites.Single(s => s.SiteIdentifier == identifier);
foreach (var (name, config) in connections)
ctx.DataConnections.Add(new DataConnection(name, "OpcUa", site.Id) { PrimaryConfiguration = config, FailoverRetryCount = 3 });
});
}
private async Task SeedInstanceAsync(string siteIdentifier, string name, string boundTo, int? areaId = null)
{
if (!await AnyTemplateAsync()) await SeedTemplateAsync("Pump");
await MutateAsync(ctx =>
{
var site = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier);
var conn = ctx.DataConnections.Single(c => c.SiteId == site.Id && c.Name == boundTo);
var instance = new Instance(name)
{
TemplateId = ctx.Templates.First().Id, SiteId = site.Id, State = InstanceState.Enabled, AreaId = areaId,
};
instance.ConnectionBindings.Add(new InstanceConnectionBinding("Flow")
{
DataConnectionId = conn.Id, DataSourceReferenceOverride = "ns=2;s=Flow",
});
ctx.Instances.Add(instance);
});
}
private async Task<bool> AnyTemplateAsync()
{
await using var scope = _provider.CreateAsyncScope();
return await scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().Templates.AnyAsync();
}
private async Task<(int Line1Cell, int Line2Cell)> SeedTwoCellsAsync(string siteIdentifier)
{
int line1Cell = 0, line2Cell = 0;
await MutateAsync(ctx =>
{
var siteId = ctx.Sites.Single(s => s.SiteIdentifier == siteIdentifier).Id;
ctx.Areas.Add(new Area("Line1") { SiteId = siteId });
ctx.Areas.Add(new Area("Line2") { SiteId = siteId });
});
await MutateAsync(ctx =>
{
var line1 = ctx.Areas.Single(a => a.Name == "Line1");
var line2 = ctx.Areas.Single(a => a.Name == "Line2");
ctx.Areas.Add(new Area("Cell") { SiteId = line1.SiteId, ParentAreaId = line1.Id });
ctx.Areas.Add(new Area("Cell") { SiteId = line2.SiteId, ParentAreaId = line2.Id });
});
await using var scope = _provider.CreateAsyncScope();
var c = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var l1 = await c.Areas.SingleAsync(a => a.Name == "Line1");
var l2 = await c.Areas.SingleAsync(a => a.Name == "Line2");
line1Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l1.Id)).Id;
line2Cell = (await c.Areas.SingleAsync(a => a.Name == "Cell" && a.ParentAreaId == l2.Id)).Id;
return (line1Cell, line2Cell);
}
private static InstanceDto Instance(string name, string site, IReadOnlyList<InstanceConnectionBindingDto>? bindings = null) =>
new(name, "Pump", site, AreaName: null, InstanceState.NotDeployed,
Array.Empty<InstanceAttributeOverrideDto>(),
Array.Empty<InstanceAlarmOverrideDto>(),
Array.Empty<InstanceNativeAlarmSourceOverrideDto>(),
bindings ?? Array.Empty<InstanceConnectionBindingDto>());
private static BundleContentDto Content(
IReadOnlyList<SiteDto>? sites = null,
IReadOnlyList<DataConnectionDto>? connections = null,
IReadOnlyList<InstanceDto>? instances = null) =>
new(
TemplateFolders: Array.Empty<TemplateFolderDto>(),
Templates: Array.Empty<TemplateDto>(),
SharedScripts: Array.Empty<SharedScriptDto>(),
ExternalSystems: Array.Empty<ExternalSystemDto>(),
DatabaseConnections: Array.Empty<DatabaseConnectionDto>(),
NotificationLists: Array.Empty<NotificationListDto>(),
SmtpConfigs: Array.Empty<SmtpConfigDto>(),
ApiMethods: Array.Empty<ApiMethodDto>())
{
Sites = sites ?? Array.Empty<SiteDto>(),
DataConnections = connections ?? Array.Empty<DataConnectionDto>(),
Instances = instances ?? Array.Empty<InstanceDto>(),
};
private async Task<Guid> PackAndLoadAsync(BundleContentDto content)
{
await using var scope = _provider.CreateAsyncScope();
var manifestBuilder = scope.ServiceProvider.GetRequiredService<ManifestBuilder>();
var serializer = scope.ServiceProvider.GetRequiredService<BundleSerializer>();
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
var summary = new BundleSummary(
Templates: 0, TemplateFolders: 0, SharedScripts: 0, ExternalSystems: 0, DbConnections: 0,
NotificationLists: 0, SmtpConfigs: 0, ApiMethods: 0,
Sites: content.Sites.Count, DataConnections: content.DataConnections.Count, Instances: content.Instances.Count);
var manifest = manifestBuilder.Build(
sourceEnvironment: "dev", exportedBy: "alice", scadaBridgeVersion: "1.0.0", encryption: null,
summary: summary, contents: Array.Empty<ManifestContentEntry>(),
contentBytes: serializer.SerializeContentBytes(content));
await using var packed = serializer.Pack(content, manifest, passphrase: null, encryptor: null);
using var ms = new MemoryStream();
await packed.CopyToAsync(ms);
ms.Position = 0;
return (await importer.LoadAsync(ms, passphrase: null)).SessionId;
}
private async Task<Guid> ExportSitesAndLoadAsync()
{
byte[] bytes;
await using (var scope = _provider.CreateAsyncScope())
{
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var selection = new ExportSelection(
TemplateIds: Array.Empty<int>(), SharedScriptIds: Array.Empty<int>(),
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: true,
SiteIds: await ctx.Sites.Select(s => s.Id).ToListAsync());
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
passphrase: null, cancellationToken: CancellationToken.None);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
bytes = ms.ToArray();
}
return await LoadAsync(bytes);
}
private async Task<byte[]> ExportTemplatesAsync()
{
await using var scope = _provider.CreateAsyncScope();
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var selection = new ExportSelection(
TemplateIds: await ctx.Templates.Select(t => t.Id).ToListAsync(), SharedScriptIds: Array.Empty<int>(),
ExternalSystemIds: Array.Empty<int>(), DatabaseConnectionIds: Array.Empty<int>(),
NotificationListIds: Array.Empty<int>(), SmtpConfigurationIds: Array.Empty<int>(),
ApiMethodIds: Array.Empty<int>(), IncludeDependencies: false);
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
passphrase: null, cancellationToken: CancellationToken.None);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
return ms.ToArray();
}
private async Task<Guid> LoadAsync(byte[] bundle)
{
await using var scope = _provider.CreateAsyncScope();
using var ms = new MemoryStream(bundle, writable: false);
return (await scope.ServiceProvider.GetRequiredService<IBundleImporter>().LoadAsync(ms, passphrase: null)).SessionId;
}
private async Task<ImportPreview> PreviewAsync(Guid sessionId, BundleNameMap? map = null)
{
await using var scope = _provider.CreateAsyncScope();
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>().PreviewAsync(sessionId, CancellationToken.None, map);
}
private async Task<ImportResult> ApplyAsync(Guid sessionId, IReadOnlyList<ImportResolution> resolutions, BundleNameMap map)
{
await using var scope = _provider.CreateAsyncScope();
return await scope.ServiceProvider.GetRequiredService<IBundleImporter>()
.ApplyAsync(sessionId, resolutions, user: "bob", ct: CancellationToken.None, nameMap: map);
}
}
@@ -0,0 +1,173 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
/// <summary>
/// TRN-1 (WP2 task 2.1): a notification-list Overwrite must REPLACE the target's
/// recipients with the bundle's. <c>GetListByNameAsync</c> used to load the list
/// without its recipients, so the apply's <c>Recipients.Clear()</c> ran on an
/// unloaded collection, deleted nothing, and the bundle's recipients were appended
/// on top — duplicating shared recipients and keeping removed ones, with another
/// copy added on every re-import.
/// </summary>
public sealed class NotificationListOverwriteTests : IDisposable
{
private readonly ServiceProvider _provider;
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
public NotificationListOverwriteTests()
{
var services = new ServiceCollection();
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
var dbName = $"NotificationListOverwriteTests_{Guid.NewGuid()}";
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
.UseInMemoryDatabase(dbName)
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
services.AddScoped<INotificationRepository, NotificationRepository>();
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
services.AddScoped<IAuditService, AuditService>();
services.AddTransport();
_provider = services.BuildServiceProvider();
}
/// <summary>Releases the resources held by this instance.</summary>
public void Dispose() => _provider.Dispose();
/// <summary>
/// Target {A,B} + bundle {A,C} must end as exactly {A,C}, and a second
/// Overwrite import of the same bundle must leave it at {A,C}.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Overwrite_replaces_recipients_and_is_idempotent_on_reimport()
{
// Source state the bundle captures: {A, C}.
await using (var scope = _provider.CreateAsyncScope())
{
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var list = new NotificationList("Ops");
list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com"));
list.Recipients.Add(NotificationRecipient.ForEmail("C", "c@example.com"));
ctx.NotificationLists.Add(list);
await ctx.SaveChangesAsync();
}
var bundle = await ExportAsync();
// Turn the database into the target state: {A, B}.
await using (var scope = _provider.CreateAsyncScope())
{
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var list = await ctx.NotificationLists.Include(l => l.Recipients).SingleAsync(l => l.Name == "Ops");
var c = list.Recipients.Single(r => r.Name == "C");
list.Recipients.Remove(c);
ctx.Remove(c);
list.Recipients.Add(NotificationRecipient.ForEmail("B", "b@example.com"));
await ctx.SaveChangesAsync();
}
Assert.Equal(new[] { "A", "B" }, await RecipientNamesAsync());
await ImportOverwriteAsync(bundle);
Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync());
// Re-import the same bundle: still exactly {A, C}, no extra copies.
await ImportOverwriteAsync(bundle);
Assert.Equal(new[] { "A", "C" }, await RecipientNamesAsync());
}
/// <summary>
/// The repository method itself must return the list with its recipients — every
/// caller (importer, delivery adapters) relies on the navigation being populated.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task GetListByNameAsync_loads_recipients()
{
await using (var scope = _provider.CreateAsyncScope())
{
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var list = new NotificationList("Ops");
list.Recipients.Add(NotificationRecipient.ForEmail("A", "a@example.com"));
ctx.NotificationLists.Add(list);
await ctx.SaveChangesAsync();
}
await using (var scope = _provider.CreateAsyncScope())
{
var repo = scope.ServiceProvider.GetRequiredService<INotificationRepository>();
var loaded = await repo.GetListByNameAsync("Ops");
Assert.NotNull(loaded);
Assert.Single(loaded!.Recipients);
}
}
private async Task<byte[]> ExportAsync()
{
await using var scope = _provider.CreateAsyncScope();
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var listIds = await ctx.NotificationLists.Select(l => l.Id).ToListAsync();
var selection = new ExportSelection(
TemplateIds: Array.Empty<int>(),
SharedScriptIds: Array.Empty<int>(),
ExternalSystemIds: Array.Empty<int>(),
DatabaseConnectionIds: Array.Empty<int>(),
NotificationListIds: listIds,
SmtpConfigurationIds: Array.Empty<int>(),
ApiMethodIds: Array.Empty<int>(),
IncludeDependencies: false);
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
passphrase: null, cancellationToken: CancellationToken.None);
using var ms = new MemoryStream();
await stream.CopyToAsync(ms);
return ms.ToArray();
}
private async Task ImportOverwriteAsync(byte[] bundle)
{
Guid sessionId;
await using (var scope = _provider.CreateAsyncScope())
{
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
using var input = new MemoryStream(bundle, writable: false);
sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId;
}
await using (var scope = _provider.CreateAsyncScope())
{
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
var result = await importer.ApplyAsync(sessionId,
new List<ImportResolution> { new("NotificationList", "Ops", ResolutionAction.Overwrite, null) },
user: "bob");
Assert.Equal(1, result.Overwritten);
}
}
private async Task<string[]> RecipientNamesAsync()
{
await using var scope = _provider.CreateAsyncScope();
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
return await ctx.NotificationRecipients
.Where(r => r.NotificationListId == ctx.NotificationLists.Single(l => l.Name == "Ops").Id)
.OrderBy(r => r.Name)
.Select(r => r.Name)
.ToArrayAsync();
}
}
@@ -118,3 +118,45 @@ public sealed class BundleSecretEncryptorTests
Assert.Equal(plaintext, recovered);
}
}
/// <summary>
/// TRN-10 (WP2 task 2.7): the PBKDF2 iteration count read from an uploaded manifest
/// must be range-checked before the key is derived, so a hostile bundle cannot pin a
/// thread (and the single-flight transport gate) with an absurd count.
/// </summary>
public sealed class BundleSecretEncryptorIterationBoundTests
{
private static EncryptionMetadata ValidMetadata() =>
new("AES-256-GCM", "PBKDF2-SHA256", EncryptionMetadata.MinPbkdf2Iterations,
Convert.ToBase64String(new byte[16]), Convert.ToBase64String(new byte[12]));
/// <summary>A metadata record whose iteration count was set past the ceiling is refused before PBKDF2 runs.</summary>
[Theory]
[InlineData(int.MaxValue)]
[InlineData(EncryptionMetadata.MaxPbkdf2Iterations + 1)]
[InlineData(EncryptionMetadata.MinPbkdf2Iterations - 1)]
[InlineData(0)]
[InlineData(-1)]
public void Decrypt_rejects_out_of_range_iterations_without_deriving(int iterations)
{
// `with` bypasses the record constructor's range check — the encryptor must
// not rely on it.
var metadata = ValidMetadata() with { Iterations = iterations };
var sw = System.Diagnostics.Stopwatch.StartNew();
Assert.ThrowsAny<CryptographicException>(() =>
new BundleSecretEncryptor().Decrypt(new byte[32], metadata, "pass"));
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(5), "the key must not be derived first");
}
/// <summary>A manifest JSON carrying an absurd iteration count does not yield a usable metadata record.</summary>
[Fact]
public void Manifest_with_absurd_iterations_is_rejected_on_read()
{
var json = """
{"algorithm":"AES-256-GCM","kdf":"PBKDF2-SHA256","iterations":2147483647,"saltB64":"","ivB64":""}
""";
Assert.ThrowsAny<Exception>(() =>
System.Text.Json.JsonSerializer.Deserialize<EncryptionMetadata>(
json, ZB.MOM.WW.ScadaBridge.Transport.Serialization.BundleJsonOptions.Default));
}
}
@@ -534,12 +534,15 @@ public sealed class ArtifactDiffTests
Assert.Equal("MxAccess", change.GetProperty("newValue").GetString());
}
/// <summary>Verifies that a changed secret value with preserved presence is reported without echoing the secret.</summary>
/// <summary>
/// TRN-2: a changed secret value with preserved presence classifies Modified (it used to
/// read Identical and be force-skipped) and is reported as a value-free marker.
/// </summary>
[Fact]
public void CompareDataConnection_SecretValueChangesButPresencePreserved_NoSecretEcho()
public void CompareDataConnection_SecretValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
{
// Both sides HAVE a primary configuration secret; only the value differs.
// Presence-only comparison => no Secrets.* change, and the value is never echoed.
// Compared by hash => a value-free "<changed>" marker; the value is never echoed.
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
{
FailoverRetryCount = 3,
@@ -553,10 +556,79 @@ public sealed class ArtifactDiffTests
var item = _diff.CompareDataConnection(dto, existing);
Assert.Equal(ConflictKind.Identical, item.Kind);
Assert.Null(item.FieldDiffJson);
Assert.Equal(ConflictKind.Modified, item.Kind);
var change = ChangeFor(item, "Secrets.PrimaryConfiguration");
Assert.Equal("<present>", change.GetProperty("oldValue").GetString());
Assert.Equal("<changed>", change.GetProperty("newValue").GetString());
// The secret value must never appear anywhere in the diff output.
Assert.DoesNotContain("4840", item.FieldDiffJson ?? string.Empty);
Assert.DoesNotContain("4840", item.FieldDiffJson!);
Assert.DoesNotContain("OLD", item.FieldDiffJson!);
Assert.DoesNotContain("NEW", item.FieldDiffJson!);
}
/// <summary>TRN-2: an unchanged secret value (same on both sides) stays Identical.</summary>
[Fact]
public void CompareDataConnection_SameSecretValue_Identical()
{
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
{
FailoverRetryCount = 3,
PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://h:4840\"}",
};
var dto = new DataConnectionDto("site-a", "opc1", "OpcUa", 3,
new SecretsBlock(new Dictionary<string, string>
{
["PrimaryConfiguration"] = "{\"endpoint\":\"opc.tcp://h:4840\"}",
}));
var item = _diff.CompareDataConnection(dto, existing);
Assert.Equal(ConflictKind.Identical, item.Kind);
}
/// <summary>
/// TRN-2 scenario B: when only FailoverRetryCount differs on the surface but the
/// protocol configuration also changed, the diff shows the configuration change too,
/// so an Overwrite no longer replaces it unseen.
/// </summary>
[Fact]
public void CompareDataConnection_RetryCountAndHiddenConfigChange_BothReported()
{
var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
{
FailoverRetryCount = 3,
PrimaryConfiguration = "{\"endpoint\":\"opc.tcp://target:4840\"}",
};
var dto = new DataConnectionDto("site-a", "opc1", "OpcUa", 5,
new SecretsBlock(new Dictionary<string, string>
{
["PrimaryConfiguration"] = "{\"endpoint\":\"opc.tcp://source:4840\"}",
}));
var item = _diff.CompareDataConnection(dto, existing);
Assert.Equal(ConflictKind.Modified, item.Kind);
ChangeFor(item, "FailoverRetryCount");
Assert.Equal("<changed>", ChangeFor(item, "Secrets.PrimaryConfiguration").GetProperty("newValue").GetString());
Assert.DoesNotContain("source", item.FieldDiffJson!);
}
/// <summary>TRN-2: external-system auth, DB connection string and SMTP credentials changes are Modified, value-free.</summary>
[Fact]
public void CompareOtherSecretBearingTypes_ChangedValue_ModifiedWithoutEcho()
{
var es = _diff.CompareExternalSystem(
new ExternalSystemDto("Erp", "https://erp", "ApiKey",
MaxRetries: 3, RetryDelay: TimeSpan.FromSeconds(5), Methods: [],
Secrets: new SecretsBlock(new Dictionary<string, string> { ["AuthConfiguration"] = "key-NEW" })),
new ExternalSystemDefinition("Erp", "https://erp", "ApiKey")
{
MaxRetries = 3, RetryDelay = TimeSpan.FromSeconds(5), AuthConfiguration = "key-OLD",
},
existingMethods: null);
Assert.Equal(ConflictKind.Modified, es.Kind);
Assert.Equal("<changed>", ChangeFor(es, "Secrets.AuthConfiguration").GetProperty("newValue").GetString());
Assert.DoesNotContain("key-", es.FieldDiffJson!);
}
/// <summary>Verifies that a flip in secret presence is shown only as a present marker, without the secret value.</summary>
@@ -607,11 +679,14 @@ public sealed class ArtifactDiffTests
Assert.Equal("AC1", item.Name);
}
/// <summary>Verifies that an SMS configuration whose fields and secret presence all match compares as identical.</summary>
/// <summary>Verifies that an SMS configuration whose fields and secret value all match compares as identical.</summary>
[Fact]
public void CompareSmsConfiguration_AllFieldsAndPresenceMatch_Identical()
public void CompareSmsConfiguration_AllFieldsAndSecretMatch_Identical()
{
var item = _diff.CompareSmsConfiguration(SmsDto(), ExistingSms());
// TRN-2: secrets are compared by value (hash), so the token must match too.
var existing = ExistingSms();
existing.AuthToken = "wire-token";
var item = _diff.CompareSmsConfiguration(SmsDto(), existing);
Assert.Equal(ConflictKind.Identical, item.Kind);
Assert.Null(item.FieldDiffJson);
@@ -629,15 +704,16 @@ public sealed class ArtifactDiffTests
Assert.Equal("+15559999999", change.GetProperty("newValue").GetString());
}
/// <summary>Verifies that a changed auth token value with preserved presence is reported without echoing the secret.</summary>
/// <summary>TRN-2: a changed auth token value with preserved presence is Modified, without echoing the secret.</summary>
[Fact]
public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_NoSecretEcho()
public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
{
// Both sides carry a token; only the value differs. Presence-only comparison =>
// no Secrets.AuthToken change, and neither token value is ever echoed.
// Both sides carry a token; only the value differs. Compared by hash =>
// a value-free "<changed>" marker, and neither token value is ever echoed.
var item = _diff.CompareSmsConfiguration(SmsDto(withSecret: true), ExistingSms());
Assert.Equal(ConflictKind.Identical, item.Kind);
Assert.Equal(ConflictKind.Modified, item.Kind);
Assert.Equal("<changed>", ChangeFor(item, "Secrets.AuthToken").GetProperty("newValue").GetString());
var json = item.FieldDiffJson ?? string.Empty;
Assert.DoesNotContain("stored-token", json);
Assert.DoesNotContain("wire-token", json);
@@ -672,19 +748,62 @@ public sealed class ArtifactDiffTests
Assert.Equal("inst-1", item.Name);
}
/// <summary>Verifies that an instance with a differing state compares as modified.</summary>
/// <summary>
/// TRN-6: State is not compared — the import never carries a live state, so a
/// State-only difference must not read Modified (an Overwrite would then reset a live
/// instance to NotDeployed for no configuration change).
/// </summary>
[Fact]
public void CompareInstance_StateDiffers_Modified()
public void CompareInstance_StateOnlyDiffers_Identical()
{
var existing = new Instance("inst-1") { State = InstanceState.Disabled };
var dto = MakeInstanceDto("inst-1", state: InstanceState.Enabled);
var existing = new Instance("inst-1") { State = InstanceState.Enabled };
var dto = MakeInstanceDto("inst-1", state: InstanceState.Disabled);
var item = _diff.CompareInstance(dto, existing);
Assert.Equal(ConflictKind.Identical, item.Kind);
}
/// <summary>TRN-6: a binding moved to another connection (same attribute + reference) is Modified.</summary>
[Fact]
public void CompareInstance_BindingRebindToOtherConnection_Modified()
{
var existing = new Instance("inst-1") { State = InstanceState.Enabled };
existing.ConnectionBindings.Add(new InstanceConnectionBinding("Flow")
{
DataConnectionId = 10,
DataSourceReferenceOverride = "ns=2;s=Flow",
});
var dto = MakeInstanceDto("inst-1") with
{
ConnectionBindings = [new InstanceConnectionBindingDto("Flow", "OPC2", "ns=2;s=Flow")],
};
var names = new Dictionary<int, string> { [10] = "OPC1", [11] = "OPC2" };
var item = _diff.CompareInstance(dto, existing, existingConnectionNameById: names);
Assert.Equal(ConflictKind.Modified, item.Kind);
var change = ChangeFor(item, "State");
Assert.Equal("Disabled", change.GetProperty("oldValue").GetString());
Assert.Equal("Enabled", change.GetProperty("newValue").GetString());
// Same connection (case-insensitively) => Identical.
var same = _diff.CompareInstance(
dto with { ConnectionBindings = [new InstanceConnectionBindingDto("Flow", "opc1", "ns=2;s=Flow")] },
existing, existingConnectionNameById: names);
Assert.Equal(ConflictKind.Identical, same.Kind);
}
/// <summary>TRN-8: with an incoming area path the full path is compared, not the leaf name.</summary>
[Fact]
public void CompareInstance_SameLeafDifferentAreaPath_Modified()
{
var existing = new Instance("inst-1") { State = InstanceState.Enabled, AreaId = 5 };
var dto = MakeInstanceDto("inst-1") with { AreaName = "Cell", AreaPath = ["Line2", "Cell"] };
var item = _diff.CompareInstance(dto, existing, existingAreaName: "Cell", existingAreaPath: ["Line1", "Cell"]);
Assert.Equal(ConflictKind.Modified, item.Kind);
var change = ChangeFor(item, "AreaPath");
Assert.Equal("Line1/Cell", change.GetProperty("oldValue").GetString());
Assert.Equal("Line2/Cell", change.GetProperty("newValue").GetString());
}
/// <summary>Verifies that an instance with no changes compares as identical.</summary>