using System.Buffers;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using MQTTnet;
using MQTTnet.Protocol;
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser;
///
/// Bespoke MQTT address-picker browser: opens a short-lived, strictly passive observation
/// window against the broker named by the form's JSON.
///
/// MQTT has no discovery protocol, so there is nothing to enumerate — the browser subscribes
/// to a wildcard (# / {topicPrefix}/# in plain mode, spBv1.0/{groupId}/#
/// in Sparkplug mode) and lets accumulate whatever arrives:
/// a topic segment tree in plain mode, a Group → EdgeNode → Device → Metric tree decoded from
/// observed birth certificates in Sparkplug mode. Nothing on any browse path publishes — in
/// either mode: an operator opening a picker must not be able to inject a message into a
/// running plant. The session's operator-triggered RequestRebirthAsync is the sole
/// sanctioned publish, and it is never reached by OpenAsync or by any browse call.
///
///
/// Layering note. This project depends on the shared leaves only — .Contracts for
/// the Sparkplug wire schema and codec, .Transport for
/// — and NOT on the runtime .Driver project, which
/// it used to reference under a documented exception. Reuse of the TLS / CA-pin path
/// is what that exception bought, and it is preserved: there is still exactly one copy, now in
/// .Transport. Do not fork it. Pinned by MqttBrowserLayeringTests.
///
///
public sealed class MqttDriverBrowser : IDriverBrowser
{
/// Floor on the open budget — a 1 s ConnectTimeoutSeconds would make browse unusable.
internal const int MinOpenBudgetSeconds = 5;
/// Ceiling on the open budget — the picker must never hang on an unreachable broker.
internal const int MaxOpenBudgetSeconds = 30;
/// Marks the transient browse identity in the broker's client-id/session logs.
internal const string BrowseClientIdPrefix = "-browse-";
private readonly ILogger _logger;
///
/// Creates a browser. Connection-free by contract — the universal browser's
/// CanBrowse constructs a throwaway instance purely to ask which driver type it
/// handles, so the constructor must never touch the network.
///
/// Optional logger; defaults to . Never receives credentials.
public MqttDriverBrowser(ILogger? logger = null) =>
_logger = logger ?? NullLogger.Instance;
///
public string DriverType => DriverTypeNames.Mqtt;
// Connects with a browse-only client id, subscribes the wildcard at QoS 0, and hands back a
// session that serves whatever the subscription observes. The whole open is bounded by
// OpenBudget; nothing here publishes.
///
public async Task OpenAsync(string configJson, CancellationToken cancellationToken)
{
// MqttJson.Options — the ONE shared instance across factory / probe / driver / browser
// (see its remarks). Parsing the same DriverConfig blob through a second, divergent
// JsonSerializerOptions is this repo's documented systemic enum bug: the picker would accept
// a `mode` / `protocolVersion` spelling the deployed driver rejects, or vice versa.
var opts = JsonSerializer.Deserialize(configJson, MqttJson.Options)
?? throw new InvalidOperationException("Mqtt options deserialized to null.");
var filter = BuildRootFilter(opts);
var suffix = BuildBrowseClientIdSuffix();
var clientOptions = MqttClientOptionsFactory.BuildClientOptions(ToBrowseOptions(opts), suffix, _logger);
using var openCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
openCts.CancelAfter(OpenBudget(opts));
var client = new MqttClientFactory().CreateMqttClient();
var session = new MqttBrowseSession(opts.Mode, client, _logger);
try
{
// Runs on MQTTnet's dispatcher: record and return, nothing else.
client.ApplicationMessageReceivedAsync += args =>
{
var payload = args.ApplicationMessage.Payload;
ReadOnlySpan body = payload.IsSingleSegment ? payload.FirstSpan : payload.ToArray();
session.Observe(args.ApplicationMessage.Topic, body);
return Task.CompletedTask;
};
await client.ConnectAsync(clientOptions, openCts.Token).ConfigureAwait(false);
// QoS 0: a transient observation window has no delivery guarantee to offer and should
// cost the broker as little as possible.
var subscribeOptions = new MqttClientSubscribeOptionsBuilder()
.WithTopicFilter(f => f
.WithTopic(filter)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce))
.Build();
await client.SubscribeAsync(subscribeOptions, openCts.Token).ConfigureAwait(false);
_logger.LogInformation(
"AdminUI MQTT browse session opened against {Host}:{Port} in {Mode} mode observing "
+ "'{Filter}' (read-only).",
opts.Host, opts.Port, opts.Mode, filter);
return session;
}
catch
{
await session.DisposeAsync().ConfigureAwait(false); // owns the client — disconnects + disposes
throw;
}
}
///
/// The wildcard the observation window subscribes to.
///
/// Plain mode: the whole broker (#) unless the config scopes it with a
/// topic prefix.
///
///
/// Sparkplug mode: the Sparkplug namespace only —
/// spBv1.0/{groupId}/#, matching the group the deployed driver itself subscribes
/// (design §3.1), or spBv1.0/# when no group has been authored yet, so the picker
/// can discover which groups exist. The Plain-mode topic prefix is deliberately ignored:
/// it is a different mode's key, and honouring it would silently narrow the window to a
/// prefix that cannot match a Sparkplug topic at all.
///
///
/// The browse configuration.
/// The MQTT topic filter to subscribe.
internal static string BuildRootFilter(MqttDriverOptions options)
{
if (options.Mode == MqttMode.SparkplugB)
{
var groupId = (options.Sparkplug?.GroupId ?? string.Empty).Trim();
return groupId.Length == 0 ? "spBv1.0/#" : $"spBv1.0/{groupId}/#";
}
var prefix = (options.Plain?.TopicPrefix ?? string.Empty).Trim();
if (prefix.Length == 0) return "#";
if (!prefix.EndsWith('/')) prefix += "/";
return prefix + "#";
}
///
/// A unique per-session client-id suffix. A broker disconnects an existing client when a new
/// one CONNECTs with the same client id, so sharing the driver's id would knock the
/// live driver offline every time an operator opened the picker.
///
/// The suffix appended to the configured client id.
internal static string BuildBrowseClientIdSuffix() =>
BrowseClientIdPrefix + Guid.NewGuid().ToString("N")[..8];
///
/// Projects the authored options into the ones the browse CONNECT uses. Clean session is
/// forced: a transient browse identity must not leave queued-message state behind on the
/// broker after the picker closes.
///
/// ⚠ THE landmine — a Last Will would break the read-only guarantee from outside it.
/// MqttDriverOptions (and MqttSparkplugOptions) carry no will, re-verified
/// since Sparkplug browse was unsealed, so there is nothing to strip and the
/// projection stays a single CleanSession override. If a will is ever added — NDEATH
/// is a will message — it MUST be cleared here: a will is published by the
/// broker, not by us, so it is invisible to
/// , and any ungraceful end to a browse
/// session (crash, dropped link, the disconnect deadline expiring) would then fire an
/// NDEATH under the plant's own edge-node identity — killing a live Sparkplug node because
/// an operator opened an address picker. MqttBrowseSessionTests'
/// MqttDriverOptions_CarryNothingWillShaped_… is the reflection guard that turns that
/// "there is nothing to strip" into a checked fact rather than a claim.
///
///
/// The authored configuration.
/// The configuration the browse CONNECT is built from.
internal static MqttDriverOptions ToBrowseOptions(MqttDriverOptions options) =>
options with { CleanSession = true };
///
/// Whole-open bound (connect + subscribe), clamped to
/// – around the config's
/// own connect deadline.
///
/// The browse configuration.
/// The clamped open budget.
internal static TimeSpan OpenBudget(MqttDriverOptions options) =>
TimeSpan.FromSeconds(Math.Clamp(options.ConnectTimeoutSeconds, MinOpenBudgetSeconds, MaxOpenBudgetSeconds));
}