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
@@ -482,7 +482,10 @@
var key = (item.EntityType, item.Name);
<div class="d-flex flex-wrap gap-2 align-items-center">
@foreach (var action in new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename })
@* TRN-9: Rename is not offered where it has no meaning (site, data connection, SMTP/SMS). *@
@foreach (var action in ImportRenameSupport.IsSupported(item.EntityType)
? new[] { ResolutionAction.Overwrite, ResolutionAction.Skip, ResolutionAction.Rename }
: new[] { ResolutionAction.Overwrite, ResolutionAction.Skip })
{
var inputId = $"res-{item.EntityType}-{item.Name}-{action}";
<div class="form-check form-check-inline mb-0">
@@ -823,9 +823,10 @@ public partial class TransportImport : ComponentBase, IDisposable
return (adds, overs, skips, renames, blockers);
}
private void GoToConfirm()
private async Task GoToConfirm()
{
if (_preview is null) return;
await RefreshPreviewUnderMappingAsync();
if (_preview.Items.Any(i => i.Kind == ConflictKind.Blocker))
{
_errorMessage = "Cannot proceed while blockers exist — resolve or remove blocker rows first.";
@@ -835,6 +836,58 @@ public partial class TransportImport : ComponentBase, IDisposable
_step = ImportWizardStep.Confirm;
}
/// <summary>
/// TRN-3: when the Map step redirects a source site or connection to a differently
/// named target, the diff rows, auto-matches and unresolved-connection blockers of
/// the first preview were computed against the SOURCE identity. Re-run the preview
/// under the current name map so the blocker gate (and the diff table) reflect the
/// mapped targets. The Map step's required-mapping lists are kept (they are keyed
/// by source reference); resolutions the operator already chose are kept unless the
/// row's conflict kind changed, in which case that row gets its new default.
/// </summary>
private async Task RefreshPreviewUnderMappingAsync()
{
if (_session is null || _preview is null || _resolutions is null) return;
var map = BuildNameMap();
var redirects = map.Sites.Any(m => m.Action == MappingAction.MapToExisting
&& !string.Equals(m.TargetSiteIdentifier, m.SourceSiteIdentifier, StringComparison.Ordinal))
|| map.Connections.Any(m => m.Action == MappingAction.MapToExisting
&& !string.Equals(m.TargetConnectionName, m.SourceConnectionName, StringComparison.Ordinal));
if (!redirects) return;
ImportPreview? refreshed;
try
{
refreshed = await BundleImporter.PreviewAsync(_session.SessionId, CancellationToken.None, map);
}
catch (Exception ex)
{
_errorMessage = $"Failed to refresh the import preview for the chosen mappings: {ex.Message}";
return;
}
if (refreshed is null) return;
var previousKinds = new Dictionary<(string, string), ConflictKind>();
foreach (var item in _preview.Items) previousKinds[(item.EntityType, item.Name)] = item.Kind;
var defaults = BuildDefaultResolutions(refreshed);
foreach (var item in refreshed.Items)
{
var key = (item.EntityType, item.Name);
if (!_resolutions.ContainsKey(key)
|| !previousKinds.TryGetValue(key, out var previousKind)
|| previousKind != item.Kind)
{
_resolutions[key] = defaults[key];
}
}
_preview = refreshed with
{
RequiredSiteMappings = _preview.RequiredSiteMappings,
RequiredConnectionMappings = _preview.RequiredConnectionMappings,
};
}
private void BackToDiff()
{
_step = ImportWizardStep.Diff;
@@ -30,8 +30,15 @@ public interface IBundleImporter
/// </summary>
/// <param name="sessionId">Session id returned by <see cref="LoadAsync"/>.</param>
/// <param name="ct">Cancellation token.</param>
/// <param name="nameMap">
/// TRN-3: optional operator site/connection mapping. When supplied, every site-scoped
/// preview lookup (connection and instance diffs, the required-mapping auto-match and
/// the unresolved-connection blocker) runs against the MAPPED target site and connection
/// names instead of the source identity, so a preview reflects what the apply with the
/// same map will do. <c>null</c> (the default) keeps the identity auto-match.
/// </param>
/// <returns>A task that resolves to a per-artifact import preview with conflict details.</returns>
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default);
Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null);
/// <summary>
/// Applies the chosen conflict resolutions and commits the import transaction.
@@ -7,3 +7,25 @@ public sealed record ImportResolution(
string Name,
ResolutionAction Action,
string? RenameTo);
/// <summary>
/// TRN-9: which preview entity types a <see cref="ResolutionAction.Rename"/> resolution
/// is meaningful for. A Site, a site-scoped DataConnection, an SMTP configuration and
/// an SMS configuration have no renameable identity: a renamed site/connection was
/// silently treated as Skip, and a renamed SMTP/SMS row mangled the Host / AccountSid
/// into a junk second row that delivery (lowest-id wins) never used. The importer
/// rejects Rename for these types, the Central UI does not offer it, and the CLI's
/// <c>--conflict-policy rename</c> falls back to Skip for them with a warning.
/// </summary>
public static class ImportRenameSupport
{
private static readonly HashSet<string> Unsupported = new(StringComparer.Ordinal)
{
"Site", "DataConnection", "SmtpConfiguration", "SmsConfiguration",
};
/// <summary>True when a Rename resolution is supported for <paramref name="entityType"/>.</summary>
/// <param name="entityType">The preview item / resolution entity type.</param>
/// <returns><c>false</c> for Site, DataConnection, SmtpConfiguration and SmsConfiguration.</returns>
public static bool IsSupported(string entityType) => !Unsupported.Contains(entityType);
}
@@ -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<string>(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
}
}
/// <summary>
/// TRN-3: the operator's explicit MapToExisting redirects (a <c>--map-site</c> /
/// <c>--map-connection</c> with a target) as a <see cref="BundleNameMap"/> for the
/// preview, or <c>null</c> when there are none (the preview then keeps its identity
/// auto-match). Create-new specs are not redirects and are left to
/// <see cref="BuildNameMap"/>.
/// </summary>
private static BundleNameMap? BuildExplicitRedirectMap(ImportBundleCommand cmd)
{
var sites = (cmd.SiteMappings ?? Array.Empty<SiteMappingSpec>())
.Where(s => !string.IsNullOrWhiteSpace(s.TargetSiteIdentifier))
.Select(s => new SiteMapping(s.SourceSiteIdentifier, MappingAction.MapToExisting, s.TargetSiteIdentifier))
.ToList();
var connections = (cmd.ConnectionMappings ?? Array.Empty<ConnectionMappingSpec>())
.Where(c => !string.IsNullOrWhiteSpace(c.TargetConnectionName))
.Select(c => new ConnectionMapping(
c.SourceSiteIdentifier, c.SourceConnectionName, MappingAction.MapToExisting, c.TargetConnectionName))
.ToList();
return sites.Count == 0 && connections.Count == 0 ? null : new BundleNameMap(sites, connections);
}
/// <summary>
/// Merges the operator-supplied <see cref="SiteMappingSpec"/> /
/// <see cref="ConnectionMappingSpec"/> lists with the preview's auto-matches
@@ -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<int, IReadOnlyList<string>>();
if (referencedAreaIds.Count > 0)
{
var areaSiteIds = await _dbContext.Areas
.Where(a => referencedAreaIds.Contains(a.Id))
.Select(a => a.SiteId)
.Distinct()
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
var siteAreas = await _dbContext.Areas.AsNoTracking()
.Where(a => areaSiteIds.Contains(a.SiteId))
.Select(a => new { a.Id, a.Name, a.ParentAreaId })
.ToDictionaryAsync(a => a.Id, cancellationToken)
.ConfigureAwait(false);
foreach (var areaId in referencedAreaIds)
{
var path = new List<string>();
var seen = new HashSet<int>();
int? current = areaId;
while (current is { } id && siteAreas.TryGetValue(id, out var area) && seen.Add(id))
{
path.Add(area.Name);
current = area.ParentAreaId;
}
if (path.Count == 0 || current is not null) continue; // orphan/cyclic chain: leaf name only
path.Reverse();
areaPathById[areaId] = path;
}
}
// 2. Convert to the wire-shaped DTO (strips EF identity, refs-by-name).
// The resolver's site/dataConnection/instance closure is wired
// through via object-initializer — without this the aggregate would
@@ -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);
@@ -237,15 +237,10 @@ public sealed class ArtifactDiff
// target's existing timeout untouched in that case.
AddIfDifferent(changes, "TimeoutSeconds", existing.TimeoutSeconds, incoming.TimeoutSeconds ?? existing.TimeoutSeconds);
// Secrets: presence-only comparison (we never echo the value in the diff).
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthConfiguration);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthConfiguration");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.AuthConfiguration",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// Secrets: compared by hash, reported presence-only (TRN-2 — the value is never
// echoed in the diff, but a changed value is no longer read as Identical).
AddSecretChange(changes, "Secrets.AuthConfiguration",
existing.AuthConfiguration, SecretValue(incoming.Secrets, "AuthConfiguration"));
// Methods are name-keyed children.
var existingForCompare = existingMethods ?? Array.Empty<ExternalSystemMethod>();
@@ -276,15 +271,10 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
// ConnectionString lives in Secrets only — presence-only comparison.
var existingHasSecret = !string.IsNullOrEmpty(existing.ConnectionString);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("ConnectionString");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.ConnectionString",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// ConnectionString lives in Secrets only — compared by hash, reported
// presence-only (TRN-2).
AddSecretChange(changes, "Secrets.ConnectionString",
existing.ConnectionString, SecretValue(incoming.Secrets, "ConnectionString"));
return BuildItem("DatabaseConnection", incoming.Name, changes);
}
@@ -345,14 +335,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "OAuth2Scope", existing.OAuth2Scope, incoming.OAuth2Scope);
AddIfDifferent(changes, "Transport", existing.Transport, incoming.Transport);
var existingHasSecret = !string.IsNullOrEmpty(existing.Credentials);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("Credentials");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.Credentials",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// TRN-2: compared by hash, reported presence-only.
AddSecretChange(changes, "Secrets.Credentials",
existing.Credentials, SecretValue(incoming.Secrets, "Credentials"));
return BuildItem("SmtpConfiguration", incoming.Host, changes);
}
@@ -379,14 +364,9 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "MaxRetries", existing.MaxRetries, incoming.MaxRetries);
AddIfDifferent(changes, "RetryDelay", existing.RetryDelay.ToString(), incoming.RetryDelay.ToString());
var existingHasSecret = !string.IsNullOrEmpty(existing.AuthToken);
var incomingHasSecret = incoming.Secrets is not null && incoming.Secrets.Values.ContainsKey("AuthToken");
if (existingHasSecret != incomingHasSecret)
{
changes.Add(new FieldChange("Secrets.AuthToken",
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
}
// TRN-2: compared by hash, reported presence-only.
AddSecretChange(changes, "Secrets.AuthToken",
existing.AuthToken, SecretValue(incoming.Secrets, "AuthToken"));
return BuildItem("SmsConfiguration", incoming.AccountSid, changes);
}
@@ -481,13 +461,12 @@ public sealed class ArtifactDiff
AddIfDifferent(changes, "FailoverRetryCount", existing.FailoverRetryCount, incoming.FailoverRetryCount);
// Protocol config rides in Secrets (PrimaryConfiguration / BackupConfiguration).
// Presence-only comparison — never echo the config value.
AddSecretPresenceChange(changes, "Secrets.PrimaryConfiguration",
!string.IsNullOrEmpty(existing.PrimaryConfiguration),
HasSecretKey(incoming.Secrets, "PrimaryConfiguration"));
AddSecretPresenceChange(changes, "Secrets.BackupConfiguration",
!string.IsNullOrEmpty(existing.BackupConfiguration),
HasSecretKey(incoming.Secrets, "BackupConfiguration"));
// Compared by hash, reported presence-only — never echo the config value
// (TRN-2: a changed endpoint URL used to read Identical and be force-skipped).
AddSecretChange(changes, "Secrets.PrimaryConfiguration",
existing.PrimaryConfiguration, SecretValue(incoming.Secrets, "PrimaryConfiguration"));
AddSecretChange(changes, "Secrets.BackupConfiguration",
existing.BackupConfiguration, SecretValue(incoming.Secrets, "BackupConfiguration"));
return BuildItem("DataConnection", incoming.Name, changes);
}
@@ -510,13 +489,19 @@ public sealed class ArtifactDiff
/// <param name="existingTemplateName">The existing instance's template name (the entity carries only a FK), or null if unknown.</param>
/// <param name="existingSiteIdentifier">The existing instance's site identifier (the entity carries only a FK), or null if unknown.</param>
/// <param name="existingAreaName">The existing instance's area name (the entity carries only a FK), or null if unknown / unset.</param>
/// <param name="existingConnectionNameById">TRN-6: id→name of the existing instance's site connections, so a
/// binding's bound connection (stored as a FK) is compared by name. Null skips the connection comparison.</param>
/// <param name="existingAreaPath">TRN-8: the existing instance's root→leaf area path; compared instead of the
/// leaf name when the incoming instance carries an <see cref="InstanceDto.AreaPath"/>.</param>
/// <returns>An import preview item describing the conflict type and differences.</returns>
public ImportPreviewItem CompareInstance(
InstanceDto incoming,
Instance? existing,
string? existingTemplateName = null,
string? existingSiteIdentifier = null,
string? existingAreaName = null)
string? existingAreaName = null,
IReadOnlyDictionary<int, string>? existingConnectionNameById = null,
IReadOnlyList<string>? existingAreaPath = null)
{
ArgumentNullException.ThrowIfNull(incoming);
if (existing is null) return New("Instance", incoming.UniqueName);
@@ -533,8 +518,21 @@ public sealed class ArtifactDiff
{
AddIfDifferent(changes, "SiteIdentifier", existingSiteIdentifier, incoming.SiteIdentifier);
}
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
AddIfDifferent(changes, "State", existing.State.ToString(), incoming.State.ToString());
if (incoming.AreaPath is { Count: > 0 } incomingPath && (existingAreaPath is not null || existing.AreaId is null))
{
// TRN-8: the same leaf name can sit under two parents — compare the full path.
AddIfDifferent(changes, "AreaPath",
existingAreaPath is null ? null : string.Join("/", existingAreaPath),
string.Join("/", incomingPath));
}
else
{
AddIfDifferent(changes, "AreaName", existingAreaName, incoming.AreaName);
}
// TRN-6: State is not compared — an import always writes NotDeployed for a new
// instance and never carries a live state across environments, so a State-only
// difference used to read Modified and an Overwrite then reset a live instance
// to NotDeployed for no configuration change.
DiffChildren(
existing.AttributeOverrides,
@@ -573,10 +571,14 @@ public sealed class ArtifactDiff
incoming.ConnectionBindings,
e => e.AttributeName,
i => i.AttributeName,
// ConnectionName resolves to a FK on the entity (DataConnectionId) that
// can't be compared cross-environment, so the binding diff compares only
// the per-attribute DataSourceReference override.
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride,
// TRN-6: the entity binds by FK (DataConnectionId); the caller resolves it to
// the target connection's name, which is compared (case-insensitively, like
// the unique (SiteId, Name) index) together with the per-attribute
// DataSourceReference override. A rebind OPC1 -> OPC2 used to read Identical.
(e, i) => e.DataSourceReferenceOverride == i.DataSourceReferenceOverride
&& (existingConnectionNameById is null
|| (existingConnectionNameById.TryGetValue(e.DataConnectionId, out var boundName)
&& string.Equals(boundName, i.ConnectionName, StringComparison.OrdinalIgnoreCase))),
"ConnectionBindings",
changes);
@@ -657,24 +659,37 @@ public sealed class ArtifactDiff
};
/// <summary>True if <paramref name="secrets"/> carries the named key.</summary>
private static bool HasSecretKey(SecretsBlock? secrets, string key) =>
secrets is not null && secrets.Values.ContainsKey(key);
private static string? SecretValue(SecretsBlock? secrets, string key) =>
secrets is not null && secrets.Values.TryGetValue(key, out var value) ? value : null;
/// <summary>
/// Records a presence-only secret change (a flip in whether a value is set on
/// each side) using the <c>&lt;present&gt;</c> / null marker convention. The
/// secret value itself is NEVER read into the diff — only its presence.
/// TRN-2: compares a secret-bearing value by SHA-256 hash and reports the result
/// presence-only. A flip in presence uses the <c>&lt;present&gt;</c> / null markers;
/// a value present on both sides that DIFFERS is reported as
/// <c>&lt;present&gt;</c> → <c>&lt;changed&gt;</c>, so the row classifies Modified
/// (it used to read Identical and be force-skipped) while the value itself never
/// reaches the diff.
/// </summary>
private static void AddSecretPresenceChange(List<FieldChange> changes, string field, bool existingHasSecret, bool incomingHasSecret)
private static void AddSecretChange(List<FieldChange> changes, string field, string? existingValue, string? incomingValue)
{
if (existingHasSecret != incomingHasSecret)
var existingHas = !string.IsNullOrEmpty(existingValue);
var incomingHas = !string.IsNullOrEmpty(incomingValue);
if (existingHas != incomingHas)
{
changes.Add(new FieldChange(field,
existingHasSecret ? "<present>" : null,
incomingHasSecret ? "<present>" : null));
existingHas ? "<present>" : null,
incomingHas ? "<present>" : null));
return;
}
if (existingHas && !SecretHash(existingValue!).AsSpan().SequenceEqual(SecretHash(incomingValue!)))
{
changes.Add(new FieldChange(field, "<present>", "<changed>"));
}
}
private static byte[] SecretHash(string value) =>
System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(value));
private static void DiffChildren<TExisting, TIncoming>(
IEnumerable<TExisting> existing,
IEnumerable<TIncoming> incoming,
@@ -477,7 +477,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
/// <inheritdoc />
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default)
public async Task<ImportPreview> PreviewAsync(Guid sessionId, CancellationToken ct = default, BundleNameMap? nameMap = null)
{
var session = _sessionStore.Get(sessionId)
?? throw new InvalidOperationException($"Bundle session {sessionId} not found or expired.");
@@ -628,10 +628,16 @@ public sealed partial class BundleImporter : IBundleImporter
var targetConnectionsBySiteIdentifier =
new Dictionary<string, IReadOnlyList<DataConnection>>(StringComparer.Ordinal);
// TRN-3: the preview honours the operator's name map, so the diffs, the
// connection auto-match and the unresolved-connection blocker are computed
// against the MAPPED target site / connection — not the source identity.
var previewMap = new PreviewNameMap(nameMap ?? BundleNameMap.Empty);
async Task<Site?> ResolveTargetSiteAsync(string siteIdentifier)
{
if (targetSiteByIdentifier.TryGetValue(siteIdentifier, out var cached)) return cached;
var site = await _siteRepo.GetSiteByIdentifierAsync(siteIdentifier, ct).ConfigureAwait(false);
var site = await _siteRepo.GetSiteByIdentifierAsync(
previewMap.TargetSiteIdentifier(siteIdentifier), ct).ConfigureAwait(false);
targetSiteByIdentifier[siteIdentifier] = site;
return site;
}
@@ -684,7 +690,10 @@ public sealed partial class BundleImporter : IBundleImporter
foreach (var dcDto in content.DataConnections)
{
var targetConns = await ResolveTargetConnectionsAsync(dcDto.SiteIdentifier).ConfigureAwait(false);
var existing = targetConns.FirstOrDefault(c => string.Equals(c.Name, dcDto.Name, StringComparison.Ordinal));
// TRN-7: names compare the way the database's case-insensitive collation
// (and its unique (SiteId, Name) index) does — exact spelling first.
var existing = FindByName(targetConns, c => c.Name,
previewMap.TargetConnectionName(dcDto.SiteIdentifier, dcDto.Name));
var item = _diff.CompareDataConnection(dcDto, existing);
items.Add(item with { Name = QualifiedConnectionName(dcDto.SiteIdentifier, dcDto.Name) });
}
@@ -698,14 +707,21 @@ public sealed partial class BundleImporter : IBundleImporter
// batched read for every bundled instance, and the template / site / area
// names come from the library projection, one site list and one area list
// per site — not four queries per instance.
// TRN-7: case-insensitive like the unique index on UniqueName (exact spelling wins).
var bundleInstanceNames = content.Instances.Select(i => i.UniqueName).ToHashSet(StringComparer.Ordinal);
var existingInstanceByName = content.Instances.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal)
: (await _templateRepo
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: ToNameLookup(
(await _templateRepo
.GetInstancesByUniqueNamesAsync(content.Instances.Select(i => i.UniqueName), ct)
.ConfigureAwait(false))
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
.OrderBy(i => bundleInstanceNames.Contains(i.UniqueName) ? 0 : 1),
i => i.UniqueName);
// TRN-6: an existing binding stores a DataConnectionId; resolve it to the
// connection's name (per site, one read) so the diff can compare it.
var connectionNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
Dictionary<int, string>? siteIdentifierById = null;
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, string>>();
var areaNameByIdBySite = new Dictionary<int, IReadOnlyDictionary<int, Area>>();
foreach (var instDto in content.Instances)
{
existingInstanceByName.TryGetValue(instDto.UniqueName, out var existing);
@@ -713,8 +729,17 @@ public sealed partial class BundleImporter : IBundleImporter
string? existingTemplateName = null;
string? existingSiteIdentifier = null;
string? existingAreaName = null;
IReadOnlyList<string>? existingAreaPath = null;
IReadOnlyDictionary<int, string>? existingConnectionNames = null;
if (existing is not null)
{
if (!connectionNameByIdBySite.TryGetValue(existing.SiteId, out existingConnectionNames))
{
existingConnectionNames = (await _siteRepo.GetDataConnectionsBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(c => c.Id, c => c.Name);
connectionNameByIdBySite[existing.SiteId] = existingConnectionNames;
}
// The entity stores template/site/area as numeric FKs that can't be
// compared cross-environment, so resolve each to the same stable
// string identity the incoming DTO carries.
@@ -726,27 +751,39 @@ public sealed partial class BundleImporter : IBundleImporter
if (existing.AreaId is int areaId)
{
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areaNames))
if (!areaNameByIdBySite.TryGetValue(existing.SiteId, out var areasById))
{
areaNames = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(a => a.Id, a => a.Name);
areaNameByIdBySite[existing.SiteId] = areaNames;
areasById = (await _templateRepo.GetAreasBySiteIdAsync(existing.SiteId, ct).ConfigureAwait(false))
.ToDictionary(a => a.Id, a => a);
areaNameByIdBySite[existing.SiteId] = areasById;
}
existingAreaName = areaNames.TryGetValue(areaId, out var an) ? an : null;
existingAreaName = areasById.TryGetValue(areaId, out var area) ? area.Name : null;
existingAreaPath = AreaPathOf(areaId, areasById);
}
}
// Compare against what the apply would write: the mapped target site and
// the mapped target connection names (TRN-3).
var mappedDto = instDto with
{
SiteIdentifier = previewMap.TargetSiteIdentifier(instDto.SiteIdentifier),
ConnectionBindings = instDto.ConnectionBindings
.Select(b => b with { ConnectionName = previewMap.TargetConnectionName(instDto.SiteIdentifier, b.ConnectionName) })
.ToList(),
};
items.Add(_diff.CompareInstance(
instDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName));
mappedDto, existing, existingTemplateName, existingSiteIdentifier, existingAreaName,
existingConnectionNames, existingAreaPath));
}
// ---- Required site/connection mappings ----
var (requiredSites, requiredConnections) = await BuildRequiredMappingsAsync(
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync).ConfigureAwait(false);
content, ResolveTargetSiteAsync, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName).ConfigureAwait(false);
// ---- Blocker detection ----
items.AddRange(await DetectBlockersAsync(
content, ResolveTargetConnectionsAsync, library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
content, ResolveTargetConnectionsAsync, previewMap.TargetConnectionName,
library, allSharedScripts, allExternalSystems, ct).ConfigureAwait(false));
return new ImportPreview(sessionId, items, requiredSites, requiredConnections);
}
@@ -772,7 +809,8 @@ public sealed partial class BundleImporter : IBundleImporter
BuildRequiredMappingsAsync(
BundleContentDto content,
Func<string, Task<Site?>> resolveTargetSite,
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections)
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
Func<string, string, string> targetConnectionName)
{
// Distinct source-site identifiers, with a best-effort display name.
// SiteDto carries a Name; instances / data-connections only carry the
@@ -838,11 +876,11 @@ public sealed partial class BundleImporter : IBundleImporter
// Auto-match only WITHIN the auto-matched target site: a connection of
// the same name under a different site is not a valid match.
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
var matched = targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal));
var matched = FindByName(targetConns, c => c.Name, targetConnectionName(site, name));
connectionMappings.Add(new RequiredConnectionMapping(
SourceSiteIdentifier: site,
SourceConnectionName: name,
AutoMatchTargetName: matched ? name : null));
AutoMatchTargetName: matched?.Name));
}
return (siteMappings, connectionMappings);
@@ -860,6 +898,7 @@ public sealed partial class BundleImporter : IBundleImporter
private async Task<IReadOnlyList<ImportPreviewItem>> DetectBlockersAsync(
BundleContentDto content,
Func<string, Task<IReadOnlyList<DataConnection>>> resolveTargetConnections,
Func<string, string, string> targetConnectionName,
TemplateLibrary library,
IReadOnlyList<SharedScript> allSharedScripts,
IReadOnlyList<ExternalSystemDefinition> allExternalSystems,
@@ -871,7 +910,8 @@ public sealed partial class BundleImporter : IBundleImporter
// The set of template names the import can satisfy = (in-bundle templates)
// ∪ (templates already in the target DB). An instance whose TemplateName is
// in neither is unresolvable.
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
// TRN-7: instance template names resolve case-insensitively on apply.
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// A derived slot template is not something an instance is created from (#118).
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t))) bundleTemplateNames.Add(t.Name);
// ScadaBridge#118: a malformed or cyclic derivation fails the apply outright.
@@ -893,7 +933,7 @@ public sealed partial class BundleImporter : IBundleImporter
// Members + lock flags are needed below (CollectLockedOverrideWarnings) but
// never script bodies — the body-free, untracked analysis projection (04/P4).
var targetTemplates = await library.GetAnalysisAsync(ct).ConfigureAwait(false);
var targetTemplateNames = new HashSet<string>(StringComparer.Ordinal);
var targetTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var t in targetTemplates)
{
targetTemplateNames.Add(t.Name);
@@ -951,7 +991,7 @@ public sealed partial class BundleImporter : IBundleImporter
{
if (bundleConnections.Contains((site, name))) continue;
var targetConns = await resolveTargetConnections(site).ConfigureAwait(false);
if (targetConns.Any(c => string.Equals(c.Name, name, StringComparison.Ordinal))) continue;
if (FindByName(targetConns, c => c.Name, targetConnectionName(site, name)) is not null) continue;
// Site-qualify the blocker Name so two sites' same-named-but-missing
// connections surface as distinct blockers (a bare name would collide).
blockers.Add(new ImportPreviewItem(
@@ -1613,6 +1653,21 @@ public sealed partial class BundleImporter : IBundleImporter
ArgumentNullException.ThrowIfNull(resolutions);
ArgumentNullException.ThrowIfNull(user);
// TRN-9: Rename is meaningless for a site, a data connection and the SMTP /
// SMS configurations (it was silently Skipped, or wrote a mangled junk row
// delivery never uses). Reject it up front rather than report "Renamed: 1".
var unsupportedRenames = resolutions
.Where(r => r.Action == ResolutionAction.Rename && !ImportRenameSupport.IsSupported(r.EntityType))
.Select(r => $"{r.EntityType} '{r.Name}'")
.ToList();
if (unsupportedRenames.Count > 0)
{
throw new ArgumentException(
"Rename is not supported for sites, data connections, SMTP or SMS configurations; "
+ "choose Skip or Overwrite for: " + string.Join(", ", unsupportedRenames) + ".",
nameof(resolutions));
}
// Normalise null → Empty so the resolve-or-create logic always has a map
// to consult. An empty map means "no explicit operator mappings" — every
// referenced site/connection falls through to the identity auto-match.
@@ -1995,9 +2050,10 @@ public sealed partial class BundleImporter : IBundleImporter
// It writes the instance row + its four child collections (attribute /
// alarm / native-alarm-source overrides + connection bindings) and
// rewires every name-keyed FK to the target environment's ids.
var instanceWarnings = new List<string>();
await ApplyInstancesAsync(
content, resolutionMap, siteBySourceIdentifier, connectionMaps,
library, user, summary, ct).ConfigureAwait(false);
library, user, summary, instanceWarnings, ct).ConfigureAwait(false);
// ---- Pre-commit point: stale-instance computation ----
// Everything the import will write is staged on the change tracker at
@@ -2050,7 +2106,9 @@ public sealed partial class BundleImporter : IBundleImporter
StaleInstanceIds: staleInstanceIds,
AuditEventCorrelation: bundleImportId.ToString(),
ApiKeysIgnored: apiKeysIgnored,
Warnings: derivedWarnings.Count == 0 ? validationWarnings : validationWarnings.Concat(derivedWarnings).ToList());
Warnings: derivedWarnings.Count == 0 && instanceWarnings.Count == 0
? validationWarnings
: validationWarnings.Concat(derivedWarnings).Concat(instanceWarnings).ToList());
}
/// <summary>
@@ -2208,7 +2266,7 @@ public sealed partial class BundleImporter : IBundleImporter
{
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
if (resolution.Action != ResolutionAction.Overwrite) continue;
if (targetTemplateIdByName.TryGetValue(dto.Name, out var templateId))
if (TryGetIdByNameIgnoreCase(targetTemplateIdByName, dto.Name, out var templateId))
{
overwrittenTemplateIds.Add(templateId);
}
@@ -2418,6 +2476,96 @@ public sealed partial class BundleImporter : IBundleImporter
/// throw on a duplicate key: the first row for a name wins. Used wherever a
/// by-name DB result is re-keyed in memory (ScadaBridge#93).
/// </summary>
/// <summary>
/// TRN-7: finds the row named <paramref name="wanted"/> the way the database's
/// case-insensitive collation (and its unique indexes) would — the exact spelling
/// first, otherwise a case-insensitive match. Null when neither exists.
/// </summary>
internal static T? FindByName<T>(IEnumerable<T> rows, Func<T, string> name, string wanted)
where T : class
{
T? ignoreCase = null;
foreach (var row in rows)
{
var n = name(row);
if (string.Equals(n, wanted, StringComparison.Ordinal)) return row;
if (ignoreCase is null && string.Equals(n, wanted, StringComparison.OrdinalIgnoreCase)) ignoreCase = row;
}
return ignoreCase;
}
/// <summary>
/// TRN-8: the root→leaf name path of area <paramref name="areaId"/>, or null when the
/// parent chain is broken or cyclic.
/// </summary>
private static IReadOnlyList<string>? AreaPathOf(int areaId, IReadOnlyDictionary<int, Area> areasById)
{
var path = new List<string>();
var seen = new HashSet<int>();
int? current = areaId;
while (current is { } id)
{
if (!seen.Add(id) || !areasById.TryGetValue(id, out var area)) return null;
path.Add(area.Name);
current = area.ParentAreaId;
}
path.Reverse();
return path;
}
/// <summary>
/// TRN-7: looks <paramref name="name"/> up in an ordinal name→id map, falling back to a
/// case-insensitive match when exactly one key matches that way (two case variants are
/// ambiguous and resolve to nothing, as a missing name does).
/// </summary>
internal static bool TryGetIdByNameIgnoreCase(IReadOnlyDictionary<string, int> idByName, string name, out int id)
{
if (idByName.TryGetValue(name, out id)) return true;
var found = false;
foreach (var (key, value) in idByName)
{
if (!string.Equals(key, name, StringComparison.OrdinalIgnoreCase)) continue;
if (found) { id = 0; return false; }
id = value;
found = true;
}
if (!found) id = 0;
return found;
}
/// <summary>
/// TRN-3: the operator's <see cref="BundleNameMap"/> as seen by the preview — the
/// target site identifier and target connection name a source reference resolves to.
/// Only a <see cref="MappingAction.MapToExisting"/> entry with an explicit target
/// redirects; every other reference keeps its source identity (the identity
/// auto-match the apply performs for it as well).
/// </summary>
private sealed class PreviewNameMap
{
private readonly Dictionary<string, string> _siteTargets = new(StringComparer.Ordinal);
private readonly Dictionary<(string Site, string Name), string> _connectionTargets = new();
public PreviewNameMap(BundleNameMap map)
{
foreach (var m in map.Sites)
{
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetSiteIdentifier))
_siteTargets.TryAdd(m.SourceSiteIdentifier, m.TargetSiteIdentifier);
}
foreach (var m in map.Connections)
{
if (m.Action == MappingAction.MapToExisting && !string.IsNullOrEmpty(m.TargetConnectionName))
_connectionTargets.TryAdd((m.SourceSiteIdentifier, m.SourceConnectionName), m.TargetConnectionName);
}
}
public string TargetSiteIdentifier(string sourceSiteIdentifier) =>
_siteTargets.TryGetValue(sourceSiteIdentifier, out var t) ? t : sourceSiteIdentifier;
public string TargetConnectionName(string sourceSiteIdentifier, string sourceConnectionName) =>
_connectionTargets.TryGetValue((sourceSiteIdentifier, sourceConnectionName), out var t) ? t : sourceConnectionName;
}
internal static Dictionary<string, T> ToNameLookup<T>(IEnumerable<T> rows, Func<T, string> name)
{
var lookup = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
@@ -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!);
}
/// <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>
/// 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
@@ -3659,6 +3805,13 @@ public sealed partial class BundleImporter : IBundleImporter
&& !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(
IEnumerable<Template> stubs, CancellationToken ct)
{
@@ -4638,7 +4791,11 @@ public sealed partial class BundleImporter : IBundleImporter
target = await _siteRepo.GetSiteByIdentifierAsync(targetId, ct).ConfigureAwait(false);
}
if (action == MappingAction.CreateNew || target is null)
// TRN-3: an explicit CreateNew for an identifier the target already holds
// would violate the unique SiteIdentifier index and roll the whole import
// back with a raw SQL error — treat it as a match to that existing site
// (the site's own Skip/Overwrite resolution then applies).
if (target is null)
{
var created = BuildSite(siteDto);
await _siteRepo.AddSiteAsync(created, ct).ConfigureAwait(false);
@@ -4813,13 +4970,14 @@ public sealed partial class BundleImporter : IBundleImporter
&& mapping.TargetConnectionName is { Length: > 0 } tn
? tn
: dcDto.Name;
var existing = targetConns.FirstOrDefault(c =>
string.Equals(c.Name, targetName, StringComparison.Ordinal));
// TRN-7: case-insensitive like the unique (SiteId, Name) index, exact first.
var existing = FindByName(targetConns, c => c.Name, targetName);
var action = mapping?.Action
?? (existing is not null ? MappingAction.MapToExisting : MappingAction.CreateNew);
if (action == MappingAction.CreateNew || existing is null)
// TRN-3: CreateNew against a connection the target site already holds
// (same name) would violate the unique (SiteId, Name) index and roll the
// import back with a raw SQL error — match the existing row instead (the
// connection's own Skip/Overwrite resolution then applies).
if (existing is null)
{
var created = BuildDataConnection(dcDto, targetSite.Id);
await _siteRepo.AddDataConnectionAsync(created, ct).ConfigureAwait(false);
@@ -4893,8 +5051,7 @@ public sealed partial class BundleImporter : IBundleImporter
: connName;
var targetConns = await TargetConnsAsync(targetSite.Id).ConfigureAwait(false);
var existing = targetConns.FirstOrDefault(c =>
string.Equals(c.Name, targetName, StringComparison.Ordinal));
var existing = FindByName(targetConns, c => c.Name, targetName);
if (existing is null)
{
// Should already be a preview blocker (present in neither bundle nor
@@ -4994,6 +5151,7 @@ public sealed partial class BundleImporter : IBundleImporter
TemplateLibrary library,
string user,
ImportSummary summary,
List<string> warnings,
CancellationToken ct)
{
if (content.Instances.Count == 0) return;
@@ -5002,8 +5160,13 @@ public sealed partial class BundleImporter : IBundleImporter
// for pre-existing templates, overlaid with the tracked (Local) templates —
// which include everything this apply added or renamed, flushed (so their ids
// are real) before this pass (review 2026-10-21 04/P4).
var templateIdByName = new Dictionary<string, int>(
await library.GetIdByNameAsync(ct).ConfigureAwait(false), StringComparer.Ordinal);
// TRN-7: case-insensitive like the template name index (exact spelling wins —
// the ordinal library map is copied first, so a case variant only fills a gap).
var templateIdByName = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, id) in await library.GetIdByNameAsync(ct).ConfigureAwait(false))
{
templateIdByName.TryAdd(name, id);
}
foreach (var local in _dbContext.Templates.Local)
{
// A tracked derived slot template never displaces a base of the same name
@@ -5023,14 +5186,19 @@ public sealed partial class BundleImporter : IBundleImporter
lookupNames.Add(dto.UniqueName);
if (r.Action == ResolutionAction.Rename && !string.IsNullOrEmpty(r.RenameTo)) lookupNames.Add(r.RenameTo);
}
// TRN-7: case-insensitive like the unique index on UniqueName; an exact-spelling
// row wins over a case variant.
var existingByName = lookupNames.Count == 0
? new Dictionary<string, Instance>(StringComparer.Ordinal)
: (await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
.ToDictionary(i => i.UniqueName, i => i, StringComparer.Ordinal);
? new Dictionary<string, Instance>(StringComparer.OrdinalIgnoreCase)
: ToNameLookup(
(await _templateRepo.GetInstancesByUniqueNamesAsync(lookupNames, ct).ConfigureAwait(false))
.OrderBy(i => lookupNames.Contains(i.UniqueName) ? 0 : 1),
i => i.UniqueName);
// Memoise area resolution per (siteId, areaName) so two instances under the
// Memoise area resolution per (siteId, area key) so two instances under the
// same area don't each create a duplicate row.
var areaIdByKey = new Dictionary<(int SiteId, string Name), int>();
var areasBySite = new Dictionary<int, List<Area>>();
foreach (var dto in content.Instances)
{
@@ -5060,7 +5228,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
int? areaId = await ResolveOrCreateAreaIdAsync(
dto.AreaName, targetSite.Id, areaIdByKey, ct).ConfigureAwait(false);
dto, targetSite.Id, areaIdByKey, areasBySite, warnings, ct).ConfigureAwait(false);
switch (resolution.Action)
{
@@ -5132,37 +5300,96 @@ public sealed partial class BundleImporter : IBundleImporter
}
/// <summary>
/// Resolves an instance's area by name within the target site, creating the
/// area if it doesn't exist. Returns null when <paramref name="areaName"/> is
/// null/empty (the instance has no area). Memoised via
/// <paramref name="areaIdByKey"/> so repeated references resolve to one row.
/// Resolves an instance's area within the target site, creating what is missing.
/// Returns null when the instance has no area.
/// <para>
/// TRN-8: when the bundle carries <see cref="InstanceDto.AreaPath"/> the area is
/// resolved level by level from the site root (exact name first, then
/// case-insensitive, like the database collation), and any missing level is created
/// under its real parent — the same leaf name may exist under two parents, and a
/// missing nested area used to be recreated at the site root. A pre-TRN-8 bundle
/// carries only the leaf <see cref="InstanceDto.AreaName"/>: it is matched across the
/// site as before, but an ambiguous leaf (several areas with that name) is resolved
/// deterministically (a root-level area, else the lowest id) and reported as a
/// warning instead of silently taking whichever row came back first.
/// </para>
/// </summary>
private async Task<int?> ResolveOrCreateAreaIdAsync(
string? areaName,
InstanceDto dto,
int siteId,
Dictionary<(int SiteId, string Name), int> areaIdByKey,
Dictionary<int, List<Area>> areasBySite,
List<string> warnings,
CancellationToken ct)
{
if (string.IsNullOrEmpty(areaName)) return null;
IReadOnlyList<string>? path = dto.AreaPath is { Count: > 0 } p && p.All(segment => !string.IsNullOrEmpty(segment))
? p
: null;
if (path is null && string.IsNullOrEmpty(dto.AreaName)) return null;
var key = (siteId, areaName);
var key = (siteId, path is null ? "leaf:" + dto.AreaName : "path:" + string.Join("\u001f", path));
if (areaIdByKey.TryGetValue(key, out var cached)) return cached;
var existingAreas = await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false);
var match = existingAreas.FirstOrDefault(a => string.Equals(a.Name, areaName, StringComparison.Ordinal));
if (match is not null)
if (!areasBySite.TryGetValue(siteId, out var areas))
{
areaIdByKey[key] = match.Id;
return match.Id;
areas = (await _templateRepo.GetAreasBySiteIdAsync(siteId, ct).ConfigureAwait(false)).ToList();
areasBySite[siteId] = areas;
}
var area = new Area(areaName) { SiteId = siteId };
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
// Flush so the area's surrogate id materialises before it's used as an
// instance FK (relational provider). Rides the outer transaction.
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areaIdByKey[key] = area.Id;
return area.Id;
int resolvedId;
if (path is not null)
{
int? parentId = null;
Area? current = null;
foreach (var segment in path)
{
var level = parentId;
current = FindByName(areas.Where(a => a.ParentAreaId == level), a => a.Name, segment);
if (current is null)
{
current = new Area(segment) { SiteId = siteId, ParentAreaId = parentId };
await _templateRepo.AddAreaAsync(current, ct).ConfigureAwait(false);
// Flush so the area's surrogate id materialises before it is used as a
// parent / instance FK (relational provider). Rides the outer transaction.
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areas.Add(current);
}
parentId = current.Id;
}
resolvedId = current!.Id;
}
else
{
var leaf = dto.AreaName!;
var exact = areas.Where(a => string.Equals(a.Name, leaf, StringComparison.Ordinal)).ToList();
var matches = exact.Count > 0
? exact
: areas.Where(a => string.Equals(a.Name, leaf, StringComparison.OrdinalIgnoreCase)).ToList();
if (matches.Count == 0)
{
var area = new Area(leaf) { SiteId = siteId };
await _templateRepo.AddAreaAsync(area, ct).ConfigureAwait(false);
await _dbContext.SaveChangesAsync(ct).ConfigureAwait(false);
areas.Add(area);
resolvedId = area.Id;
}
else
{
var chosen = matches.Where(a => a.ParentAreaId is null).OrderBy(a => a.Id).FirstOrDefault()
?? matches.OrderBy(a => a.Id).First();
if (matches.Count > 1)
{
warnings.Add(
$"Instance '{dto.UniqueName}': area '{leaf}' matches {matches.Count} areas in the target site "
+ "and the bundle carries no area path (it predates area paths); it was assigned to area id "
+ $"{chosen.Id}. Check the instance's area after the import.");
}
resolvedId = chosen.Id;
}
}
areaIdByKey[key] = resolvedId;
return resolvedId;
}
/// <summary>
@@ -5437,7 +5664,7 @@ public sealed partial class BundleImporter : IBundleImporter
? tn
: name;
var conns = await _siteRepo.GetDataConnectionsBySiteIdAsync(targetSite.Id, ct).ConfigureAwait(false);
if (!conns.Any(c => string.Equals(c.Name, targetName, StringComparison.Ordinal)))
if (FindByName(conns, c => c.Name, targetName) is null)
{
errors.Add(
$"Connection '{site}/{name}' is referenced by the bundle but is neither carried in "
@@ -5446,7 +5673,8 @@ public sealed partial class BundleImporter : IBundleImporter
}
// ---- Instance template references ----
var bundleTemplateNames = new HashSet<string>(StringComparer.Ordinal);
// TRN-7: instance template names resolve case-insensitively on apply.
var bundleTemplateNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var t in content.Templates.Where(t => !DerivedTemplatePlan.IsDerived(t)))
{
var resolution = ResolveOrDefault(resolutionMap, "Template", t.Name);
@@ -5457,7 +5685,7 @@ public sealed partial class BundleImporter : IBundleImporter
}
var targetTemplateNames = new HashSet<string>(
(await library.GetIdByNameAsync(ct).ConfigureAwait(false)).Keys,
StringComparer.Ordinal);
StringComparer.OrdinalIgnoreCase);
foreach (var inst in content.Instances)
{
@@ -67,6 +67,14 @@ public sealed record EntityAggregate(
/// </summary>
public IReadOnlyDictionary<int, string> AreaNameById { get; init; } =
new Dictionary<int, string>();
/// <summary>
/// TRN-8: lookup from area ID to the area's full path from the site root (one
/// element per level) for the exported instances' <c>AreaId</c> FKs. Empty default:
/// the serializer then emits <c>AreaPath: null</c> and the importer uses the leaf name.
/// </summary>
public IReadOnlyDictionary<int, IReadOnlyList<string>> AreaPathById { get; init; } =
new Dictionary<int, IReadOnlyList<string>>();
}
/// <summary>
@@ -482,4 +490,16 @@ public sealed record InstanceDto(
IReadOnlyList<InstanceAttributeOverrideDto> AttributeOverrides,
IReadOnlyList<InstanceAlarmOverrideDto> AlarmOverrides,
IReadOnlyList<InstanceNativeAlarmSourceOverrideDto> NativeAlarmSourceOverrides,
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings);
IReadOnlyList<InstanceConnectionBindingDto> ConnectionBindings)
{
/// <summary>
/// TRN-8 (additive, 2026-12-03): the instance's area as its full path from the site
/// root, one element per level (e.g. <c>["Line2", "Cell"]</c>; the last element equals
/// <see cref="AreaName"/>). The same leaf name may exist under two parents, so the
/// importer resolves (and creates missing levels of) the path instead of matching the
/// leaf name across the whole site. Null on a bundle written before the field existed
/// (the importer then falls back to the leaf <see cref="AreaName"/>) and when the
/// instance has no area. An older importer ignores the unknown property.
/// </summary>
public IReadOnlyList<string>? AreaPath { get; init; }
}
@@ -319,7 +319,14 @@ public sealed class EntitySerializer
ConnectionBindings: inst.ConnectionBindings.Select(b => new InstanceConnectionBindingDto(
AttributeName: b.AttributeName,
ConnectionName: connectionNameByConnectionId.TryGetValue(b.DataConnectionId, out var cn) ? cn : string.Empty,
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())).ToList(),
DataSourceReferenceOverride: b.DataSourceReferenceOverride)).ToList())
{
// TRN-8: the full area path (root → leaf) so the importer can tell two
// same-named areas under different parents apart.
AreaPath = inst.AreaId is { } pathAreaId && aggregate.AreaPathById.TryGetValue(pathAreaId, out var ap)
? ap
: null,
}).ToList(),
};
}