fix(transport): template Overwrite clears compositions and cascades removed slots' derived templates (TRN-4, TRN-5, WP2 task 2.6)
TRN-4: the composition rewire skipped any bundle template with zero compositions before the clear ran, so an Overwrite never removed the target's slots although the preview reported the removals. It now skips only an Add/Rename (nothing to clear). TRN-5: a slot the bundle removes is deleted through TemplateService.DeleteCompositionAsync, which cascades the slot-owned derived template (no DB relationship on OwnerCompositionId, so the row-only delete orphaned it and blocked deleting its base). A slot the bundle re-composes keeps the row-only delete so a pre-#118 bundle that re-composes the slot onto its derived template by name still resolves. Tests run the real importer against an EF context and fail on the previous importer.
This commit is contained in:
@@ -315,6 +315,8 @@ Site identifiers and connection names are environment-specific, so a bundle expo
|
||||
- `InstanceConnectionBinding.DataConnectionId` is resolved via the connection map, with a **Pass-2** that also binds connections which already exist in the target but were not carried in the bundle.
|
||||
- `InstanceNativeAlarmSourceOverride.ConnectionNameOverride` is rewritten to the **mapped target** connection name.
|
||||
|
||||
**Composition Overwrite (2026-12-03, TRN-4/TRN-5).** An Overwrite of a template whose bundle copy has **no** compositions still runs the composition clear — it used to skip the template entirely, so the target's slots survived an Overwrite the preview said would remove them. A slot the bundle **removes** (its instance name is not among the bundle owner's compositions, and no bundle composition names its composed template) is deleted through `TemplateService.DeleteCompositionAsync`, which also deletes its slot-owned derived template (and that template's nested slots); before, only the row was deleted, leaving a derived template with a dangling `OwnerCompositionId` and a live `ParentTemplateId` that then blocked deleting its base. A slot the bundle re-composes keeps the plain row delete-and-re-add, so a pre-#118 bundle that re-composes a slot onto its derived template by name still resolves.
|
||||
|
||||
### Derived (composition-slot) templates (ScadaBridge#118)
|
||||
|
||||
Composing a template into a slot creates a slot-owned **derived** template (`IsDerived`, `ParentTemplateId` = the base, `OwnerCompositionId` = the slot) named after the slot. Before #118 the bundle did not say so, and the importer re-created every such template as a **base** template named after its slot. Owner decision (2026-11-10): carry the relationship and rebuild the slot through the normal compose flow.
|
||||
|
||||
@@ -3346,7 +3346,11 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
{
|
||||
var resolution = ResolveOrDefault(resolutionMap, "Template", dto.Name);
|
||||
if (resolution.Action == ResolutionAction.Skip) continue;
|
||||
if (dto.Compositions.Count == 0) continue;
|
||||
// TRN-4: a bundle template with NO compositions must still run the
|
||||
// clear below when it overwrites an existing target row — the source
|
||||
// removed every slot, and the diff reports those removals. Only an
|
||||
// Add/Rename (a brand-new row with nothing to clear) can be skipped.
|
||||
if (dto.Compositions.Count == 0 && resolution.Action != ResolutionAction.Overwrite) continue;
|
||||
|
||||
var importedName = resolution.Action == ResolutionAction.Rename
|
||||
? (resolution.RenameTo ?? dto.Name)
|
||||
@@ -3378,9 +3382,42 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
var existingComps = parent.Compositions
|
||||
.Where(c => derivedSlots is null || !derivedSlots.Contains(c.InstanceName))
|
||||
.ToList();
|
||||
// TRN-5: a slot row owns its slot-derived template (OwnerCompositionId,
|
||||
// no database relationship), so deleting the row alone orphaned the
|
||||
// derived template with a live ParentTemplateId that then blocked
|
||||
// deleting its base. A slot the bundle REMOVES (its instance name is
|
||||
// not among the bundle's compositions for this owner, and no bundle
|
||||
// composition names its composed template) is deleted through
|
||||
// TemplateService.DeleteCompositionAsync, which cascades the slot-owned
|
||||
// derived templates (it saves inside the import's transaction, as the
|
||||
// derived-template pass already does). A slot the bundle re-composes
|
||||
// keeps the row-only delete: a pre-#118 bundle re-composes the slot
|
||||
// onto that very derived template by name, so it must survive.
|
||||
var bundleSlotNames = dto.Compositions
|
||||
.Select(c => c.InstanceName)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var bundleComposedNames = dto.Compositions
|
||||
.Where(c => !string.IsNullOrEmpty(c.ComposedTemplateName))
|
||||
.Select(c => c.ComposedTemplateName!)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
TemplateService? compositionService = null;
|
||||
foreach (var existing in existingComps)
|
||||
{
|
||||
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
var removedSlot = !bundleSlotNames.Contains(existing.InstanceName)
|
||||
&& await IsRemovableSlotDerivedAsync(existing, bundleComposedNames, ct).ConfigureAwait(false);
|
||||
if (!removedSlot)
|
||||
{
|
||||
await _templateRepo.DeleteTemplateCompositionAsync(existing.Id, ct).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
compositionService ??= new TemplateService(_templateRepo, _auditService);
|
||||
var deleted = await compositionService.DeleteCompositionAsync(existing.Id, user, ct).ConfigureAwait(false);
|
||||
if (!deleted.IsSuccess)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Could not remove composition '{parent.Name}.{existing.InstanceName}': {deleted.Error}");
|
||||
}
|
||||
}
|
||||
if (derivedSlots is null)
|
||||
{
|
||||
@@ -3602,6 +3639,26 @@ public sealed partial class BundleImporter : IBundleImporter
|
||||
/// 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
|
||||
/// bundle composition of the same owner names — i.e. deleting the slot must cascade
|
||||
/// the derived template. A slot that composes a base directly (pre-derived data) has
|
||||
/// nothing to cascade and keeps the plain row delete.
|
||||
/// </summary>
|
||||
private async Task<bool> IsRemovableSlotDerivedAsync(
|
||||
TemplateComposition composition, IReadOnlySet<string> bundleComposedNames, CancellationToken ct)
|
||||
{
|
||||
var composed = await _dbContext.Templates.AsNoTracking()
|
||||
.Where(t => t.Id == composition.ComposedTemplateId)
|
||||
.Select(t => new { t.Name, t.IsDerived, t.OwnerCompositionId })
|
||||
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
|
||||
return composed is not null
|
||||
&& composed.IsDerived
|
||||
&& composed.OwnerCompositionId == composition.Id
|
||||
&& !bundleComposedNames.Contains(composed.Name);
|
||||
}
|
||||
|
||||
private async Task<Dictionary<int, Template>> LoadTemplatesWithChildrenAsync(
|
||||
IEnumerable<Template> stubs, CancellationToken ct)
|
||||
{
|
||||
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Transport;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Repositories;
|
||||
using ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Services;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.Transport.IntegrationTests.Import;
|
||||
|
||||
/// <summary>
|
||||
/// WP2 task 2.6 — template Overwrite and the composition rewire.
|
||||
/// TRN-4: a bundle template with no compositions skipped the clear, so the target's
|
||||
/// slots survived an Overwrite the preview said would remove them.
|
||||
/// TRN-5: the rewire deleted a removed slot's row without its slot-owned derived
|
||||
/// template, leaving an orphan with a dangling <c>OwnerCompositionId</c>.
|
||||
/// </summary>
|
||||
public sealed class CompositionOverwriteTests : IDisposable
|
||||
{
|
||||
private readonly ServiceProvider _provider;
|
||||
|
||||
/// <summary>Builds an in-memory configuration database plus the Transport services.</summary>
|
||||
public CompositionOverwriteTests()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().AddInMemoryCollection().Build());
|
||||
var dbName = $"CompositionOverwriteTests_{Guid.NewGuid()}";
|
||||
services.AddDbContext<ScadaBridgeDbContext>(opts => opts
|
||||
.UseInMemoryDatabase(dbName)
|
||||
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning)));
|
||||
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
|
||||
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
|
||||
services.AddScoped<IExternalSystemRepository, ExternalSystemRepository>();
|
||||
services.AddScoped<INotificationRepository, NotificationRepository>();
|
||||
services.AddScoped<IInboundApiRepository, InboundApiRepository>();
|
||||
services.AddScoped<ISiteRepository, SiteRepository>();
|
||||
services.AddScoped<IAuditCorrelationContext, AuditCorrelationContext>();
|
||||
services.AddScoped<IAuditService, AuditService>();
|
||||
services.AddTransport();
|
||||
_provider = services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
/// <summary>Releases the resources held by this instance.</summary>
|
||||
public void Dispose() => _provider.Dispose();
|
||||
|
||||
/// <summary>TRN-4: Overwrite with a composition-less bundle template removes the target's slots.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Overwrite_with_no_bundle_compositions_removes_target_compositions()
|
||||
{
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.Templates.Add(new Template("B"));
|
||||
ctx.Templates.Add(new Template("A"));
|
||||
});
|
||||
var bundle = await ExportAllTemplatesAsync();
|
||||
|
||||
// Target: A now composes B as b1.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
ctx.TemplateCompositions.Add(new TemplateComposition("b1") { TemplateId = a.Id, ComposedTemplateId = b.Id });
|
||||
});
|
||||
|
||||
await ImportOverwriteAsync(bundle, "A", "B");
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
|
||||
Assert.False(await ctx.TemplateCompositions.AnyAsync(c => c.TemplateId == aId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TRN-5: target owner has slot S1 with a slot-owned derived template; the bundle
|
||||
/// owner has only S2. Overwrite removes S1 AND its derived template.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Overwrite_removing_a_slot_deletes_its_slot_owned_derived_template()
|
||||
{
|
||||
// Source: A composes B directly as S2.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.Templates.Add(new Template("B"));
|
||||
ctx.Templates.Add(new Template("A"));
|
||||
});
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
ctx.TemplateCompositions.Add(new TemplateComposition("S2") { TemplateId = a.Id, ComposedTemplateId = b.Id });
|
||||
});
|
||||
var bundle = await ExportAllTemplatesAsync();
|
||||
|
||||
// Target: drop S2; A instead owns slot S1 whose composed template is a
|
||||
// slot-owned derived template of B.
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
ctx.TemplateCompositions.RemoveRange(ctx.TemplateCompositions);
|
||||
});
|
||||
int derivedId = 0;
|
||||
await SeedAsync(ctx =>
|
||||
{
|
||||
var a = ctx.Templates.Single(t => t.Name == "A");
|
||||
var b = ctx.Templates.Single(t => t.Name == "B");
|
||||
var derived = new Template("A.S1") { ParentTemplateId = b.Id, IsDerived = true };
|
||||
ctx.Templates.Add(derived);
|
||||
ctx.SaveChanges();
|
||||
var slot = new TemplateComposition("S1") { TemplateId = a.Id, ComposedTemplateId = derived.Id };
|
||||
ctx.TemplateCompositions.Add(slot);
|
||||
ctx.SaveChanges();
|
||||
derived.OwnerCompositionId = slot.Id;
|
||||
derivedId = derived.Id;
|
||||
});
|
||||
|
||||
await ImportOverwriteAsync(bundle, "A", "B");
|
||||
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var aId = await ctx.Templates.Where(t => t.Name == "A").Select(t => t.Id).SingleAsync();
|
||||
var slots = await ctx.TemplateCompositions.Where(c => c.TemplateId == aId).Select(c => c.InstanceName).ToListAsync();
|
||||
Assert.Equal(new[] { "S2" }, slots);
|
||||
Assert.False(await ctx.Templates.AnyAsync(t => t.Id == derivedId),
|
||||
"the removed slot's derived template must be deleted with it");
|
||||
}
|
||||
|
||||
private async Task SeedAsync(Action<ScadaBridgeDbContext> seed)
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
seed(ctx);
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<byte[]> ExportAllTemplatesAsync()
|
||||
{
|
||||
await using var scope = _provider.CreateAsyncScope();
|
||||
var exporter = scope.ServiceProvider.GetRequiredService<IBundleExporter>();
|
||||
var ctx = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
|
||||
var templateIds = await ctx.Templates.Select(t => t.Id).ToListAsync();
|
||||
var selection = new ExportSelection(
|
||||
TemplateIds: templateIds,
|
||||
SharedScriptIds: Array.Empty<int>(),
|
||||
ExternalSystemIds: Array.Empty<int>(),
|
||||
DatabaseConnectionIds: Array.Empty<int>(),
|
||||
NotificationListIds: Array.Empty<int>(),
|
||||
SmtpConfigurationIds: Array.Empty<int>(),
|
||||
ApiMethodIds: Array.Empty<int>(),
|
||||
IncludeDependencies: false);
|
||||
var stream = await exporter.ExportAsync(selection, user: "alice", sourceEnvironment: "dev",
|
||||
passphrase: null, cancellationToken: CancellationToken.None);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms);
|
||||
return ms.ToArray();
|
||||
}
|
||||
|
||||
private async Task ImportOverwriteAsync(byte[] bundle, params string[] templateNames)
|
||||
{
|
||||
Guid sessionId;
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
using var input = new MemoryStream(bundle, writable: false);
|
||||
sessionId = (await importer.LoadAsync(input, passphrase: null)).SessionId;
|
||||
}
|
||||
|
||||
await using (var scope = _provider.CreateAsyncScope())
|
||||
{
|
||||
var importer = scope.ServiceProvider.GetRequiredService<IBundleImporter>();
|
||||
await importer.ApplyAsync(sessionId,
|
||||
templateNames.Select(n => new ImportResolution("Template", n, ResolutionAction.Overwrite, null)).ToList(),
|
||||
user: "bob");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user