diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index 96eff1dc..7a417320 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -370,7 +370,7 @@ The explicit server-configured development auto-login mode preserves its synthet ### Isolated Test Run workers -Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. Queueing, compilation, execution and gateway calls consume the requested deadline (1–10 seconds); cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation. +Test Run executes in a disposable `CentralUI.SandboxWorker` process. A process-wide admission gate permits at most four workers. The requested deadline (1–10 seconds) covers execution and gateway calls only: it starts when the worker reports it is about to run user code (UI-13, 2026-12-03). Queueing for an admission slot, worker start-up and compilation are bounded instead by a separate start-up ceiling (30 seconds plus the requested deadline), whose expiry is reported as its own timeout message; cancellation kills the process tree and capacity is released only after confirmed exit. Console capture retains at most 32,000 characters with an explicit truncation marker; return JSON is limited to 32,000 bytes. Private IPC frames are limited to 1 MiB and stderr is drained without accumulation. Each worker has a 512 MiB managed-heap ceiling. The worker is a resource/lifetime boundary; the semantic script trust policy still gates compilation. External calls, shared-script lookup and bound-instance operations use a parent broker. `Notify` is simulated, not brokered: `Notify.To(list).Send` returns a fake `NotificationId`, queues and sends nothing, and writes a `[sandbox] … not delivered` line to the console pane; `Notify.Status` reports `Unknown`. A real send needs a deployed instance (Deployment → Flow Debugger) (#151). Configured SQL connections are recreated inside the worker using credentials passed only over its private pipe, preserving the existing SQL permissions and API. Termination prevents further calls and closes worker-owned sockets; it cannot undo SQL or remote work already accepted by another server. Timeout results do not retain a terminated worker's partial console buffer. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs index e100664d..7fd136b5 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/SiteScopeService.cs @@ -64,6 +64,14 @@ public sealed class SiteScopeService public async Task> PermittedSiteIdsAsync() => (await ResolveAsync()).Sites; + /// + /// UI-12: the system-wide flag AND the permitted site ids from ONE authoritative resolve — + /// for callers that need both (calling then + /// revalidates the session twice). + /// + /// Whether the user is unrestricted, and otherwise the permitted Site.Id set. + public Task<(bool IsSystemWide, IReadOnlySet Sites)> ResolveScopeAsync() => ResolveAsync(); + /// /// Returns the subset of the user is permitted to /// see. A system-wide user gets the full list back unchanged. diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor index 00874e94..c9706ee2 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/Deployments.razor @@ -603,10 +603,12 @@ // instance, rather than by loading every instance to build an // InstanceId → SiteId map. A system-wide user passes null (no filter); // a scoped user's EMPTY grant is a real filter that matches nothing. - var systemWide = await SiteScope.IsSystemWideAsync(); + // UI-12: one authoritative resolve per reload (reloads arrive every 500 ms during a + // bulk deploy), not one for the flag and another for the id set. + var (systemWide, permittedSites) = await SiteScope.ResolveScopeAsync(); IReadOnlyCollection? siteScope = systemWide ? null - : (await SiteScope.PermittedSiteIdsAsync()).ToArray(); + : permittedSites.ToArray(); _appliedSearch = _searchInput.Trim(); var filter = new DeploymentListFilter( diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor index d6f8e974..c3a2c97a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/InstanceConfigure.razor @@ -1422,20 +1422,43 @@ return; } - var failures = new List(); - foreach (var (attrName, value) in toSave) + // UI-6: send only the overrides that actually changed. _overrideValues is seeded + // with every existing override, so saving the whole map rewrote (and audited) all + // of them — ~260 transactions and audit rows to change one value. + var changed = OverrideSaveDiff.Changed(toSave, _existingOverrides); + if (changed.Count == 0) { - var result = await MutationServices.GetRequiredService().ExecuteInstanceAsync(Id, null, (instanceService, currentUser) => instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser)); - if (result.IsSuccess) - _existingOverrides[attrName] = result.Value!; - else - failures.Add($"{attrName}: {result.Error}"); + _toast.ShowInfo("No override changes to save."); + _saving = false; + return; + } + + // ...and apply them in ONE configuration transaction: a failure on any row rolls + // the whole save back instead of leaving a partial apply reported only as a count. + try + { + var saved = await MutationServices.GetRequiredService().ExecuteInstanceAsync(Id, null, async (instanceService, currentUser) => + { + var rows = new List<(string Name, InstanceAttributeOverride Row)>(changed.Count); + var failed = new List(); + foreach (var (attrName, value) in changed) + { + var result = await instanceService.SetAttributeOverrideAsync(Id, attrName, value, currentUser); + if (result.IsSuccess) rows.Add((attrName, result.Value!)); + else failed.Add($"{attrName}: {result.Error}"); + } + if (failed.Count > 0) throw new OverrideSaveDiff.BatchFailedException(failed); + return rows; + }); + foreach (var (attrName, row) in saved) + _existingOverrides[attrName] = row; + _toast.ShowSuccess($"Saved {saved.Count} override(s)."); + } + catch (OverrideSaveDiff.BatchFailedException batch) + { + _toast.ShowError( + $"No overrides were saved — {batch.Failures.Count} failed: {string.Join("; ", batch.Failures)}"); } - if (failures.Count > 0) - _toast.ShowError($"Failed to save {failures.Count} override(s): {string.Join("; ", failures)}"); - var savedCount = toSave.Count - failures.Count; - if (savedCount > 0) - _toast.ShowSuccess($"Saved {savedCount} override(s)."); } catch (Exception ex) { diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs new file mode 100644 index 00000000..38182f2d --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Deployment/OverrideSaveDiff.cs @@ -0,0 +1,35 @@ +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; + +namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment; + +/// +/// UI-6: the Instance Configure "Save overrides" diff — which working values differ from the +/// stored override rows — and the failure that rolls a batched save back. +/// +internal static class OverrideSaveDiff +{ + /// + /// The working values that are new or differ (ordinal) from the stored override; an + /// unchanged value is not re-saved (no transaction, no audit row). + /// + /// The page's working override values, by attribute name. + /// The stored override rows, by attribute name. + /// The (attribute, value) pairs to save. + public static IReadOnlyList<(string Name, string? Value)> Changed( + IReadOnlyDictionary working, + IReadOnlyDictionary existing) => + working + .Where(kv => !existing.TryGetValue(kv.Key, out var row) + || !string.Equals(row.OverrideValue, kv.Value, StringComparison.Ordinal)) + .Select(kv => (kv.Key, kv.Value)) + .ToList(); + + /// Thrown inside the save transaction when any row fails, so nothing commits. + /// The per-attribute failure messages. + public sealed class BatchFailedException(IReadOnlyList failures) + : Exception($"{failures.Count} override(s) failed to save.") + { + /// Gets the per-attribute failure messages. + public IReadOnlyList Failures { get; } = failures; + } +} diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor index 8f833efe..74bb6236 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Monitoring/ParkedMessages.razor @@ -644,15 +644,21 @@ _bulkInProgress = true; _bulkAction = "Retry"; int success = 0, failed = 0; + // UI-12: authorise ONCE per bulk action — the role check and the site-scope check each + // force an LDAP-group → role re-map against the database, and the site list is a full + // read; per message that was ~3 round trips × N before any relay was sent. + if (!await AuthorizeBulkMutationAsync()) + { + _bulkInProgress = false; + _bulkAction = null; + return; + } foreach (var id in ids) { try { var req = new ParkedMessageRetryRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow); - await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); - var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); - if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked."); - var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req); + var resp = await CommunicationService.RetryParkedMessageAsync(_selectedSiteId, req); if (resp.Success) success++; else failed++; } catch { failed++; } @@ -680,15 +686,21 @@ _bulkInProgress = true; _bulkAction = "Discard"; int success = 0, failed = 0; + // UI-12: authorise ONCE per bulk action — the role check and the site-scope check each + // force an LDAP-group → role re-map against the database, and the site list is a full + // read; per message that was ~3 round trips × N before any relay was sent. + if (!await AuthorizeBulkMutationAsync()) + { + _bulkInProgress = false; + _bulkAction = null; + return; + } foreach (var id in ids) { try { var req = new ParkedMessageDiscardRequest(Guid.NewGuid().ToString("N"), _selectedSiteId, id, DateTimeOffset.UtcNow); - await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); - var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); - if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) throw new UnauthorizedAccessException("Site access was revoked."); - var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req); + var resp = await CommunicationService.DiscardParkedMessageAsync(_selectedSiteId, req); if (resp.Success) success++; else failed++; } catch { failed++; } @@ -700,6 +712,27 @@ await FetchPage(); } + /// + /// UI-12: the bulk actions' one-time authorisation — Deployer role and the selected site + /// still in scope — taken once before the per-message loop instead of per message. + /// + private async Task AuthorizeBulkMutationAsync() + { + try + { + await MutationAuth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Deployer); + var mutationSite = (await SiteRepository.GetAllSitesAsync()).FirstOrDefault(s => s.SiteIdentifier == _selectedSiteId); + if (mutationSite is null || !await SiteScope.IsSiteAllowedAsync(mutationSite.Id)) + throw new UnauthorizedAccessException("Site access was revoked."); + return true; + } + catch (Exception ex) + { + _toast.ShowError($"Not permitted: {ex.Message}"); + return false; + } + } + // ── Single actions ── private async Task RetrySingle(ParkedMessageEntry msg) diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor index dc40eed0..13cba155 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Operations/SecuredWrites.razor @@ -332,10 +332,15 @@ try { _sites = await SiteRepository.GetAllSitesAsync(); + // UI-12: one connection read for every site, not one per site (the N+1 the Sites + // page removed under CentralUI-012). + var connectionsBySiteId = (await SiteRepository.GetAllDataConnectionsAsync()) + .GroupBy(c => c.SiteId) + .ToDictionary(g => g.Key, g => (IReadOnlyList)g.ToList()); foreach (var site in _sites) { _connectionsBySite[site.SiteIdentifier] = - await SiteRepository.GetDataConnectionsBySiteIdAsync(site.Id); + connectionsBySiteId.TryGetValue(site.Id, out var conns) ? conns : Array.Empty(); } } catch (Exception ex) diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs index 04f048ab..8ed78b87 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/SandboxWorkerProtocol.cs @@ -20,6 +20,15 @@ public static class SandboxWorkerProtocol private sealed record Start(SandboxRunRequest Request, bool External, bool Database, bool Bound); private sealed record ConnectionInfo(string Provider, string ConnectionString, bool Open); + /// + /// UI-13: the generous ceiling on everything BEFORE user code runs — admission wait, worker + /// process start-up, runtime JIT and the first Roslyn compile — added on top of the + /// script's own budget. The script deadline (TimeoutSeconds) only starts when the + /// worker reports it is about to run user code, so a cold start or a queue behind other + /// Test Runs no longer eats the budget the operator set for the script. Settable for tests. + /// + internal static TimeSpan StartupCeiling { get; set; } = TimeSpan.FromSeconds(30); + /// Runs one child under a deadline; a slot remains charged until confirmed process exit. /// The sandbox run request to execute in the child process. /// The service provider supplying host services for the run. @@ -41,8 +50,14 @@ public static class SandboxWorkerProtocol ISharedScriptCatalog catalog, CancellationToken caller, Action? started = null) { var seconds = Math.Clamp(request.TimeoutSeconds ?? 5, 1, 10); - using var deadline = CancellationTokenSource.CreateLinkedTokenSource(caller); - deadline.CancelAfter(TimeSpan.FromSeconds(seconds)); + // UI-13: two deadlines. The ceiling covers start-up + compile + the script budget and is + // armed now; the script deadline is armed only when the worker sends its "running" frame. + // Every wait below uses deadline.Token, which the ceiling (and the caller) also cancel. + var ceilingSpan = StartupCeiling + TimeSpan.FromSeconds(seconds); + using var ceiling = CancellationTokenSource.CreateLinkedTokenSource(caller); + ceiling.CancelAfter(ceilingSpan); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ceiling.Token); + var userCodeStarted = false; var clock = Stopwatch.StartNew(); var acquired = false; Process? process = null; @@ -84,6 +99,16 @@ public static class SandboxWorkerProtocol var frame = await ReadAsync(process.StandardOutput.BaseStream, deadline.Token); if (frame.Kind == "result") return frame.Data.Deserialize(Json) ?? throw new InvalidDataException("Missing sandbox result."); + if (frame.Kind == "running") + { + // UI-13: user code is about to run — start the script's own budget now. + if (!userCodeStarted) + { + userCodeStarted = true; + deadline.CancelAfter(TimeSpan.FromSeconds(seconds)); + } + continue; + } if (frame.Kind != "call") throw new InvalidDataException("Unexpected sandbox message."); deadline.Token.ThrowIfCancellationRequested(); Frame reply; @@ -98,6 +123,8 @@ public static class SandboxWorkerProtocol await WriteAsync(process.StandardInput.BaseStream, reply, deadline.Token); } } + catch (OperationCanceledException) when (!userCodeStarted && ceiling.IsCancellationRequested && !caller.IsCancellationRequested) + { return new(false, null, null, "", $"The sandbox did not start running the script within its {ceilingSpan.TotalSeconds:0}-second start-up ceiling (Test Runs queued or the node is busy); try again.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); } catch (OperationCanceledException) { return new(false, null, null, "", $"Script execution exceeded the {seconds}-second sandbox timeout or was canceled.", SandboxErrorKind.Timeout, clock.ElapsedMilliseconds, null); } catch (ScriptSandboxException ex) @@ -189,13 +216,23 @@ public static class SandboxWorkerProtocol using var provider = services.BuildServiceProvider(); using var cache = new MemoryCache(new MemoryCacheOptions()); var runner = new ScriptAnalysisService(rpc, cache, provider); - var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None); + var result = await runner.RunInWorkerAsync(start.Request, CancellationToken.None, rpc.NotifyRunningAsync); await WriteAsync(output, new Frame("result", null, Encode(result)), CancellationToken.None); } private sealed class Rpc(Stream input, Stream output) : ISharedScriptCatalog, IExternalSystemClient, IDatabaseGateway, ISandboxInstanceGateway { private readonly SemaphoreSlim _gate = new(1); + + /// UI-13: tells the host user code is about to run, so it starts the script deadline. + /// Cancellation token. + /// A task that represents the asynchronous operation. + public async Task NotifyRunningAsync(CancellationToken ct) + { + await _gate.WaitAsync(ct); + try { await WriteAsync(output, new Frame("running", null, Encode(null)), ct); } + finally { _gate.Release(); } + } private async Task Call(string method, object?[] args, CancellationToken ct) { await _gate.WaitAsync(ct); diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs index 90536b56..01022ed4 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -286,6 +286,18 @@ public class ScriptAnalysisService /// Cancellation token for the run. /// A describing the outcome, return value, console output, and any error. public async Task RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct) + => await RunInWorkerAsync(request, ct, userCodeStarting: null); + + /// Execution core invoked only by the disposable worker executable. + /// The sandbox run request including code, kind, parameters, and optional instance binding. + /// Cancellation token for the run. + /// + /// UI-13: invoked once compile, trust check and admission are done, immediately before the + /// root script runs — the worker reports it so the host starts the script deadline then. + /// + /// A describing the outcome, return value, console output, and any error. + public async Task RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct, + Func? userCodeStarting) { if (string.IsNullOrWhiteSpace(request.Code)) { @@ -513,6 +525,8 @@ public class ScriptAnalysisService // and a queued run reports Timeout rather than hanging. await SandboxRunGate.WaitAsync(linkedCts.Token).ConfigureAwait(false); gateAcquired = true; + if (userCodeStarting is not null) + await userCodeStarting(linkedCts.Token).ConfigureAwait(false); // Run on a thread-pool thread with no SynchronizationContext: a // bound script's Instance.SetAttribute / Attributes[...] block diff --git a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs index 43db0eb0..5962637e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs +++ b/src/ZB.MOM.WW.ScadaBridge.TemplateEngine/Services/InstanceService.cs @@ -180,6 +180,15 @@ public class InstanceService var overrides = await _repository.GetOverridesByInstanceIdAsync(instanceId, cancellationToken); var existingOverride = overrides.FirstOrDefault(o => o.AttributeName == attributeName); + // UI-6: an unchanged value is not rewritten — no save and no UpdateOverride audit row + // burying the one real edit of a bulk save. + if (existingOverride != null + && string.Equals(existingOverride.OverrideValue, overrideValue, StringComparison.Ordinal) + && existingOverride.ElementDataType == templateAttr.ElementDataType) + { + return Result.Success(existingOverride); + } + if (existingOverride != null) { existingOverride.OverrideValue = overrideValue; diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/ParkedMessagesMutationRegressionTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/ParkedMessagesMutationRegressionTests.cs index 1dbcca5a..6bebeb6d 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/ParkedMessagesMutationRegressionTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/ParkedMessagesMutationRegressionTests.cs @@ -70,6 +70,46 @@ public class ParkedMessagesMutationRegressionTests : BunitContext await system.Terminate(); } + /// + /// UI-12 (WP6 6.8): a bulk retry authorises once — one site-list read for the whole batch, + /// not one per message — and still relays every selected message. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage() + { + using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N")); + var dispatched = new ConcurrentQueue(); + var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger.Instance); + comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5)))); + Services.AddSingleton(comms); + var sites = Substitute.For(); + sites.GetAllSitesAsync(Arg.Any()).Returns(new List { new("Plant A", "plant-a") { Id = 42 } }); + Services.AddSingleton(sites); + Services.AddSingleton(new MutableAuth("42")); + Services.AddScoped(); + Services.AddAuthorizationCore(); + Services.AddLogging(); + var dialog = Substitute.For(); + dialog.ConfirmAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); + Services.AddSingleton(dialog); + JSInterop.Mode = JSRuntimeMode.Loose; + + var page = Render(); + await page.Find("select").ChangeAsync(new() { Value = "plant-a" }); + page.WaitForAssertion(() => Assert.Equal(5, page.FindAll("tr.parked-row").Count)); + await page.Find("input[aria-label='Select all']").ChangeAsync(new() { Value = true }); + page.WaitForAssertion(() => Assert.Contains("Retry selected", page.Markup)); + sites.ClearReceivedCalls(); + + await page.FindAll("button").Single(b => b.TextContent.Trim() == "Retry selected").ClickAsync(new()); + + page.WaitForAssertion(() => Assert.Equal(5, dispatched.Count(e => e.Message is ParkedMessageRetryRequest))); + // One read for the bulk authorisation (the page refresh afterwards adds none of its own here). + await sites.Received(1).GetAllSitesAsync(Arg.Any()); + await system.Terminate(); + } + private sealed class MutableAuth(string siteId) : AuthenticationStateProvider { /// Gets or sets the site identifier carried in the user's site-scope claim. @@ -87,14 +127,15 @@ public class ParkedMessagesMutationRegressionTests : BunitContext { /// Initializes the actor with the queue that records relayed retry requests. /// The queue that receives each relayed retry envelope. - public ReplyActor(ConcurrentQueue dispatched) + /// How many parked rows the query reply carries. + public ReplyActor(ConcurrentQueue dispatched, int rows = 1) { Receive(envelope => { if (envelope.Message is ParkedMessageQueryRequest query) Sender.Tell(new ParkedMessageQueryResponse(query.CorrelationId, envelope.SiteId, - new[] { new ParkedMessageEntry("parked-message-1", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow) }, - 1, 1, 25, true, null, DateTimeOffset.UtcNow)); + Enumerable.Range(1, rows).Select(i => new ParkedMessageEntry($"parked-message-{i}", "ERP", "Send", "Offline", 2, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow)).ToArray(), + rows, 1, 25, true, null, DateTimeOffset.UtcNow)); else if (envelope.Message is ParkedMessageRetryRequest retry) { dispatched.Enqueue(envelope); diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Deployment/OverrideSaveDiffTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Deployment/OverrideSaveDiffTests.cs new file mode 100644 index 00000000..c908ab40 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Deployment/OverrideSaveDiffTests.cs @@ -0,0 +1,24 @@ +using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment; +using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; + +namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Deployment; + +/// UI-6 (WP6 6.8): Save overrides sends only the values that changed. +public class OverrideSaveDiffTests +{ + /// Only new or changed values are saved; an unchanged override (of ~260) is not. + [Fact] + public void Changed_ReturnsOnlyNewOrDifferentValues() + { + var existing = Enumerable.Range(0, 260).ToDictionary( + i => $"A{i}", i => new InstanceAttributeOverride($"A{i}") { OverrideValue = i.ToString() }); + var working = existing.ToDictionary(kv => kv.Key, kv => kv.Value.OverrideValue); + working["A7"] = "changed"; + working["New"] = "1"; + + var changed = OverrideSaveDiff.Changed(working, existing); + + Assert.Equal(new[] { ("A7", (string?)"changed"), ("New", (string?)"1") }, + changed.OrderBy(c => c.Name).ToArray()); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/ScriptAnalysis/SandboxWorkerIsolationTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/ScriptAnalysis/SandboxWorkerIsolationTests.cs index e5acde57..d12fab61 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/ScriptAnalysis/SandboxWorkerIsolationTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/ScriptAnalysis/SandboxWorkerIsolationTests.cs @@ -29,15 +29,54 @@ public class SandboxWorkerIsolationTests { await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(8)); var fifthStarted = false; + // UI-13: the queue wait is charged to the start-up ceiling; shrink it so the + // queued fifth run still gives up quickly here. + SandboxWorkerProtocol.StartupCeiling = TimeSpan.Zero; var fifth = await SandboxWorkerProtocol.RunCoreAsync(new SandboxRunRequest("return 1;", null, 1), services, catalog, CancellationToken.None, _ => fifthStarted = true); Assert.Equal(SandboxErrorKind.Timeout, fifth.ErrorKind); Assert.False(fifthStarted); } - finally { release.TrySetResult(new ExternalCallResult(true, "null", null)); } + finally + { + SandboxWorkerProtocol.StartupCeiling = TimeSpan.FromSeconds(30); + release.TrySetResult(new ExternalCallResult(true, "null", null)); + } foreach (var result in await Task.WhenAll(workers)) Assert.True(result.Success, result.Error); } + /// + /// UI-13 (WP6 6.8): the script deadline starts when the worker reports user code is about to + /// run. A 1-second run queued behind four busy Test Runs for ~2 s (plus a cold worker start) + /// used to report "exceeded the 1-second sandbox timeout"; it now succeeds. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task QueuedAndColdStartTime_IsNotChargedToTheScriptBudget() + { + var allEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var count = 0; + var external = Substitute.For(); + external.CallAsync("probe", "blocked", Arg.Any?>(), Arg.Any()) + .Returns(_ => { if (Interlocked.Increment(ref count) == 4) allEntered.TrySetResult(); return release.Task; }); + using var services = new ServiceCollection().AddSingleton(external).BuildServiceProvider(); + var catalog = Substitute.For(); + var busy = Enumerable.Range(0, 4).Select(_ => SandboxWorkerProtocol.RunAsync(new SandboxRunRequest( + "await ExternalSystem.Call(\"probe\", \"blocked\"); return 42;", null, 10), services, catalog, CancellationToken.None)).ToArray(); + await allEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + var queued = SandboxWorkerProtocol.RunAsync(new SandboxRunRequest("return 7;", null, 1), + services, catalog, CancellationToken.None); + await Task.Delay(TimeSpan.FromSeconds(2)); // queued longer than its whole 1 s script budget + release.TrySetResult(new ExternalCallResult(true, "null", null)); + + var result = await queued.WaitAsync(TimeSpan.FromSeconds(30)); + Assert.True(result.Success, result.Error); + Assert.Equal("7", result.ReturnValueJson); + foreach (var r in await Task.WhenAll(busy)) Assert.True(r.Success, r.Error); + } + /// Verifies that an uncooperative broker still has its child killed at the deadline and keeps the lifetime until the broker completes. /// A task that represents the asynchronous operation. [Fact] diff --git a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs index dde5c6b1..4bb76057 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.TemplateEngine.Tests/Services/InstanceServiceTests.cs @@ -109,6 +109,32 @@ public class InstanceServiceTests Assert.Contains("does not exist", result.Error); } + /// + /// UI-6 (WP6 6.8): re-saving an override with its current value writes nothing and adds no + /// UpdateOverride audit row. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task SetAttributeOverride_UnchangedValue_SkipsTheWriteAndTheAuditRow() + { + var instance = new Instance("Inst1") { Id = 1, TemplateId = 1 }; + var existing = new InstanceAttributeOverride("Threshold") { Id = 5, InstanceId = 1, OverrideValue = "99" }; + _repoMock.Setup(r => r.GetInstanceByIdAsync(1, It.IsAny())).ReturnsAsync(instance); + _repoMock.Setup(r => r.GetAttributesByTemplateIdAsync(1, It.IsAny())) + .ReturnsAsync(new List { new("Threshold") { IsLocked = false } }); + _repoMock.Setup(r => r.GetOverridesByInstanceIdAsync(1, It.IsAny())) + .ReturnsAsync(new List { existing }); + + var result = await _sut.SetAttributeOverrideAsync(1, "Threshold", "99", "admin"); + + Assert.True(result.IsSuccess); + Assert.Same(existing, result.Value); + _repoMock.Verify(r => r.UpdateInstanceAttributeOverrideAsync(It.IsAny(), It.IsAny()), Times.Never); + _repoMock.Verify(r => r.SaveChangesAsync(It.IsAny()), Times.Never); + _auditMock.Verify(a => a.LogAsync(It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + /// Verifies that overriding an unlocked attribute returns success. /// A task that represents the asynchronous operation. [Fact]