Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Services/CircuitDbContextTrackingTests.cs
T
Joseph Doherty 2969ee44e5 fix(centralui): no-tracking default on the circuit DbContext; mutations on their own scope (UI-1, WP5 task 5.1)
The circuit-lifetime ScadaBridgeDbContext tracked every entity a page ever
loaded, so a reload returned the first-loaded instance and never saw changes
made in another scope (Move to Site, Topology area renames, a template script
edited by the CLI/import - which a later save then silently reverted).

- CircuitDbContextTrackingHandler (CircuitHandler, registered by AddCentralUI)
  sets QueryTrackingBehavior.NoTracking on the circuit scope's context only,
  when the circuit host is built (before any component). Management-actor,
  command-transaction, HTTP-request and hosted-service scopes keep TrackAll.
- Every remaining page mutation that ran a load-modify-save service on the
  circuit context now runs it via ScopeFactory.InNewScopeAsync (fresh tracking
  context): TemplateEdit (17 TemplateService calls), Templates (5 TemplateService
  + 5 TemplateFolderService), TemplateCreate, SharedScripts, SharedScriptForm,
  TransportImport.ApplyAsync. (Sites/Topology moved in 5.2.)
- Design doc: Component-CentralUI.md 'Circuit DbContext lifetime'.

Tests: CircuitDbContextTrackingTests - handler scoping + registration, the three
finding scenarios against a real SQLite context (moved connection also asserts
the pre-fix staleness without the handler), and a source-scan guard that fails
on any mutating call through a circuit-injected load-modify-save service.
2026-12-03 09:52:56 -05:00

231 lines
11 KiB
C#

