84 lines
3.0 KiB
C#
84 lines
3.0 KiB
C#
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
|
|
|
namespace ZB.MOM.WW.MxGateway.Client;
|
|
|
|
/// <summary>
|
|
/// One node in a lazy-loaded Galaxy browse tree. Holds the underlying
|
|
/// <see cref="GalaxyObject"/> and exposes <see cref="ExpandAsync"/> to fetch
|
|
/// its direct children on demand. Expansion is one-shot: a second call is a
|
|
/// no-op. Pagination of large sibling sets is handled internally.
|
|
/// </summary>
|
|
public sealed class LazyBrowseNode
|
|
{
|
|
private readonly GalaxyRepositoryClient _client;
|
|
private readonly BrowseChildrenOptions _options;
|
|
private readonly List<LazyBrowseNode> _children = [];
|
|
private bool _isExpanded;
|
|
|
|
internal LazyBrowseNode(
|
|
GalaxyRepositoryClient client,
|
|
GalaxyObject @object,
|
|
bool hasChildrenHint,
|
|
BrowseChildrenOptions options)
|
|
{
|
|
_client = client;
|
|
Object = @object;
|
|
HasChildrenHint = hasChildrenHint;
|
|
_options = options;
|
|
}
|
|
|
|
/// <summary>The underlying Galaxy object for this node.</summary>
|
|
public GalaxyObject Object { get; }
|
|
|
|
/// <summary>True when the server reports this node has at least one matching descendant.</summary>
|
|
public bool HasChildrenHint { get; }
|
|
|
|
/// <summary>Direct children loaded by <see cref="ExpandAsync"/>; empty until then.</summary>
|
|
public IReadOnlyList<LazyBrowseNode> Children => _children;
|
|
|
|
/// <summary>True after the first <see cref="ExpandAsync"/> call completes.</summary>
|
|
public bool IsExpanded => _isExpanded;
|
|
|
|
/// <summary>
|
|
/// Fetches direct children from the gateway and populates <see cref="Children"/>.
|
|
/// Idempotent: subsequent calls are no-ops.
|
|
/// </summary>
|
|
/// <param name="cancellationToken">Token to observe for cancellation.</param>
|
|
public async Task ExpandAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
if (_isExpanded)
|
|
{
|
|
return;
|
|
}
|
|
|
|
string pageToken = string.Empty;
|
|
HashSet<string> seenPageTokens = new(StringComparer.Ordinal);
|
|
do
|
|
{
|
|
BrowseChildrenRequest request = GalaxyRepositoryClient.BuildBrowseChildrenRequest(_options);
|
|
request.ParentGobjectId = Object.GobjectId;
|
|
request.PageToken = pageToken;
|
|
|
|
BrowseChildrenReply reply = await _client
|
|
.BrowseChildrenRawAsync(request, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
|
|
for (int i = 0; i < reply.Children.Count; i++)
|
|
{
|
|
bool hint = i < reply.ChildHasChildren.Count && reply.ChildHasChildren[i];
|
|
_children.Add(new LazyBrowseNode(_client, reply.Children[i], hint, _options));
|
|
}
|
|
|
|
pageToken = reply.NextPageToken;
|
|
if (!string.IsNullOrWhiteSpace(pageToken) && !seenPageTokens.Add(pageToken))
|
|
{
|
|
throw new MxGatewayException(
|
|
$"Galaxy BrowseChildren returned a repeated page token '{pageToken}'.");
|
|
}
|
|
}
|
|
while (!string.IsNullOrWhiteSpace(pageToken));
|
|
|
|
_isExpanded = true;
|
|
}
|
|
}
|