Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browser/GalaxyBrowseSession.cs
T
Joseph Doherty 560b327ee1
v2-ci / build (push) Failing after 33s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
refactor(galaxy): migrate to ZB.MOM.WW.MxGateway.* nupkg packages
Imports the freshly-rebuilt ZB.MOM.WW.MxGateway.Client + ZB.MOM.WW.MxGateway.Contracts
nupkgs (0.1.0) from /tmp/mxgw-dist. Replaces the vendored libs/ DLLs and the
pre-restructure MxGateway.* namespaces across the runtime Galaxy driver,
Galaxy.Browser, and their tests.

Key changes:
- nuget-packages/ added as a local feed via NuGet.config; .gitignore exempts it
  from the *.nupkg rule so the packages are tracked
- Directory.Packages.props pins both packages at 0.1.0
- 4 csprojs swap <Reference HintPath="libs/...dll"/> for <PackageReference/>
- 36 .cs files renamed `using MxGateway.*` -> `using ZB.MOM.WW.MxGateway.*`
- libs/ removed (vendored DLLs + README.md)

GalaxyBrowseSession rewritten around the new lazy API:
- RootAsync calls GalaxyRepositoryClient.BrowseAsync (returns LazyBrowseNodes)
  and caches them by TagName instead of bulk-fetching the whole hierarchy
- ExpandAsync looks up the cached LazyBrowseNode and calls its ExpandAsync,
  giving true one-wire-call-per-click instead of in-memory parent/child scan
- _byGobjectId + _hasChildrenSet dropped (LazyBrowseNode carries HasChildrenHint)
- AttributesAsync unchanged (already uses DiscoverHierarchyAsync MaxDepth=0)

Tests: Galaxy.Tests 245/245, Galaxy.Browser.Tests 10/10, AdminUI.Tests 66/66.
Pre-existing 12 solution errors unchanged (test sinks + Cli XML comments).
2026-05-29 07:14:18 -04:00

180 lines
7.3 KiB
C#

