feat: author and inspect grpc data connections

This commit is contained in:
Joseph Doherty
2026-11-16 20:58:43 -05:00
parent 8ad03e9c5d
commit 1df29a3124
31 changed files with 1246 additions and 141 deletions
@@ -0,0 +1,246 @@
@page "/clusters/{ClusterId}/data-connections"
@attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)]
@rendermode RenderMode.InteractiveServer
@using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Configuration.Validation
@using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections
@using ZB.MOM.WW.OtOpcUa.Commons.OpcUa
@using ZB.MOM.WW.OtOpcUa.Commons.Interfaces
@using ZB.MOM.WW.OtOpcUa.Commons.Types
@inject DataConnectionAdminService Service
@inject IFleetDiagnosticsClient Diagnostics
<PageErrorBoundary>
<PageTitle>Data connections · OtOpcUa</PageTitle>
<div class="page-head"><h1>Data connections · <span class="mono">@ClusterId</span></h1></div>
<ClusterNav ClusterId="@ClusterId" ActiveTab="data" />
<p>Connections are directional. Exports grant a peer access to local data; mappings place remote data under a local Raw or UNS parent.</p>
<section class="panel notice">Changes are saved as drafts. Deploy them from <a href="/deployments">Deployments</a>; saving alone does not start or stop an import. Runtime status is unavailable until reported by a node.</section>
@if (_snapshot is null) { <p>Loading…</p> }
else
{
@if (_error is not null) { <div class="alert alert-danger" role="alert">@_error</div> }
@if (_message is not null) { <div class="alert alert-success" role="status">@_message</div> }
<section class="panel mt-3">
<h2 class="panel-head">Connections</h2>
<div class="p-3">
@if (!ConnectionRows.Any()) { <p class="text-muted">No draft, applied, or observed connections.</p> }
@foreach (var row in ConnectionRows)
{
<div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@row.Id</strong>@if (row.Draft is { } draft) { <span class="chip chip-idle">Draft: @(draft.Enabled ? "enabled" : "disabled")</span> } else { <span class="chip chip-warn">Removed from draft</span> }@if (!_live.Any(x => Same(x.Row.ConnectionId, row.Id))) { <span>Runtime: unavailable</span> }
@foreach (var live in _live.Where(x => Same(x.Row.ConnectionId, row.Id)))
{
<div class="w-100 small"><strong>@live.NodeId: @DataConnectionDiagnostics.State(live.Row.State)</strong> · revision @live.Row.Revision · endpoint @DataConnectionDiagnostics.Endpoint(live.Row.SelectedEndpoint)
@if (live.Row.Serving is { } serving) { <span> · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation</span> }
<div>Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)</div>
<div>Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)</div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @Measure(live.Row.ProtocolMajor).@Measure(live.Row.ProtocolMinor)</div></div>
}
@foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { <span class="small">@applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled"))</span> }
@if (row.Draft is { } editable) { <AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(editable)">Edit</button></AuthorizeView> }</div>
}
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewConnection">New connection</button></AuthorizeView>
</div>
</section>
<section class="panel mt-3">
<h2 class="panel-head">Exports</h2><div class="p-3">
@if (!Exports.Any()) { <p class="text-muted">No export grants have been authored.</p> }
@foreach (var e in Exports) { <div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@e.DataExportId</strong><span>@e.Realm · @e.RootKind · @e.PrincipalId</span><span class="chip chip-idle">Draft: @(e.Enabled ? "enabled" : "disabled")</span><AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(e)">Edit</button></AuthorizeView></div> }
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewExport">New export</button></AuthorizeView></div>
</section>
<section class="panel mt-3"><h2 class="panel-head">Mappings</h2><div class="p-3">
@if (!Mappings.Any()) { <p class="text-muted">No remote branches have been mapped.</p> }
@foreach (var m in Mappings) { <div class="d-flex flex-wrap gap-2 align-items-center mb-2"><strong>@m.RemoteNamespaceMappingId</strong><span>@m.Realm · @m.BranchName via @m.DataConnectionId</span><span class="chip chip-idle">Draft: @(m.Enabled ? "enabled" : "disabled")</span><AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(m)">Edit</button></AuthorizeView></div> }
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewMapping">New mapping</button></AuthorizeView></div>
</section>
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor">
@if (_deleteCandidate is not null)
{
<section class="panel notice mt-3" role="alert"><p>Delete this draft? The change takes effect only after deployment.</p><button class="btn btn-danger btn-sm me-2" @onclick="() => Delete(_deleteCandidate)">Confirm delete</button><button class="btn btn-outline-secondary btn-sm" @onclick="() => _deleteCandidate = null">Keep draft</button></section>
}
@if (_connection is not null)
{
var c = _connection.Value;
<section class="panel mt-3"><h2 class="panel-head">Connection draft</h2><div class="p-3">
<label class="form-label" for="connection-id">Connection ID</label><input id="connection-id" class="form-control mb-2" @bind="c.DataConnectionId" disabled="@(c.DataConnectionRowId != Guid.Empty)" />
<label class="form-label" for="target-cluster">Expected cluster ID</label><input id="target-cluster" class="form-control mb-2" @bind="c.ExpectedClusterId" />
<label class="form-label" for="target-mode">Target</label><select id="target-mode" class="form-select mb-2" @bind="c.TargetMode" @bind:after="() => TargetChanged(c)"><option value="@DataTargetMode.Node">Node</option><option value="@DataTargetMode.Cluster">Cluster</option></select>
@if (c.TargetMode == DataTargetMode.Node) { <label class="form-label" for="target-node">Expected node ID</label><input id="target-node" class="form-control mb-2" @bind="c.ExpectedNodeId" /> }
else { <label class="form-label" for="eligible">Eligible target node IDs, one per line</label><textarea id="eligible" class="form-control mb-2" @bind="_connection.EligibleNodes"></textarea> }
<label class="form-label" for="consistency">Consistency</label><select id="consistency" class="form-select mb-2" @bind="c.Consistency"><option value="@DataConsistency.Primary">Primary</option><option value="@DataConsistency.ReadyReplica">Ready replica</option></select>
<label class="form-label" for="endpoints">HTTPS endpoints, one per line</label><textarea id="endpoints" class="form-control mb-2" @bind="_connection.Endpoints"></textarea>
<label class="form-label" for="secret-ref">Secret reference</label><input id="secret-ref" class="form-control mb-2" placeholder="secret:data/…" @bind="c.SecretReference" /><div class="form-text">Reference only; never enter a key or secret value.</div>
<fieldset><legend class="fs-6">Consumer nodes</legend>@foreach (var n in Nodes) { <label class="me-3"><input type="checkbox" checked="@c.ConsumerNodeIds.Contains(n.NodeId)" @onchange="e => Toggle(c.ConsumerNodeIds, n.NodeId, (bool)e.Value!)" /> @n.NodeId</label> }</fieldset>
@Operations(c.AllowedOperations, v => c.AllowedOperations = v)
<label><input type="checkbox" @bind="c.Enabled" /> Enabled in next deployment</label>
@Actions(c, c.DataConnectionRowId != Guid.Empty)
</div></section>
}
@if (_export is not null)
{
var e = _export;
<section class="panel mt-3"><h2 class="panel-head">Export draft</h2><div class="p-3">
<label class="form-label" for="export-id">Export ID</label><input id="export-id" class="form-control mb-2" @bind="e.DataExportId" disabled="@(e.DataExportRowId != Guid.Empty)" />
<label class="form-label" for="principal">Peer principal</label><input id="principal" class="form-control mb-2" @bind="e.PrincipalId" />
<label class="form-label" for="export-realm">Realm</label><select id="export-realm" class="form-select mb-2" @bind="e.Realm"><option value="@DataRealm.Raw">Raw</option><option value="@DataRealm.Uns">UNS</option></select>
<label class="form-label" for="export-root">Local export root</label><select id="export-root" class="form-select mb-2" value="@(e.RootKind + "|" + e.RootEntityId)" @onchange="args => SetExportRoot(e, args.Value?.ToString())"><option value="">Choose a root</option>@foreach (var p in ExportRoots(e.Realm)) { <option value="@p.Value">@p.Label</option> }</select>
@Operations(e.AllowedOperations, v => e.AllowedOperations = v)
<label><input type="checkbox" @bind="e.Enabled" /> Enabled in next deployment</label>@Actions(e, e.DataExportRowId != Guid.Empty)
</div></section>
}
@if (_mapping is not null)
{
var m = _mapping.Value;
<section class="panel mt-3"><h2 class="panel-head">Mapping draft</h2><div class="p-3">
<label class="form-label" for="mapping-id">Mapping ID</label><input id="mapping-id" class="form-control mb-2" @bind="m.RemoteNamespaceMappingId" disabled="@(m.RemoteNamespaceMappingRowId != Guid.Empty)" />
<label class="form-label" for="mapping-connection">Connection</label><select id="mapping-connection" class="form-select mb-2" @bind="m.DataConnectionId"><option value="">Choose a connection</option>@foreach (var c in Connections) { <option value="@c.DataConnectionId">@c.DataConnectionId</option> }</select>
<label class="form-label" for="mapping-realm">Realm</label><select id="mapping-realm" class="form-select mb-2" @bind="m.Realm" @bind:after="() => SetRealm(m)"><option value="@DataRealm.Raw">Raw</option><option value="@DataRealm.Uns">UNS</option></select>
<label class="form-label" for="mapping-parent">Local parent</label><select id="mapping-parent" class="form-select mb-2" value="@(m.LocalParentKind + "|" + m.LocalParentId)" @onchange="args => SetParent(m, args.Value?.ToString())"><option value="">Choose a parent</option>@foreach (var p in Parents(m.Realm)) { <option value="@p.Value">@p.Label</option> }</select>
<label class="form-label" for="branch">Branch name</label><input id="branch" class="form-control mb-2" @bind="m.BranchName" />
<label class="form-label" for="remote-root">Remote root entity</label><select id="remote-root" class="form-select mb-2" @bind="m.RemoteRootEntityId"><option value="">Choose a root</option>@foreach (var p in RemoteRoots(m)) { <option value="@p.Id">@p.Label</option> }</select><div class="form-text">The picker uses the configured target cluster. For a separately managed cluster, enter its root ID below.</div><label class="form-label" for="remote-root-id">Remote root ID</label><input id="remote-root-id" class="form-control mb-2" @bind="m.RemoteRootEntityId" />
<label class="form-label" for="identifier-kind">Remote canonical identifier kind</label><input id="identifier-kind" class="form-control mb-2" @bind="m.RemoteIdentifierKind" />
<label class="form-label" for="identifier">Remote canonical identifier</label><input id="identifier" class="form-control mb-2" @bind="m.RemoteIdentifier" />
<fieldset><legend class="fs-6">Consumer nodes</legend>@foreach (var n in Nodes) { <label class="me-3"><input type="checkbox" checked="@m.ConsumerNodeIds.Contains(n.NodeId)" @onchange="e => Toggle(m.ConsumerNodeIds, n.NodeId, (bool)e.Value!)" /> @n.NodeId</label> }</fieldset>
@Operations(m.AllowedOperations, v => m.AllowedOperations = v)
<div><label><input type="checkbox" @bind="m.WriteThrough" /> Allow write-through</label></div><label><input type="checkbox" @bind="m.Enabled" /> Enabled in next deployment</label>@Actions(m, m.RemoteNamespaceMappingRowId != Guid.Empty)
</div></section>
}
</AuthorizeView>
}
</PageErrorBoundary>
@code {
[Parameter] public string ClusterId { get; set; } = "";
private DraftSnapshot? _snapshot;
private DataConnectionEditorModel? _connection;
private DataExport? _export;
private RemoteMappingEditorModel? _mapping;
private string? _error, _message;
private object? _deleteCandidate;
private IReadOnlyList<AppliedConnection> _applied = [];
private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = [];
private IReadOnlyList<ConnectionDisplayRow> ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId));
private IEnumerable<DataConnection> Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<DataExport> Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<RemoteNamespaceMapping> Mappings => _snapshot!.RemoteNamespaceMappings.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<ClusterNode> Nodes => _snapshot!.ClusterNodes.Where(x => Same(x.ClusterId, ClusterId) && x.Enabled);
protected override async Task OnInitializedAsync() => await Reload();
private async Task Reload()
{
_snapshot = await Service.LoadAsync(); _applied = await Service.LoadAppliedAsync(ClusterId);
var observations = await Task.WhenAll(Nodes.Select(async node =>
{
try { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)await Diagnostics.GetDiagnosticsAsync(NodeId.Parse($"{node.Host}:{node.AkkaPort}"), CancellationToken.None)); }
catch (Exception) { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)null); }
}));
_live = observations.Where(x => x.Snapshot?.DataConnections is not null)
.SelectMany(x => x.Snapshot!.DataConnections!.Select(row => (x.NodeId, row))).ToList();
}
private static string Measure<T>(T? value) where T : struct => value?.ToString() ?? "unavailable";
private static string Time(DateTime? value) => value?.ToString("u") ?? "unavailable";
private static bool Same(string? a, string? b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
private static T Clone<T>(T value) => System.Text.Json.JsonSerializer.Deserialize<T>(System.Text.Json.JsonSerializer.Serialize(value))!;
private void Clear() { _connection = null; _export = null; _mapping = null; _deleteCandidate = null; _error = null; _message = null; }
private void NewConnection() { Clear(); _connection = new(); _connection.Value.ClusterId = ClusterId; _connection.Value.SecretScopeClusterId = ClusterId; }
private void NewExport() { Clear(); _export = new() { ClusterId = ClusterId, Realm = DataRealm.Raw, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe }; }
private void NewMapping() { Clear(); _mapping = new(); _mapping.Value.ClusterId = ClusterId; SetRealm(_mapping.Value); }
private void Edit(DataConnection c) { Clear(); _connection = new() { Value = Clone(c) }; }
private void Edit(DataExport e) { Clear(); _export = Clone(e); }
private void Edit(RemoteNamespaceMapping m) { Clear(); _mapping = new() { Value = Clone(m) }; }
private static void Toggle(List<string> ids, string id, bool on) { if (on && !ids.Contains(id)) ids.Add(id); else if (!on) ids.Remove(id); }
private static void TargetChanged(DataConnection c) { if (c.TargetMode == DataTargetMode.Cluster) c.ExpectedNodeId = null; else c.EligibleTargetNodeIds.Clear(); }
private static void SetRealm(RemoteNamespaceMapping m) { m.RemoteRealm = m.Realm; m.RemoteNamespaceUri = m.Realm == DataRealm.Raw ? V3NodeIds.RawNamespaceUri : V3NodeIds.UnsNamespaceUri; }
private static void SetParent(RemoteNamespaceMapping m, string? value) { var p = (value ?? "").Split('|', 2); m.LocalParentKind = p[0]; m.LocalParentId = p.Length > 1 ? p[1] : ""; }
private static void SetExportRoot(DataExport e, string? value) { var p = (value ?? "").Split('|', 2); e.RootKind = p[0]; e.RootEntityId = p.Length > 1 ? p[1] : ""; }
private IEnumerable<(string Value, string Label)> Parents(DataRealm realm)
{
yield return ($"Cluster|{ClusterId}", "Cluster root");
if (realm == DataRealm.Raw)
{
foreach (var x in _snapshot!.RawFolders.Where(x => Same(x.ClusterId, ClusterId))) yield return ($"RawFolder|{x.RawFolderId}", $"Folder: {x.Name} ({x.RawFolderId})");
foreach (var x in _snapshot.DriverInstances.Where(x => Same(x.ClusterId, ClusterId))) yield return ($"RawDriver|{x.DriverInstanceId}", $"Driver: {x.Name} ({x.DriverInstanceId})");
var drivers = _snapshot.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).ToList();
foreach (var x in devices) yield return ($"RawDevice|{x.DeviceId}", $"Device: {x.Name} ({x.DeviceId})");
var ids = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.TagGroups.Where(x => ids.Contains(x.DeviceId))) yield return ($"RawTagGroup|{x.TagGroupId}", $"Tag group: {x.Name} ({x.TagGroupId})");
}
else if (realm == DataRealm.Uns)
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).ToList();
foreach (var x in areas) yield return ($"UnsArea|{x.UnsAreaId}", $"Area: {x.Name} ({x.UnsAreaId})");
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToList();
foreach (var x in lines) yield return ($"UnsLine|{x.UnsLineId}", $"Line: {x.Name} ({x.UnsLineId})");
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return ($"Equipment|{x.EquipmentId}", $"Equipment: {x.Name} ({x.EquipmentId})");
}
}
private IEnumerable<(string Value, string Label)> ExportRoots(DataRealm realm)
{
foreach (var parent in Parents(realm)) yield return parent;
if (realm == DataRealm.Raw)
{
var drivers = _snapshot!.DriverInstances.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => drivers.Contains(x.DriverInstanceId)).Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.Tags.Where(x => devices.Contains(x.DeviceId))) yield return ($"RawTag|{tag.TagId}", $"Tag: {tag.Name} ({tag.TagId})");
}
else if (realm == DataRealm.Uns)
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, ClusterId)).Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areas.Contains(x.UnsAreaId)).Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var equipment = _snapshot.Equipment.Where(x => lines.Contains(x.UnsLineId)).Select(x => x.EquipmentId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var tag in _snapshot.VirtualTags.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"VirtualTag|{tag.VirtualTagId}", $"Virtual tag: {tag.Name} ({tag.VirtualTagId})");
foreach (var tag in _snapshot.UnsTagReferences.Where(x => equipment.Contains(x.EquipmentId))) yield return ($"UnsTagReference|{tag.UnsTagReferenceId}", $"Tag reference: {tag.UnsTagReferenceId}");
}
}
private IEnumerable<(string Id, string Label)> RemoteRoots(RemoteNamespaceMapping mapping)
{
var target = Connections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId))?.ExpectedClusterId;
if (string.IsNullOrEmpty(target)) yield break;
yield return (target, "Cluster root: " + target);
if (mapping.Realm == DataRealm.Raw)
{
foreach (var x in _snapshot!.RawFolders.Where(x => Same(x.ClusterId, target))) yield return (x.RawFolderId, $"Folder: {x.Name} ({x.RawFolderId})");
var drivers = _snapshot.DriverInstances.Where(x => Same(x.ClusterId, target)).ToList();
foreach (var x in drivers) yield return (x.DriverInstanceId, $"Driver: {x.Name} ({x.DriverInstanceId})");
var driverIds = drivers.Select(x => x.DriverInstanceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var devices = _snapshot.Devices.Where(x => driverIds.Contains(x.DriverInstanceId)).ToList();
foreach (var x in devices) yield return (x.DeviceId, $"Device: {x.Name} ({x.DeviceId})");
var deviceIds = devices.Select(x => x.DeviceId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.TagGroups.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagGroupId, $"Tag group: {x.Name} ({x.TagGroupId})");
foreach (var x in _snapshot.Tags.Where(x => deviceIds.Contains(x.DeviceId))) yield return (x.TagId, $"Tag: {x.Name} ({x.TagId})");
}
else
{
var areas = _snapshot!.UnsAreas.Where(x => Same(x.ClusterId, target)).ToList();
foreach (var x in areas) yield return (x.UnsAreaId, $"Area: {x.Name} ({x.UnsAreaId})");
var areaIds = areas.Select(x => x.UnsAreaId).ToHashSet(StringComparer.OrdinalIgnoreCase);
var lines = _snapshot.UnsLines.Where(x => areaIds.Contains(x.UnsAreaId)).ToList();
foreach (var x in lines) yield return (x.UnsLineId, $"Line: {x.Name} ({x.UnsLineId})");
var lineIds = lines.Select(x => x.UnsLineId).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var x in _snapshot.Equipment.Where(x => lineIds.Contains(x.UnsLineId))) yield return (x.EquipmentId, $"Equipment: {x.Name} ({x.EquipmentId})");
}
}
private RenderFragment Operations(DataOperations current, Action<DataOperations> set) => builder =>
{
builder.OpenElement(0, "fieldset"); builder.OpenElement(1, "legend"); builder.AddAttribute(2, "class", "fs-6"); builder.AddContent(3, "Allowed operations"); builder.CloseElement();
foreach (var bit in new[] { DataOperations.Browse, DataOperations.Metadata, DataOperations.Read, DataOperations.Subscribe, DataOperations.Write })
{
builder.OpenElement(4, "label"); builder.AddAttribute(5, "class", "me-3"); builder.OpenElement(6, "input"); builder.AddAttribute(7, "type", "checkbox"); builder.AddAttribute(8, "checked", current.HasFlag(bit));
builder.AddAttribute(9, "onchange", EventCallback.Factory.Create<ChangeEventArgs>(this, args => set((bool)args.Value! ? current | bit : current & ~bit))); builder.CloseElement(); builder.AddContent(10, " " + bit); builder.CloseElement();
}
builder.CloseElement();
};
private RenderFragment Actions(object row, bool existing) => builder =>
{
builder.OpenElement(0, "div"); builder.AddAttribute(1, "class", "d-flex gap-2 mt-3");
builder.OpenElement(2, "button"); builder.AddAttribute(3, "class", "btn btn-primary"); builder.AddAttribute(4, "onclick", EventCallback.Factory.Create(this, () => Save(row))); builder.AddContent(5, "Save draft"); builder.CloseElement();
builder.OpenElement(6, "button"); builder.AddAttribute(7, "class", "btn btn-outline-secondary"); builder.AddAttribute(8, "onclick", EventCallback.Factory.Create(this, Clear)); builder.AddContent(9, "Cancel"); builder.CloseElement();
if (existing) { builder.OpenElement(10, "button"); builder.AddAttribute(11, "class", "btn btn-outline-danger"); builder.AddAttribute(12, "onclick", EventCallback.Factory.Create(this, () => _deleteCandidate = row)); builder.AddContent(13, "Delete draft"); builder.CloseElement(); }
builder.CloseElement();
};
private async Task Save(object row) { try { await Service.SaveAsync(ClusterId, row); Clear(); await Reload(); _message = "Draft saved. Deploy to apply it."; } catch (Exception ex) { _error = ex is UnauthorizedAccessException or InvalidOperationException ? ex.Message : "Could not save the draft. It may have changed; reload and try again."; } }
private async Task Delete(object? row) { try { if (row is null) return; await Service.DeleteAsync(ClusterId, row); Clear(); await Reload(); _message = "Draft deleted. Deploy to apply the change."; } catch (Exception ex) { _error = ex is UnauthorizedAccessException or InvalidOperationException ? ex.Message : "Could not delete the draft. Reload and try again."; } }
}
@@ -10,6 +10,7 @@
<ul class="nav nav-tabs mb-3">
<li class="nav-item"><a class="nav-link @Active("overview")" aria-current='@(ActiveTab == "overview" ? "page" : null)' href="/clusters/@ClusterId">Overview</a></li>
<li class="nav-item"><a class="nav-link @Active("data")" aria-current='@(ActiveTab == "data" ? "page" : null)' href="/clusters/@ClusterId/data-connections">Data connections</a></li>
<li class="nav-item"><a class="nav-link @Active("acls")" aria-current='@(ActiveTab == "acls" ? "page" : null)' href="/clusters/@ClusterId/acls">ACLs</a></li>
<li class="nav-item"><a class="nav-link @Active("audit")" aria-current='@(ActiveTab == "audit" ? "page" : null)' href="/clusters/@ClusterId/audit">Audit</a></li>
<li class="nav-item"><a class="nav-link @Active("redundancy")" aria-current='@(ActiveTab == "redundancy" ? "page" : null)' href="/clusters/@ClusterId/redundancy">Redundancy</a></li>
@@ -0,0 +1,160 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Authorizes and validates data-connection draft mutations. Deployment remains a separate operation.</summary>
public sealed class DataConnectionAdminService(IDbContextFactory<OtOpcUaConfigDbContext> factory,
IAuthorizationService authorization, AuthenticationStateProvider authentication)
{
public async Task<DraftSnapshot> LoadAsync(CancellationToken ct = default)
{
await using var db = await factory.CreateDbContextAsync(ct);
return await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
}
/// <summary>Returns the last successfully applied artifact's connection revision per node, when available.</summary>
public async Task<IReadOnlyList<AppliedConnection>> LoadAppliedAsync(string clusterId, CancellationToken ct = default)
{
await using var db = await factory.CreateDbContextAsync(ct);
var nodes = await db.ClusterNodes.AsNoTracking().Where(n => n.ClusterId == clusterId).Select(n => n.NodeId).ToListAsync(ct);
var result = new List<AppliedConnection>();
foreach (var node in nodes)
{
var deployment = await db.NodeDeploymentStates.AsNoTracking().Where(s => s.NodeId == node && s.Status == NodeDeploymentStatus.Applied)
.OrderByDescending(s => s.StartedAtUtc).Select(s => (Guid?)s.DeploymentId).FirstOrDefaultAsync(ct);
if (deployment is null) continue;
var blob = await db.Deployments.AsNoTracking().Where(d => d.DeploymentId == deployment).Select(d => d.ArtifactBlob).FirstOrDefaultAsync(ct);
if (blob is not { Length: > 0 }) continue;
try
{
result.AddRange(DeploymentArtifact.ParseDataConnections(blob, node)
.Select(c => new AppliedConnection(node, c.DataConnectionId, c.Revision, c.Enabled)));
}
catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or System.Text.Json.JsonException)
{
// An unreadable artifact is unknown, not evidence of an empty deployment.
}
}
return result;
}
public async Task SaveAsync(string clusterId, object row, CancellationToken ct = default)
{
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
switch (row)
{
case DataConnection c:
CheckIdentity(clusterId, c.ClusterId, c.DataConnectionId);
await SaveRow(db, snapshot.DataConnections, c, x => x.DataConnectionRowId, x => x.DataConnectionId, ct);
break;
case DataExport e:
CheckIdentity(clusterId, e.ClusterId, e.DataExportId);
await SaveRow(db, snapshot.DataExports, e, x => x.DataExportRowId, x => x.DataExportId, ct);
break;
case RemoteNamespaceMapping m:
CheckIdentity(clusterId, m.ClusterId, m.RemoteNamespaceMappingId);
await SaveRow(db, snapshot.RemoteNamespaceMappings, m, x => x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct);
break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
await db.SaveChangesAsync(ct);
}
public async Task DeleteAsync(string clusterId, object row, CancellationToken ct = default)
{
await RequireEditorAsync();
await using var db = await factory.CreateDbContextAsync(ct);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, ct);
switch (row)
{
case DataConnection c:
CheckIdentity(clusterId, c.ClusterId, c.DataConnectionId);
await DeleteRow(db, snapshot.DataConnections, c, x => x.DataConnectionRowId, x => x.DataConnectionId, ct); break;
case DataExport e:
CheckIdentity(clusterId, e.ClusterId, e.DataExportId);
await DeleteRow(db, snapshot.DataExports, e, x => x.DataExportRowId, x => x.DataExportId, ct); break;
case RemoteNamespaceMapping m:
CheckIdentity(clusterId, m.ClusterId, m.RemoteNamespaceMappingId);
await DeleteRow(db, snapshot.RemoteNamespaceMappings, m, x => x.RemoteNamespaceMappingRowId, x => x.RemoteNamespaceMappingId, ct); break;
default: throw new ArgumentException("Unsupported draft row.", nameof(row));
}
var errors = DataConnectionValidator.Validate(snapshot);
if (errors.Count != 0) throw new InvalidOperationException(string.Join(" ", errors.Select(e => e.Message)));
await db.SaveChangesAsync(ct);
}
private async Task RequireEditorAsync()
{
var user = (await authentication.GetAuthenticationStateAsync()).User;
if (!(await authorization.AuthorizeAsync(user, AdminUiPolicies.ConfigEditor)).Succeeded)
throw new UnauthorizedAccessException("Configuration editor access is required.");
}
private static void CheckIdentity(string cluster, string owner, string id)
{
if (string.IsNullOrWhiteSpace(id) || !string.Equals(cluster, owner, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("A row ID and matching cluster are required.");
}
private static async Task SaveRow<T>(OtOpcUaConfigDbContext db, IReadOnlyList<T> rows, T row,
Func<T, Guid> key, Func<T, string> id, CancellationToken ct) where T : class
{
var list = (List<T>)rows;
var existing = list.FirstOrDefault(x => key(x) == key(row) && key(row) != Guid.Empty);
if (existing is null)
{
if (key(row) != Guid.Empty || list.Any(x => string.Equals(id(x), id(row), StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("The row no longer exists or its ID is already in use.");
db.Set<T>().Add(row); list.Add(row);
}
else
{
if (!string.Equals(id(existing), id(row), StringComparison.OrdinalIgnoreCase) ||
!string.Equals(Owner(existing), Owner(row), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("The row ID cannot be changed.");
if (Revision(existing) != Revision(row)) throw new DbUpdateConcurrencyException("This draft has changed. Reload it before saving.");
var tracked = await db.Set<T>().FindAsync([key(row)], ct) ?? throw new InvalidOperationException("The row no longer exists.");
db.Entry(tracked).CurrentValues.SetValues(row);
db.Entry(tracked).Property("RowVersion").OriginalValue = db.Entry(row).Property("RowVersion").CurrentValue;
var revision = db.Entry(tracked).Property<long>("Revision");
revision.CurrentValue = checked(revision.OriginalValue + 1);
list[list.IndexOf(existing)] = tracked;
}
}
private static string Owner<T>(T row) => row switch
{
DataConnection c => c.ClusterId, DataExport e => e.ClusterId, RemoteNamespaceMapping m => m.ClusterId,
_ => throw new ArgumentException("Unsupported draft row.")
};
private static long Revision<T>(T row) => row switch
{
DataConnection c => c.Revision, DataExport e => e.Revision, RemoteNamespaceMapping m => m.Revision,
_ => throw new ArgumentException("Unsupported draft row.")
};
private static async Task DeleteRow<T>(OtOpcUaConfigDbContext db, IReadOnlyList<T> rows, T row,
Func<T, Guid> getKey, Func<T, string> getId, CancellationToken ct) where T : class
{
var list = (List<T>)rows;
var key = getKey(row);
var existing = list.FirstOrDefault(x => getKey(x) == key && string.Equals(Owner(x), Owner(row), StringComparison.OrdinalIgnoreCase)) ?? throw new InvalidOperationException("The row no longer exists.");
if (!string.Equals(getId(existing), getId(row), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("The row ID cannot be changed.");
if (Revision(existing) != Revision(row)) throw new DbUpdateConcurrencyException("This draft has changed. Reload it before deleting.");
var tracked = await db.Set<T>().FindAsync([key], ct) ?? throw new InvalidOperationException("The row no longer exists.");
db.Entry(tracked).Property("RowVersion").OriginalValue = db.Entry(row).Property("RowVersion").CurrentValue;
db.Remove(tracked); list.Remove(existing);
}
}
/// <summary>Connection configuration in a node’s last successfully applied artifact.</summary>
public sealed record AppliedConnection(string NodeId, string ConnectionId, long Revision, bool Enabled);
@@ -0,0 +1,31 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Display helpers that never equate an authored draft with a running connection.</summary>
public static class DataConnectionDiagnostics
{
/// <summary>Includes evidence for connections removed from the draft until it is no longer reported.</summary>
public static IReadOnlyList<ConnectionDisplayRow> Rows(
IEnumerable<DataConnection> drafts, IEnumerable<string> appliedIds, IEnumerable<string> observedIds)
{
var result = new Dictionary<string, ConnectionDisplayRow>(StringComparer.OrdinalIgnoreCase);
foreach (var draft in drafts) result[draft.DataConnectionId] = new(draft.DataConnectionId, draft);
foreach (var id in appliedIds.Concat(observedIds))
if (!string.IsNullOrWhiteSpace(id) && !result.ContainsKey(id)) result.Add(id, new(id, null));
return result.Values.OrderBy(x => x.Id, StringComparer.OrdinalIgnoreCase).ToArray();
}
/// <summary>Uses the reporting node's measured duration, independent of the admin clock.</summary>
public static string SampleAge(ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row) =>
row.SampleAgeUpperBound is { } age ? $"{age.TotalSeconds:F0}s at observation" : "unavailable";
public static string State(string? state) => state?.ToLowerInvariant() switch
{
"disabled" => "Disabled", "connecting" => "Connecting", "ready" => "Ready", "degraded" => "Degraded",
"auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable"
};
public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& uri.Scheme == Uri.UriSchemeHttps ? (uri.HostNameType == UriHostNameType.IPv6 ? $"https://[{uri.Host}]{(uri.IsDefaultPort ? "" : $":{uri.Port}")}" : $"https://{uri.IdnHost}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}") : "Unavailable";
}
/// <summary>A connection identity and its optional current draft.</summary>
public sealed record ConnectionDisplayRow(string Id, DataConnection? Draft);
@@ -0,0 +1,13 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Safe defaults and list editing helpers for a directional connection.</summary>
public sealed class DataConnectionEditorModel
{
public DataConnection Value { get; set; } = new() { TargetMode = DataTargetMode.Node, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe };
public string Endpoints { get => string.Join("\n", Value.Endpoints); set => Value.Endpoints = Lines(value); }
public string EligibleNodes { get => string.Join("\n", Value.EligibleTargetNodeIds); set => Value.EligibleTargetNodeIds = Lines(value); }
public static List<string> Lines(string? value) => (value ?? "").Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
@@ -0,0 +1,10 @@
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
/// <summary>Creates disabled mapping drafts with read-only operation defaults.</summary>
public sealed class RemoteMappingEditorModel
{
public RemoteNamespaceMapping Value { get; set; } = new() { Realm = DataRealm.Raw, RemoteRealm = DataRealm.Raw, AllowedOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe };
}
@@ -87,6 +87,7 @@ public static class EndpointRouteBuilderExtensions
// mirror the deploy gate's NodeAclScope* rules. Scoped, because it composes the two scoped tree
// services above.
services.AddScoped<Acls.IAclScopeService, Acls.AclScopeService>();
services.AddScoped<DataConnections.DataConnectionAdminService>();
// lmxopcua#749: per-API-key Galaxy alarm-ack identity, held in the Secrets store (never the DB).
services.AddScoped<ApiKeyAck.IApiKeyGalaxyAckIdentityService>(sp => new ApiKeyAck.ApiKeyGalaxyAckIdentityService(
sp.GetRequiredService<ZB.MOM.WW.Secrets.Abstractions.ISecretStore>(),
@@ -51,6 +51,14 @@ public sealed class ActorProjectedValuePublisher : IProjectedValuePublisher, IDi
}
public long PendingBytes { get { lock (_sync) return _pendingBytes; } }
public long RetainedControlBytes { get { lock (_sync) return _controlBytes; } }
/// <summary>Counts retained import routes by configured connection, without exposing node or secret labels.</summary>
public IReadOnlyDictionary<string, int> CaptureSourceCounts()
{
lock (_sync)
return _bindings.Values.Where(x => x.Route.DriverInstanceId.StartsWith("grpc-data:", StringComparison.Ordinal))
.GroupBy(x => x.Route.DriverInstanceId[10..], StringComparer.OrdinalIgnoreCase)
.ToDictionary(x => x.Key, x => x.Count(), StringComparer.OrdinalIgnoreCase);
}
private static (DataRealm, string) Key(ProjectedValueRoute route) => (route.Realm, route.LocalIdentifier);
private bool Authorized(ProjectedValueRoute route)
{
@@ -72,6 +72,24 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
/// <summary>Configured redundancy mode from the current validated artifact.</summary>
public RedundancyMode CurrentConsumerMode { get { lock (_sync) return _desired?.ConsumerMode ?? RedundancyMode.None; } }
/// <summary>Captures only this node's applied scope and current transport evidence.</summary>
public IReadOnlyList<ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot> CaptureDiagnostics(IReadOnlyDictionary<string, int>? retainedSourceCounts = null)
{
lock (_sync)
{
if (_disposed || _desired is not { } desired) return [];
return desired.Specs.Values.Select(spec =>
{
if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready)
return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with
{ SourceCount = retainedSourceCounts is null ? null : retainedSourceCounts.TryGetValue(spec.Id, out var count) ? count : 0 };
return new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot(spec.Id, spec.Revision,
_attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting",
null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime);
}).ToArray();
}
}
/// <summary>Withdraws current routes before parsing or staging a different artifact.</summary>
public void BeginAttempt(string artifactRevision)
{
@@ -0,0 +1,78 @@
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using Grpc.Core;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public sealed partial class GrpcDataConnection
{
private string? _diagnosticEndpoint;
private ServingIdentity? _diagnosticServing;
private int? _diagnosticMajor, _diagnosticMinor;
private string _diagnosticState = "connecting";
private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc;
private TimeSpan? _sampleAgeUpper;
private long _sampleReceivedTimestamp;
private long _resetCount, _coalescedCount, _writeSucceededCount, _writeRejectedCount, _writeUnknownCount, _writeFailedCount, _writeUnconfirmedCount;
internal DataConnectionDiagnosticsSnapshot CaptureDiagnostics(long revision, long scopeVersion, string artifactRevision)
{
lock (_sync)
return new(_id, revision, _disposed || _scope.CancellationToken.IsCancellationRequested ? "disabled" :
_nextProbeTimestamp > Clock.GetTimestamp() && _diagnosticState != "auth-failed" ? "backoff" : _diagnosticState,
_diagnosticEndpoint, _diagnosticServing, _activeStreams, _activeWork, scopeVersion, artifactRevision,
Clock.GetUtcNow().UtcDateTime, _lastSampleAtUtc, _metadataLeaseExpiresAtUtc,
RegistrationCount: _streams.Sum(x => Volatile.Read(ref x.DiagnosticRegistrationCount)),
ResetCount: Interlocked.Read(ref _resetCount),
WriteSucceededCount: Interlocked.Read(ref _writeSucceededCount), WriteRejectedCount: Interlocked.Read(ref _writeRejectedCount),
WriteUnknownCount: Interlocked.Read(ref _writeUnknownCount), ProtocolMajor: _diagnosticMajor, ProtocolMinor: _diagnosticMinor, LastVerifiedAtUtc: _lastVerifiedAtUtc,
WriteFailedCount: Interlocked.Read(ref _writeFailedCount), WriteUnconfirmedCount: Interlocked.Read(ref _writeUnconfirmedCount),
SampleAgeUpperBound: ObservedUpperAge(),
CoalescedCount: Interlocked.Read(ref _coalescedCount));
}
private TimeSpan? ObservedUpperAge()
{
if (_sampleAgeUpper is not { } upper) return null;
var elapsed = Clock.GetElapsedTime(_sampleReceivedTimestamp);
if (upper < TimeSpan.Zero || elapsed < TimeSpan.Zero) return null;
return TimeSpan.FromTicks(upper.Ticks > long.MaxValue - elapsed.Ticks ? long.MaxValue : upper.Ticks + elapsed.Ticks);
}
private void RecordSelected(Uri endpoint, DataCapabilities capabilities)
{
lock (_sync)
{
_diagnosticEndpoint = new UriBuilder(endpoint.Scheme, endpoint.Host, endpoint.Port).Uri.GetLeftPart(UriPartial.Authority);
_diagnosticServing = capabilities.Serving; _lastVerifiedAtUtc = Clock.GetUtcNow().UtcDateTime;
_diagnosticMajor = capabilities.ProtocolMajor; _diagnosticMinor = capabilities.ProtocolMinor;
_diagnosticState = capabilities.Readiness == DataReadiness.Ready ? "ready" : "degraded";
}
}
private void RecordSampleAge(DataAgeBounds age)
{
lock (_sync)
{
_sampleAgeUpper = age.Upper; _sampleReceivedTimestamp = Clock.GetTimestamp();
_lastSampleAtUtc = age.Upper is { } upper && upper >= TimeSpan.Zero && upper.Ticks <= Clock.GetUtcNow().UtcDateTime.Ticks
? Clock.GetUtcNow().UtcDateTime - upper : null;
}
}
private void RecordFailure(Exception failure)
{
lock (_sync) _diagnosticState = failure is UnauthorizedAccessException or RpcException { StatusCode: StatusCode.Unauthenticated or StatusCode.PermissionDenied }
? "auth-failed" : "degraded";
}
private void RecordWrites(IReadOnlyList<WriteItemResult> results)
{
foreach (var item in results)
switch (item.Outcome.State)
{
case DataWriteState.DriverConfirmedSuccess: Interlocked.Increment(ref _writeSucceededCount); break;
case DataWriteState.DriverConfirmedFailure: Interlocked.Increment(ref _writeFailedCount); break;
case DataWriteState.RejectedBeforeDispatch: Interlocked.Increment(ref _writeRejectedCount); break;
case DataWriteState.AcceptedUnconfirmed: Interlocked.Increment(ref _writeUnconfirmedCount); break;
case DataWriteState.OutcomeUnknown: Interlocked.Increment(ref _writeUnknownCount); break;
}
}
}
@@ -23,7 +23,7 @@ public interface IDataConnectionSecurityProvider
public sealed record DataConnectionChannelIdentity(string ConnectionId, Uri Endpoint, string CredentialVersion, string TrustFingerprint);
/// <summary>Caller-bound remote facade. All channels and requests are bounded by configured local limits.</summary>
public sealed class GrpcDataConnection : IDataConnection
public sealed partial class GrpcDataConnection : IDataConnection
{
private sealed class ChannelEntry(DataConnectionChannelIdentity identity, GrpcChannel channel, string bearer)
{
@@ -141,6 +141,8 @@ public sealed class GrpcDataConnection : IDataConnection
lock (_sync)
{
_securityGeneration++;
_diagnosticState = "connecting"; _diagnosticEndpoint = null; _diagnosticServing = null;
_lastSampleAtUtc = null; _metadataLeaseExpiresAtUtc = null; _lastVerifiedAtUtc = null; _sampleAgeUpper = null;
foreach (var item in _channels.Values)
{
_retiringChannels++;
@@ -232,6 +234,7 @@ public sealed class GrpcDataConnection : IDataConnection
Target.Mode == DataTargetMode.Cluster && !_eligibleNodeIds!.Contains(caps.Serving.NodeId))
throw new InvalidOperationException("Endpoint is not an authenticated ready target.");
linked.Token.ThrowIfCancellationRequested();
RecordSelected(endpoint, caps);
return new(channel, caps);
}
private static void Verify(W.Serving? serving, Selected selected)
@@ -265,7 +268,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch { if (result is IEnumerable<ReadResult> reads) foreach (var item in reads) item.Dispose(); throw; }
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready authenticated data endpoint.", failure);
@@ -282,6 +285,7 @@ public sealed class GrpcDataConnection : IDataConnection
public Task<DataBrowseBranch> BrowseAsync(BrowseRequest request, CancellationToken cancellationToken) =>
QueryAsync(request.Budget, async (selected, budget, options) =>
{
var browseStarted = Clock.GetTimestamp();
var wire = await selected.Channel.Client.BrowseAsync(DataProtoMapper.EncodeBrowseRequest(request with { Budget = budget }), options).ResponseAsync.ConfigureAwait(false);
Verify(wire.Serving, selected); var result = DataProtoMapper.DecodeBrowseResponse(wire, Limits(budget, selected.Capabilities));
if (result.Lease is { } lease && (lease.CatalogEpoch != selected.Capabilities.Serving.CatalogEpoch ||
@@ -290,6 +294,8 @@ public sealed class GrpcDataConnection : IDataConnection
if (result.Parent != request.Parent || result.Items.Any(x => x.CatalogRevision != selected.Capabilities.Serving.CatalogEpoch || !string.Equals(x.View.Address.OriginClusterId, selected.Capabilities.ClusterId, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("Browse response has unexpected provenance.");
Verify(wire.Serving, selected);
lock (_sync) _metadataLeaseExpiresAtUtc = result.Lease is { } observed
? Clock.GetUtcNow().UtcDateTime + TimeSpan.FromTicks(Math.Max(0, (observed.Duration - Clock.GetElapsedTime(browseStarted)).Ticks)) : null;
var serving = DataProtoMapper.DecodeServing(wire.Serving);
return result with { Serving = serving, Items = result.Items.Select(x => ExposeMetadata(x, serving, selected.Capabilities)).ToArray() };
}, cancellationToken);
@@ -318,7 +324,9 @@ public sealed class GrpcDataConnection : IDataConnection
if (result.Count != request.Items.Count || !result.Select(x => x.CorrelationId).SequenceEqual(request.Items.Select(x => x.CorrelationId)) ||
result.Any(x => x.Sample is not null && x.Sample.Serving != selected.Capabilities.Serving))
throw new InvalidOperationException("Read response has unexpected items or serving identity.");
Verify(wire.Serving, selected); return result;
Verify(wire.Serving, selected);
if (result.LastOrDefault(x => x.Sample is not null) is { } observed) RecordSampleAge(observed.AgeBounds);
return result;
}
catch { foreach (var item in result) item.Dispose(); throw; }
}, cancellationToken);
@@ -333,13 +341,18 @@ public sealed class GrpcDataConnection : IDataConnection
{
using var admission = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _scope.CancellationToken, _shutdown.Token);
admitted = await _unaryCapacity.WaitAsync(0, admission.Token).ConfigureAwait(false);
if (!admitted) return request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
if (!admitted)
{
var rejected = request.Items.Select(x => new WriteItemResult(x.CorrelationId,
new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, "Unary capacity exhausted."))).ToArray();
RecordWrites(rejected); return rejected;
}
var elapsed = Clock.GetElapsedTime(admissionStart);
var remaining = Remaining(admissionStart, request.Budget);
var reduced = request with { Budget = request.Budget with { Timeout = remaining },
Items = request.Items.Select(x => x with { RemainingBudget = x.RemainingBudget - elapsed }).ToArray() };
return await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
var outcomes = await WriteCoreAsync(reduced, cancellationToken).ConfigureAwait(false);
RecordWrites(outcomes); return outcomes;
}
finally { if (admitted) _unaryCapacity.Release(); ExitWork(); }
}
@@ -500,7 +513,7 @@ public sealed class GrpcDataConnection : IDataConnection
try
{
var call = selected.Channel.Client.Subscribe(Headers(selected.Channel), cancellationToken: lifetime.Token);
subscription = new RemoteSubscription(call, selected, lifetime, _maxMessageBytes,
subscription = new RemoteSubscription(this, call, selected, lifetime, _maxMessageBytes,
Math.Min(_maxMonitoredItems, selected.Capabilities.Limits.MaxMonitoredItems), _maxPendingCommands,
_maxCommandTimeout, _commandBudget, ClaimStreamEpoch, PendingIdentityObserverForTests, AfterTimerCancelledForTests, () => { lock (_sync) { _streams.Remove(subscription!); Interlocked.Decrement(ref _activeStreams); CheckDrainedLocked(); } });
if (BeforeStreamInstallForTests is { } pause) await pause().ConfigureAwait(false);
@@ -529,7 +542,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
catch (Exception ex) when (ex is RpcException or InvalidOperationException or UnauthorizedAccessException or HttpRequestException)
{ failure = ex; }
{ failure = ex; RecordFailure(ex); }
}
ProbeFailed();
throw new InvalidOperationException("No ready subscription endpoint.", failure);
@@ -541,7 +554,7 @@ public sealed class GrpcDataConnection : IDataConnection
}
}
private sealed class RemoteSubscription(
private sealed class RemoteSubscription(GrpcDataConnection owner,
AsyncDuplexStreamingCall<W.SubscriptionCommand, W.SubscriptionFrame> call, Selected selected,
CancellationTokenSource lifetime, int maxBytes, int maxItems, int maxPendingCommands,
TimeSpan maxCommandTimeout, CommandStateBudget commandBudget, Func<string, long, bool> claimEpoch, Action<WeakReference>? observePending,
@@ -667,6 +680,7 @@ public sealed class GrpcDataConnection : IDataConnection
catch (OperationCanceledException) { if (afterTimerCancelled is not null) await afterTimerCancelled().ConfigureAwait(false); }
catch (ObjectDisposedException) { }
}
internal int DiagnosticRegistrationCount;
public async IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
if (Interlocked.Exchange(ref _reading, 1) != 0) throw new InvalidOperationException("A stream has one reader.");
@@ -748,6 +762,7 @@ public sealed class GrpcDataConnection : IDataConnection
_pendingBytes -= pending.Bytes; commandBudget.Release(pending.Bytes);
pending.Timer.Cancel(); pending.Timer.Dispose();
_handles = next; _clientHandles = nextClients; _usedHandles = nextUsed; _versions = nextVersions;
Volatile.Write(ref DiagnosticRegistrationCount, next.Count);
}
}
if (frame is DataSubscriptionValues values)
@@ -765,6 +780,9 @@ public sealed class GrpcDataConnection : IDataConnection
_sequence = wire.Sequence;
}
catch { if (frame is IDisposable owned) owned.Dispose(); throw; }
if (frame is DataSubscriptionValues { Items.Count: > 0 } observedValues) owner.RecordSampleAge(observedValues.Items[^1].AgeBounds);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset }) Interlocked.Increment(ref owner._resetCount);
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Coalesced }) Interlocked.Increment(ref owner._coalescedCount);
yield return frame;
if (frame is DataSubscriptionControl { Kind: DataStreamControlKind.Reset })
{ await lifetime.CancelAsync().ConfigureAwait(false); yield break; }
@@ -2980,7 +2980,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
CurrentRevision: _currentRevision,
Drivers: drivers,
AsOfUtc: DateTime.UtcNow,
RunningFromCache: _isRunningFromCache);
RunningFromCache: _isRunningFromCache,
DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts()));
Sender.Tell(snapshot);
}