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; /// /// 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 (), 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. /// 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().UseSqlite(_connection).Options; var services = new ServiceCollection(); services.AddScoped(_ => new ScadaBridgeDbContext(options)); services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); _root = services.BuildServiceProvider(); using var scope = _root.CreateScope(); scope.ServiceProvider.GetRequiredService().Database.EnsureCreated(); } public void Dispose() { _root.Dispose(); _connection.Dispose(); } /// Opens a scope shaped like a Blazor circuit: the circuit handler is built first. private IServiceScope OpenCircuitScope(bool withHandler = true) { var scope = _root.CreateScope(); if (withHandler) scope.ServiceProvider.GetRequiredService(); return scope; } private async Task InOtherScopeAsync(Func change) { using var scope = _root.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); 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(); 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); } /// The handler switches only the circuit scope's context; other scopes keep tracking. [Fact] public void Handler_SetsNoTrackingOnTheCircuitContextOnly() { using var circuit = OpenCircuitScope(); using var command = _root.CreateScope(); Assert.Equal(QueryTrackingBehavior.NoTracking, circuit.ServiceProvider.GetRequiredService().ChangeTracker.QueryTrackingBehavior); Assert.Equal(QueryTrackingBehavior.TrackAll, command.ServiceProvider.GetRequiredService().ChangeTracker.QueryTrackingBehavior); } /// The handler tolerates a host with no configuration database registered. [Fact] public void Handler_WithoutAConfigurationDatabase_IsANoOp() { using var empty = new ServiceCollection().BuildServiceProvider(); _ = new CircuitDbContextTrackingHandler(empty); } /// AddCentralUI registers the handler as a circuit handler. [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); } /// Scenario 1: a data connection moved in another scope shows under its new site. /// Whether the circuit scope runs the no-tracking handler. /// A task that represents the asynchronous operation. [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(); 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 } /// Scenario 2: a renamed / re-parented area is seen by the next Topology refresh. /// A task that represents the asynchronous operation. [Fact] public async Task RenamedArea_IsSeenOnRefresh() { var (siteA, _, _) = await SeedConnectionAsync(); int areaId; using (var seed = _root.CreateScope()) { var db = seed.ServiceProvider.GetRequiredService(); 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(); 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); } /// Scenario 3: a script edited by the CLI / an import is what the editor reloads. /// A task that represents the asynchronous operation. [Fact] public async Task ScriptEditedElsewhere_IsWhatTheEditorReloads() { int templateId, scriptId; using (var seed = _root.CreateScope()) { var db = seed.ServiceProvider.GetRequiredService(); 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(); 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); } /// /// 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 (or the /// configuration command boundary). /// [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.]+\.)?(?" + ServiceTypes + @")\s+(?\w+))" + @"|(?:\[Inject\]\s*(?:private|public|protected|internal)?\s*(?:[\w.]+\.)?(?" + ServiceTypes + @")\s+(?\w+))"); var offenders = new List(); 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)); } }