using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Components.Server.Circuits;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
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.CentralUI.Tests.Services;
/// <summary>
/// Code review 2026-12-02 UI-1: the circuit-lifetime configuration DbContext served stale
/// tracked entities after changes made in another scope. The circuit's context now reads with a
/// no-tracking default (<see cref="CircuitDbContextTrackingHandler"/>), contexts in every other
/// scope keep EF's tracking default, and no page runs a mutating service on the circuit's context.
/// These tests drive the three scenarios from the finding against a real (SQLite) context.
/// </summary>
public sealed class CircuitDbContextTrackingTests : IDisposable
{
private readonly SqliteConnection _connection = new("Data Source=:memory:");
private readonly ServiceProvider _root;
public CircuitDbContextTrackingTests()
{
_connection.Open();
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(_connection).Options;
var services = new ServiceCollection();
services.AddScoped(_ => new ScadaBridgeDbContext(options));
services.AddSingleton<ITemplateGraphWatermark, TemplateGraphWatermark>();
services.AddScoped<ISiteRepository, SiteRepository>();
services.AddScoped<ITemplateEngineRepository, TemplateEngineRepository>();
services.AddScoped<CircuitDbContextTrackingHandler>();
_root = services.BuildServiceProvider();
using var scope = _root.CreateScope();
scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().Database.EnsureCreated();
}
public void Dispose()
{
_root.Dispose();
_connection.Dispose();
}
/// <summary>Opens a scope shaped like a Blazor circuit: the circuit handler is built first.</summary>
private IServiceScope OpenCircuitScope(bool withHandler = true)
{
var scope = _root.CreateScope();
if (withHandler)
scope.ServiceProvider.GetRequiredService<CircuitDbContextTrackingHandler>();
return scope;
}
private async Task InOtherScopeAsync(Func<ScadaBridgeDbContext, Task> change)
{
using var scope = _root.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
await change(db);
await db.SaveChangesAsync();
}
private async Task<(int SiteA, int SiteB, int ConnectionId)> SeedConnectionAsync()
{
using var scope = _root.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var a = new Site("Site A", "site-a");
var b = new Site("Site B", "site-b");
db.Sites.AddRange(a, b);
await db.SaveChangesAsync();
var connection = new DataConnection("PLC", "OpcUa", a.Id);
db.DataConnections.Add(connection);
await db.SaveChangesAsync();
return (a.Id, b.Id, connection.Id);
}
/// <summary>The handler switches only the circuit scope's context; other scopes keep tracking.</summary>
[Fact]
public void Handler_SetsNoTrackingOnTheCircuitContextOnly()
{
using var circuit = OpenCircuitScope();
using var command = _root.CreateScope();
Assert.Equal(QueryTrackingBehavior.NoTracking,
circuit.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().ChangeTracker.QueryTrackingBehavior);
Assert.Equal(QueryTrackingBehavior.TrackAll,
command.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>().ChangeTracker.QueryTrackingBehavior);
}
/// <summary>The handler tolerates a host with no configuration database registered.</summary>
[Fact]
public void Handler_WithoutAConfigurationDatabase_IsANoOp()
{
using var empty = new ServiceCollection().BuildServiceProvider();
_ = new CircuitDbContextTrackingHandler(empty);
}
/// <summary>AddCentralUI registers the handler as a circuit handler.</summary>
[Fact]
public void AddCentralUI_RegistersTheTrackingHandler()
{
var services = new ServiceCollection();
services.AddCentralUI();
Assert.Contains(services, d => d.ServiceType == typeof(CircuitHandler)
&& d.ImplementationType == typeof(CircuitDbContextTrackingHandler)
&& d.Lifetime == ServiceLifetime.Scoped);
}
/// <summary>Scenario 1: a data connection moved in another scope shows under its new site.</summary>
/// <param name="withHandler">Whether the circuit scope runs the no-tracking handler.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task MovedDataConnection_IsSeenOnReload(bool withHandler)
{
var (_, siteB, connectionId) = await SeedConnectionAsync();
using var circuit = OpenCircuitScope(withHandler);
var repo = circuit.ServiceProvider.GetRequiredService<ISiteRepository>();
Assert.NotEqual(siteB, (await repo.GetAllDataConnectionsAsync()).Single().SiteId);
// The Move to Site… dialog moves it through the ManagementActor, i.e. another scope.
await InOtherScopeAsync(async db => (await db.DataConnections.SingleAsync(c => c.Id == connectionId)).SiteId = siteB);
var reloaded = (await repo.GetAllDataConnectionsAsync()).Single().SiteId;
if (withHandler)
Assert.Equal(siteB, reloaded);
else
Assert.NotEqual(siteB, reloaded); // the pre-fix behaviour this guards against
}
/// <summary>Scenario 2: a renamed / re-parented area is seen by the next Topology refresh.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RenamedArea_IsSeenOnRefresh()
{
var (siteA, _, _) = await SeedConnectionAsync();
int areaId;
using (var seed = _root.CreateScope())
{
var db = seed.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var area = new Area("Line 1") { SiteId = siteA };
db.Areas.Add(area);
await db.SaveChangesAsync();
areaId = area.Id;
}
using var circuit = OpenCircuitScope();
var repo = circuit.ServiceProvider.GetRequiredService<ITemplateEngineRepository>();
Assert.Equal("Line 1", (await repo.GetAreasBySiteIdAsync(siteA)).Single().Name);
await InOtherScopeAsync(async db => (await db.Areas.SingleAsync(a => a.Id == areaId)).Name = "Line 1 (renamed)");
Assert.Equal("Line 1 (renamed)", (await repo.GetAreasBySiteIdAsync(siteA)).Single().Name);
}
/// <summary>Scenario 3: a script edited by the CLI / an import is what the editor reloads.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ScriptEditedElsewhere_IsWhatTheEditorReloads()
{
int templateId, scriptId;
using (var seed = _root.CreateScope())
{
var db = seed.ServiceProvider.GetRequiredService<ScadaBridgeDbContext>();
var template = new Template("Pump");
template.Scripts.Add(new TemplateScript("OnStart", "return 1;"));
db.Templates.Add(template);
await db.SaveChangesAsync();
templateId = template.Id;
scriptId = template.Scripts.Single().Id;
}
using var circuit = OpenCircuitScope();
var repo = circuit.ServiceProvider.GetRequiredService<ITemplateEngineRepository>();
Assert.Equal("return 1;", (await repo.GetTemplateWithChildrenAsync(templateId))!.Scripts.Single().Code);
await InOtherScopeAsync(async db => (await db.TemplateScripts.SingleAsync(s => s.Id == scriptId)).Code = "return 2;");
Assert.Equal("return 2;", (await repo.GetScriptsByTemplateIdAsync(templateId)).Single().Code);
Assert.Equal("return 2;", (await repo.GetTemplateWithChildrenAsync(templateId))!.Scripts.Single().Code);
}
/// <summary>
/// The circuit's context reads without tracking, so a load-modify-save service run on it
/// would silently persist nothing. Guard: no CentralUI page or component calls a mutating
/// method on a circuit-injected instance of one of the load-modify-save services; those calls
/// go through <see cref="ScopedServiceExtensions.InNewScopeAsync{TService, TResult}"/> (or the
/// configuration command boundary).
/// </summary>
[Fact]
public void NoPageMutatesThroughACircuitInjectedLoadModifySaveService()
{
var root = AppContext.BaseDirectory;
for (var i = 0; i < 6; i++) root = Directory.GetParent(root)!.FullName;
var uiRoot = Path.Combine(root, "src", "ZB.MOM.WW.ScadaBridge.CentralUI");
Assert.True(Directory.Exists(uiRoot), uiRoot);
const string ServiceTypes = "TemplateService|TemplateFolderService|SharedScriptService|InstanceService|AreaService|"
+ "SiteService|DeploymentService|ArtifactDeploymentService|IBundleImporter|TemplateDeletionService";
var injected = new Regex(
@"(?:@inject\s+(?:[\w.]+\.)?(?<type>" + ServiceTypes + @")\s+(?<name>\w+))"
+ @"|(?:\[Inject\]\s*(?:private|public|protected|internal)?\s*(?:[\w.]+\.)?(?<type>" + ServiceTypes + @")\s+(?<name>\w+))");
var offenders = new List<string>();
foreach (var file in Directory.EnumerateFiles(uiRoot, "*.*", SearchOption.AllDirectories)
.Where(f => f.EndsWith(".razor", StringComparison.Ordinal) || f.EndsWith(".razor.cs", StringComparison.Ordinal))
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)))
{
var text = File.ReadAllText(file);
foreach (Match m in injected.Matches(text))
{
var name = m.Groups["name"].Value;
var mutation = new Regex(@"\b" + Regex.Escape(name)
+ @"\.(?:Create|Update|Delete|Add|Remove|Move|Rename|Reorder|Resync|Set|Enable|Disable|Deploy|Retry|Apply|Import)\w*\(");
foreach (Match call in mutation.Matches(text))
offenders.Add($"{Path.GetFileName(file)}: {call.Value}");
}
}
Assert.True(offenders.Count == 0,
"Mutating call on a circuit-scoped service (run it via ScopeFactory.InNewScopeAsync instead): "
+ string.Join("; ", offenders));
}
}