fix(transport): import diff compares secrets and bindings; preview honours the name map; CI lookups; area paths; no Rename where unsupported (TRN-2, TRN-3, TRN-6, TRN-7, TRN-8, TRN-9, WP2 tasks 2.4+2.5)

2.4 — ArtifactDiff:
- TRN-2: secret-bearing values (data-connection primary/backup config, DB
  connection string, external-system auth, SMTP credentials, SMS token) are
  compared by SHA-256 and reported value-free as <present> -> <changed>, so a
  changed endpoint no longer reads Identical and is force-skipped.
- TRN-6: the instance diff resolves each existing binding's DataConnectionId to
  its name and compares it (a rebind OPC1 -> OPC2 is Modified); State is no
  longer compared (the import never carries a live state).

2.5 — BundleImporter / ManagementActor / Central UI:
- TRN-3: PreviewAsync takes an optional BundleNameMap (additive optional param);
  under a MapToExisting redirect the connection/instance diffs, connection
  auto-match and unresolved-connection blocker run against the mapped target.
  The CLI import path passes its explicit --map-site/--map-connection redirects
  to the preview before the blocker gate; the Central UI re-runs the preview
  under the Map-step choices at Confirm. Apply binds a CreateNew site/connection
  whose identifier/name already exists to that row instead of inserting a
  duplicate the unique index rejects.
- TRN-7: connection, instance, instance-template and composition/base-template
  lookups match exact spelling first, then case-insensitively.
- TRN-8: InstanceDto gains the additive AreaPath (root->leaf); the exporter
  fills it and the importer resolves/creates areas level by level under their
  real parent. A legacy leaf-only bundle with an ambiguous leaf resolves
  deterministically and adds an ImportResult warning.
- TRN-9: Rename is rejected by ApplyAsync for Site, DataConnection,
  SmtpConfiguration and SmsConfiguration (ImportRenameSupport); the UI does not
  offer it there and the CLI rename policy falls back to Skip with a warning.