using System.Collections.Concurrent;
using ZB.MOM.WW.MxGateway.Client;
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browser;
/// <summary>
/// Lazy Galaxy browse over <see cref="GalaxyRepositoryClient.BrowseAsync"/>.
/// <see cref="RootAsync"/> returns the top-level <see cref="LazyBrowseNode"/>s
/// directly from the gateway; <see cref="ExpandAsync"/> fetches the direct children
/// of a previously-handed-out node via <see cref="LazyBrowseNode.ExpandAsync"/>
/// (one wire call per click, paginated internally by the client). Attribute fetches
/// are per-object via <c>DiscoverHierarchyAsync(MaxDepth=0, IncludeAttributes=true)</c>.
/// Owns the supplied <see cref="GalaxyRepositoryClient"/> and disposes it best-effort.
/// </summary>
internal sealed class GalaxyBrowseSession : IBrowseSession
{
private readonly GalaxyRepositoryClient _client;
private readonly ConcurrentDictionary<string, LazyBrowseNode> _byTagName = new(StringComparer.Ordinal);
private readonly SemaphoreSlim _rootGate = new(1, 1);
private volatile bool _disposed;
private IReadOnlyList<LazyBrowseNode>? _roots;
/// <summary>Opaque token identifying this session in the AdminUI registry.</summary>
public Guid Token { get; } = Guid.NewGuid();
/// <summary>Wall-clock time of the most recent successful Root/Expand/Attributes call.</summary>
public DateTime LastUsedUtc { get; private set; } = DateTime.UtcNow;
/// <summary>
/// Initializes a new session wrapping a connected repository client. The factory
/// in <c>GalaxyDriverBrowser</c> constructs the client via
/// <see cref="GalaxyRepositoryClient.Create"/> and hands it off here for the
/// session's lifetime.
/// </summary>
/// <param name="client">Galaxy repository client to query for browse and attributes.</param>
internal GalaxyBrowseSession(GalaxyRepositoryClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}
/// <summary>
/// Fetches the top-level <see cref="LazyBrowseNode"/>s from the gateway and
/// returns them as <see cref="BrowseNode"/>s. Result is cached; a second call
/// returns the cached roots without a re-fetch.
/// </summary>
public async Task<IReadOnlyList<BrowseNode>> RootAsync(CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
await _rootGate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
_roots ??= await _client.BrowseAsync(new BrowseChildrenOptions(), cancellationToken)
.ConfigureAwait(false);
LastUsedUtc = DateTime.UtcNow;
return Project(_roots);
}
finally
{
_rootGate.Release();
}
}
/// <summary>
/// Fetches the direct children of the cached node identified by
/// <paramref name="nodeId"/> (the object's <c>TagName</c>) via
/// <see cref="LazyBrowseNode.ExpandAsync"/>. Throws <see cref="ArgumentException"/>
/// if the tag hasn't been handed out by a prior Root/Expand call.
/// </summary>
public async Task<IReadOnlyList<BrowseNode>> ExpandAsync(string nodeId, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (!_byTagName.TryGetValue(nodeId, out var node))
{
throw new ArgumentException(
$"Galaxy object '{nodeId}' is not in the current browse-session cache. " +
"Re-open the browser or expand its parent first.", nameof(nodeId));
}
await node.ExpandAsync(cancellationToken).ConfigureAwait(false);
LastUsedUtc = DateTime.UtcNow;
return Project(node.Children);
}
/// <summary>
/// Fetches the attributes of the Galaxy object identified by <paramref name="nodeId"/>
/// via <c>DiscoverHierarchyAsync(MaxDepth=0, RootTagName=nodeId, IncludeAttributes=true)</c>.
/// Returns an empty list if the gateway has no matching object.
/// </summary>
public async Task<IReadOnlyList<AttributeInfo>> AttributesAsync(string nodeId, CancellationToken cancellationToken)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var rows = await _client.DiscoverHierarchyAsync(
new DiscoverHierarchyOptions
{
RootTagName = nodeId,
MaxDepth = 0,
IncludeAttributes = true,
}, cancellationToken).ConfigureAwait(false);
LastUsedUtc = DateTime.UtcNow;
var obj = rows.FirstOrDefault();
if (obj is null) return Array.Empty<AttributeInfo>();
var result = new List<AttributeInfo>(obj.Attributes.Count);
foreach (var attr in obj.Attributes)
{
var driverType = !string.IsNullOrEmpty(attr.DataTypeName)
? attr.DataTypeName
: attr.MxDataType.ToString(System.Globalization.CultureInfo.InvariantCulture);
result.Add(new AttributeInfo(
Name: attr.AttributeName,
DriverDataType: driverType,
IsArray: attr.IsArray,
SecurityClass: MapSecurityClass(attr.SecurityClassification)));
}
return result;
}
/// <summary>
/// Projects <see cref="LazyBrowseNode"/>s to <see cref="BrowseNode"/>s, caching
/// each by <c>TagName</c> so a subsequent <see cref="ExpandAsync"/> can locate
/// it. Galaxy nodes are always <see cref="BrowseNodeKind.Folder"/> — leaves only
/// appear in the attribute side-panel.
/// </summary>
private IReadOnlyList<BrowseNode> Project(IReadOnlyList<LazyBrowseNode> nodes)
{
var result = new List<BrowseNode>(nodes.Count);
foreach (var n in nodes)
{
_byTagName[n.Object.TagName] = n;
var displayName = !string.IsNullOrEmpty(n.Object.ContainedName)
? n.Object.ContainedName
: n.Object.TagName;
result.Add(new BrowseNode(
NodeId: n.Object.TagName,
DisplayName: displayName,
Kind: BrowseNodeKind.Folder,
HasChildrenHint: n.HasChildrenHint));
}
return result;
}
/// <summary>
/// Maps the Galaxy raw security-classification integer to a display string.
/// Buckets: 0=FreeAccess, 1=Operate, 2=Tune, 3=Configure, 4=ViewOnly;
/// anything else surfaces as <c>Unknown(N)</c>.
/// </summary>
private static string MapSecurityClass(int raw) => raw switch
{
0 => "FreeAccess",
1 => "Operate",
2 => "Tune",
3 => "Configure",
4 => "ViewOnly",
_ => $"Unknown({raw})",
};
/// <summary>
/// Idempotently tears down the underlying repository client. Swallows exceptions
/// on shutdown — the registry's reaper may be racing a client-initiated close.
/// </summary>
public async ValueTask DisposeAsync()
{
if (_disposed) return;
_disposed = true;
_rootGate.Dispose();
try
{
await _client.DisposeAsync().ConfigureAwait(false);
}
catch
{
// Best-effort: a gateway-side close that hits a torn-down channel is normal.
}
}
}