diff --git a/docs/requirements/Component-Transport.md b/docs/requirements/Component-Transport.md index 3662d271..1858ba03 100644 --- a/docs/requirements/Component-Transport.md +++ b/docs/requirements/Component-Transport.md @@ -22,7 +22,7 @@ As of M8 (T18), Transport is no longer limited to central-only configuration: it - Move **site-scoped configuration** (T18): `Site` definitions, site-scoped `DataConnection`s (protocol connections — distinct from External-System `DatabaseConnection`s), and `Instance`s along with their `InstanceAttributeOverride` / `InstanceAlarmOverride` / `InstanceNativeAlarmSourceOverride` / `InstanceConnectionBinding` children and `Area` membership (carried by name). - Reconcile cross-environment site identifiers and connection names through the **name-mapping subsystem** (`BundleNameMap`): auto-match by identifier/name, operator override via the import-wizard Map step or CLI flags, and per-conflict create-or-bind resolution (see "Name Mapping"). - Compute a **per-line (Myers) diff** for code fields on Modified artifacts (T20) via the pure `LineDiffer`, embedding a size-capped structured line diff in each `ArtifactDiff`. Two independent caps guard the diff: a 400-line **output** cap on the emitted hunk list, and — as of arch-review 05 (Task 22) — a `MaxInputLines` **input** cap (4000 combined lines) that short-circuits the O((N+M)²) Myers trace to a summary-only result (`Truncated = true`, add/remove totals only) so a bloated or crafted bundle cannot OOM the active central node from the import preview. -- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature). Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack. +- Serialize and deserialize all transportable entity types to/from bundle DTOs, carving secret fields into an isolated `SecretsBlock`. A template travels with **all** of its child collections — `TemplateAttribute`, `TemplateAlarm`, `TemplateScript`, `TemplateComposition`, and `TemplateNativeAlarmSource` (including `IsInherited` placeholder rows, which the collision detector depends on) — each field-faithful on Add and reconciled add/update/delete on Overwrite. Field completeness is verified by a reflection round-trip guard over every writable property (Add + Overwrite), and includes the fields earlier revisions dropped: the derived-lock flag `LockedInDerived` on attributes/alarms/scripts, script cadence/timeout (`MinTimeBetweenRuns` / `ExecutionTimeoutSeconds`), and — for instances — the real `AreaName` (the exporter previously emitted `null`, half-shipping the Area-by-name feature) plus, since 2026-12-03 (TRN-8), the additive `AreaPath` (root→leaf names): the importer resolves the area level by level and creates any missing level under its real parent, since the same leaf name may sit under two parents. A pre-TRN-8 bundle carries only the leaf; an ambiguous leaf then resolves deterministically (a root-level area, else the lowest id) with an `ImportResult.Warnings` entry instead of taking whichever row came back first. Carrying the native alarm sources is what keeps an imported `InstanceNativeAlarmSourceOverride` from dangling against a source the target template would otherwise lack. - Encrypt content with AES-256-GCM + PBKDF2-SHA256 (600 000 iterations) when a passphrase is supplied; leave content plaintext with a UI warning and an `UnencryptedBundleExport` audit event when none is given. - Validate `manifest.json` on upload: format version gating, SHA-256 content hash verification. - **Optionally sign** exported bundles (ECDSA P-256 detached signature in `manifest.sig`) and enforce an import-side signature policy against a trust store — off by default (ScadaBridge#45; see "Bundle Signing"). @@ -97,7 +97,7 @@ The manifest is plaintext so the import wizard can preview bundle contents and s ### `content.json` / `content.enc` - One top-level array per entity type, POCO shapes serialized via `System.Text.Json`. As of schema 1.1 (T18) this includes `sites`, `dataConnections`, and `instances` arrays (`SiteDto`, `DataConnectionDto`, `InstanceDto` + its override-child and connection-binding DTOs) alongside the existing central-config arrays. -- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs as presence-only and are never echoed in plaintext. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields. +- Secret fields (API key hashes, SMTP password, external system credentials, DB connection passwords) live in a nested `secrets` block on each affected entity. Per the D3 "carry full config (encrypted secrets)" decision, a `DataConnection`'s `PrimaryConfiguration` / `BackupConfiguration` (endpoint + credentials) also ride inside this encrypted `SecretsBlock`; they appear in diffs presence-only and are never echoed in plaintext. **Secret values are still compared (2026-12-03, TRN-2):** the preview hashes both sides (SHA-256) and, when a value present on both sides differs, reports the value-free marker `` → ``, so the row classifies **Modified**. Before, only a presence flip counted, so a changed OPC UA endpoint (or DB connection string, external-system auth, SMTP credentials, SMS token) read *Identical* and was force-skipped, and an Overwrite driven by an unrelated field replaced the value unseen. A `Site`'s `NodeA`/`NodeB` and `GrpcNodeA`/`GrpcNodeB` addresses travel as ordinary (non-secret) `SiteDto` fields. - The whole `content` blob is AES-256-GCM encrypted with a key derived via PBKDF2-SHA256 (600 000 iterations) from the user's passphrase, with per-bundle random salt and per-encryption random IV. - Unencrypted bundles are allowed but the UI warns and audit-tags them `UnencryptedBundleExport`. @@ -234,7 +234,7 @@ Upload → Passphrase → Diff → Confirm → Result. The **Map** step is not a **Step 4 — Diff & resolve conflicts.** For each artifact in the bundle, compare to existing by name: - **Identical** (field-by-field) → marked, auto-skipped, cannot be selected. -- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename. +- **Modified** → shows a real per-line `+/-` diff for code fields (`TemplateScript.Code`, `SharedScript.Code`, `ApiMethod.Script`), rendered by the shared `LineDiffView` component from the structured `lineDiff` payload (T20). User picks Skip / Overwrite / Rename — **Rename is not offered for a Site, DataConnection, SmtpConfiguration or SmsConfiguration (TRN-9, 2026-12-03)**: it was silently treated as Skip for sites/connections and wrote a junk second SMTP/SMS row (mangled Host / AccountSid) that delivery never used. `ApplyAsync` rejects such a resolution (`ImportRenameSupport`), and the CLI's `--on-conflict rename` falls back to Skip for those types with a result warning. - **New** → marked `+ Add`. User can opt to skip individually. Bulk "Apply to all" at the top (Overwrite / Skip / Rename), overridable per row. Summary line at the bottom: "5 add · 2 overwrite · 1 skip · 0 rename". @@ -302,7 +302,7 @@ Site identifiers and connection names are environment-specific, so a bundle expo **Identity keys.** Sites are matched by `SiteIdentifier`; connections by the **site-qualified** key `{SiteIdentifier}/{Name}`; instances by `UniqueName`. -**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply. +**Auto-match → operator override → apply.** The importer first auto-matches every source site and connection against the target by these identity keys. **The preview honours the name map (2026-12-03, TRN-3):** `PreviewAsync` takes an optional `BundleNameMap`; under a MapToExisting redirect, the connection / instance diffs, the connection auto-match and the unresolved-connection blocker run against the **mapped** target site and connection. The CLI import passes its explicit `--map-site` / `--map-connection` redirects to the preview before the blocker gate (a connection present only on the mapped site used to be a blocker no mapping could clear), and the Central UI re-runs the preview under the Map-step choices when Confirm is pressed. On apply, a Create-new for a site identifier or a `(site, connection)` name the target already holds binds to that existing row (its own Skip/Overwrite resolution then applies) instead of inserting a duplicate the unique index rejects. **Site-scoped and template-reference lookups are case-insensitive (TRN-7)** — connections, instances, the instance's template, and the composition / inheritance rewire fallbacks match exact spelling first, then case-insensitively, the way the database collation and its unique indexes do. **Instance diff (TRN-6):** a binding's bound connection is compared by name (the existing FK is resolved per site), and `State` is no longer compared — the import never carries a live state, so a State-only difference read Modified and an Overwrite reset a live instance to `NotDeployed` for nothing. The operator confirms/overrides via the Central UI **Map step** (Step 3) or the CLI `--map-site` / `--map-connection` / `--create-missing-*` flags. References that neither auto-match nor are set to Create-new become **blocker rows** (UI) — or, on the CLI without `--create-missing-sites` / `--create-missing-connections`, abort before apply. **Template library reads (review 2026-10-21 04/P4 + 08/P1).** A preview and each apply attempt read the target template library **once**, through body-free projections (`GetTemplateStubsAsync` for id/name maps, `GetAllTemplatesForAnalysisAsync` — untracked, members and lock flags but no script bodies — where members or edges are needed), held on a per-session `TemplateLibrary` and threaded to every consumer: preview diff names, blocker and locked-override scans, apply-time validation, the composition/inheritance rewire fallbacks (formerly a full library reload *inside* the per-template loop), the instance pass's name→id map (overlaid with the change tracker's just-flushed templates), the acyclicity guard and the stale-instance expansion. The full tracked graph is loaded only for the templates the bundle **Overwrites** (`GetTemplatesWithChildrenAsync` by name), since their child syncs mutate it. The acyclicity guard reads the change tracker's staged templates overlaid on that snapshot — the untouched part of the graph has not changed during the apply. Instance lookups are batched by name set (`ITemplateEngineRepository.GetInstancesByUniqueNamesAsync`, one tracked + hydrated read for preview and one for the instance pass, Rename targets included), and the preview resolves an existing instance's template / site / area names from the library, one site list and one area list per site, and reads shared scripts and external systems once each. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor index 0659a4e2..1ce3bce2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor @@ -482,7 +482,10 @@ var key = (item.EntityType, item.Name);
- @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}";
diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs index f6f7fe3e..6c2f7fc8 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportImport.razor.cs @@ -823,9 +823,10 @@ public partial class TransportImport : ComponentBase, IDisposable return (adds, overs, skips, renames, blockers); } - private void GoToConfirm() + private async Task GoToConfirm() { if (_preview is null) return; + await RefreshPreviewUnderMappingAsync(); if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker)) { _errorMessage = "Cannot proceed while blockers exist — resolve or remove blocker rows first."; @@ -835,6 +836,58 @@ public partial class TransportImport : ComponentBase, IDisposable _step = ImportWizardStep.Confirm; } + /// + /// 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. + /// + private async Task RefreshPreviewUnderMappingAsync() + { + if (_session is null || _preview is null || _resolutions is null) return; + var map = BuildNameMap(); + var redirects = map.Sites.Any(m => m.Action == MappingAction.MapToExisting + && !string.Equals(m.TargetSiteIdentifier, m.SourceSiteIdentifier, StringComparison.Ordinal)) + || map.Connections.Any(m => m.Action == MappingAction.MapToExisting + && !string.Equals(m.TargetConnectionName, m.SourceConnectionName, StringComparison.Ordinal)); + if (!redirects) return; + + ImportPreview? refreshed; + try + { + refreshed = await BundleImporter.PreviewAsync(_session.SessionId, CancellationToken.None, map); + } + catch (Exception ex) + { + _errorMessage = $"Failed to refresh the import preview for the chosen mappings: {ex.Message}"; + return; + } + if (refreshed is null) return; + + var previousKinds = new Dictionary<(string, string), ConflictKind>(); + foreach (var item in _preview.Items) previousKinds[(item.EntityType, item.Name)] = item.Kind; + var defaults = BuildDefaultResolutions(refreshed); + foreach (var item in refreshed.Items) + { + var key = (item.EntityType, item.Name); + if (!_resolutions.ContainsKey(key) + || !previousKinds.TryGetValue(key, out var previousKind) + || previousKind != item.Kind) + { + _resolutions[key] = defaults[key]; + } + } + + _preview = refreshed with + { + RequiredSiteMappings = _preview.RequiredSiteMappings, + RequiredConnectionMappings = _preview.RequiredConnectionMappings, + }; + } + private void BackToDiff() { _step = ImportWizardStep.Diff; diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs index 4e6d6176..4fff74f4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleImporter.cs @@ -30,8 +30,15 @@ public interface IBundleImporter /// /// Session id returned by . /// Cancellation token. + /// + /// 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. null (the default) keeps the identity auto-match. + /// /// A task that resolves to a per-artifact import preview with conflict details. - Task PreviewAsync(Guid sessionId, CancellationToken ct = default); + Task PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null); /// /// Applies the chosen conflict resolutions and commits the import transaction. diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs index af41e137..e7b6b1fe 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Types/Transport/ImportResolution.cs @@ -7,3 +7,25 @@ public sealed record ImportResolution( string Name, ResolutionAction Action, string? RenameTo); + +/// +/// TRN-9: which preview entity types a 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 +/// --conflict-policy rename falls back to Skip for them with a warning. +/// +public static class ImportRenameSupport +{ + private static readonly HashSet Unsupported = new(StringComparer.Ordinal) + { + "Site", "DataConnection", "SmtpConfiguration", "SmsConfiguration", + }; + + /// True when a Rename resolution is supported for . + /// The preview item / resolution entity type. + /// false for Site, DataConnection, SmtpConfiguration and SmsConfiguration. + public static bool IsSupported(string entityType) => !Unsupported.Contains(entityType); +} diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 951c65b0..6dcdc81d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -4664,7 +4664,13 @@ public class ManagementActor : ReceiveActor // is safe even when ApplyAsync already released the same id. try { - var preview = await importer.PreviewAsync(session.SessionId); + // TRN-3: an explicit --map-site / --map-connection redirect changes what + // the site-scoped preview rows resolve against, so the preview (and its + // unresolved-connection blockers and auto-matches) runs under those + // redirects — otherwise a connection present only on the MAPPED site was + // a blocker no mapping could clear. + var preview = await importer.PreviewAsync( + session.SessionId, nameMap: BuildExplicitRedirectMap(cmd)); var blockers = preview.Items.Where(i => i.Kind == ConflictKind.Blocker).ToList(); if (blockers.Count > 0) @@ -4690,6 +4696,7 @@ public class ManagementActor : ReceiveActor // automatically correct — no bare-connection-name special case needed. var renameStamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss"); var resolutionsMap = new Dictionary<(string, string), ImportResolution>(); + var renameFallbacks = new SortedSet(StringComparer.Ordinal); foreach (var item in preview.Items) { var action = item.Kind switch @@ -4699,15 +4706,31 @@ public class ManagementActor : ReceiveActor ConflictKind.Modified => policy, _ => ResolutionAction.Skip, }; - var renameTo = (item.Kind == ConflictKind.Modified && policy == ResolutionAction.Rename) + // TRN-9: --conflict-policy rename has no meaning for a site, data + // connection or SMTP/SMS configuration (the importer rejects it); + // fall back to Skip for those and say so in the result. + if (action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(item.EntityType)) + { + action = ResolutionAction.Skip; + renameFallbacks.Add($"{item.EntityType} '{item.Name}'"); + } + var renameTo = (item.Kind == ConflictKind.Modified && action == ResolutionAction.Rename) ? $"{item.Name}-imported-{renameStamp}" : null; resolutionsMap[(item.EntityType, item.Name)] = new ImportResolution( item.EntityType, item.Name, action, renameTo); } - return await importer.ApplyAsync( + var importResult = await importer.ApplyAsync( session.SessionId, resolutionsMap.Values.ToList(), username, nameMap: nameMap); + if (renameFallbacks.Count == 0) return importResult; + return importResult with + { + Warnings = importResult.Warnings + .Concat(renameFallbacks.Select(f => + $"{f} was skipped: Rename is not supported for sites, data connections, SMTP or SMS configurations.")) + .ToList(), + }; } finally { @@ -4720,6 +4743,27 @@ public class ManagementActor : ReceiveActor } } + /// + /// TRN-3: the operator's explicit MapToExisting redirects (a --map-site / + /// --map-connection with a target) as a for the + /// preview, or null when there are none (the preview then keeps its identity + /// auto-match). Create-new specs are not redirects and are left to + /// . + /// + private static BundleNameMap? BuildExplicitRedirectMap(ImportBundleCommand cmd) + { + var sites = (cmd.SiteMappings ?? Array.Empty()) + .Where(s => !string.IsNullOrWhiteSpace(s.TargetSiteIdentifier)) + .Select(s => new SiteMapping(s.SourceSiteIdentifier, MappingAction.MapToExisting, s.TargetSiteIdentifier)) + .ToList(); + var connections = (cmd.ConnectionMappings ?? Array.Empty()) + .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); + } + /// /// Merges the operator-supplied / /// lists with the preview's auto-matches diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs index 8a54e9f6..cb681c5d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs @@ -98,6 +98,38 @@ public sealed class BundleExporter : IBundleExporter .ToDictionaryAsync(a => a.Id, a => a.Name, cancellationToken) .ConfigureAwait(false); + // TRN-8: the full root→leaf path of each referenced area — the same leaf name + // may exist under two parents. One read of the areas of the sites involved. + var areaPathById = new Dictionary>(); + 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(); + var seen = new HashSet(); + int? current = areaId; + while (current is { } id && siteAreas.TryGetValue(id, out var area) && seen.Add(id)) + { + path.Add(area.Name); + current = area.ParentAreaId; + } + if (path.Count == 0 || current is not null) continue; // orphan/cyclic chain: leaf name only + path.Reverse(); + areaPathById[areaId] = path; + } + } + // 2. Convert to the wire-shaped DTO (strips EF identity, refs-by-name). // The resolver's site/dataConnection/instance closure is wired // through via object-initializer — without this the aggregate would @@ -126,6 +158,7 @@ public sealed class BundleExporter : IBundleExporter // Area id→name lookup for the exported instances — feeds the serializer's // AreaName projection so each instance's area travels by name. AreaNameById = areaNameById, + AreaPathById = areaPathById, }; var contentDto = _entitySerializer.ToBundleContent(aggregate); diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/ArtifactDiff.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/ArtifactDiff.cs index a9fbf5f0..7a51994c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/ArtifactDiff.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/ArtifactDiff.cs @@ -237,15 +237,10 @@ public sealed class ArtifactDiff // target's existing timeout untouched in that case. AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds); - // Secrets: presence-only comparison (we never echo the value in the diff). - var existingHasSecret = !string.IsNullOrEmpty(existing.AuthConfiguration); - var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthConfiguration"); - if (existingHasSecret != incomingHasSecret) - { - changes.Add(new FieldChange("Secrets.AuthConfiguration", - existingHasSecret ? "" : null, - incomingHasSecret ? "" : null)); - } + // Secrets: compared by hash, reported presence-only (TRN-2 — the value is never + // echoed in the diff, but a changed value is no longer read as Identical). + AddSecretChange(changes, "Secrets.AuthConfiguration", + existing.AuthConfiguration, SecretValue(incoming.Secrets, "AuthConfiguration")); // Methods are name-keyed children. var existingForCompare = existingMethods ?? Array.Empty(); @@ -276,15 +271,10 @@ public sealed class ArtifactDiff AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries); AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString()); - // ConnectionString lives in Secrets only — presence-only comparison. - var existingHasSecret = !string.IsNullOrEmpty(existing.ConnectionString); - var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("ConnectionString"); - if (existingHasSecret != incomingHasSecret) - { - changes.Add(new FieldChange("Secrets.ConnectionString", - existingHasSecret ? "" : null, - incomingHasSecret ? "" : null)); - } + // ConnectionString lives in Secrets only — compared by hash, reported + // presence-only (TRN-2). + AddSecretChange(changes, "Secrets.ConnectionString", + existing.ConnectionString, SecretValue(incoming.Secrets, "ConnectionString")); return BuildItem("DatabaseConnection", incoming.Name, changes); } @@ -345,14 +335,9 @@ public sealed class ArtifactDiff AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope); AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport); - var existingHasSecret = !string.IsNullOrEmpty(existing.Credentials); - var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("Credentials"); - if (existingHasSecret != incomingHasSecret) - { - changes.Add(new FieldChange("Secrets.Credentials", - existingHasSecret ? "" : null, - incomingHasSecret ? "" : null)); - } + // TRN-2: compared by hash, reported presence-only. + AddSecretChange(changes, "Secrets.Credentials", + existing.Credentials, SecretValue(incoming.Secrets, "Credentials")); return BuildItem("SmtpConfiguration", incoming.Host, changes); } @@ -379,14 +364,9 @@ public sealed class ArtifactDiff AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries); AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString()); - var existingHasSecret = !string.IsNullOrEmpty(existing.AuthToken); - var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthToken"); - if (existingHasSecret != incomingHasSecret) - { - changes.Add(new FieldChange("Secrets.AuthToken", - existingHasSecret ? "" : null, - incomingHasSecret ? "" : null)); - } + // TRN-2: compared by hash, reported presence-only. + AddSecretChange(changes, "Secrets.AuthToken", + existing.AuthToken, SecretValue(incoming.Secrets, "AuthToken")); return BuildItem("SmsConfiguration", incoming.AccountSid, changes); } @@ -481,13 +461,12 @@ public sealed class ArtifactDiff AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount); // Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration). - // Presence-only comparison — never echo the config value. - AddSecretPresenceChange(changes, "Secrets.PrimaryConfiguration", - !string.IsNullOrEmpty(existing.PrimaryConfiguration), - HasSecretKey(incoming.Secrets, "PrimaryConfiguration")); - AddSecretPresenceChange(changes, "Secrets.BackupConfiguration", - !string.IsNullOrEmpty(existing.BackupConfiguration), - HasSecretKey(incoming.Secrets, "BackupConfiguration")); + // Compared by hash, reported presence-only — never echo the config value + // (TRN-2: a changed endpoint URL used to read Identical and be force-skipped). + AddSecretChange(changes, "Secrets.PrimaryConfiguration", + existing.PrimaryConfiguration, SecretValue(incoming.Secrets, "PrimaryConfiguration")); + AddSecretChange(changes, "Secrets.BackupConfiguration", + existing.BackupConfiguration, SecretValue(incoming.Secrets, "BackupConfiguration")); return BuildItem("DataConnection", incoming.Name, changes); } @@ -510,13 +489,19 @@ public sealed class ArtifactDiff /// The existing instance's template name (the entity carries only a FK), or null if unknown. /// The existing instance's site identifier (the entity carries only a FK), or null if unknown. /// The existing instance's area name (the entity carries only a FK), or null if unknown / unset. + /// 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. + /// TRN-8: the existing instance's root→leaf area path; compared instead of the + /// leaf name when the incoming instance carries an . /// An import preview item describing the conflict type and differences. public ImportPreviewItem CompareInstance( InstanceDto incoming, Instance? existing, string? existingTemplateName = null, string? existingSiteIdentifier = null, - string? existingAreaName = null) + string? existingAreaName = null, + IReadOnlyDictionary? existingConnectionNameById = null, + IReadOnlyList? existingAreaPath = null) { ArgumentNullException.ThrowIfNull(incoming); if (existing is null) return New("Instance", incoming.UniqueName); @@ -533,8 +518,21 @@ public sealed class ArtifactDiff { AddIfDifferent(changes, "SiteIdentifier", existingSiteIdentifier, incoming.SiteIdentifier); } - AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName); - AddIfDifferent(changes, "State", existing.State.ToString(), incoming.State.ToString()); + if (incoming.AreaPath is { Count: > 0 } incomingPath && (existingAreaPath is not null || existing.AreaId is null)) + { + // TRN-8: the same leaf name can sit under two parents — compare the full path. + AddIfDifferent(changes, "AreaPath", + existingAreaPath is null ? null : string.Join("/", existingAreaPath), + string.Join("/", incomingPath)); + } + else + { + AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName); + } + // TRN-6: State is not compared — an import always writes NotDeployed for a new + // instance and never carries a live state across environments, so a State-only + // difference used to read Modified and an Overwrite then reset a live instance + // to NotDeployed for no configuration change. DiffChildren( existing.AttributeOverrides, @@ -573,10 +571,14 @@ public sealed class ArtifactDiff incoming.ConnectionBindings, e => e.AttributeName, i => i.AttributeName, - // ConnectionName resolves to a FK on the entity (DataConnectionId) that - // can't be compared cross-environment, so the binding diff compares only - // the per-attribute DataSourceReference override. - (e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride, + // TRN-6: the entity binds by FK (DataConnectionId); the caller resolves it to + // the target connection's name, which is compared (case-insensitively, like + // the unique (SiteId, Name) index) together with the per-attribute + // DataSourceReference override. A rebind OPC1 -> OPC2 used to read Identical. + (e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride + && (existingConnectionNameById is null + || (existingConnectionNameById.TryGetValue(e.DataConnectionId, out var boundName) + && string.Equals(boundName, i.ConnectionName, StringComparison.OrdinalIgnoreCase))), "ConnectionBindings", changes); @@ -657,24 +659,37 @@ public sealed class ArtifactDiff }; /// True if carries the named key. - private static bool HasSecretKey(SecretsBlock? secrets, string key) => - secrets is not null && secrets.Values.ContainsKey(key); + private static string? SecretValue(SecretsBlock? secrets, string key) => + secrets is not null && secrets.Values.TryGetValue(key, out var value) ? value : null; /// - /// Records a presence-only secret change (a flip in whether a value is set on - /// each side) using the <present> / null marker convention. The - /// secret value itself is NEVER read into the diff — only its presence. + /// TRN-2: compares a secret-bearing value by SHA-256 hash and reports the result + /// presence-only. A flip in presence uses the <present> / null markers; + /// a value present on both sides that DIFFERS is reported as + /// <present> → <changed>, so the row classifies Modified + /// (it used to read Identical and be force-skipped) while the value itself never + /// reaches the diff. /// - private static void AddSecretPresenceChange(List changes, string field, bool existingHasSecret, bool incomingHasSecret) + private static void AddSecretChange(List changes, string field, string? existingValue, string? incomingValue) { - if (existingHasSecret != incomingHasSecret) + var existingHas = !string.IsNullOrEmpty(existingValue); + var incomingHas = !string.IsNullOrEmpty(incomingValue); + if (existingHas != incomingHas) { changes.Add(new FieldChange(field, - existingHasSecret ? "" : null, - incomingHasSecret ? "" : null)); + existingHas ? "" : null, + incomingHas ? "" : null)); + return; + } + if (existingHas && !SecretHash(existingValue!).AsSpan().SequenceEqual(SecretHash(incomingValue!))) + { + changes.Add(new FieldChange(field, "", "")); } } + private static byte[] SecretHash(string value) => + System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value)); + private static void DiffChildren( IEnumerable existing, IEnumerable incoming, diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs index 470ab3c7..b7c3526d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Import/BundleImporter.cs @@ -477,7 +477,7 @@ public sealed partial class BundleImporter : IBundleImporter } /// - public async Task PreviewAsync(Guid sessionId, CancellationToken ct = default) + public async Task PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null) { var session = _sessionStore.Get(sessionId) ?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired."); @@ -628,10 +628,16 @@ public sealed partial class BundleImporter : IBundleImporter var targetConnectionsBySiteIdentifier = new Dictionary>(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 ResolveTargetSiteAsync(string siteIdentifier) { if (targetSiteByIdentifier.TryGetValue(siteIdentifier, out var cached)) return cached; - var site = await _siteRepo.GetSiteByIdentifierAsync(siteIdentifier, ct).ConfigureAwait(false); + var site = await _siteRepo.GetSiteByIdentifierAsync( + previewMap.TargetSiteIdentifier(siteIdentifier), ct).ConfigureAwait(false); targetSiteByIdentifier[siteIdentifier] = site; return site; } @@ -684,7 +690,10 @@ public sealed partial class BundleImporter : IBundleImporter foreach (var dcDto in content.DataConnections) { var targetConns = await ResolveTargetConnectionsAsync(dcDto.SiteIdentifier).ConfigureAwait(false); - var existing = targetConns.FirstOrDefault(c => string.Equals(c.Name, dcDto.Name, StringComparison.Ordinal)); + // TRN-7: names compare the way the database's case-insensitive collation + // (and its unique (SiteId, Name) index) does — exact spelling first. + var existing = FindByName(targetConns, c => c.Name, + previewMap.TargetConnectionName(dcDto.SiteIdentifier, dcDto.Name)); var item = _diff.CompareDataConnection(dcDto, existing); items.Add(item with { Name = QualifiedConnectionName(dcDto.SiteIdentifier, dcDto.Name) }); } @@ -698,14 +707,21 @@ public sealed partial class BundleImporter : IBundleImporter // batched read for every bundled instance, and the template / site / area // names come from the library projection, one site list and one area list // per site — not four queries per instance. + // TRN-7: case-insensitive like the unique index on UniqueName (exact spelling wins). + var bundleInstanceNames = content.Instances.Select(i => i.UniqueName).ToHashSet(StringComparer.Ordinal); var existingInstanceByName = content.Instances.Count == 0 - ? new Dictionary(StringComparer.Ordinal) - : (await _templateRepo + ? new Dictionary(StringComparer.OrdinalIgnoreCase) + : ToNameLookup( + (await _templateRepo .GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct) .ConfigureAwait(false)) - .ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal); + .OrderBy(i => bundleInstanceNames.Contains(i.UniqueName) ? 0 : 1), + i => i.UniqueName); + // TRN-6: an existing binding stores a DataConnectionId; resolve it to the + // connection's name (per site, one read) so the diff can compare it. + var connectionNameByIdBySite = new Dictionary>(); Dictionary? siteIdentifierById = null; - var areaNameByIdBySite = new Dictionary>(); + var areaNameByIdBySite = new Dictionary>(); foreach (var instDto in content.Instances) { existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing); @@ -713,8 +729,17 @@ public sealed partial class BundleImporter : IBundleImporter string? existingTemplateName = null; string? existingSiteIdentifier = null; string? existingAreaName = null; + IReadOnlyList? existingAreaPath = null; + IReadOnlyDictionary? existingConnectionNames = null; if (existing is not null) { + if (!connectionNameByIdBySite.TryGetValue(existing.SiteId, out existingConnectionNames)) + { + existingConnectionNames = (await _siteRepo.GetDataConnectionsBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false)) + .ToDictionary(c => c.Id, c => c.Name); + connectionNameByIdBySite[existing.SiteId] = existingConnectionNames; + } + // The entity stores template/site/area as numeric FKs that can't be // compared cross-environment, so resolve each to the same stable // string identity the incoming DTO carries. @@ -726,27 +751,39 @@ public sealed partial class BundleImporter : IBundleImporter if (existing.AreaId is int areaId) { - if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areaNames)) + if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areasById)) { - areaNames = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false)) - .ToDictionary(a => a.Id, a => a.Name); - areaNameByIdBySite[existing.SiteId] = areaNames; + areasById = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false)) + .ToDictionary(a => a.Id, a => a); + areaNameByIdBySite[existing.SiteId] = areasById; } - existingAreaName = areaNames.TryGetValue(areaId, out var an) ? an : null; + existingAreaName = areasById.TryGetValue(areaId, out var area) ? area.Name : null; + existingAreaPath = AreaPathOf(areaId, areasById); } } + // Compare against what the apply would write: the mapped target site and + // the mapped target connection names (TRN-3). + var mappedDto = instDto with + { + SiteIdentifier = previewMap.TargetSiteIdentifier(instDto.SiteIdentifier), + ConnectionBindings = instDto.ConnectionBindings + .Select(b => b with { ConnectionName = previewMap.TargetConnectionName(instDto.SiteIdentifier, b.ConnectionName) }) + .ToList(), + }; items.Add(_diff.CompareInstance( - instDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName)); + mappedDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName, + existingConnectionNames, existingAreaPath)); } // ---- Required site/connection mappings ---- var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync( - content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync).ConfigureAwait(false); + content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName).ConfigureAwait(false); // ---- Blocker detection ---- items.AddRange(await DetectBlockersAsync( - content, ResolveTargetConnectionsAsync, library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false)); + content, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName, + library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false)); return new ImportPreview(sessionId, items, requiredSites, requiredConnections); } @@ -772,7 +809,8 @@ public sealed partial class BundleImporter : IBundleImporter BuildRequiredMappingsAsync( BundleContentDto content, Func> resolveTargetSite, - Func>> resolveTargetConnections) + Func>> resolveTargetConnections, + Func targetConnectionName) { // Distinct source-site identifiers, with a best-effort display name. // SiteDto carries a Name; instances / data-connections only carry the @@ -838,11 +876,11 @@ public sealed partial class BundleImporter : IBundleImporter // Auto-match only WITHIN the auto-matched target site: a connection of // the same name under a different site is not a valid match. var targetConns = await resolveTargetConnections(site).ConfigureAwait(false); - var matched = targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal)); + var matched = FindByName(targetConns, c => c.Name, targetConnectionName(site, name)); connectionMappings.Add(new RequiredConnectionMapping( SourceSiteIdentifier: site, SourceConnectionName: name, - AutoMatchTargetName: matched ? name : null)); + AutoMatchTargetName: matched?.Name)); } return (siteMappings, connectionMappings); @@ -860,6 +898,7 @@ public sealed partial class BundleImporter : IBundleImporter private async Task> DetectBlockersAsync( BundleContentDto content, Func>> resolveTargetConnections, + Func targetConnectionName, TemplateLibrary library, IReadOnlyList allSharedScripts, IReadOnlyList allExternalSystems, @@ -871,7 +910,8 @@ public sealed partial class BundleImporter : IBundleImporter // The set of template names the import can satisfy = (in-bundle templates) // ∪ (templates already in the target DB). An instance whose TemplateName is // in neither is unresolvable. - var bundleTemplateNames = new HashSet(StringComparer.Ordinal); + // TRN-7: instance template names resolve case-insensitively on apply. + var bundleTemplateNames = new HashSet(StringComparer.OrdinalIgnoreCase); // A derived slot template is not something an instance is created from (#118). foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t))) bundleTemplateNames.Add(t.Name); // ScadaBridge#118: a malformed or cyclic derivation fails the apply outright. @@ -893,7 +933,7 @@ public sealed partial class BundleImporter : IBundleImporter // Members + lock flags are needed below (CollectLockedOverrideWarnings) but // never script bodies — the body-free, untracked analysis projection (04/P4). var targetTemplates = await library.GetAnalysisAsync(ct).ConfigureAwait(false); - var targetTemplateNames = new HashSet(StringComparer.Ordinal); + var targetTemplateNames = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var t in targetTemplates) { targetTemplateNames.Add(t.Name); @@ -951,7 +991,7 @@ public sealed partial class BundleImporter : IBundleImporter { if (bundleConnections.Contains((site, name))) continue; var targetConns = await resolveTargetConnections(site).ConfigureAwait(false); - if (targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) continue; + if (FindByName(targetConns, c => c.Name, targetConnectionName(site, name)) is not null) continue; // Site-qualify the blocker Name so two sites' same-named-but-missing // connections surface as distinct blockers (a bare name would collide). blockers.Add(new ImportPreviewItem( @@ -1613,6 +1653,21 @@ public sealed partial class BundleImporter : IBundleImporter ArgumentNullException.ThrowIfNull(resolutions); ArgumentNullException.ThrowIfNull(user); + // TRN-9: Rename is meaningless for a site, a data connection and the SMTP / + // SMS configurations (it was silently Skipped, or wrote a mangled junk row + // delivery never uses). Reject it up front rather than report "Renamed: 1". + var unsupportedRenames = resolutions + .Where(r => r.Action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(r.EntityType)) + .Select(r => $"{r.EntityType} '{r.Name}'") + .ToList(); + if (unsupportedRenames.Count > 0) + { + throw new ArgumentException( + "Rename is not supported for sites, data connections, SMTP or SMS configurations; " + + "choose Skip or Overwrite for: " + string.Join(", ", unsupportedRenames) + ".", + nameof(resolutions)); + } + // Normalise null → Empty so the resolve-or-create logic always has a map // to consult. An empty map means "no explicit operator mappings" — every // referenced site/connection falls through to the identity auto-match. @@ -1995,9 +2050,10 @@ public sealed partial class BundleImporter : IBundleImporter // It writes the instance row + its four child collections (attribute / // alarm / native-alarm-source overrides + connection bindings) and // rewires every name-keyed FK to the target environment's ids. + var instanceWarnings = new List(); await ApplyInstancesAsync( content, resolutionMap, siteBySourceIdentifier, connectionMaps, - library, user, summary, ct).ConfigureAwait(false); + library, user, summary, instanceWarnings, ct).ConfigureAwait(false); // ---- Pre-commit point: stale-instance computation ---- // Everything the import will write is staged on the change tracker at @@ -2050,7 +2106,9 @@ public sealed partial class BundleImporter : IBundleImporter StaleInstanceIds: staleInstanceIds, AuditEventCorrelation: bundleImportId.ToString(), ApiKeysIgnored: apiKeysIgnored, - Warnings: derivedWarnings.Count == 0 ? validationWarnings : validationWarnings.Concat(derivedWarnings).ToList()); + Warnings: derivedWarnings.Count == 0 && instanceWarnings.Count == 0 + ? validationWarnings + : validationWarnings.Concat(derivedWarnings).Concat(instanceWarnings).ToList()); } /// @@ -2208,7 +2266,7 @@ public sealed partial class BundleImporter : IBundleImporter { var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name); if (resolution.Action != ResolutionAction.Overwrite) continue; - if (targetTemplateIdByName.TryGetValue(dto.Name, out var templateId)) + if (TryGetIdByNameIgnoreCase(targetTemplateIdByName, dto.Name, out var templateId)) { overwrittenTemplateIds.Add(templateId); } @@ -2418,6 +2476,96 @@ public sealed partial class BundleImporter : IBundleImporter /// throw on a duplicate key: the first row for a name wins. Used wherever a /// by-name DB result is re-keyed in memory (ScadaBridge#93). /// + /// + /// TRN-7: finds the row named 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. + /// + internal static T? FindByName(IEnumerable rows, Func 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; + } + + /// + /// TRN-8: the root→leaf name path of area , or null when the + /// parent chain is broken or cyclic. + /// + private static IReadOnlyList? AreaPathOf(int areaId, IReadOnlyDictionary areasById) + { + var path = new List(); + var seen = new HashSet(); + 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; + } + + /// + /// TRN-7: looks 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). + /// + internal static bool TryGetIdByNameIgnoreCase(IReadOnlyDictionary 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; + } + + /// + /// TRN-3: the operator's as seen by the preview — the + /// target site identifier and target connection name a source reference resolves to. + /// Only a entry with an explicit target + /// redirects; every other reference keeps its source identity (the identity + /// auto-match the apply performs for it as well). + /// + private sealed class PreviewNameMap + { + private readonly Dictionary _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 ToNameLookup(IEnumerable rows, Func name) { var lookup = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -3458,11 +3606,13 @@ public sealed partial class BundleImporter : IBundleImporter // The fallback is a dictionary lookup into the per-apply library // snapshot (04/P4) — a name not in Local is a pre-existing target // template this apply has not touched, so its pre-write id is current. - localByName.TryGetValue(compDto.ComposedTemplateName, out var composedStub); + // TRN-7: exact spelling first, then case-insensitive (the database's + // collation treats a case variant as the same template). + localByName.TryGetImported(compDto.ComposedTemplateName, out var composedStub); int? composedId = composedStub?.Id; if (composedId is null - && (await library.GetIdByNameAsync(ct).ConfigureAwait(false)) - .TryGetValue(compDto.ComposedTemplateName, out var libraryId)) + && TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false), + compDto.ComposedTemplateName, out var libraryId)) { composedId = libraryId; } @@ -3551,10 +3701,13 @@ public sealed partial class BundleImporter : IBundleImporter ? (baseResolution.RenameTo ?? dto.BaseTemplateName) : dto.BaseTemplateName; - localByName.TryGetValue(baseName, out var baseStub); + // TRN-7: exact spelling first, then case-insensitive — a bundle base + // 'PumpBase' overwriting target 'pumpbase' used to miss both lookups and + // null the child's ParentTemplateId. + localByName.TryGetImported(baseName, out var baseStub); int? baseId = baseStub?.Id; if (baseId is null - && (await library.GetIdByNameAsync(ct).ConfigureAwait(false)).TryGetValue(baseName, out var libraryId)) + && TryGetIdByNameIgnoreCase(await library.GetIdByNameAsync(ct).ConfigureAwait(false), baseName, out var libraryId)) { baseId = libraryId; } @@ -3632,13 +3785,6 @@ public sealed partial class BundleImporter : IBundleImporter _exact.TryGetValue(name, out template!) || _ignoreCase.TryGetValue(name, out template!); } - /// - /// Loads the given tracked templates with their child collections in one batched - /// read (Gitea #47 — previously one GetTemplateWithChildrenAsync 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. - /// /// /// TRN-5: true when owns a slot-derived template /// (IsDerived with OwnerCompositionId pointing back at the row) that no @@ -3659,6 +3805,13 @@ public sealed partial class BundleImporter : IBundleImporter && !bundleComposedNames.Contains(composed.Name); } + /// + /// Loads the given tracked templates with their child collections in one batched + /// read (Gitea #47 — previously one GetTemplateWithChildrenAsync 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. + /// private async Task> LoadTemplatesWithChildrenAsync( IEnumerable