Guard and name Raw manual entry and browsing workflows

This commit is contained in:
Joseph Doherty
2026-11-14 00:19:09 -05:00
parent 78b95cab08
commit ea5bb6a0bc
78 changed files with 3462 additions and 211 deletions
@@ -23,19 +23,19 @@
@inject AuthenticationStateProvider AuthState
@inject IAuthorizationService AuthorizationService
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Browse device <span class="text-muted small">(@_driverType)</span>
</h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
@using Microsoft.Extensions.Logging
@inject ILogger<RawBrowseModal> Logger
@{
var presentation = _openGeneration;
var closeAction = VisibleChanged;
var savedAction = OnSaved;
var sessionOpen = _token != Guid.Empty;
Func<Task> connectionAction = sessionOpen ? () => { RefreshTree(); return Task.CompletedTask; } : OpenBrowseAsync;
}
<ModalFrame Visible="@Visible" Title="Browse device" DialogClass="modal-lg modal-dialog-scrollable" Target="@presentation" Busy="@WritePending" OnClose="() => ClosePresentation(presentation, closeAction)">
<TitleContent>Browse device <span class="text-muted small">(@_driverType)</span></TitleContent>
<ChildContent>
<fieldset disabled="@WritePending">
@if (_resolving)
{
<div class="text-muted small"><span class="spinner-border spinner-border-sm me-1"></span>Loading device config&hellip;</div>
@@ -53,51 +53,33 @@
Committing under: <code class="mono">@TargetLabel()</code>
</div>
@if (_token == Guid.Empty)
<div class="d-flex flex-wrap align-items-center gap-2 mb-2">
@* Keep this control mounted: connecting changes its action to Refresh,
so keyboard focus remains inside the dialog when the session opens. *@
<button type="button" class="btn btn-sm @(sessionOpen ? "btn-outline-secondary" : "btn-outline-primary")"
title='@(sessionOpen ? "Re-read what this session has observed since it opened" : null)'
disabled="@WritePending" aria-disabled="@(_opening || WritePending ? "true" : "false")" aria-busy="@(_opening ? "true" : "false")" @onclick="() => Run(presentation, connectionAction)">
@if (_opening) { <span class="spinner-border spinner-border-sm me-1" aria-hidden="true"></span> }
@(sessionOpen ? "Refresh" : "Connect & browse")
</button>
@if (sessionOpen) { <span class="chip chip-ok">Browser open</span> }
@if (_openError is not null) { <RefusalChip Message="@_openError" /> }
</div>
@if (sessionOpen)
{
<div class="d-flex align-items-center gap-2">
<button type="button" class="btn btn-outline-primary btn-sm"
disabled="@_opening" @onclick="OpenBrowseAsync">
@if (_opening) { <span class="spinner-border spinner-border-sm me-1"></span> }
Connect &amp; browse
</button>
@if (_openError is not null)
{
<RefusalChip Message="@_openError" />
}
</div>
}
else
{
<div class="d-flex align-items-center justify-content-between mb-2">
<div class="d-flex align-items-center gap-2">
<span class="chip chip-ok">Browser open</span>
@* An observation window ACCUMULATES — the session keeps recording every
message after the tree was first rendered — but the tree itself loads
exactly once, when it is created. Without this the operator sees the
t=0 snapshot forever: on MQTT the first render is usually empty (a
topic that has not published yet is invisible) and on Sparkplug it is
almost always empty, because births are never retained. Re-keying the
tree re-runs its root load against the SAME session, so nothing
reconnects and nothing already observed is lost. *@
<button type="button" class="btn btn-outline-secondary btn-sm"
title="Re-read what this session has observed since it opened"
@onclick="RefreshTree">
Refresh
</button>
</div>
<div class="d-flex flex-wrap align-items-center justify-content-between mb-2">
<div class="form-check form-switch mb-0">
<input class="form-check-input" type="checkbox" id="raw-browse-mirror"
checked="@_createGroups" @onchange="@(e => _createGroups = e.Value is true)" />
<label class="form-check-label small" for="raw-browse-mirror">
<input class="form-check-input" type="checkbox" id='@FieldId("mirror")'
checked="@_createGroups" @onchange="@(e => Run(presentation, () => _createGroups = e.Value is true))" />
<label class="form-check-label small" for='@FieldId("mirror")'>
Create matching tag-groups (mirror browse folders)
</label>
</div>
</div>
<DriverBrowseTree @key="_treeGeneration" SessionToken="_token" MultiSelect="true"
SelectedLeafIds="_selectedIds" OnLeafToggled="OnLeafToggledAsync"
OnNodeSelectedWithPath="OnScopeNodeSelected" />
<DriverBrowseTree @key="(presentation, _treeGeneration)" SessionToken="_token" MultiSelect="true"
SelectedLeafIds="_selectedIds" OnLeafToggled="sel => Run(presentation, () => OnLeafToggledAsync(sel))"
OnNodeSelectedWithPath="sel => Run(presentation, () => OnScopeNodeSelected(sel))" />
@if (_canRebirth && _canOperate)
{
@@ -118,7 +100,7 @@
{
<button type="button" class="btn btn-outline-warning btn-sm text-nowrap"
disabled="@(_rebirthTarget is null || _rebirthBusy)"
@onclick="BeginRebirth">
@onclick="() => Run(presentation, BeginRebirth)">
Request rebirth&hellip;
</button>
}
@@ -139,21 +121,18 @@
before this window opened, name one directly:
</div>
<div class="input-group input-group-sm mt-1">
<span class="input-group-text">Edge node</span>
<input class="form-control mono" placeholder="group/edgeNode"
aria-label="Sparkplug edge-node scope"
<label for='@FieldId("edge-node")' class="input-group-text">Edge node</label>
<input id='@FieldId("edge-node")' class="form-control mono" placeholder="group/edgeNode"
aria-label="Sparkplug edge-node scope" aria-describedby='@FieldId("scope-error")' aria-invalid='@(!string.IsNullOrWhiteSpace(_manualScope) && ManualScopeError is not null ? "true" : null)'
value="@_manualScope"
@oninput="@(e => _manualScope = e.Value?.ToString() ?? "")" />
@oninput="@(e => Run(presentation, () => _manualScope = e.Value?.ToString() ?? ""))" />
<button type="button" class="btn btn-outline-secondary"
disabled="@(ManualScopeError is not null)"
@onclick="ApplyManualScope">
@onclick="() => Run(presentation, ApplyManualScope)">
Use this scope
</button>
</div>
@if (!string.IsNullOrWhiteSpace(_manualScope) && ManualScopeError is { } manualErr)
{
<div class="small text-danger mt-1">@manualErr</div>
}
<div id='@FieldId("scope-error")' class="small text-danger mt-1" role="alert">@(!string.IsNullOrWhiteSpace(_manualScope) ? ManualScopeError : null)</div>
}
else
{
@@ -182,12 +161,12 @@
</div>
<div class="btn-group btn-group-sm mt-2" role="group">
<button type="button" class="btn btn-warning btn-sm"
disabled="@_rebirthBusy" @onclick="ConfirmRebirthAsync">
disabled="@_rebirthBusy" @onclick="() => Run(presentation, ConfirmRebirthAsync)">
@if (_rebirthBusy) { <span class="spinner-border spinner-border-sm me-1"></span> }
Publish rebirth request
</button>
<button type="button" class="btn btn-outline-secondary btn-sm"
disabled="@_rebirthBusy" @onclick="CancelRebirth">
disabled="@_rebirthBusy" @onclick="() => Run(presentation, CancelRebirth)">
Cancel
</button>
</div>
@@ -234,21 +213,19 @@
</div>
}
}
</div>
<div class="modal-footer">
</fieldset>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="CommitAsync"
disabled="@(_busy || _selected.Count == 0)">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => ClosePresentation(presentation, closeAction)" disabled="@WritePending">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="() => CommitPresentation(presentation, savedAction, closeAction)"
disabled="@(WritePending || _selected.Count == 0)">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
Add @_selected.Count tag@(_selected.Count == 1 ? "" : "s")
</button>
</div>
</div>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
/// <summary>Fallback OPC-UA built-in type for browse-committed leaves whose browser cannot report a
@@ -280,6 +257,15 @@
/// <summary>Raised after a successful commit so the host can refresh the affected subtree.</summary>
[Parameter] public EventCallback OnSaved { get; set; }
/// <summary>Optional identity for otherwise identical successive browse targets.</summary>
[Parameter] public object? Target { get; set; }
private object? _identity;
private readonly string _fieldScope = "ot-browse-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private Task Run(int generation, Func<Task> action) => !IsStale(generation) && !WritePending ? action() : Task.CompletedTask;
private void Run(int generation, Action action) { if (!IsStale(generation) && !WritePending) action(); }
private bool WritePending => _busy || _rebirthBusy;
private bool _open; // guards re-seeding on unrelated re-renders
/// <summary>
@@ -343,31 +329,47 @@
protected override async Task OnInitializedAsync()
{
var auth = await AuthState.GetAuthenticationStateAsync();
if (_disposed) return;
var result = await AuthorizationService.AuthorizeAsync(auth.User, null, AdminUiPolicies.DriverOperator);
_canOperate = result.Succeeded;
if (!_disposed) _canOperate = result.Succeeded;
}
protected override async Task OnParametersSetAsync()
{
if (_disposed) return;
var identity = (Target, DeviceId, TagGroupId, DriverType);
if (_open && Visible && Equals(_identity, identity)) return;
var retired = _token;
_token = Guid.Empty;
if (retired != Guid.Empty) _ = CloseRetiredSessionAsync(retired);
if (!Visible)
{
if (_open) ++_openGeneration;
_open = false;
return;
}
if (_open) { return; }
_open = true;
_identity = identity;
await ResetAndResolveAsync();
}
private async Task CloseRetiredSessionAsync(Guid token)
{
try { await BrowserService.CloseAsync(token); }
catch (Exception ex) { Logger.LogWarning(ex, "Retired browse session could not be closed."); }
}
private async Task ResetAndResolveAsync()
{
var generation = ++_openGeneration;
var device = DeviceId;
var group = TagGroupId;
var service = Svc;
_token = Guid.Empty;
_opening = false;
_openError = null;
_createGroups = false;
_busy = false;
_commitErrors = new();
_selected.Clear();
_selectedIds.Clear();
@@ -388,7 +390,7 @@
{
// Merged Driver+Device config — endpoint lives in DeviceConfig in v3, so the browser must dial
// the merged blob (same merge the driver-probe/test-connect path uses).
var merged = await Svc.LoadMergedProbeConfigAsync(DeviceId);
var merged = await service.LoadMergedProbeConfigAsync(device);
// A superseded open must never install its device under the displayed modal — see
// _openGeneration. Every post-await write below is behind this check.
if (IsStale(generation)) { return; }
@@ -400,9 +402,9 @@
}
// Resolve the target group's device-relative path prefix (prepended to every committed tag).
if (!string.IsNullOrEmpty(TagGroupId))
if (!string.IsNullOrEmpty(group))
{
var ctx = await ExportReader.ResolveGroupContextAsync(TagGroupId!);
var ctx = await ExportReader.ResolveGroupContextAsync(group!);
if (IsStale(generation)) { return; } // same race, second await: this one retargets the commit
if (ctx is { } c)
@@ -451,10 +453,15 @@
/// </summary>
/// <param name="generation">The <see cref="_openGeneration"/> value captured when the open started.</param>
/// <returns><see langword="true"/> when no state may be written for that open.</returns>
private bool IsStale(int generation) => generation != _openGeneration || !Visible;
private bool IsStale(int generation) => _disposed || generation != _openGeneration || !Visible || !_open;
private async Task OpenBrowseAsync()
{
if (IsStale(_openGeneration) || _opening || WritePending || _resolving || !_canBrowse || _token != Guid.Empty) return;
var driverType = _driverType;
var config = _mergedConfig;
var device = _effectiveDeviceId;
var service = Svc;
_opening = true;
_openError = null;
// Captured BEFORE the await: a close-then-reopen while this open is in flight leaves Visible true
@@ -465,10 +472,11 @@
{
// lmxopcua#835: name the owning driver so its own secret:<ns>/<id>/… references are told apart from
// another instance's (an unresolvable owner is treated as a new driver — stricter).
var ownerDriverId = string.IsNullOrEmpty(_effectiveDeviceId)
var ownerDriverId = string.IsNullOrEmpty(device)
? null
: await Svc.LoadDeviceDriverInstanceIdAsync(_effectiveDeviceId);
var result = await BrowserService.OpenAsync(_driverType, _mergedConfig, ownerDriverId, default);
: await service.LoadDeviceDriverInstanceIdAsync(device);
if (IsStale(generation)) return;
var result = await BrowserService.OpenAsync(driverType, config, ownerDriverId, default);
// Host disposed, modal closed, or modal re-opened mid-open: close the session nobody will (R04 L4).
if (BrowseOpenGuard.CloseIfOrphaned(result, _disposed || IsStale(generation), BrowserService)) { return; }
if (result.Ok)
@@ -496,13 +504,19 @@
}
finally
{
_opening = false;
StateHasChanged();
if (!IsStale(generation))
{
_opening = false;
StateHasChanged();
}
}
}
private async Task OnLeafToggledAsync(BrowseLeafSelection sel)
{
var generation = _openGeneration;
var token = _token;
if (IsStale(generation) || WritePending || token == Guid.Empty) return;
var nodeId = sel.Leaf.NodeId;
if (_selectedIds.Contains(nodeId))
{
@@ -520,7 +534,7 @@
string? descriptor = null;
try
{
var attrs = await BrowserService.AttributesAsync(_token, nodeId, default);
var attrs = await BrowserService.AttributesAsync(token, nodeId, default);
if (attrs.Count > 0)
{
name = string.IsNullOrWhiteSpace(attrs[0].Name) ? sel.Leaf.DisplayName : attrs[0].Name;
@@ -539,6 +553,7 @@
// For a tuple-addressed driver that also means "no address", which CommitAsync refuses in words.
}
if (IsStale(generation) || token != _token || WritePending) return;
_selectedIds.Add(nodeId);
_selected[nodeId] = new SelectedLeaf(nodeId, name, driverDataType, sel.FolderPath, addressFields, descriptor);
@@ -689,6 +704,8 @@
/// </summary>
private async Task ConfirmRebirthAsync()
{
var generation = _openGeneration;
if (IsStale(generation) || WritePending || !_canOperate || !_rebirthConfirming) return;
if (_rebirthTarget is null) { return; }
// #510 again, at the last moment before publishing: the reap can land between arming the confirm
// step and clicking it, and this is the one path that reaches a live broker.
@@ -705,7 +722,8 @@
// The session's RequestRebirthAsync returns only once the births it asked for have arrived and
// gone quiet (bounded by the window), so the tree can be re-read now instead of telling the
// operator to re-expand it later (G2-F3). Skipped if the session or modal went away meanwhile.
var refreshed = token == _token && Visible && !_disposed;
if (IsStale(generation) || token != _token) return;
var refreshed = true;
if (refreshed)
{
// Re-key the tree against the SAME session (as the Refresh button does). The armed scope is
@@ -724,12 +742,12 @@
}
catch (Exception ex)
{
_rebirthError = ex.Message;
if (!IsStale(generation) && token == _token) _rebirthError = ex.Message;
}
finally
{
_rebirthBusy = false;
StateHasChanged();
if (!_disposed) StateHasChanged();
}
}
@@ -784,13 +802,17 @@
{
_rebirthTarget = null;
_rebirthConfirming = false;
_rebirthBusy = false;
_rebirthOutcome = null;
_rebirthError = null;
}
private async Task CommitAsync()
private async Task CommitAsync() => await CommitPresentation(_openGeneration, OnSaved, VisibleChanged);
private async Task CommitPresentation(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
if (IsStale(generation) || WritePending || _selected.Count == 0) return;
var service = Svc;
var device = _effectiveDeviceId;
_busy = true;
_commitErrors = new();
StateHasChanged();
@@ -823,15 +845,20 @@
.ToList();
if (_commitErrors.Count > 0) { return; }
var outcome = await Svc.ImportTagsAsync(_effectiveDeviceId, rows);
var outcome = await service.ImportTagsAsync(device, rows);
if (IsStale(generation)) return;
if (outcome.Errors.Count > 0)
{
_commitErrors = outcome.Errors.ToList();
return;
}
await OnSaved.InvokeAsync();
await CloseAsync();
await savedAction.InvokeAsync();
if (!IsStale(generation)) await ClosePresentation(generation, closeAction, completed: true);
}
catch (Exception) when (IsStale(generation))
{
// Preserve current failures, while retiring exceptions from a previous presentation.
}
finally
{
@@ -839,8 +866,11 @@
}
}
private async Task CloseAsync()
private Task CloseAsync() => ClosePresentation(_openGeneration, VisibleChanged);
private async Task ClosePresentation(int generation, EventCallback<bool> closeAction, bool completed = false)
{
if (IsStale(generation) || (WritePending && !completed)) return;
var t = _token;
_token = Guid.Empty;
_canRebirth = false;
@@ -849,8 +879,9 @@
ResetRebirthState();
Visible = false;
_open = false;
await VisibleChanged.InvokeAsync(false);
if (t != Guid.Empty) { await BrowserService.CloseAsync(t); }
++_openGeneration;
try { await closeAction.InvokeAsync(false); }
finally { if (t != Guid.Empty) await CloseRetiredSessionAsync(t); }
}
private string TargetLabel()
@@ -859,11 +890,14 @@
public ValueTask DisposeAsync()
{
if (_disposed) return ValueTask.CompletedTask;
_disposed = true;
++_openGeneration;
if (_token != Guid.Empty)
{
// Fire-and-forget — don't block circuit teardown on a slow remote.
_ = BrowserService.CloseAsync(_token);
_ = CloseRetiredSessionAsync(_token);
_token = Guid.Empty;
}
return ValueTask.CompletedTask;
}
@@ -12,27 +12,26 @@
@using ZB.MOM.WW.OtOpcUa.Configuration.Enums
@inject IRawTreeService Svc
@if (Visible)
{
<div class="modal-backdrop fade show" style="display:block"></div>
<div class="modal fade show" tabindex="-1" role="dialog" style="display:block">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add tags — manual entry <span class="text-muted small">(@DriverType)</span></h5>
<button type="button" class="btn-close" aria-label="Close" @onclick="CloseAsync"></button>
</div>
<div class="modal-body">
<div class="table-responsive">
@implements IDisposable
@{
var presentation = _openGeneration;
var savedAction = OnSaved;
var closeAction = VisibleChanged;
}
<ModalFrame Visible="@Visible" Title="Add tags — manual entry" DialogClass="modal-xl modal-dialog-scrollable" Target="@presentation" Busy="@_busy" OnClose="() => Cancel(presentation, closeAction)">
<TitleContent>Add tags — manual entry <span class="text-muted small">(@DriverType)</span></TitleContent>
<ChildContent>
<fieldset disabled="@_busy">
<div class="table-responsive" role="region" aria-label="Manual tag rows" tabindex="0">
<table class="table table-sm align-middle">
<thead>
<tr>
<th style="width:22%">Name</th>
<th style="width:14%">Data type</th>
<th style="width:14%">Access</th>
<th style="width:12%">WriteIdemp.</th>
<th style="width:18%">PollGroup</th>
<th style="width:12%">Config</th>
<th style="width:22%" scope="col" id='@FieldId("col-name")'>Name</th>
<th style="width:14%" scope="col" id='@FieldId("col-type")'>Data type</th>
<th style="width:14%" scope="col" id='@FieldId("col-access")'>Access</th>
<th style="width:12%" scope="col" id='@FieldId("col-write")'>WriteIdemp.</th>
<th style="width:18%" scope="col" id='@FieldId("col-poll")'>PollGroup</th>
<th style="width:12%" scope="col" id='@FieldId("col-config")'>Config</th>
<th style="width:8%"></th>
</tr>
</thead>
@@ -41,25 +40,23 @@
{
<tr @key="row.Key">
<td>
<input class="form-control form-control-sm" placeholder="TagName"
value="@row.Name" @onchange="@(e => row.Name = e.Value?.ToString() ?? "")" />
@if (row.Error is not null)
{
<div class="text-danger small">@row.Error</div>
}
<span id='@FieldId(row.Key + "-label")' class="visually-hidden">Tag row @(_rows.IndexOf(row) + 1)</span>
<input id='@FieldId(row.Key + "-name")' aria-labelledby='@(FieldId("col-name") + " " + FieldId(row.Key + "-label"))' aria-describedby='@FieldId(row.Key + "-error")' aria-invalid='@(row.ErrorField == "name" ? "true" : null)' class="form-control form-control-sm" placeholder="TagName"
value="@row.Name" @onchange="@(e => { if (Current(presentation) && !_busy) row.Name = e.Value?.ToString() ?? ""; })" />
<div id='@FieldId(row.Key + "-error")' class="text-danger small" role="alert">@row.Error</div>
</td>
<td>
@if (RawTagRowDefaults.DictatedDataType(DriverType, row.TagConfig) is { } dictated)
{
@* lmxopcua#830: the driver dictates the type for this address — show it, locked,
rather than offer a choice the commit would replace. *@
<input class="form-control form-control-sm mono" value="@dictated" disabled readonly
<input id='@FieldId(row.Key + "-type")' aria-labelledby='@(FieldId("col-type") + " " + FieldId(row.Key + "-label"))' class="form-control form-control-sm mono" value="@dictated" disabled readonly
title="Set by the address — the driver publishes this type" />
}
else
{
<select class="form-select form-select-sm" value="@row.DataType"
@onchange="@(e => row.DataType = e.Value?.ToString() ?? "Float")">
<select id='@FieldId(row.Key + "-type")' aria-labelledby='@(FieldId("col-type") + " " + FieldId(row.Key + "-label"))' class="form-select form-select-sm" value="@row.DataType"
@onchange="@(e => { if (Current(presentation) && !_busy) row.DataType = e.Value?.ToString() ?? "Float"; })">
@foreach (var dt in DataTypes)
{
<option value="@dt">@dt</option>
@@ -68,50 +65,50 @@
}
</td>
<td>
<select class="form-select form-select-sm" value="@row.AccessLevel"
<select id='@FieldId(row.Key + "-access")' aria-labelledby='@(FieldId("col-access") + " " + FieldId(row.Key + "-label"))' class="form-select form-select-sm" value="@row.AccessLevel"
disabled="@RawTagRowDefaults.IsReadOnlyDriver(DriverType)"
@onchange="@(e => row.AccessLevel = ParseAccess(e.Value))">
@onchange="@(e => { if (Current(presentation) && !_busy) row.AccessLevel = ParseAccess(e.Value); })">
<option value="@TagAccessLevel.Read">Read</option>
<option value="@TagAccessLevel.ReadWrite">ReadWrite</option>
</select>
</td>
<td class="text-center">
<input type="checkbox" class="form-check-input" checked="@row.WriteIdempotent"
@onchange="@(e => row.WriteIdempotent = e.Value is true)" />
<input id='@FieldId(row.Key + "-write")' aria-labelledby='@(FieldId("col-write") + " " + FieldId(row.Key + "-label"))' type="checkbox" class="form-check-input" checked="@row.WriteIdempotent"
@onchange="@(e => { if (Current(presentation) && !_busy) row.WriteIdempotent = e.Value is true; })" />
</td>
<td>
<input class="form-control form-control-sm mono" placeholder="(optional)"
value="@row.PollGroupId" @onchange="@(e => row.PollGroupId = e.Value?.ToString())" />
<input id='@FieldId(row.Key + "-poll")' aria-labelledby='@(FieldId("col-poll") + " " + FieldId(row.Key + "-label"))' class="form-control form-control-sm mono" placeholder="(optional)"
value="@row.PollGroupId" @onchange="@(e => { if (Current(presentation) && !_busy) row.PollGroupId = e.Value?.ToString(); })" />
</td>
<td>
<button type="button" class="btn btn-sm btn-outline-secondary"
@onclick="@(() => row.Expanded = !row.Expanded)">
aria-expanded="@row.Expanded.ToString().ToLowerInvariant()" aria-label="@($"Configure tag row {_rows.IndexOf(row) + 1}")" @onclick="@(() => { if (Current(presentation) && !_busy) row.Expanded = !row.Expanded; })">
@(row.Expanded ? "Hide" : "Configure")
</button>
</td>
<td class="text-end">
<button type="button" class="btn btn-sm btn-outline-danger"
@onclick="@(() => RemoveRow(row))" disabled="@(_rows.Count == 1)">✕</button>
aria-label="@($"Remove tag row {_rows.IndexOf(row) + 1}")" @onclick="@(() => RemoveRow(row))" disabled="@(_rows.Count == 1)">✕</button>
</td>
</tr>
@if (row.Expanded)
{
<tr @key="@(row.Key + "-cfg")">
<td colspan="7">
<div class="border rounded p-2 bg-body-tertiary">
<div class="border rounded p-2 bg-body-tertiary" role="group" aria-labelledby='@(FieldId("col-config") + " " + FieldId(row.Key + "-label"))' aria-describedby='@FieldId(row.Key + "-error")' aria-invalid='@(row.ErrorField == "config" ? "true" : null)'>
@{
var editorType = TagConfigEditorMap.Resolve(DriverType);
}
@if (editorType is not null)
{
<DynamicComponent Type="editorType" Parameters="BuildEditorParameters(row)" />
<DynamicComponent @key="(presentation, row.Key)" Type="editorType" Parameters="BuildEditorParameters(row)" />
}
else
{
<textarea class="form-control form-control-sm mono" rows="4"
<textarea aria-describedby='@FieldId(row.Key + "-error")' aria-invalid='@(row.ErrorField == "config" ? "true" : null)' id='@FieldId(row.Key + "-config")' aria-labelledby='@(FieldId("col-config") + " " + FieldId(row.Key + "-label"))' class="form-control form-control-sm mono" rows="4"
placeholder='{ "FullName": "tag_name.AttributeName" }'
value="@row.TagConfig"
@onchange="@(e => row.TagConfig = e.Value?.ToString() ?? "{}")"></textarea>
@onchange="@(e => { if (Current(presentation) && !_busy) row.TagConfig = e.Value?.ToString() ?? "{}"; })"></textarea>
<div class="form-text">Schemaless per driver type. Validated server-side at deploy.</div>
}
</div>
@@ -123,27 +120,24 @@
</table>
</div>
<button type="button" class="btn btn-sm btn-outline-primary" @onclick="AddRow">+ Add row</button>
<button type="button" class="btn btn-sm btn-outline-primary" @onclick="() => AddRow(presentation)">+ Add row</button>
@if (!string.IsNullOrWhiteSpace(_summary))
{
<div class="alert @(_summaryOk ? "alert-success" : "alert-warning") py-2 mt-3 mb-0">@_summary</div>
}
</div>
<div class="modal-footer">
</fieldset>
</ChildContent>
<Footer>
<div class="btn-group" role="group">
<button type="button" class="btn btn-outline-secondary" @onclick="CloseAsync" disabled="@_busy">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="CommitAsync" disabled="@_busy">
<button type="button" class="btn btn-outline-secondary" data-initial-focus="true" @onclick="() => Cancel(presentation, closeAction)" disabled="@_busy">Cancel</button>
<button type="button" class="btn btn-primary" @onclick="() => CommitAsync(presentation, savedAction, closeAction)" disabled="@_busy">
@if (_busy) { <span class="spinner-border spinner-border-sm me-1"></span> }
Create @_rows.Count tag@(_rows.Count == 1 ? "" : "s")
</button>
</div>
</div>
</div>
</div>
</div>
}
</Footer>
</ModalFrame>
@code {
private static readonly string[] DataTypes =
["Boolean", "SByte", "Byte", "Int16", "UInt16", "Int32", "UInt32",
@@ -167,10 +161,18 @@
/// <summary>Raised after at least one tag is committed so the host can refresh the tree.</summary>
[Parameter] public EventCallback OnSaved { get; set; }
/// <summary>Optional identity for otherwise identical successive authoring targets.</summary>
[Parameter] public object? Target { get; set; }
private readonly List<RowModel> _rows = new();
private bool _busy;
private string? _summary;
private bool _summaryOk;
private bool _disposed;
private object? _identity;
private readonly string _fieldScope = "ot-manual-" + Guid.NewGuid().ToString("N");
private string FieldId(string suffix) => _fieldScope + "-" + suffix;
private bool Current(int generation) => !_disposed && Visible && _open && generation == _openGeneration;
private bool _open; // guards re-seeding rows on unrelated re-renders
// Identifies WHICH open a post-await write belongs to; _open alone cannot tell two opens apart.
@@ -179,35 +181,42 @@
// Merged Driver+Device config for each row's address picker — the same blob Test-connect and
// RawBrowseModal dial, resolved once per open; null (→ "{}") when the resolve failed: the picker's
// browse degrades to its graceful error chip.
private string? _mergedConfigJson;
private sealed class ProbeSnapshot { public string? Json { get; set; } }
private ProbeSnapshot _probe = new();
protected override async Task OnParametersSetAsync()
{
if (_disposed) return;
var identity = (Target, DeviceId, TagGroupId, DriverType);
if (!Visible)
{
if (_open) ++_openGeneration;
_open = false;
_mergedConfigJson = null;
return;
}
if (_open) { return; } // same open, re-render → preserve in-progress rows
if (_open && Equals(_identity, identity)) { return; } // same open, re-render → preserve in-progress rows
_open = true;
_identity = identity;
_probe = new();
var generation = ++_openGeneration;
_rows.Clear();
_rows.Add(new RowModel());
_summary = null;
_summaryOk = false;
_mergedConfigJson = null;
var probe = _probe;
var device = DeviceId;
var service = Svc;
if (!string.IsNullOrEmpty(DeviceId))
{
try
{
var merged = await Svc.LoadMergedProbeConfigAsync(DeviceId);
var merged = await service.LoadMergedProbeConfigAsync(device);
// A close-reopen onto another device can complete while this resolve is in flight, so a
// superseded open must never install its device's config under the displayed grid.
if (generation != _openGeneration || !Visible) { return; }
if (!Current(generation)) { return; }
if (merged is { } m) { _mergedConfigJson = m.MergedConfigJson; }
if (merged is { } m) { probe.Json = m.MergedConfigJson; }
}
catch
{
@@ -217,52 +226,64 @@
}
}
private IDictionary<string, object> BuildEditorParameters(RowModel row) => new Dictionary<string, object>
private IDictionary<string, object> BuildEditorParameters(RowModel row)
{
["ConfigJson"] = row.TagConfig,
["ConfigJsonChanged"] = EventCallback.Factory.Create<string>(this, v =>
var generation = _openGeneration;
var driverType = DriverType;
var probe = _probe;
return new Dictionary<string, object>
{
row.TagConfig = v;
RawTagRowDefaults.Apply(DriverType, row.TagConfig, a => row.AccessLevel = a, d => row.DataType = d);
}),
["DriverType"] = DriverType,
["GetDriverConfigJson"] = (Func<string>)(() => _mergedConfigJson ?? "{}"),
};
["ConfigJson"] = row.TagConfig,
["ConfigJsonChanged"] = EventCallback.Factory.Create<string>(this, v =>
{
if (!Current(generation) || _busy || !_rows.Contains(row)) return;
row.TagConfig = v;
RawTagRowDefaults.Apply(driverType, row.TagConfig, a => row.AccessLevel = a, d => row.DataType = d);
}),
["DriverType"] = driverType,
["GetDriverConfigJson"] = (Func<string>)(() => probe.Json ?? "{}"),
};
}
private void AddRow() => _rows.Add(new RowModel());
private void AddRow(int generation) { if (Current(generation) && !_busy) _rows.Add(new RowModel()); }
private void RemoveRow(RowModel row)
{
if (_rows.Count > 1) { _rows.Remove(row); }
if (Current(_openGeneration) && !_busy && _rows.Count > 1) { _rows.Remove(row); }
}
private static TagAccessLevel ParseAccess(object? v)
=> Enum.TryParse<TagAccessLevel>(v?.ToString(), out var a) ? a : TagAccessLevel.Read;
private async Task CommitAsync()
private async Task CommitAsync(int generation, EventCallback savedAction, EventCallback<bool> closeAction)
{
if (!Current(generation) || _busy) return;
var service = Svc;
var device = DeviceId;
var group = TagGroupId;
var driverType = DriverType;
_busy = true;
_summary = null;
try
{
// --- Client-side validation first: name segment + per-driver config + intra-grid dup names. ---
foreach (var row in _rows) { row.Error = null; }
foreach (var row in _rows) { row.Error = null; row.ErrorField = null; }
var seen = new HashSet<string>(RawPaths.Comparer);
var anyClientError = false;
foreach (var row in _rows)
{
var nameError = RawPaths.ValidateSegment(row.Name);
if (nameError is not null) { row.Error = nameError; anyClientError = true; continue; }
if (!seen.Add(row.Name)) { row.Error = "Duplicate name in this batch."; anyClientError = true; continue; }
var configError = TagConfigValidator.Validate(DriverType, row.TagConfig);
if (configError is not null) { row.Error = configError; anyClientError = true; continue; }
if (nameError is not null) { row.Error = nameError; row.ErrorField = "name"; anyClientError = true; continue; }
if (!seen.Add(row.Name)) { row.Error = "Duplicate name in this batch."; row.ErrorField = "name"; anyClientError = true; continue; }
var configError = TagConfigValidator.Validate(driverType, row.TagConfig);
if (configError is not null) { row.Error = configError; row.ErrorField = "config"; anyClientError = true; continue; }
// The dictated fields are locked to the driver's values (applied on every config edit), so this
// re-application changes nothing the operator could see; the row rule then runs exactly as the
// server's will — a mismatch is SHOWN, never silently rewritten.
RawTagRowDefaults.Apply(DriverType, row.TagConfig, a => row.AccessLevel = a, d => row.DataType = d);
var rowError = RawTagRowRules.Problem(DriverType, row.AccessLevel, row.DataType, row.TagConfig);
if (rowError is not null) { row.Error = rowError; anyClientError = true; }
RawTagRowDefaults.Apply(driverType, row.TagConfig, a => row.AccessLevel = a, d => row.DataType = d);
var rowError = RawTagRowRules.Problem(driverType, row.AccessLevel, row.DataType, row.TagConfig);
if (rowError is not null) { row.Error = rowError; row.ErrorField = "config"; anyClientError = true; }
}
if (anyClientError)
{
@@ -271,20 +292,18 @@
return;
}
// --- Commit each row; keep failures (with their error), drop committed rows. ---
// Freeze every row before the first dispatch; queued edits cannot alter later writes.
var submitted = _rows.Select(row => (Row: row, Input: new RawTagInput(
row.Name, row.DataType, row.AccessLevel, row.WriteIdempotent,
string.IsNullOrWhiteSpace(row.PollGroupId) ? null : row.PollGroupId,
string.IsNullOrWhiteSpace(row.TagConfig) ? "{}" : row.TagConfig))).ToArray();
var created = 0;
var failed = 0;
foreach (var row in _rows)
foreach (var (row, input) in submitted)
{
var input = new RawTagInput(
row.Name,
row.DataType,
row.AccessLevel,
row.WriteIdempotent,
string.IsNullOrWhiteSpace(row.PollGroupId) ? null : row.PollGroupId,
string.IsNullOrWhiteSpace(row.TagConfig) ? "{}" : row.TagConfig);
var result = await Svc.CreateTagAsync(DeviceId, TagGroupId, input);
if (!Current(generation)) return;
var result = await service.CreateTagAsync(device, group, input);
if (!Current(generation)) return;
if (result.Ok)
{
row.Committed = true;
@@ -301,31 +320,51 @@
if (failed == 0)
{
if (created > 0) { await OnSaved.InvokeAsync(); }
await CloseAsync();
if (created > 0)
{
await savedAction.InvokeAsync();
if (!Current(generation)) return;
}
await Close(generation, closeAction);
}
else
{
// Some succeeded, some failed: refresh the tree for the good ones, keep the modal open on
// the failed rows so the operator can correct them without re-entering the whole batch.
if (created > 0) { await OnSaved.InvokeAsync(); }
if (created > 0)
{
await savedAction.InvokeAsync();
if (!Current(generation)) return;
}
_summaryOk = false;
_summary = $"{created} tag(s) created; {failed} failed. Fix the highlighted rows and retry.";
}
}
catch (Exception) when (!Current(generation))
{
// A dispatched retired operation may fail, but cannot fault its replacement view.
}
finally
{
_busy = false;
}
}
private async Task CloseAsync()
private Task Cancel(int generation, EventCallback<bool> closeAction)
=> Current(generation) && !_busy ? Close(generation, closeAction) : Task.CompletedTask;
private async Task Close(int generation, EventCallback<bool> closeAction)
{
if (!Current(generation)) return;
Visible = false;
_open = false;
await VisibleChanged.InvokeAsync(false);
++_openGeneration;
await closeAction.InvokeAsync(false);
}
/// <summary>Retires UI callbacks without cancelling a dispatched tag creation.</summary>
public void Dispose() { _disposed = true; ++_openGeneration; }
private sealed class RowModel
{
public string Key { get; } = Guid.NewGuid().ToString("N");
@@ -338,5 +377,6 @@
public bool Expanded { get; set; }
public bool Committed { get; set; }
public string? Error { get; set; }
public string? ErrorField { get; set; }
}
}