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:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user