perf(central-ui): save only changed overrides in one transaction; authorise once per action; split Test Run deadline (UI-6, UI-12, UI-13, WP6 task 6.8)
UI-6: Save overrides diffs the working values against the stored rows (OverrideSaveDiff) and applies only the changed ones inside ONE ExecuteInstanceAsync transaction; any row failure throws inside it so nothing commits (no partial apply). InstanceService.SetAttributeOverrideAsync skips the write and the UpdateOverride audit row when the value is unchanged. ~260 overrides, one edited: 260 transactions / ~1,300 round trips / 260 audit rows -> 1 transaction / 1 SetAttributeOverride / 1 audit row. UI-12: ParkedMessages bulk retry/discard authorise once per action (role + site scope + site list) instead of per message (bunit: 5 messages -> 1 site read, was 5; each also saved two forced session revalidations). Deployments.LoadDataAsync resolves the scope once (new SiteScopeService.ResolveScopeAsync) instead of IsSystemWide + PermittedSiteIds (2 -> 1 revalidation per 500 ms reload). SecuredWrites loads connections with one GetAllDataConnectionsAsync instead of one query per site. Not changed: ConnectionHealthQueryService's per-tick site/connection reads. UI-13 (decided: split deadline): the script deadline is armed when the worker sends a new 'running' frame (RunInWorkerAsync's userCodeStarting hook, after compile + trust check + gate); admission, process start-up and compile are bounded by a separate StartupCeiling (30 s + the script budget) with its own message. Test QueuedAndColdStartTime_IsNotChargedToTheScriptBudget (TimeoutSeconds=1, queued ~2 s behind four busy workers + a cold worker start): before: 'Script execution exceeded the 1-second sandbox timeout' after: succeeds, returns 7.
This commit is contained in:
@@ -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.
|
||||
|
||||
|
||||
@@ -64,6 +64,14 @@ public sealed class SiteScopeService
|
||||
public async Task<IReadOnlySet<int>> PermittedSiteIdsAsync()
|
||||
=> (await ResolveAsync()).Sites;
|
||||
|
||||
/// <summary>
|
||||
/// UI-12: the system-wide flag AND the permitted site ids from ONE authoritative resolve —
|
||||
/// for callers that need both (calling <see cref="IsSystemWideAsync"/> then
|
||||
/// <see cref="PermittedSiteIdsAsync"/> revalidates the session twice).
|
||||
/// </summary>
|
||||
/// <returns>Whether the user is unrestricted, and otherwise the permitted <c>Site.Id</c> set.</returns>
|
||||
public Task<(bool IsSystemWide, IReadOnlySet<int> Sites)> ResolveScopeAsync() => ResolveAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Returns the subset of <paramref name="sites"/> the user is permitted to
|
||||
/// see. A system-wide user gets the full list back unchanged.
|
||||
|
||||
@@ -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<int>? siteScope = systemWide
|
||||
? null
|
||||
: (await SiteScope.PermittedSiteIdsAsync()).ToArray();
|
||||
: permittedSites.ToArray();
|
||||
|
||||
_appliedSearch = _searchInput.Trim();
|
||||
var filter = new DeploymentListFilter(
|
||||
|
||||
+35
-12
@@ -1422,20 +1422,43 @@
|
||||
return;
|
||||
}
|
||||
|
||||
var failures = new List<string>();
|
||||
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<ConfigurationCommandService>().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<ConfigurationCommandService>().ExecuteInstanceAsync(Id, null, async (instanceService, currentUser) =>
|
||||
{
|
||||
var rows = new List<(string Name, InstanceAttributeOverride Row)>(changed.Count);
|
||||
var failed = new List<string>();
|
||||
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)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Deployment;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class OverrideSaveDiff
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <param name="working">The page's working override values, by attribute name.</param>
|
||||
/// <param name="existing">The stored override rows, by attribute name.</param>
|
||||
/// <returns>The (attribute, value) pairs to save.</returns>
|
||||
public static IReadOnlyList<(string Name, string? Value)> Changed(
|
||||
IReadOnlyDictionary<string, string?> working,
|
||||
IReadOnlyDictionary<string, InstanceAttributeOverride> 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();
|
||||
|
||||
/// <summary>Thrown inside the save transaction when any row fails, so nothing commits.</summary>
|
||||
/// <param name="failures">The per-attribute failure messages.</param>
|
||||
public sealed class BatchFailedException(IReadOnlyList<string> failures)
|
||||
: Exception($"{failures.Count} override(s) failed to save.")
|
||||
{
|
||||
/// <summary>Gets the per-attribute failure messages.</summary>
|
||||
public IReadOnlyList<string> Failures { get; } = failures;
|
||||
}
|
||||
}
|
||||
+41
-8
@@ -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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private async Task<bool> 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)
|
||||
|
||||
@@ -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<DataConnection>)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<DataConnection>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<c>TimeoutSeconds</c>) 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.
|
||||
/// </summary>
|
||||
internal static TimeSpan StartupCeiling { get; set; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>Runs one child under a deadline; a slot remains charged until confirmed process exit.</summary>
|
||||
/// <param name="request">The sandbox run request to execute in the child process.</param>
|
||||
/// <param name="services">The service provider supplying host services for the run.</param>
|
||||
@@ -41,8 +50,14 @@ public static class SandboxWorkerProtocol
|
||||
ISharedScriptCatalog catalog, CancellationToken caller, Action<int>? 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<SandboxRunResult>(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);
|
||||
|
||||
/// <summary>UI-13: tells the host user code is about to run, so it starts the script deadline.</summary>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
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<JsonElement> Call(string method, object?[] args, CancellationToken ct)
|
||||
{
|
||||
await _gate.WaitAsync(ct);
|
||||
|
||||
@@ -286,6 +286,18 @@ public class ScriptAnalysisService
|
||||
/// <param name="ct">Cancellation token for the run.</param>
|
||||
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
|
||||
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct)
|
||||
=> await RunInWorkerAsync(request, ct, userCodeStarting: null);
|
||||
|
||||
/// <summary>Execution core invoked only by the disposable worker executable.</summary>
|
||||
/// <param name="request">The sandbox run request including code, kind, parameters, and optional instance binding.</param>
|
||||
/// <param name="ct">Cancellation token for the run.</param>
|
||||
/// <param name="userCodeStarting">
|
||||
/// 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.
|
||||
/// </param>
|
||||
/// <returns>A <see cref="SandboxRunResult"/> describing the outcome, return value, console output, and any error.</returns>
|
||||
public async Task<SandboxRunResult> RunInWorkerAsync(SandboxRunRequest request, CancellationToken ct,
|
||||
Func<CancellationToken, Task>? 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
|
||||
|
||||
@@ -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<InstanceAttributeOverride>.Success(existingOverride);
|
||||
}
|
||||
|
||||
if (existingOverride != null)
|
||||
{
|
||||
existingOverride.OverrideValue = overrideValue;
|
||||
|
||||
+44
-3
@@ -70,6 +70,46 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task BulkRetry_AuthorisesOncePerAction_NotPerMessage()
|
||||
{
|
||||
using var system = ActorSystem.Create("parked-bulk-" + Guid.NewGuid().ToString("N"));
|
||||
var dispatched = new ConcurrentQueue<SiteEnvelope>();
|
||||
var comms = new CommunicationService(Options.Create(new CommunicationOptions()), NullLogger<CommunicationService>.Instance);
|
||||
comms.SetCommunicationActor(system.ActorOf(Props.Create(() => new ReplyActor(dispatched, 5))));
|
||||
Services.AddSingleton(comms);
|
||||
var sites = Substitute.For<ISiteRepository>();
|
||||
sites.GetAllSitesAsync(Arg.Any<CancellationToken>()).Returns(new List<Site> { new("Plant A", "plant-a") { Id = 42 } });
|
||||
Services.AddSingleton(sites);
|
||||
Services.AddSingleton<AuthenticationStateProvider>(new MutableAuth("42"));
|
||||
Services.AddScoped<SiteScopeService>();
|
||||
Services.AddAuthorizationCore();
|
||||
Services.AddLogging();
|
||||
var dialog = Substitute.For<IDialogService>();
|
||||
dialog.ConfirmAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>(), Arg.Any<string?>()).Returns(true);
|
||||
Services.AddSingleton(dialog);
|
||||
JSInterop.Mode = JSRuntimeMode.Loose;
|
||||
|
||||
var page = Render<ParkedMessages>();
|
||||
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<CancellationToken>());
|
||||
await system.Terminate();
|
||||
}
|
||||
|
||||
private sealed class MutableAuth(string siteId) : AuthenticationStateProvider
|
||||
{
|
||||
/// <summary>Gets or sets the site identifier carried in the user's site-scope claim.</summary>
|
||||
@@ -87,14 +127,15 @@ public class ParkedMessagesMutationRegressionTests : BunitContext
|
||||
{
|
||||
/// <summary>Initializes the actor with the queue that records relayed retry requests.</summary>
|
||||
/// <param name="dispatched">The queue that receives each relayed retry envelope.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched)
|
||||
/// <param name="rows">How many parked rows the query reply carries.</param>
|
||||
public ReplyActor(ConcurrentQueue<SiteEnvelope> dispatched, int rows = 1)
|
||||
{
|
||||
Receive<SiteEnvelope>(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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>UI-6 (WP6 6.8): Save overrides sends only the values that changed.</summary>
|
||||
public class OverrideSaveDiffTests
|
||||
{
|
||||
/// <summary>Only new or changed values are saved; an unchanged override (of ~260) is not.</summary>
|
||||
[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());
|
||||
}
|
||||
}
|
||||
+40
-1
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task QueuedAndColdStartTime_IsNotChargedToTheScriptBudget()
|
||||
{
|
||||
var allEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var release = new TaskCompletionSource<ExternalCallResult>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var count = 0;
|
||||
var external = Substitute.For<IExternalSystemClient>();
|
||||
external.CallAsync("probe", "blocked", Arg.Any<IReadOnlyDictionary<string, object?>?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_ => { if (Interlocked.Increment(ref count) == 4) allEntered.TrySetResult(); return release.Task; });
|
||||
using var services = new ServiceCollection().AddSingleton(external).BuildServiceProvider();
|
||||
var catalog = Substitute.For<ISharedScriptCatalog>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an uncooperative broker still has its child killed at the deadline and keeps the lifetime until the broker completes.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
@@ -109,6 +109,32 @@ public class InstanceServiceTests
|
||||
Assert.Contains("does not exist", result.Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// UI-6 (WP6 6.8): re-saving an override with its current value writes nothing and adds no
|
||||
/// UpdateOverride audit row.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<CancellationToken>())).ReturnsAsync(instance);
|
||||
_repoMock.Setup(r => r.GetAttributesByTemplateIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<TemplateAttribute> { new("Threshold") { IsLocked = false } });
|
||||
_repoMock.Setup(r => r.GetOverridesByInstanceIdAsync(1, It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new List<InstanceAttributeOverride> { 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<InstanceAttributeOverride>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
_repoMock.Verify(r => r.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
|
||||
_auditMock.Verify(a => a.LogAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object?>(), It.IsAny<CancellationToken>()), Times.Never);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that overriding an unlocked attribute returns success.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user