Also moves a doc comment misplaced by the 2.6 commit. Reflection round-trip
guard (RoundTripEquivalenceTests) re-run: green.
This commit is contained in:
Joseph Doherty
2026-12-03 10:11:07 -05:00
parent cbdd9fc40b
commit baecf10fea
16 changed files with 1391 additions and 169 deletions
+4 -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). - 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"). - 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. - 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. - 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. - 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"). - **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` ### `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. - 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. - 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`. - 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: **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. - **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. - **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". 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`. **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. **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.
@@ -482,7 +482,10 @@
var key = (item.EntityType, item.Name); var key = (item.EntityType, item.Name);
<div class="d-flex flex-wrap gap-2 align-items-center"> <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}"; var inputId = $"res-{item.EntityType}-{item.Name}-{action}";
<div class="form-check form-check-inline mb-0"> <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); return (adds, overs, skips, renames, blockers);
} }
private void GoToConfirm() private async Task GoToConfirm()
{ {
if (_preview is null) return; if (_preview is null) return;
await RefreshPreviewUnderMappingAsync();
if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker)) if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker))
{ {
_errorMessage = "Cannot proceed while blockers exist — resolve or remove blocker rows first."; _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; _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() private void BackToDiff()
{ {
_step = ImportWizardStep.Diff; _step = ImportWizardStep.Diff;
@@ -30,8 +30,15 @@ public interface IBundleImporter
/// </summary> /// </summary>
/// <param name="sessionId">Session id returned by <see cref="LoadAsync"/>.</param> /// <param name="sessionId">Session id returned by <see cref="LoadAsync"/>.</param>
/// <param name="ct">Cancellation token.</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> /// <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> /// <summary>
/// Applies the chosen conflict resolutions and commits the import transaction. /// Applies the chosen conflict resolutions and commits the import transaction.
@@ -7,3 +7,25 @@ public sealed record ImportResolution(
string Name, string Name,
ResolutionAction Action, ResolutionAction Action,
string? RenameTo); 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);
}
@@ -4664,7 +4664,13 @@ public class ManagementActor : ReceiveActor
// is safe even when ApplyAsync already released the same id. // is safe even when ApplyAsync already released the same id.
try 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(); var blockers = preview.Items.Where(i => i.Kind == ConflictKind.Blocker).ToList();
if (blockers.Count > 0) if (blockers.Count > 0)
@@ -4690,6 +4696,7 @@ public class ManagementActor : ReceiveActor
// automatically correct — no bare-connection-name special case needed. // automatically correct — no bare-connection-name special case needed.
var renameStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); var renameStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
var resolutionsMap = new Dictionary<(string, string), ImportResolution>(); var resolutionsMap = new Dictionary<(string, string), ImportResolution>();
var renameFallbacks = new SortedSet<string>(StringComparer.Ordinal);
foreach (var item in preview.Items) foreach (var item in preview.Items)
{ {
var action = item.Kind switch var action = item.Kind switch
@@ -4699,15 +4706,31 @@ public class ManagementActor : ReceiveActor
ConflictKind.Modified => policy, ConflictKind.Modified => policy,
_ => ResolutionAction.Skip, _ => 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}" ? $"{item.Name}-imported-{renameStamp}"
: null; : null;
resolutionsMap[(item.EntityType, item.Name)] = new ImportResolution( resolutionsMap[(item.EntityType, item.Name)] = new ImportResolution(
item.EntityType, item.Name, action, renameTo); item.EntityType, item.Name, action, renameTo);
} }
return await importer.ApplyAsync( var importResult = await importer.ApplyAsync(
session.SessionId, resolutionsMap.Values.ToList(), username, nameMap: nameMap); 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 finally
{ {
@@ -4720,6 +4743,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> /// <summary>
/// Merges the operator-supplied <see cref="SiteMappingSpec"/> / /// Merges the operator-supplied <see cref="SiteMappingSpec"/> /
/// <see cref="ConnectionMappingSpec"/> lists with the preview's auto-matches /// <see cref="ConnectionMappingSpec"/> lists with the preview's auto-matches
@@ -98,6 +98,38 @@ public sealed class BundleExporter : IBundleExporter
.ToDictionaryAsync(a => a.Id, a => a.Name, cancellationToken) .ToDictionaryAsync(a => a.Id, a => a.Name, cancellationToken)
.ConfigureAwait(false); .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). // 2. Convert to the wire-shaped DTO (strips EF identity, refs-by-name).
// The resolver's site/dataConnection/instance closure is wired // The resolver's site/dataConnection/instance closure is wired
// through via object-initializer — without this the aggregate would // through via object-initializer — without this the aggregate would
@@ -126,6 +158,7 @@ public sealed class BundleExporter : IBundleExporter
// Area id→name lookup for the exported instances — feeds the serializer's // Area id→name lookup for the exported instances — feeds the serializer's
// AreaName projection so each instance's area travels by name. // AreaName projection so each instance's area travels by name.
AreaNameById = areaNameById, AreaNameById = areaNameById,
AreaPathById = areaPathById,
}; };
var contentDto = _entitySerializer.ToBundleContent(aggregate); var contentDto = _entitySerializer.ToBundleContent(aggregate);
@@ -237,15 +237,10 @@ public sealed class ArtifactDiff
// target's existing timeout untouched in that case. // target's existing timeout untouched in that case.
AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds); AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds);
// Secrets: presence-only comparison (we never echo the value in the diff). // Secrets: compared by hash, reported presence-only (TRN-2 — the value is never
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthConfiguration); // echoed in the diff, but a changed value is no longer read as Identical).
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthConfiguration"); AddSecretChange(changes, "Secrets.AuthConfiguration",
if (existingHasSecret != incomingHasSecret) existing.AuthConfiguration, SecretValue(incoming.Secrets, "AuthConfiguration"));
{
changes.Add(new FieldChange("Secrets.AuthConfiguration",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// Methods are name-keyed children. // Methods are name-keyed children.
var existingForCompare = existingMethods ?? Array.Empty<ExternalSystemMethod>(); var existingForCompare = existingMethods ?? Array.Empty<ExternalSystemMethod>();
@@ -276,15 +271,10 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries); AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString()); AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
// ConnectionString lives in Secrets only — presence-only comparison. // ConnectionString lives in Secrets only — compared by hash, reported
var existingHasSecret = !string.IsNullOrEmpty(existing.ConnectionString); // presence-only (TRN-2).
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("ConnectionString"); AddSecretChange(changes, "Secrets.ConnectionString",
if (existingHasSecret != incomingHasSecret) existing.ConnectionString, SecretValue(incoming.Secrets, "ConnectionString"));
{
changes.Add(new FieldChange("Secrets.ConnectionString",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
return BuildItem("DatabaseConnection", incoming.Name, changes); return BuildItem("DatabaseConnection", incoming.Name, changes);
} }
@@ -345,14 +335,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope); AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope);
AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport); AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport);
var existingHasSecret = !string.IsNullOrEmpty(existing.Credentials); // TRN-2: compared by hash, reported presence-only.
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("Credentials"); AddSecretChange(changes, "Secrets.Credentials",
if (existingHasSecret != incomingHasSecret) existing.Credentials, SecretValue(incoming.Secrets, "Credentials"));
{
changes.Add(new FieldChange("Secrets.Credentials",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
return BuildItem("SmtpConfiguration", incoming.Host, changes); return BuildItem("SmtpConfiguration", incoming.Host, changes);
} }
@@ -379,14 +364,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries); AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString()); AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthToken); // TRN-2: compared by hash, reported presence-only.
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthToken"); AddSecretChange(changes, "Secrets.AuthToken",
if (existingHasSecret != incomingHasSecret) existing.AuthToken, SecretValue(incoming.Secrets, "AuthToken"));
{
changes.Add(new FieldChange("Secrets.AuthToken",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
return BuildItem("SmsConfiguration", incoming.AccountSid, changes); return BuildItem("SmsConfiguration", incoming.AccountSid, changes);
} }
@@ -481,13 +461,12 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount); AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount);
// Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration). // Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration).
// Presence-only comparison — never echo the config value. // Compared by hash, reported presence-only — never echo the config value
AddSecretPresenceChange(changes, "Secrets.PrimaryConfiguration", // (TRN-2: a changed endpoint URL used to read Identical and be force-skipped).
!string.IsNullOrEmpty(existing.PrimaryConfiguration), AddSecretChange(changes, "Secrets.PrimaryConfiguration",
HasSecretKey(incoming.Secrets, "PrimaryConfiguration")); existing.PrimaryConfiguration, SecretValue(incoming.Secrets, "PrimaryConfiguration"));
AddSecretPresenceChange(changes, "Secrets.BackupConfiguration", AddSecretChange(changes, "Secrets.BackupConfiguration",
!string.IsNullOrEmpty(existing.BackupConfiguration), existing.BackupConfiguration, SecretValue(incoming.Secrets, "BackupConfiguration"));
HasSecretKey(incoming.Secrets, "BackupConfiguration"));
return BuildItem("DataConnection", incoming.Name, changes); 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="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="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="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> /// <returns>An import preview item describing the conflict type and differences.</returns>
public ImportPreviewItem CompareInstance( public ImportPreviewItem CompareInstance(
InstanceDto incoming, InstanceDto incoming,
Instance? existing, Instance? existing,
string? existingTemplateName = null, string? existingTemplateName = null,
string? existingSiteIdentifier = null, string? existingSiteIdentifier = null,
string? existingAreaName = null) string? existingAreaName = null,
IReadOnlyDictionary<int, string>? existingConnectionNameById = null,
IReadOnlyList<string>? existingAreaPath = null)
{ {
ArgumentNullException.ThrowIfNull(incoming); ArgumentNullException.ThrowIfNull(incoming);
if (existing is null) return New("Instance", incoming.UniqueName); 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, "SiteIdentifier", existingSiteIdentifier, incoming.SiteIdentifier);
} }
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName); if (incoming.AreaPath is { Count: > 0 } incomingPath && (existingAreaPath is not null || existing.AreaId is null))
AddIfDifferent(changes, "State", existing.State.ToString(), incoming.State.ToString()); {
// 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( DiffChildren(
existing.AttributeOverrides, existing.AttributeOverrides,
@@ -573,10 +571,14 @@ public sealed class ArtifactDiff
incoming.ConnectionBindings, incoming.ConnectionBindings,
e => e.AttributeName, e => e.AttributeName,
i => i.AttributeName, i => i.AttributeName,
// ConnectionName resolves to a FK on the entity (DataConnectionId) that // TRN-6: the entity binds by FK (DataConnectionId); the caller resolves it to
// can't be compared cross-environment, so the binding diff compares only // the target connection's name, which is compared (case-insensitively, like
// the per-attribute DataSourceReference override. // the unique (SiteId, Name) index) together with the per-attribute
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride, // 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", "ConnectionBindings",
changes); changes);
@@ -657,24 +659,37 @@ public sealed class ArtifactDiff
}; };
/// <summary>True if <paramref name="secrets"/> carries the named key.</summary> /// <summary>True if <paramref name="secrets"/> carries the named key.</summary>
private static bool HasSecretKey(SecretsBlock? secrets, string key) => private static string? SecretValue(SecretsBlock? secrets, string key) =>
secrets is not null && secrets.Values.ContainsKey(key); secrets is not null && secrets.Values.TryGetValue(key, out var value) ? value : null;
/// <summary> /// <summary>
/// Records a presence-only secret change (a flip in whether a value is set on /// TRN-2: compares a secret-bearing value by SHA-256 hash and reports the result
/// each side) using the <c>&lt;present&gt;</c> / null marker convention. The /// presence-only. A flip in presence uses the <c>&lt;present&gt;</c> / null markers;
/// secret value itself is NEVER read into the diff — only its presence. /// 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> /// </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, changes.Add(new FieldChange(field,
existingHasSecret ? "<present>" : null, existingHas ? "<present>" : null,
incomingHasSecret ? "<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>( private static void DiffChildren<TExisting, TIncoming>(
IEnumerable<TExisting> existing, IEnumerable<TExisting> existing,
IEnumerable<TIncoming> incoming, IEnumerable<TIncoming> incoming,
@@ -477,7 +477,7 @@ public sealed partial class BundleImporter : IBundleImporter
} }
/// <inheritdoc /> /// <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) var session = _sessionStore.Get(sessionId)
?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired."); ?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired.");
@@ -628,10 +628,16 @@ public sealed partial class BundleImporter : IBundleImporter
var targetConnectionsBySiteIdentifier = var targetConnectionsBySiteIdentifier =
new Dictionary<string, IReadOnlyList<DataConnection>>(StringComparer.Ordinal); 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) async Task<Site?> ResolveTargetSiteAsync(string siteIdentifier)
{ {
if (targetSiteByIdentifier.TryGetValue(siteIdentifier, out var cached)) return cached; 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; targetSiteByIdentifier[siteIdentifier] = site;
return site; return site;
} }
@@ -684,7 +690,10 @@ public sealed partial class BundleImporter : IBundleImporter
foreach (var dcDto in content.DataConnections) foreach (var dcDto in content.DataConnections)
{ {
var targetConns = await ResolveTargetConnectionsAsync(dcDto.SiteIdentifier).ConfigureAwait(false); 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); var item = _diff.CompareDataConnection(dcDto, existing);
items.Add(item with { Name = QualifiedConnectionName(dcDto.SiteIdentifier, dcDto.Name) }); 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 // batched read for every bundled instance, and the template / site / area
// names come from the library projection, one site list and one area list // names come from the library projection, one site list and one area list
// per site — not four queries per instance. // 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 var existingInstanceByName = content.Instances.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal) ? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: (await _templateRepo : ToNameLookup(
(await _templateRepo
.GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct) .GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct)
.ConfigureAwait(false)) .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; 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) foreach (var instDto in content.Instances)
{ {
existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing); existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing);
@@ -713,8 +729,17 @@ public sealed partial class BundleImporter : IBundleImporter
string? existingTemplateName = null; string? existingTemplateName = null;
string? existingSiteIdentifier = null; string? existingSiteIdentifier = null;
string? existingAreaName = null; string? existingAreaName = null;
IReadOnlyList<string>? existingAreaPath = null;
IReadOnlyDictionary<int, string>? existingConnectionNames = null;
if (existing is not 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 // The entity stores template/site/area as numeric FKs that can't be
// compared cross-environment, so resolve each to the same stable // compared cross-environment, so resolve each to the same stable
// string identity the incoming DTO carries. // string identity the incoming DTO carries.
@@ -726,27 +751,39 @@ public sealed partial class BundleImporter : IBundleImporter
if (existing.AreaId is int areaId) 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)) areasById = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(a => a.Id, a => a.Name); .ToDictionary(a => a.Id, a => a);
areaNameByIdBySite[existing.SiteId] = areaNames; 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( items.Add(_diff.CompareInstance(
instDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName)); mappedDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName,
existingConnectionNames, existingAreaPath));
} }
// ---- Required site/connection mappings ---- // ---- Required site/connection mappings ----
var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync( var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync(
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync).ConfigureAwait(false); content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName).ConfigureAwait(false);
// ---- Blocker detection ---- // ---- Blocker detection ----
items.AddRange(await DetectBlockersAsync( 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); return new ImportPreview(sessionId, items, requiredSites, requiredConnections);
} }
@@ -772,7 +809,8 @@ public sealed partial class BundleImporter : IBundleImporter
BuildRequiredMappingsAsync( BuildRequiredMappingsAsync(
BundleContentDto content, BundleContentDto content,
Func<string, Task<Site?>> resolveTargetSite, 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. // Distinct source-site identifiers, with a best-effort display name.
// SiteDto carries a Name; instances / data-connections only carry the // 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 // Auto-match only WITHIN the auto-matched target site: a connection of
// the same name under a different site is not a valid match. // the same name under a different site is not a valid match.
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false); 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( connectionMappings.Add(new RequiredConnectionMapping(
SourceSiteIdentifier: site, SourceSiteIdentifier: site,
SourceConnectionName: name, SourceConnectionName: name,
AutoMatchTargetName: matched ? name : null)); AutoMatchTargetName: matched?.Name));
} }
return (siteMappings, connectionMappings); return (siteMappings, connectionMappings);
@@ -860,6 +898,7 @@ public sealed partial class BundleImporter : IBundleImporter
private async Task<IReadOnlyList<ImportPreviewItem>> DetectBlockersAsync( private async Task<IReadOnlyList<ImportPreviewItem>> DetectBlockersAsync(
BundleContentDto content, BundleContentDto content,
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections, Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
Func<string, string, string> targetConnectionName,
TemplateLibrary library, TemplateLibrary library,
IReadOnlyList<SharedScript> allSharedScripts, IReadOnlyList<SharedScript> allSharedScripts,
IReadOnlyList<ExternalSystemDefinition> allExternalSystems, 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) // The set of template names the import can satisfy = (in-bundle templates)
// ∪ (templates already in the target DB). An instance whose TemplateName is // ∪ (templates already in the target DB). An instance whose TemplateName is
// in neither is unresolvable. // 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). // 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); 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. // 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 // Members + lock flags are needed below (CollectLockedOverrideWarnings) but
// never script bodies — the body-free, untracked analysis projection (04/P4). // never script bodies — the body-free, untracked analysis projection (04/P4).
var targetTemplates = await library.GetAnalysisAsync(ct).ConfigureAwait(false); 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) foreach (var t in targetTemplates)
{ {
targetTemplateNames.Add(t.Name); targetTemplateNames.Add(t.Name);
@@ -951,7 +991,7 @@ public sealed partial class BundleImporter : IBundleImporter
{ {
if (bundleConnections.Contains((site, name))) continue; if (bundleConnections.Contains((site, name))) continue;
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false); 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 // Site-qualify the blocker Name so two sites' same-named-but-missing
// connections surface as distinct blockers (a bare name would collide). // connections surface as distinct blockers (a bare name would collide).
blockers.Add(new ImportPreviewItem( blockers.Add(new ImportPreviewItem(
@@ -1613,6 +1653,21 @@ public sealed partial class BundleImporter : IBundleImporter
ArgumentNullException.ThrowIfNull(resolutions); ArgumentNullException.ThrowIfNull(resolutions);
ArgumentNullException.ThrowIfNull(user); 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 // Normalise null → Empty so the resolve-or-create logic always has a map
// to consult. An empty map means "no explicit operator mappings" — every // to consult. An empty map means "no explicit operator mappings" — every
// referenced site/connection falls through to the identity auto-match. // 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 / // It writes the instance row + its four child collections (attribute /
// alarm / native-alarm-source overrides + connection bindings) and // alarm / native-alarm-source overrides + connection bindings) and
// rewires every name-keyed FK to the target environment's ids. // rewires every name-keyed FK to the target environment's ids.
var instanceWarnings = new List<string>();
await ApplyInstancesAsync( await ApplyInstancesAsync(
content, resolutionMap, siteBySourceIdentifier, connectionMaps, content, resolutionMap, siteBySourceIdentifier, connectionMaps,
library, user, summary, ct).ConfigureAwait(false); library, user, summary, instanceWarnings, ct).ConfigureAwait(false);
// ---- Pre-commit point: stale-instance computation ---- // ---- Pre-commit point: stale-instance computation ----
// Everything the import will write is staged on the change tracker at // Everything the import will write is staged on the change tracker at
@@ -2050,7 +2106,9 @@ public sealed partial class BundleImporter : IBundleImporter
StaleInstanceIds: staleInstanceIds, StaleInstanceIds: staleInstanceIds,
AuditEventCorrelation: bundleImportId.ToString(), AuditEventCorrelation: bundleImportId.ToString(),
ApiKeysIgnored: apiKeysIgnored, 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> /// <summary>
@@ -2208,7 +2266,7 @@ public sealed partial class BundleImporter : IBundleImporter
{ {
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name); var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
if (resolution.Action != ResolutionAction.Overwrite) continue; 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); 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 /// 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). /// by-name DB result is re-keyed in memory (ScadaBridge#93).
/// </summary> /// </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) internal static Dictionary<string, T> ToNameLookup<T>(IEnumerable<T> rows, Func<T, string> name)
{ {
var lookup = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); var lookup = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
@@ -3458,11 +3606,13 @@ public sealed partial class BundleImporter : IBundleImporter
// The fallback is a dictionary lookup into the per-apply library // The fallback is a dictionary lookup into the per-apply library
// snapshot (04/P4) — a name not in Local is a pre-existing target // 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. // 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; int? composedId = composedStub?.Id;
if (composedId is null if (composedId is null
&& (await library.GetIdByNameAsync(ct).ConfigureAwait(false)) && TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false),
.TryGetValue(compDto.ComposedTemplateName, out var libraryId)) compDto.ComposedTemplateName, out var libraryId))
{ {
composedId = libraryId; composedId = libraryId;
} }
@@ -3551,10 +3701,13 @@ public sealed partial class BundleImporter : IBundleImporter
? (baseResolution.RenameTo ?? dto.BaseTemplateName) ? (baseResolution.RenameTo ?? dto.BaseTemplateName)
: 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; int? baseId = baseStub?.Id;
if (baseId is null 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; baseId = libraryId;
} }
@@ -3632,13 +3785,6 @@ public sealed partial class BundleImporter : IBundleImporter
_exact.TryGetValue(name, out template!) || _ignoreCase.TryGetValue(name, out template!); _exact.TryGetValue(name, out template!) || _ignoreCase.TryGetValue(name, out template!);
} }
/// <summary>
/// Loads the given tracked templates with their child collections in one batched
/// read (Gitea #47 — previously one <c>GetTemplateWithChildrenAsync</c> per
/// template), keyed by id. The read is by name, so the result is keyed by id and
/// looked up by each stub's id: a database collation that matches names
/// case-insensitively can only add rows, never swap the exact one out.
/// </summary>
/// <summary> /// <summary>
/// TRN-5: true when <paramref name="composition"/> owns a slot-derived template /// 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 /// (<c>IsDerived</c> with <c>OwnerCompositionId</c> pointing back at the row) that no
@@ -3659,6 +3805,13 @@ public sealed partial class BundleImporter : IBundleImporter
&& !bundleComposedNames.Contains(composed.Name); && !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
/// template), keyed by id. The read is by name, so the result is keyed by id and
/// looked up by each stub's id: a database collation that matches names
/// case-insensitively can only add rows, never swap the exact one out.
/// </summary>
private async Task<Dictionary<int, Template>> LoadTemplatesWithChildrenAsync( private async Task<Dictionary<int, Template>> LoadTemplatesWithChildrenAsync(
IEnumerable<Template> stubs, CancellationToken ct) IEnumerable<Template> stubs, CancellationToken ct)
{ {
@@ -4638,7 +4791,11 @@ public sealed partial class BundleImporter : IBundleImporter
target = await _siteRepo.GetSiteByIdentifierAsync(targetId, ct).ConfigureAwait(false); 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); var created = BuildSite(siteDto);
await _siteRepo.AddSiteAsync(created, ct).ConfigureAwait(false); await _siteRepo.AddSiteAsync(created, ct).ConfigureAwait(false);
@@ -4813,13 +4970,14 @@ public sealed partial class BundleImporter : IBundleImporter
&& mapping.TargetConnectionName is { Length: > 0 } tn && mapping.TargetConnectionName is { Length: > 0 } tn
? tn ? tn
: dcDto.Name; : dcDto.Name;
var existing = targetConns.FirstOrDefault(c => // TRN-7: case-insensitive like the unique (SiteId, Name) index, exact first.
string.Equals(c.Name, targetName, StringComparison.Ordinal)); var existing = FindByName(targetConns, c => c.Name, targetName);
var action = mapping?.Action // TRN-3: CreateNew against a connection the target site already holds
?? (existing is not null ? MappingAction.MapToExisting : MappingAction.CreateNew); // (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
if (action == MappingAction.CreateNew || existing is null) // connection's own Skip/Overwrite resolution then applies).
if (existing is null)
{ {
var created = BuildDataConnection(dcDto, targetSite.Id); var created = BuildDataConnection(dcDto, targetSite.Id);
await _siteRepo.AddDataConnectionAsync(created, ct).ConfigureAwait(false); await _siteRepo.AddDataConnectionAsync(created, ct).ConfigureAwait(false);
@@ -4893,8 +5051,7 @@ public sealed partial class BundleImporter : IBundleImporter
: connName; : connName;
var targetConns = await TargetConnsAsync(targetSite.Id).ConfigureAwait(false); var targetConns = await TargetConnsAsync(targetSite.Id).ConfigureAwait(false);
var existing = targetConns.FirstOrDefault(c => var existing = FindByName(targetConns, c => c.Name, targetName);
string.Equals(c.Name, targetName, StringComparison.Ordinal));
if (existing is null) if (existing is null)
{ {
// Should already be a preview blocker (present in neither bundle nor // Should already be a preview blocker (present in neither bundle nor
@@ -4994,6 +5151,7 @@ public sealed partial class BundleImporter : IBundleImporter
TemplateLibrary library, TemplateLibrary library,
string user, string user,
ImportSummary summary, ImportSummary summary,
List<string> warnings,
CancellationToken ct) CancellationToken ct)
{ {
if (content.Instances.Count == 0) return; if (content.Instances.Count == 0) return;
@@ -5002,8 +5160,13 @@ public sealed partial class BundleImporter : IBundleImporter
// for pre-existing templates, overlaid with the tracked (Local) templates — // for pre-existing templates, overlaid with the tracked (Local) templates —
// which include everything this apply added or renamed, flushed (so their ids // which include everything this apply added or renamed, flushed (so their ids
// are real) before this pass (review 2026-10-21 04/P4). // are real) before this pass (review 2026-10-21 04/P4).
var templateIdByName = new Dictionary<string, int>( // TRN-7: case-insensitive like the template name index (exact spelling wins —
await library.GetIdByNameAsync(ct).ConfigureAwait(false), StringComparer.Ordinal); // 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) foreach (var local in _dbContext.Templates.Local)
{ {
// A tracked derived slot template never displaces a base of the same name // A tracked derived slot template never displaces a base of the same name
@@ -5023,14 +5186,19 @@ public sealed partial class BundleImporter : IBundleImporter
lookupNames.Add(dto.UniqueName); lookupNames.Add(dto.UniqueName);
if (r.Action == ResolutionAction.Rename && !string.IsNullOrEmpty(r.RenameTo)) lookupNames.Add(r.RenameTo); 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 var existingByName = lookupNames.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal) ? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: (await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false)) : ToNameLookup(
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal); (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. // same area don't each create a duplicate row.
var areaIdByKey = new Dictionary<(int SiteId, string Name), int>(); var areaIdByKey = new Dictionary<(int SiteId, string Name), int>();
var areasBySite = new Dictionary<int, List<Area>>();
foreach (var dto in content.Instances) foreach (var dto in content.Instances)
{ {
@@ -5060,7 +5228,7 @@ public sealed partial class BundleImporter : IBundleImporter
} }
int? areaId = await ResolveOrCreateAreaIdAsync( int? areaId = await ResolveOrCreateAreaIdAsync(
dto.AreaName, targetSite.Id, areaIdByKey, ct).ConfigureAwait(false); dto, targetSite.Id, areaIdByKey, areasBySite, warnings, ct).ConfigureAwait(false);
switch (resolution.Action) switch (resolution.Action)
{ {
@@ -5132,37 +5300,96 @@ public sealed partial class BundleImporter : IBundleImporter
} }
/// <summary> /// <summary>
/// Resolves an instance's area by name within the target site, creating the /// Resolves an instance's area within the target site, creating what is missing.
/// area if it doesn't exist. Returns null when <paramref name="areaName"/> is /// Returns null when the instance has no area.
/// null/empty (the instance has no area). Memoised via /// <para>
/// <paramref name="areaIdByKey"/> so repeated references resolve to one row. /// 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> /// </summary>
private async Task<int?> ResolveOrCreateAreaIdAsync( private async Task<int?> ResolveOrCreateAreaIdAsync(
string? areaName, InstanceDto dto,
int siteId, int siteId,
Dictionary<(int SiteId, string Name), int> areaIdByKey, Dictionary<(int SiteId, string Name), int> areaIdByKey,
Dictionary<int, List<Area>> areasBySite,
List<string> warnings,
CancellationToken ct) 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; if (areaIdByKey.TryGetValue(key, out var cached)) return cached;
var existingAreas = await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false); if (!areasBySite.TryGetValue(siteId, out var areas))
var match = existingAreas.FirstOrDefault(a => string.Equals(a.Name, areaName, StringComparison.Ordinal));
if (match is not null)
{ {
areaIdByKey[key] = match.Id; areas = (await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false)).ToList();
return match.Id; areasBySite[siteId] = areas;
} }
var area = new Area(areaName) { SiteId = siteId }; int resolvedId;
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false); if (path is not null)
// Flush so the area's surrogate id materialises before it's used as an {
// instance FK (relational provider). Rides the outer transaction. int? parentId = null;
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false); Area? current = null;
areaIdByKey[key] = area.Id; foreach (var segment in path)
return area.Id; {
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> /// <summary>
@@ -5437,7 +5664,7 @@ public sealed partial class BundleImporter : IBundleImporter
? tn ? tn
: name; : name;
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false); 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( errors.Add(
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in " $"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
@@ -5446,7 +5673,8 @@ public sealed partial class BundleImporter : IBundleImporter
} }
// ---- Instance template references ---- // ---- 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))) foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t)))
{ {
var resolution = ResolveOrDefault(resolutionMap, "Template", t.Name); var resolution = ResolveOrDefault(resolutionMap, "Template", t.Name);
@@ -5457,7 +5685,7 @@ public sealed partial class BundleImporter : IBundleImporter
} }
var targetTemplateNames = new HashSet<string>( var targetTemplateNames = new HashSet<string>(
(await library.GetIdByNameAsync(ct).ConfigureAwait(false)).Keys, (await library.GetIdByNameAsync(ct).ConfigureAwait(false)).Keys,
StringComparer.Ordinal); StringComparer.OrdinalIgnoreCase);
foreach (var inst in content.Instances) foreach (var inst in content.Instances)
{ {
@@ -67,6 +67,14 @@ public sealed record EntityAggregate(
/// </summary> /// </summary>
public IReadOnlyDictionary<int, string> AreaNameById { get; init; } = public IReadOnlyDictionary<int, string> AreaNameById { get; init; } =
new Dictionary<int, string>(); 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> /// <summary>
@@ -482,4 +490,16 @@ public sealed record InstanceDto(
IReadOnlyList<InstanceAttributeOverrideDto> AttributeOverrides, IReadOnlyList<InstanceAttributeOverrideDto> AttributeOverrides,
IReadOnlyList<InstanceAlarmOverrideDto> AlarmOverrides, IReadOnlyList<InstanceAlarmOverrideDto> AlarmOverrides,
IReadOnlyList<InstanceNativeAlarmSourceOverrideDto> NativeAlarmSourceOverrides, 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( ConnectionBindings: inst.ConnectionBindings.Select(b => new InstanceConnectionBindingDto(
AttributeName: b.AttributeName, AttributeName: b.AttributeName,
ConnectionName: connectionNameByConnectionId.TryGetValue(b.DataConnectionId, out var cn) ? cn : string.Empty, 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(),
}; };
} }
@@ -434,6 +434,75 @@ public class TransportImportPageTests : BunitContext
Assert.Empty(cut.FindAll("[data-testid='map-section']")); 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 // Test 9: the operator's Map choices fold into the BundleNameMap
// passed to ApplyAsync — a chosen target → MapToExisting, "Create new" → // 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()."); => throw new NotSupportedException("These tests seed sessions via OpenSession().");
/// <inheritdoc /> /// <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>())); => Task.FromResult(new ImportPreview(sessionId, new List<ImportPreviewItem>()));
/// <inheritdoc /> /// <inheritdoc />
@@ -1025,7 +1094,7 @@ public class TransportImportPageTests : BunitContext
return (T)field.GetValue(obj)!; 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( var method = obj.GetType().GetMethod(
name, name,
@@ -1033,7 +1102,7 @@ public class TransportImportPageTests : BunitContext
| System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Public) | System.Reflection.BindingFlags.Public)
?? throw new InvalidOperationException($"Method '{name}' not found on {obj.GetType()}."); ?? 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; await task;
} }
@@ -93,7 +93,7 @@ public class TransportImportSessionDisposeRaceTests : BunitContext
} }
/// <inheritdoc /> /// <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."); => throw new NotSupportedException("Not exercised by these tests.");
/// <inheritdoc /> /// <inheritdoc />
@@ -4426,7 +4426,8 @@ public class ManagementActorTests : TestKit, IDisposable
Manifest = null!, Manifest = null!,
ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5), 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( .Returns(new Commons.Types.Transport.ImportPreview(
sessionId, sessionId,
Array.Empty<Commons.Types.Transport.ImportPreviewItem>(), Array.Empty<Commons.Types.Transport.ImportPreviewItem>(),
@@ -4449,6 +4450,87 @@ public class ManagementActorTests : TestKit, IDisposable
return (sessionId, () => captured); 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> /// <summary>Verifies that import bundle command, when explicit spec, overrides auto match.</summary>
[Fact] [Fact]
public void ImportBundleCommand_ExplicitSpec_OverridesAutoMatch() public void ImportBundleCommand_ExplicitSpec_OverridesAutoMatch()
@@ -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);
}
}
@@ -534,12 +534,15 @@ public sealed class ArtifactDiffTests
Assert.Equal("MxAccess", change.GetProperty("newValue").GetString()); 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] [Fact]
public void CompareDataConnection_SecretValueChangesButPresencePreserved_NoSecretEcho() public void CompareDataConnection_SecretValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
{ {
// Both sides HAVE a primary configuration secret; only the value differs. // 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) var existing = new DataConnection("opc1", "OpcUa", siteId: 1)
{ {
FailoverRetryCount = 3, FailoverRetryCount = 3,
@@ -553,10 +556,79 @@ public sealed class ArtifactDiffTests
var item = _diff.CompareDataConnection(dto, existing); var item = _diff.CompareDataConnection(dto, existing);
Assert.Equal(ConflictKind.Identical, item.Kind); Assert.Equal(ConflictKind.Modified, item.Kind);
Assert.Null(item.FieldDiffJson); 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. // 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> /// <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); 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] [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.Equal(ConflictKind.Identical, item.Kind);
Assert.Null(item.FieldDiffJson); Assert.Null(item.FieldDiffJson);
@@ -629,15 +704,16 @@ public sealed class ArtifactDiffTests
Assert.Equal("+15559999999", change.GetProperty("newValue").GetString()); 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] [Fact]
public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_NoSecretEcho() public void CompareSmsConfiguration_AuthTokenValueChangesButPresencePreserved_ModifiedWithoutSecretEcho()
{ {
// Both sides carry a token; only the value differs. Presence-only comparison => // Both sides carry a token; only the value differs. Compared by hash =>
// no Secrets.AuthToken change, and neither token value is ever echoed. // a value-free "<changed>" marker, and neither token value is ever echoed.
var item = _diff.CompareSmsConfiguration(SmsDto(withSecret: true), ExistingSms()); 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; var json = item.FieldDiffJson ?? string.Empty;
Assert.DoesNotContain("stored-token", json); Assert.DoesNotContain("stored-token", json);
Assert.DoesNotContain("wire-token", json); Assert.DoesNotContain("wire-token", json);
@@ -672,19 +748,62 @@ public sealed class ArtifactDiffTests
Assert.Equal("inst-1", item.Name); 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] [Fact]
public void CompareInstance_StateDiffers_Modified() public void CompareInstance_StateOnlyDiffers_Identical()
{ {
var existing = new Instance("inst-1") { State = InstanceState.Disabled }; var existing = new Instance("inst-1") { State = InstanceState.Enabled };
var dto = MakeInstanceDto("inst-1", state: InstanceState.Enabled); var dto = MakeInstanceDto("inst-1", state: InstanceState.Disabled);
var item = _diff.CompareInstance(dto, existing); 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); Assert.Equal(ConflictKind.Modified, item.Kind);
var change = ChangeFor(item, "State");
Assert.Equal("Disabled", change.GetProperty("oldValue").GetString()); // Same connection (case-insensitively) => Identical.
Assert.Equal("Enabled", change.GetProperty("newValue").GetString()); 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> /// <summary>Verifies that an instance with no changes compares as identical.</summary>