d2818e2ef2
- V3NodeIds.ValidateSegment is the single rule Uns()/UnsChild() enforce; the VirtualTag modal ([UnsLeafName]), UnsTreeService (VirtualTag create/update, SetReferenceOverrideAsync) and the deploy gate (VirtualTagNameInvalid, UnsEffectiveNameInvalid) all call it (C-1, C-4). - Effective name is stated once (EquipmentReferenceMap.EffectiveName): an empty override falls back to the tag name in the gate and the Monaco catalog, as at both compose seams (C-4). - UnsSegment patterns anchored \A..\z, so a trailing newline is rejected (C-7). - VirtualTagScriptNotFound / ScriptedAlarmScriptNotFound deploy-gate rules; ScriptEdit refuses to delete a script used by a VirtualTag, ScriptedAlarm or Calculation tag and names them (C-2). - R-5 backstop: VirtualTagHostActor skips (Error log) a plan whose NodeId cannot be built instead of crashing on every apply; AddressSpaceApplier counts it as a failed node instead of aborting the VirtualTag materialise pass.
274 lines
13 KiB
Plaintext
274 lines
13 KiB
Plaintext
@page "/scripts/new"
|
|
@page "/scripts/{ScriptId}"
|
|
@* Script CRUD. SourceHash is computed automatically from SourceCode on save so the
|
|
integrity check in v2's deployment pipeline doesn't require operator action. *@
|
|
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
|
|
@rendermode RenderMode.InteractiveServer
|
|
@using Microsoft.AspNetCore.Components.Forms
|
|
@using Microsoft.EntityFrameworkCore
|
|
@using System.ComponentModel.DataAnnotations
|
|
@using System.Security.Cryptography
|
|
@using System.Text
|
|
@using ZB.MOM.WW.OtOpcUa.Configuration
|
|
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
|
|
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
|
|
@using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis
|
|
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
|
|
@inject NavigationManager Nav
|
|
@implements IDisposable
|
|
|
|
@{
|
|
var presentation = _generation;
|
|
var form = _form;
|
|
var confirmation = _confirmationEpoch;
|
|
}
|
|
|
|
<PageErrorBoundary>
|
|
<PageTitle>Script editor · OtOpcUa</PageTitle>
|
|
<div class="page-head">
|
|
<h1>@(IsNew ? "New script" : "Edit script")</h1>
|
|
<span class="spacer"></span>
|
|
<a href="/scripts" class="btn btn-outline-secondary btn-sm">Cancel</a>
|
|
</div>
|
|
|
|
@if (!_loaded)
|
|
{
|
|
<p role="status">Loading script…</p>
|
|
}
|
|
else if (_loadError is not null)
|
|
{
|
|
<section class="panel notice notice-alert" role="alert">@_loadError</section>
|
|
}
|
|
else if (!IsNew && _existing is null)
|
|
{
|
|
<section class="panel notice rise"><span class="mono">@ScriptId</span> not found.</section>
|
|
}
|
|
else
|
|
{
|
|
@* OnSubmit (not OnValidSubmit): the editor text is pulled from Monaco FIRST, then validated — the bound
|
|
SourceCode is only refreshed at blur, so validating before the pull could judge stale text. *@
|
|
<EditForm @key="presentation" Model="_form" OnSubmit="context => SubmitAsync(context, presentation, form)" FormName="scriptEdit">
|
|
<fieldset disabled="@_busy" aria-busy="@_busy.ToString().ToLowerInvariant()">
|
|
<DataAnnotationsValidator />
|
|
<ValidationSummary class="alert alert-danger py-2 px-3" />
|
|
<section class="panel rise">
|
|
<h2 class="panel-head">Identity</h2>
|
|
<div style="padding:1rem">
|
|
<div class="row">
|
|
@* ScriptId is system-generated (SC-…) on create, never operator-supplied —
|
|
shown read-only when editing an existing script, hidden on the New page. *@
|
|
@if (!IsNew)
|
|
{
|
|
<div class="col-md-5 mb-3">
|
|
<label class="form-label" for="@(_fieldId + "-id")">ScriptId</label>
|
|
<input id="@(_fieldId + "-id")" value="@_form.ScriptId" disabled class="form-control form-control-sm mono" />
|
|
</div>
|
|
}
|
|
<div class="@(IsNew ? "col-md-12" : "col-md-7") mb-3">
|
|
<label class="form-label" for="@(_fieldId + "-name")">Name</label>
|
|
<InputText id="@(_fieldId + "-name")" Value="@_form.Name" ValueChanged="value => ChangeName(value, presentation, form)" ValueExpression="() => _form.Name" class="form-control form-control-sm" />
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
|
|
<section class="panel rise mt-3">
|
|
<h2 class="panel-head">Source</h2>
|
|
<div style="padding:1rem">
|
|
<MonacoEditor @key="presentation" @ref="_editor" Value="@_form.SourceCode" ValueChanged="value => ChangeSource(value, presentation, form)" Height="420px"
|
|
AriaLabel="Script source code" ReadOnly="@_busy" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
|
<ScriptProblemsList Report="_markers" OnSelect="marker => RevealProblemAsync(marker, presentation)" />
|
|
<div class="form-text">SHA-256 hash is computed automatically on save.</div>
|
|
</div>
|
|
</section>
|
|
|
|
@if (!string.IsNullOrWhiteSpace(_error)) { <div class="panel notice notice-alert mt-3" role="alert">@_error</div> }
|
|
|
|
<div class="mt-3 d-flex gap-2">
|
|
<div class="btn-group" role="group">
|
|
<button type="submit" class="btn btn-primary" disabled="@_busy">@(_busy ? "Saving…" : IsNew ? "Create" : "Save changes")</button>
|
|
<a href="/scripts" class="btn btn-outline-secondary">Cancel</a>
|
|
</div>
|
|
@if (!IsNew) { <button type="button" class="btn btn-outline-danger ms-auto" @onclick="() => OpenDelete(presentation, form)" disabled="@_busy">Delete</button> }
|
|
</div>
|
|
</fieldset>
|
|
</EditForm>
|
|
|
|
@* R04 H1: the delete used to run on the first click. *@
|
|
<RawConfirmDialog Visible="@_confirmDeleteVisible" VisibleChanged="visible => ChangeDeleteVisibility(visible, presentation, confirmation)" Title="Delete script"
|
|
Target="@confirmation" Message="@_deleteMessage"
|
|
OnConfirm="() => DeleteAsync(presentation, confirmation)" />
|
|
}
|
|
</PageErrorBoundary>
|
|
|
|
@code {
|
|
[Parameter] public string? ScriptId { get; set; }
|
|
private bool IsNew => string.IsNullOrEmpty(ScriptId);
|
|
private readonly string _fieldId = "script-" + Guid.NewGuid().ToString("N");
|
|
private FormModel _form = new();
|
|
private Script? _existing;
|
|
private bool _loaded, _busy, _disposed, _hasTarget;
|
|
private string? _target, _error, _loadError;
|
|
private long _generation, _confirmationEpoch;
|
|
private bool _confirmDeleteVisible;
|
|
private string _deleteMessage = "";
|
|
private DeleteIntent? _deleteIntent;
|
|
private MonacoEditor? _editor;
|
|
private ScriptProblemReport _markers = ScriptProblemReport.Empty;
|
|
private sealed record DeleteIntent(string Id, byte[] RowVersion);
|
|
|
|
private bool Current(long generation) => !_disposed && generation == _generation;
|
|
private void ChangeName(string value, long generation, FormModel form)
|
|
{
|
|
if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.Name = value;
|
|
}
|
|
private void ChangeSource(string value, long generation, FormModel form)
|
|
{
|
|
if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value;
|
|
}
|
|
private void OnMarkersChanged(ScriptProblemReport report, long generation)
|
|
{
|
|
if (Current(generation)) _markers = report;
|
|
}
|
|
private Task RevealProblemAsync(DiagnosticMarker marker, long generation)
|
|
=> !Current(generation) || _editor is null ? Task.CompletedTask : _editor.RevealLineAsync(marker.StartLineNumber, marker.StartColumn);
|
|
|
|
protected override async Task OnParametersSetAsync()
|
|
{
|
|
if (_disposed || (_hasTarget && string.Equals(_target, ScriptId, StringComparison.Ordinal))) return;
|
|
_hasTarget = true;
|
|
_target = ScriptId;
|
|
var id = ScriptId;
|
|
var generation = ++_generation;
|
|
++_confirmationEpoch;
|
|
_loaded = _busy = _confirmDeleteVisible = false;
|
|
_existing = null; _editor = null; _deleteIntent = null;
|
|
_form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null;
|
|
try
|
|
{
|
|
if (!string.IsNullOrEmpty(id))
|
|
{
|
|
await using var db = await DbFactory.CreateDbContextAsync();
|
|
if (!Current(generation)) return;
|
|
var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id);
|
|
if (!Current(generation)) return;
|
|
_existing = existing;
|
|
if (existing is not null)
|
|
_form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name,
|
|
SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() };
|
|
}
|
|
}
|
|
catch (Exception ex) { if (Current(generation)) _loadError = $"The script could not be loaded: {ex.Message}"; }
|
|
finally { if (Current(generation)) _loaded = true; }
|
|
}
|
|
|
|
private async Task SubmitAsync(EditContext editContext, long generation, FormModel form)
|
|
{
|
|
if (!Current(generation) || _busy || !_loaded || !ReferenceEquals(form, _form) || _confirmDeleteVisible) return;
|
|
var id = _target;
|
|
var name = form.Name;
|
|
var version = form.RowVersion.ToArray();
|
|
var editor = _editor;
|
|
_busy = true; _error = null;
|
|
try
|
|
{
|
|
// Monaco is authoritative at Save. Capture the editor/context before awaiting its current text.
|
|
var source = form.SourceCode;
|
|
if (editor is not null)
|
|
{
|
|
var read = await editor.GetValueAsync();
|
|
if (!Current(generation)) return;
|
|
if (!read.Ok) { _error = $"Not saved: {read.Error}"; return; }
|
|
source = read.Value!;
|
|
}
|
|
if (!Current(generation)) return;
|
|
form.SourceCode = source;
|
|
if (!editContext.Validate()) return;
|
|
var sourceHash = HashSource(source);
|
|
await using var db = await DbFactory.CreateDbContextAsync();
|
|
if (!Current(generation)) return;
|
|
if (string.IsNullOrEmpty(id))
|
|
{
|
|
// Preserve system-generated SC- identity and the CSharp language contract.
|
|
db.Scripts.Add(new Script { ScriptId = $"SC-{Guid.NewGuid().ToString("N")[..12]}",
|
|
Name = name, Language = "CSharp", SourceCode = source, SourceHash = sourceHash });
|
|
}
|
|
else
|
|
{
|
|
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == id);
|
|
if (!Current(generation)) return;
|
|
if (entity is null) { _error = "Row no longer exists."; return; }
|
|
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = version;
|
|
entity.Name = name; entity.SourceCode = source; entity.SourceHash = sourceHash;
|
|
}
|
|
await db.SaveChangesAsync(); // Already-dispatched writes finish independently of route lifetime.
|
|
if (Current(generation)) Nav.NavigateTo("/scripts");
|
|
}
|
|
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were editing."; }
|
|
catch (Exception ex) { if (Current(generation)) _error = ex.Message; }
|
|
finally { if (Current(generation)) _busy = false; }
|
|
}
|
|
|
|
private void OpenDelete(long generation, FormModel form)
|
|
{
|
|
if (!Current(generation) || _busy || _confirmDeleteVisible || string.IsNullOrEmpty(_target) || !ReferenceEquals(form, _form)) return;
|
|
_deleteIntent = new(_target, form.RowVersion.ToArray());
|
|
_deleteMessage = $"Delete the script '{_existing?.Name ?? form.Name}'? This cannot be undone.";
|
|
++_confirmationEpoch;
|
|
_confirmDeleteVisible = true;
|
|
}
|
|
private void ChangeDeleteVisibility(bool visible, long generation, long confirmation)
|
|
{
|
|
if (!Current(generation) || confirmation != _confirmationEpoch || _busy || visible) return;
|
|
_confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch;
|
|
}
|
|
private async Task DeleteAsync(long generation, long confirmation)
|
|
{
|
|
if (!Current(generation) || _busy || !_confirmDeleteVisible || confirmation != _confirmationEpoch || _deleteIntent is not { } intent) return;
|
|
_busy = true; _error = null;
|
|
try
|
|
{
|
|
await using var db = await DbFactory.CreateDbContextAsync();
|
|
if (!Current(generation)) return;
|
|
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
|
|
if (!Current(generation)) return;
|
|
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
|
|
// lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users —
|
|
// a deleted predicate used to drop its scripted alarm silently on the next green deploy.
|
|
var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id);
|
|
if (!Current(generation)) return;
|
|
if (inUse is not null)
|
|
{
|
|
// Close the confirmation so the page-level alert naming the users is what the operator sees.
|
|
_confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch;
|
|
_error = $"Not deleted. {inUse}";
|
|
return;
|
|
}
|
|
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = intent.RowVersion;
|
|
db.Scripts.Remove(entity);
|
|
await db.SaveChangesAsync();
|
|
if (Current(generation)) Nav.NavigateTo("/scripts");
|
|
}
|
|
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
|
|
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; }
|
|
finally { if (Current(generation)) _busy = false; }
|
|
}
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true; ++_generation; ++_confirmationEpoch;
|
|
}
|
|
|
|
private static string HashSource(string source) =>
|
|
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
|
|
|
|
private sealed class FormModel
|
|
{
|
|
// ScriptId is system-generated, display-only (not user-entered) — no validation.
|
|
public string ScriptId { get; set; } = "";
|
|
[Required] public string Name { get; set; } = "";
|
|
[Required] public string SourceCode { get; set; } = "";
|
|
public byte[] RowVersion { get; set; } = [];
|
|
}
|
|
}
|