diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index f9a3a5b8d..1d67c4cc3 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -205,6 +205,14 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa shape mismatch is `BadTypeMismatch`, malformed body / wrong declared length `BadDecodingError`); read-only. The driver reads `isArray`/`arrayLength` with `TagConfigIntent`'s exact semantics — keep them in step (`MqttArrayShapeParityTests`). +- **MQTT one-tag-takes-the-batch guards (#988):** a malformed topic FILTER (`a/#/b`, `a/b+`) is a reader + rejection (`MqttTopicFilterRules`), the manager re-checks before sending, chunks at 100 filters and bisects + only CONTENT refusals (`MqttProtocolViolationException`/`NotSupportedException`) — never a session failure; + retain handling rides only a 5.0 SUBSCRIBE (MQTTnet refuses it on 3.1.1). Sparkplug metadata rebirths are + capped at 3 per SCOPE and re-armed only by clean data for that scope (never by a birth — a rebirth request + provokes one); gap rebirths escalate to one per 5 min after 3 with no contiguous message. A `Faulted` + primary-host claim connection is not a held claim (re-claimed); with `clientId` unset the claim id is a + random `spbhost-<12 hex>`. - **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream diff --git a/docs/drivers/Mqtt.md b/docs/drivers/Mqtt.md index 86294d90a..f53fa452d 100644 --- a/docs/drivers/Mqtt.md +++ b/docs/drivers/Mqtt.md @@ -154,7 +154,9 @@ Every key has a default, so nothing is strictly required by the binder. Notable > other forever — the broker logs `Client already connected, closing old connection` and both > nodes reconnect every few seconds while still reporting `Healthy`. Unset (the default) lets MQTTnet > generate a unique id per connection, which is correct. This was observed live during the P1 gate. -> (The probe and browser already self-uniquify with `-probe-` / `-browse-` suffixes.) `MqttDriverForm` +> (The probe and browser already self-uniquify with `-probe-` / `-browse-` suffixes, and with `clientId` +> unset the Sparkplug primary-host claim presents a random per-instance `spbhost-<12 hex>` — #988 M-3; it was +> the literal `-spbhost`, so two claiming drivers on one broker evicted each other.) `MqttDriverForm` > defaults the field blank and raises this warning inline the moment a value is typed. The form validates every knob against the driver's own `[Range]` bounds (port 1–65535, keep-alive / @@ -194,8 +196,16 @@ filters, slices, wildcards or recursive descent**. ### Wildcards -The **runtime accepts** a `+`/`#` topic (it is ambiguous, not unparseable) and the deploy-time -`Inspect` pass **warns**. The **AdminUI editor rejects** it outright — the one place the editor is +The **runtime accepts** a well-formed `+`/`#` topic (it is ambiguous, not unparseable) and the deploy-time +`Inspect` pass **warns**. A **malformed** filter — `#` anywhere but the last level (`a/#/b`, `a/#b`), a `+` +that does not fill its level (`a/b+`), an embedded NUL, or over 65 535 UTF-8 bytes — is **rejected** by the +tag reader (`MqttTopicFilterRules`, #988 M-2): the tag reads `BadNodeIdUnknown`, and the deploy gate names the +cause. It used to be accepted, and MQTTnet then threw for the driver's **whole** batched SUBSCRIBE, taking +every tag dark behind a `Connected`/Healthy connection. The subscription manager also re-checks every filter +before sending, sends at most 100 filters per SUBSCRIBE packet, and bisects a batch the MQTT client refuses +for its content (never a session failure), so one bad filter costs only its own tags. On an MQTT **3.1.1** +session a `"retainSeed": false` tag no longer fails the whole SUBSCRIBE either — retain handling is a 5.0-only +option (MQTTnet refuses it on 3.1.1), so on 3.1.1 the unwanted seed is dropped client-side off the retain flag. The **AdminUI editor rejects** it outright — the one place the editor is deliberately stricter than the driver, because one Tag holds one value and a wildcard would feed it from many source topics. Wildcard tags are indexed **by filter**, not by concrete topic, so they survive a reconnect; a message fans out to *every* matching tag, and unauthored topics are dropped. @@ -245,7 +255,17 @@ One subscription (`spBv1.0/{GroupId}/#`) feeds a per-edge-node state machine - **NBIRTH is node-scoped, DBIRTH is device-scoped**, and routing a DBIRTH through the node path wipes `bdSeq`. They are handled separately on purpose. - **Sequence tracking**: `seq` is a wrapping 0–255 counter. A detected gap raises a rebirth request - when `RequestRebirthOnGap` is on, rather than silently continuing on stale metric state. + when `RequestRebirthOnGap` is on, rather than silently continuing on stale metric state. After 3 + consecutive gap rebirths with no contiguous message in between (a node that does not maintain `seq` — + always 0, or two publishers under one edge-node id) the gap rebirths for that node drop to one per + **5 minutes**, with a once-only warning; a contiguous message re-arms the normal debounce (#988 M-1). +- **Missing metadata is asked for at most 3 times per scope.** Late join, data before birth and a DATA + alias the birth does not declare each request a rebirth, counted per **scope** (edge node or device) and + only when an NCMD is actually sent. The count is re-armed only by evidence the request worked — a DATA + message for that scope whose every metric resolves — never by a birth: a rebirth request is exactly what + makes an NBIRTH arrive, so clearing on it (the pre-#988 behaviour) let a device whose DBIRTH is over + `maxPayloadBytes` drive an NCMD every 10 s forever, staling every sibling device's tags each time. Past the + cap the driver logs one "giving up" warning for the scope. - **Death → STALE.** An NDEATH whose `bdSeq` matches the live session (the bdSeq tie is what stops a stale death from killing a fresh session) marks every metric under that edge node `Bad` / `BadNoCommunication`. A DDEATH does the same for one device. The next birth restores them. @@ -373,8 +393,8 @@ warning — the driver does not publish to `spBv1.0/STATE/`, which is a legal to ### The claim is a whole connection, not a message A Will can only be registered in the **CONNECT packet**. It cannot be added to a live session, changed, -or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, forced -clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg +or withdrawn. So the claim gets its **own** broker connection (client id `{clientId}-spbhost`, or a random +per-instance `spbhost-<12 hex>` when `clientId` is unset — #988 M-3; forced clean-session) whose lifetime *is* the claim: opened on gaining Primary, closed on losing it. Every leg then follows from the connection's lifecycle rather than from bookkeeping that could drift. The ingest session is untouched by a role change — no dropped subscriptions, no lost birth cache, and @@ -425,6 +445,12 @@ raising events at per-instance drivers outlives every driver it holds a referenc - **A failed claim never faults the driver.** A broker whose ACL denies `spBv1.0/STATE/#` costs a warning and a plant-visible missing host, not every tag's value. Ingest is the data plane; the claim is an assertion to other applications. +- **A claim whose connection died is re-claimed (#988 M-6).** The claim connection's supervisor stops for + good on an unrecoverable reconnect CONNACK (`NotAuthorized` while a restarting broker's auth backend + loads, `Banned`, …). The reconcile loop used to treat "a connection object exists" as "the claim is held", + so the host never published `ONLINE` again while ingest — reconnected fine — kept the driver Healthy. A + `Faulted`/`Disposed` claim connection now counts as not held (`IsClaimed` false): it is disposed and the + next reconcile claims afresh under the normal 2 s → 30 s backoff. - **The driver still observes its own `STATE`.** The ingestor subscribes the configured host id regardless, so a claiming node sees its own retained `ONLINE` come back. Nothing gates on it, so the echo costs one log line. @@ -487,7 +513,11 @@ which is archreview 05/STAB-18. - **Every (re)subscribe pushes the cached snapshots.** `SubscribeAsync` republishes each observed reference's cached snapshot onto the new handle before any broker traffic. This is what refills a node an address-space rebuild reseeded `BadWaitingForInitialData` on a quiet topic — a rebuild - triggers no retained replay and, in Sparkplug, no rebirth. + triggers no retained replay and, in Sparkplug, no rebirth. The replay runs on the subscribing thread + unordered against ingest, so after raising each reference it re-reads the cache and re-raises (at most 3 + passes) if a newer value landed meanwhile — otherwise a value pushed mid-replay could be overwritten by + the stale snapshot and stand until the item next changed (#988 M-9). Handles a later subscribe fully + took over (the host drops its handle without unsubscribing on a re-init) are forgotten (#988 M-13). **Why the stale is what makes recovery work.** The plain path suppresses a message whose value *and* status equal the driver-owned cache, and that cache survives reconnects and redeploys. So the retained @@ -513,7 +543,7 @@ every MQTT node materialized read-only regardless of what the operator authored. | Mode | Destination | Payload | |---|---|---| -| **Plain** | the tag's `writeTopic` | the value as UTF-8 text (`Raw`/`Scalar`) or a bare JSON literal (`Json`) | +| **Plain** | the tag's `writeTopic` | the value as UTF-8 text (`Raw`/`Scalar`; a Boolean is `true`/`false`, lower-case — #988 M-15, it was .NET's `True`/`False`) or a bare JSON literal (`Json`) | | **Sparkplug B** | `spBv1.0/{group}/DCMD/{node}/{device}` for a device metric, `spBv1.0/{group}/NCMD/{node}` for an edge-node metric | a Sparkplug `Payload` carrying the metric **by name**, with an explicit `Datatype` and no `seq` | Both publish with `retain: false`. A **Plain** write goes at **QoS 1** (STAB-26): the publish completes only @@ -617,6 +647,11 @@ during the window is invisible — so manual entry remains the escape hatch. Bounds: 50 000 nodes (then `⚠ Observation truncated`), 1024-char topics / 256-char segments (then `⚠ Some topics were too long`), 512-byte payload inspection. Sessions are reaped after 2 minutes idle. +**A refused CONNECT or root SUBSCRIBE fails the open (#988 M-14).** MQTTnet 5 returns both verdicts as +results rather than throwing; the browser used to discard them, so wrong credentials surfaced as a generic +"client is not connected", and a broker ACL denying `#` / `spBv1.0/#` opened onto a silently empty tree. The +open now fails with the CONNACK reason, or with a message naming the refused filter. + **Sparkplug B browse serves a different tree from the same passive window**: observed NBIRTH/DBIRTH certificates are decoded into `Group → EdgeNode → [Device] → Metric` (a birth is the only Sparkplug message that names its metrics). Same node cap, same bounds, same "publishes nothing" guarantee. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser/MqttDriverBrowser.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser/MqttDriverBrowser.cs index 8be8affc8..0e572de57 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser/MqttDriverBrowser.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser/MqttDriverBrowser.cs @@ -99,7 +99,17 @@ public sealed class MqttDriverBrowser : IDriverBrowser return Task.CompletedTask; }; - await client.ConnectAsync(clientOptions, openCts.Token).ConfigureAwait(false); + // MQTTnet 5 returns a refused CONNECT as a RESULT and leaves the client disconnected (#988, review + // M-14) — discarding it surfaced as a generic "client is not connected" from the subscribe below, + // hiding the cause (wrong credentials, banned client id) from the operator. + var connack = await client.ConnectAsync(clientOptions, openCts.Token).ConfigureAwait(false); + if (connack is not null && connack.ResultCode != MqttClientConnectResultCode.Success) + { + throw new InvalidOperationException( + $"Broker at {opts.Host}:{opts.Port} refused the browse CONNECT ({connack.ResultCode}" + + (string.IsNullOrWhiteSpace(connack.ReasonString) ? string.Empty : $": {connack.ReasonString}") + + ")."); + } // QoS 0: a transient observation window has no delivery guarantee to offer and should // cost the broker as little as possible. @@ -108,7 +118,17 @@ public sealed class MqttDriverBrowser : IDriverBrowser .WithTopic(filter) .WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)) .Build(); - await client.SubscribeAsync(subscribeOptions, openCts.Token).ConfigureAwait(false); + // A SUBACK refusal (a broker ACL that denies this account '#' or 'spBv1.0/#') is a result too — + // ignored, the session opened "successfully" onto a silently empty tree (#988, review M-14). + var suback = await client.SubscribeAsync(subscribeOptions, openCts.Token).ConfigureAwait(false); + var verdict = suback?.Items?.FirstOrDefault(); + if (verdict is not null && (int)verdict.ResultCode > (int)MqttClientSubscribeResultCode.GrantedQoS2) + { + throw new InvalidOperationException( + $"Broker at {opts.Host}:{opts.Port} refused the browse subscription to '{filter}' " + + $"({verdict.ResultCode}). Check the broker ACL for this account, or scope the browse with " + + "a topic prefix the account may read."); + } if (opts.Mode == MqttMode.SparkplugB) { diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTagDefinitionFactory.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTagDefinitionFactory.cs index 7de88b4db..2f5280859 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTagDefinitionFactory.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTagDefinitionFactory.cs @@ -70,7 +70,10 @@ public static class MqttTagDefinitionFactory /// A wildcard topic (+ / #) is deliberately NOT rejected here: it is /// ambiguous rather than unparseable, and is the operator-visible surface /// for it. Rejecting it at runtime would turn an authoring mistake into a silent - /// BadNodeIdUnknown with no stated cause. + /// BadNodeIdUnknown with no stated cause. A malformed filter (a/#/b, + /// a/b+, a/#b — see ) IS rejected (#988): no broker + /// can subscribe it, and it used to fail the driver's one batched SUBSCRIBE for every other tag. + /// names the cause. /// /// /// ⚠️ payloadFormat is the one key whose verdict differs between the two readers @@ -107,6 +110,11 @@ public static class MqttTagDefinitionFactory var topic = ReadString(root, MqttTagConfigKeys.Topic); if (string.IsNullOrWhiteSpace(topic)) return false; + // …and it must be a legal MQTT topic FILTER (#988, review M-2). The topic is subscribed verbatim, + // and a malformed filter ('a/#/b', 'a/b+') fails the driver's batched SUBSCRIBE client-side — + // taking every OTHER tag on the driver dark with it. Refusing it here confines it to this tag. + if (!MqttTopicFilterRules.IsValid(topic)) return false; + // Strict enum reads: a present-but-invalid (typo'd) value rejects the whole tag // (→ BadNodeIdUnknown) instead of silently defaulting to a wrong-typed Good. if (!TagConfigJson.TryReadEnumStrict(root, "payloadFormat", MqttPayloadFormat.Json, out var payloadFormat)) @@ -495,6 +503,14 @@ public static class MqttTagDefinitionFactory var hasSparkplugTuple = !string.IsNullOrWhiteSpace(ReadString(root, MqttTagConfigKeys.GroupId)) && !string.IsNullOrWhiteSpace(ReadString(root, MqttTagConfigKeys.EdgeNodeId)) && !string.IsNullOrWhiteSpace(ReadString(root, MqttTagConfigKeys.MetricName)); + if (hasTopic && !hasSparkplugTuple + && MqttTopicFilterRules.DescribeInvalid(ReadString(root, MqttTagConfigKeys.Topic)) is { } filterProblem) + { + rejections.Add( + $"value '{ReadString(root, MqttTagConfigKeys.Topic)}' for 'topic' is not a legal MQTT topic filter " + + $"({filterProblem}). The driver will skip this tag and it will read BadNodeIdUnknown."); + } + if (!hasTopic && !hasSparkplugTuple) { rejections.Add( diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTopicFilterRules.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTopicFilterRules.cs new file mode 100644 index 000000000..1ae9fd388 --- /dev/null +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttTopicFilterRules.cs @@ -0,0 +1,90 @@ +using System.Text; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Mqtt; + +/// +/// The MQTT topic-FILTER grammar (MQTT 3.1.1 §4.7 / 5.0 §4.7), applied to a Plain-mode tag's +/// subscription topic. One rule set, read by the tag reader (), +/// the deploy-time inspector, and the driver's subscription manager before it sends a SUBSCRIBE. +/// +/// +/// +/// Why a malformed filter is a REJECTION, not an advisory (#988, review M-2). MQTTnet validates +/// every filter of a SUBSCRIBE client-side and throws for the WHOLE packet when one is malformed +/// (plant/#/temp: "The character '#' is only allowed as last character"); a filter the client lets +/// through but a broker rejects as malformed makes Mosquitto close the connection. The driver issues one +/// SUBSCRIBE for every authored topic, so a single mis-typed tag used to take every tag on the driver +/// dark behind a connection that still reported Healthy. Refusing the tag at the reader confines the +/// damage to that tag (BadNodeIdUnknown, skipped-tag ledger, deploy-gate rejection). +/// +/// +/// A well-formed wildcard is still accepted — a/+/b and a/# read (ambiguously, which +/// advises about). Only filters no broker could accept are +/// refused here. +/// +/// +public static class MqttTopicFilterRules +{ + /// MQTT's string length prefix is 16 bits, so a topic filter is at most this many UTF-8 bytes. + public const int MaxFilterBytes = 65535; + + /// + /// Describes why is not a legal MQTT subscription topic filter, or returns + /// when it is. + /// + /// The filter, used verbatim (no trimming — the driver subscribes it verbatim). + /// An operator-facing reason, or for a legal filter. + public static string? DescribeInvalid(string? filter) + { + if (string.IsNullOrEmpty(filter)) + { + return "a topic filter must be at least one character long"; + } + + if (filter.Contains('\0')) + { + return "a topic filter must not contain the null character (U+0000)"; + } + + for (var i = 0; i < filter.Length; i++) + { + var c = filter[i]; + if (c == '#') + { + // '#' is the multi-level wildcard: it must be the LAST character, and it must occupy a whole + // level — alone, or preceded by the level separator. + if (i != filter.Length - 1) + { + return "the multi-level wildcard '#' is only allowed as the last character of a topic filter"; + } + + if (i > 0 && filter[i - 1] != '/') + { + return "the multi-level wildcard '#' must occupy a whole topic level (e.g. 'a/#', not 'a#')"; + } + } + else if (c == '+') + { + // '+' is the single-level wildcard: it must occupy a whole level. + var startsLevel = i == 0 || filter[i - 1] == '/'; + var endsLevel = i == filter.Length - 1 || filter[i + 1] == '/'; + if (!startsLevel || !endsLevel) + { + return "the single-level wildcard '+' must occupy a whole topic level (e.g. 'a/+/b', not 'a/b+')"; + } + } + } + + if (Encoding.UTF8.GetByteCount(filter) > MaxFilterBytes) + { + return $"a topic filter must be at most {MaxFilterBytes} UTF-8 bytes long"; + } + + return null; + } + + /// Whether is a legal MQTT subscription topic filter. + /// The filter. + /// when legal. + public static bool IsValid(string? filter) => DescribeInvalid(filter) is null; +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs index 81a1a36ce..2a4dfe17e 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/MqttWriteEncoder.cs @@ -186,9 +186,15 @@ public static class MqttWriteEncoder // Raw and Scalar are both "the payload's UTF-8 text" on the read side; the write side // mirrors that. Invariant culture, or a comma decimal separator on a European host would // publish a number the device cannot parse. - text = value is IFormattable f - ? f.ToString(null, CultureInfo.InvariantCulture) - : value.ToString() ?? ""; + // bool is not IFormattable, so value.ToString() published .NET's "True"/"False" (#988, review + // M-15) — which a device comparing case-sensitively against "true"/"false" silently ignores while + // the write reports Good. Lower-case matches the Json format and the Sparkplug String coercion. + text = value switch + { + bool b => b ? "true" : "false", + IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), + _ => value.ToString() ?? "", + }; } encoded = new MqttEncodedWrite(def.WriteTopic!.Trim(), Encoding.UTF8.GetBytes(text), PlainWriteQos); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/Sparkplug/SparkplugTopic.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/Sparkplug/SparkplugTopic.cs index 287c647da..0669f07a7 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/Sparkplug/SparkplugTopic.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Contracts/Sparkplug/SparkplugTopic.cs @@ -178,6 +178,62 @@ public sealed record SparkplugTopic( return true; } + /// + /// Reads the group and edge-node segments of a non-STATE Sparkplug topic + /// (spBv1.0/{group}/{type}/{node}[/…]) as spans of , without allocating + /// and without validating the rest — a cheap pre-filter for the ingest path's unauthored-node drop + /// (#988, review M-12). remains the authority for everything that passes it. + /// + /// The topic. + /// The group segment. + /// The edge-node segment. + /// + /// for anything that is not shaped like a group-scoped Sparkplug topic (STATE in + /// either form, another namespace, too few segments) — callers fall back to . + /// + public static bool TryPeekEdgeNode(string? topic, out ReadOnlySpan groupId, out ReadOnlySpan edgeNodeId) + { + groupId = default; + edgeNodeId = default; + if (topic is null || topic.Length <= Namespace.Length + || !topic.StartsWith(Namespace, StringComparison.Ordinal) || topic[Namespace.Length] != '/') + { + return false; + } + + var rest = topic.AsSpan(Namespace.Length + 1); + var slash = rest.IndexOf('/'); + if (slash <= 0) + { + return false; + } + + var group = rest[..slash]; + if (group is "STATE") + { + return false; + } + + rest = rest[(slash + 1)..]; + slash = rest.IndexOf('/'); + if (slash <= 0) + { + return false; // no type segment, or no node segment after it + } + + rest = rest[(slash + 1)..]; + var end = rest.IndexOf('/'); + var node = end < 0 ? rest : rest[..end]; + if (node.IsEmpty) + { + return false; + } + + groupId = group; + edgeNodeId = node; + return true; + } + /// /// Parses , throwing if it is not a /// well-formed Sparkplug B topic. See for the non-throwing form. diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttConnection.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttConnection.cs index 61ff0eb61..61ff542b6 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttConnection.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttConnection.cs @@ -1069,16 +1069,25 @@ public sealed class MqttConnection : IAsyncDisposable, IMqttSubscribeTransport, + "has been established."); var builder = new MqttClientSubscribeOptionsBuilder(); + var retainHandlingSupported = _options.ProtocolVersion == MqttProtocolVersion.V500; foreach (var filter in filters) { - builder = builder.WithTopicFilter(f => f - .WithTopic(filter.Topic) - .WithQualityOfServiceLevel(MapQos(filter.Qos)) - // Only meaningful on MQTT 5.0. On 3.1.1 the broker always replays its retained - // message, so the manager also drops unwanted seeds client-side off the retain flag. - .WithRetainHandling(filter.SeedRetained - ? MqttRetainHandling.SendAtSubscribe - : MqttRetainHandling.DoNotSendOnSubscribe)); + builder = builder.WithTopicFilter(f => + { + f.WithTopic(filter.Topic).WithQualityOfServiceLevel(MapQos(filter.Qos)); + + // MQTT 5.0 only — and not merely "ignored" on 3.1.1: MQTTnet REFUSES the whole SUBSCRIBE + // ("Feature RetainHandling requires MQTT version 5.0.0") when a non-default retain + // handling rides a 3.1.1 session, so one `"retainSeed": false` tag took every tag on a + // 3.1.1 driver dark (#988). On 3.1.1 the broker always replays its retained message and + // the manager drops unwanted seeds client-side off the retain flag. + if (retainHandlingSupported) + { + f.WithRetainHandling(filter.SeedRetained + ? MqttRetainHandling.SendAtSubscribe + : MqttRetainHandling.DoNotSendOnSubscribe); + } + }); } using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(_options.ConnectTimeoutSeconds)); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttSubscriptionManager.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttSubscriptionManager.cs index 2a80209d8..72b31bdb0 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttSubscriptionManager.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/MqttSubscriptionManager.cs @@ -141,6 +141,9 @@ public sealed class MqttSubscriptionManager private IMqttSubscribeTransport? _transport; + /// Test seam: how many subscription handles this instance still tracks (#988, review M-13). + internal int LiveHandleCountForTests => _refsByHandle.Count; + /// Initializes a new instance of the class. /// Driver options — supplies the ingest mode and the default QoS. /// Driver instance id, used only for log correlation. @@ -485,9 +488,54 @@ public sealed class MqttSubscriptionManager // A SUBACK refusal (an ACL denial, say) does NOT throw: the broker answered, the refused topics are // Bad + pending, and failing the whole subscribe would take every other topic in it dark too. + RetireSupersededHandles(_refsByHandle, _handleByRawPath, handle); return handle; } + /// + /// Forgets every handle other than that no longer covers ANY reference — a + /// later subscribe took all of them over (#988, review M-13). + /// + /// + /// The host drops its handle without UnsubscribeAsync on a watchdog re-init or a Force + /// Reconnect, and both ingest objects survive the re-init, so each cycle used to leave one + /// string[] of every reference behind. Nothing fans out through such a handle + /// (_handleByRawPath is last-wins), and unsubscribing it would remove nothing — so retiring it + /// changes no behaviour. A handle still covering even one reference is kept. Shared with the + /// Sparkplug ingestor, which keeps the same two maps. + /// + /// Handle → the references it was created for. + /// RawPath → the handle currently covering it. + /// The handle just issued; never retired. + internal static void RetireSupersededHandles( + ConcurrentDictionary refsByHandle, + ConcurrentDictionary handleByRawPath, + ISubscriptionHandle current) + { + foreach (var (handle, refs) in refsByHandle) + { + if (ReferenceEquals(handle, current)) + { + continue; + } + + var stillCovers = false; + foreach (var rawPath in refs) + { + if (handleByRawPath.TryGetValue(rawPath, out var owner) && ReferenceEquals(owner, handle)) + { + stillCovers = true; + break; + } + } + + if (!stillCovers) + { + refsByHandle.TryRemove(new KeyValuePair(handle, refs)); + } + } + } + /// The authored definitions behind every still-authored pending topic. private IEnumerable PendingDefinitions(AuthoredTable authored) => _pendingTopics.Keys @@ -748,10 +796,112 @@ public sealed class MqttSubscriptionManager return EstablishOutcome.Nothing; } + var granted = new HashSet(StringComparer.Ordinal); + + // A filter no broker could accept is refused HERE, before the batch is built (#988, review M-2): + // MQTTnet validates every filter of a SUBSCRIBE client-side and throws for the WHOLE packet, so one + // malformed filter used to take every other tag dark. The tag reader already refuses such a topic, + // so this is defence in depth for any path that reaches the manager without it. + var valid = new List(filters.Count); + foreach (var filter in filters) + { + if (MqttTopicFilterRules.DescribeInvalid(filter.Topic) is { } problem) + { + _logger?.LogError( + "MQTT driver '{DriverId}': topic filter '{Topic}' is not legal MQTT ({Problem}); its tags degrade " + + "to Bad and it is not sent to the broker.", + _driverId, + filter.Topic, + problem); + DegradeTopic(filter.Topic, "InvalidTopicFilter", retry: false); + continue; + } + + valid.Add(filter); + } + + // Chunked, so a broker with a per-SUBSCRIBE filter ceiling refuses one chunk rather than the driver. + // A session-level failure ends the pass: the rest are degraded (and pending) without another round-trip + // against a broker that just failed to answer. + Exception? failure = null; + for (var at = 0; at < valid.Count; at += MaxFiltersPerSubscribe) + { + var chunk = valid.GetRange(at, Math.Min(MaxFiltersPerSubscribe, valid.Count - at)); + if (failure is not null) + { + foreach (var filter in chunk) + { + DegradeTopic(filter.Topic, failure.GetType().Name); + } + + continue; + } + + failure = await EstablishChunkAsync(transport, chunk, granted, cancellationToken).ConfigureAwait(false); + } + + return new EstablishOutcome(granted, failure); + } + + /// + /// Most filters one SUBSCRIBE packet carries. MQTT sets no limit, but brokers do (AWS IoT Core: 8), and + /// a refused oversized packet must cost one chunk, not every tag on the driver. + /// + internal const int MaxFiltersPerSubscribe = 100; + + /// + /// Issues one SUBSCRIBE for and applies its verdict. A FILTER-SPECIFIC + /// client-side refusal of a multi-filter chunk is bisected, so one offending filter costs only itself; + /// anything else is a session-level failure, degrades the whole chunk and is returned. + /// + /// The SUBSCRIBE seam. + /// The filters to establish; never empty. + /// Accumulates the granted topics. + /// Cancellation for the round-trip. + /// The session-level failure, or when the broker (or client) gave a verdict. + private async Task EstablishChunkAsync( + IMqttSubscribeTransport transport, + List chunk, + HashSet granted, + CancellationToken cancellationToken) + { IReadOnlyList outcomes; try { - outcomes = await transport.SubscribeAsync(filters, cancellationToken).ConfigureAwait(false); + outcomes = await transport.SubscribeAsync(chunk, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (IsFilterSpecificRefusal(ex) && !cancellationToken.IsCancellationRequested) + { + if (chunk.Count == 1) + { + // The client refused this one filter's packet: a per-filter verdict, exactly like a SUBACK + // refusal — Bad + pending, no throw. + _logger?.LogError( + ex, + "MQTT driver '{DriverId}': the MQTT client refused to SUBSCRIBE '{Topic}'; its tags degrade to Bad.", + _driverId, + chunk[0].Topic); + DegradeTopic(chunk[0].Topic, ex.GetType().Name); + return null; + } + + // Bisect: logarithmic in the chunk for one bad filter, never one round-trip per filter. + var half = chunk.Count / 2; + var first = await EstablishChunkAsync(transport, chunk.GetRange(0, half), granted, cancellationToken) + .ConfigureAwait(false); + if (first is not null) + { + foreach (var filter in chunk.GetRange(half, chunk.Count - half)) + { + DegradeTopic(filter.Topic, first.GetType().Name); + } + + return first; + } + + return await EstablishChunkAsync( + transport, chunk.GetRange(half, chunk.Count - half), granted, cancellationToken) + .ConfigureAwait(false); } catch (Exception ex) { @@ -759,16 +909,15 @@ public sealed class MqttSubscriptionManager ex, "MQTT driver '{DriverId}': SUBSCRIBE for {FilterCount} filter(s) failed; the affected tags degrade to Bad.", _driverId, - filters.Count); - foreach (var filter in filters) + chunk.Count); + foreach (var filter in chunk) { DegradeTopic(filter.Topic, ex.GetType().Name); } - return new EstablishOutcome(new HashSet(StringComparer.Ordinal), ex); + return ex; } - var granted = new HashSet(StringComparer.Ordinal); foreach (var outcome in outcomes) { if (outcome.Granted) @@ -788,9 +937,20 @@ public sealed class MqttSubscriptionManager } } - return new EstablishOutcome(granted, null); + return null; } + /// + /// Whether a SUBSCRIBE failure is a property of the packet's CONTENT (one filter or one filter option + /// the client refused to encode) rather than of the session. Only these are bisected: a transport + /// failure, deadline or teardown says nothing about any one filter, and bisecting it would multiply + /// round-trips against a broker that is not answering. + /// + /// The failure. + /// for a client-side content refusal. + private static bool IsFilterSpecificRefusal(Exception ex) => + ex is MQTTnet.Exceptions.MqttProtocolViolationException or NotSupportedException; + /// One SUBSCRIBE round-trip's verdict. /// The filters the broker granted. /// Set when the call produced no verdict at all (throw / deadline). @@ -810,7 +970,8 @@ public sealed class MqttSubscriptionManager /// /// The topic filter whose subscription could not be established. /// The failure reason, for logs. - private void DegradeTopic(string topic, string reason) + /// Whether the topic joins the pending set the next subscribe and every reconnect retry. + private void DegradeTopic(string topic, string reason, bool retry = true) { _subscribedTopics.TryRemove(topic, out _); @@ -826,8 +987,16 @@ public sealed class MqttSubscriptionManager return; } - // Still authored, so it must be retried — see _pendingTopics. - _pendingTopics[topic] = 0; + // Still authored, so it must be retried — see _pendingTopics. A filter no broker could ever accept + // is not: retrying it would only repeat the refusal on every subscribe and reconnect. + if (retry) + { + _pendingTopics[topic] = 0; + } + else + { + _pendingTopics.TryRemove(topic, out _); + } var now = DateTime.UtcNow; var snapshot = new DataValueSnapshot(null, StatusBadCommunicationError, null, now); @@ -965,12 +1134,37 @@ public sealed class MqttSubscriptionManager { for (var i = 0; i < defs.Count; i++) { - var snapshot = Values.Read(defs[i].Name); + var rawPath = defs[i].Name; + var snapshot = Values.Read(rawPath); if (snapshot.StatusCode == StatusBadWaitingForInitialData) continue; - Raise(defs[i].Name, snapshot); + Raise(rawPath, snapshot); + + // The replay runs on the SUBSCRIBING thread with no ordering against the dispatcher thread + // (#988, review M-9): read V1 → ingest stores and raises V2 → this raises V1, and the node holds + // the stale V1 until the item next changes (for a report-by-exception metric, possibly never; and + // plain mode's unchanged-value suppression then swallows an identical republish too). So after + // raising, re-read: if the cache moved on meanwhile, re-raise what it now holds. Bounded — a value + // changing faster than this loop is being delivered by the ingest path anyway. + for (var pass = 0; pass < MaxReplayCatchUpPasses; pass++) + { + var current = Values.Read(rawPath); + if (ReferenceEquals(current, snapshot) || current.StatusCode == StatusBadWaitingForInitialData) + { + break; + } + + snapshot = current; + Raise(rawPath, snapshot); + } } } + /// + /// How many times the initial replay re-raises a reference whose cached value moved while it was + /// being replayed — see . + /// + private const int MaxReplayCatchUpPasses = 3; + /// /// Raises for a reference, if a live subscription covers it. /// A throwing subscriber is contained so it cannot starve the rest of the fan-out — or, worse, @@ -1166,8 +1360,10 @@ public sealed class MqttSubscriptionManager i++; } - var name = path[start..i]; - if (name.Length == 0 || name == "*") + // Spans, not substrings (#988, review M-12): this runs for every tag on every message, on the + // dispatcher thread, and JsonElement.TryGetProperty takes a ReadOnlySpan directly. + var name = path.AsSpan(start, i - start); + if (name.Length == 0 || name is "*") { return false; } @@ -1187,7 +1383,7 @@ public sealed class MqttSubscriptionManager return false; } - var inner = path[(i + 1)..close].Trim(); + var inner = path.AsSpan(i + 1, close - i - 1).Trim(); i = close + 1; if (inner.Length >= 2 diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugIngestor.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugIngestor.cs index 5da964db7..def7c278c 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugIngestor.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugIngestor.cs @@ -151,6 +151,15 @@ public sealed class SparkplugIngestor /// private const int MaxConsecutiveMetadataRebirths = 3; + /// + /// The minimum spacing of gap rebirths to a node whose stream has not been contiguous across + /// consecutive gap rebirths — one that does not maintain + /// seq (always 0, or two publishers under one edge-node id). A gap normally self-heals (the next + /// message is contiguous), so this only engages for a stream a rebirth cannot fix; the floor keeps + /// trying, rarely, rather than commanding the node every debounce period forever. + /// + internal static readonly TimeSpan EscalatedGapRebirthFloor = TimeSpan.FromMinutes(5); + private readonly string _driverId; private readonly ILogger? _logger; private readonly TimeSpan _rebirthDebounce; @@ -176,15 +185,34 @@ public sealed class SparkplugIngestor private readonly ConcurrentDictionary _nodeBirthSeen = new(); /// - /// Consecutive metadata rebirths requested from an edge node since its last applied - /// birth. Capped by — see - /// . + /// Metadata rebirths actually SENT on behalf of one scope (node or device) since that scope's data + /// last resolved cleanly. Capped by — see + /// . Keyed by SCOPE, not node, and re-armed only by evidence + /// the request worked (#988, review M-1): keyed by node and cleared by any birth, it was reset by the + /// very NBIRTH each request provokes, and a healthy sibling device re-armed a broken one. /// - private readonly ConcurrentDictionary _metadataRebirths = new(); + private readonly ConcurrentDictionary _metadataRebirths = new(); + + /// + /// Consecutive sequence-gap rebirths SENT to an edge node with no contiguous message in between. Past + /// the gap path's floor escalates from the debounce to + /// (#988, review M-1). + /// + private readonly ConcurrentDictionary _gapRebirths = new(); /// Keys whose anomaly has already been logged loudly once, cleared by . private readonly ConcurrentDictionary _warned = new(StringComparer.Ordinal); + /// 's size, tracked without taking every bucket lock — see . + private int _warnedCount; + + /// + /// Whether Debug logging is on. Every Debug line on the dispatcher path is guarded by it: the + /// params object[] and the boxed enum/struct arguments are allocated at the call even when the + /// level is off (#988, review M-12). + /// + private bool DebugEnabled => _logger?.IsEnabled(LogLevel.Debug) == true; + /// In-flight rebirth publishes, so teardown and tests can drain rather than race them. private readonly List _pendingRebirths = []; @@ -196,6 +224,9 @@ public sealed class SparkplugIngestor private volatile AuthoredTable _authored = AuthoredTable.Empty; private readonly MqttDriverOptions _options; + + /// Test seam: how many subscription handles this instance still tracks (#988, review M-13). + internal int LiveHandleCountForTests => _refsByHandle.Count; private volatile SparkplugHostState? _hostState; private IMqttSubscribeTransport? _subscribeTransport; private IMqttPublishTransport? _publishTransport; @@ -418,6 +449,7 @@ public sealed class SparkplugIngestor var table = AuthoredTable.Build(byRawPath); _authored = table; _warned.Clear(); + Interlocked.Exchange(ref _warnedCount, 0); // Bound the shared last-value cache by the CURRENT authored set (R06:M-2): a dropped tag's value // and every non-authored reference's BadNodeIdUnknown marker would otherwise live forever. A @@ -433,7 +465,15 @@ public sealed class SparkplugIngestor _trackers.TryRemove(key, out _); _lastRebirthTicks.TryRemove(key, out _); _nodeBirthSeen.TryRemove(key, out _); - _metadataRebirths.TryRemove(key, out _); + _gapRebirths.TryRemove(key, out _); + } + } + + foreach (var scope in _metadataRebirths.Keys) + { + if (!table.EdgeNodes.Contains(new SparkplugNodeKey(scope.GroupId, scope.EdgeNodeId))) + { + _metadataRebirths.TryRemove(scope, out _); } } @@ -576,6 +616,9 @@ public sealed class SparkplugIngestor // rebirth — left a quiet metric waiting for the plant indefinitely. PushObservedSnapshots(defs); + // A handle every one of whose references a later subscribe took over is forgotten (#988, M-13). + MqttSubscriptionManager.RetireSupersededHandles(_refsByHandle, _handleByRawPath, handle); + return Task.FromResult(handle); } @@ -674,6 +717,7 @@ public sealed class SparkplugIngestor _trackers.Clear(); _nodeBirthSeen.Clear(); _metadataRebirths.Clear(); + _gapRebirths.Clear(); if (births > 0) { @@ -700,14 +744,36 @@ public sealed class SparkplugIngestor { try { + // Unauthored-node traffic is dropped BEFORE the topic is split into a record (#988, review M-12): + // on a group-wide '#' subscription where this driver authors 2 of 200 edge nodes, that split plus + // the debug-log argument boxing was ~10 allocations per discarded message, on the dispatcher thread. + // The peek reads spans of the topic; STATE and malformed topics fall through to the full parse. + if (SparkplugTopic.TryPeekEdgeNode(topic, out var peekGroup, out var peekNode) + && !_authored.ContainsEdgeNode(peekGroup, peekNode)) + { + if (DebugEnabled) + { + _logger!.LogDebug( + "MQTT driver '{DriverId}': '{Topic}' is for an unauthored edge node; ignored.", + _driverId, + topic); + } + + return; + } + if (!SparkplugTopic.TryParse(topic, out var parsed)) { // A group-wide '#' subscription legitimately delivers topics this driver has no opinion // about. Debug, not warn — an operator must not have to read one line per stray message. - _logger?.LogDebug( - "MQTT driver '{DriverId}': '{Topic}' is not a Sparkplug topic; ignored.", - _driverId, - topic); + if (DebugEnabled) + { + _logger!.LogDebug( + "MQTT driver '{DriverId}': '{Topic}' is not a Sparkplug topic; ignored.", + _driverId, + topic); + } + return; } @@ -744,11 +810,15 @@ public sealed class SparkplugIngestor var node = new SparkplugNodeKey(groupId, edgeNodeId); if (!_authored.EdgeNodes.Contains(node)) { - _logger?.LogDebug( - "MQTT driver '{DriverId}': {Type} for unauthored edge node '{Node}'; ignored.", - _driverId, - parsed.Type, - node); + if (DebugEnabled) + { + _logger!.LogDebug( + "MQTT driver '{DriverId}': {Type} for unauthored edge node '{Node}'; ignored.", + _driverId, + parsed.Type, + node); + } + return; } @@ -818,11 +888,15 @@ public sealed class SparkplugIngestor var node = new SparkplugNodeKey(groupId, edgeNodeId); if (!_authored.EdgeNodes.Contains(node)) { - _logger?.LogDebug( - "MQTT driver '{DriverId}': {Type} for unauthored edge node '{Node}'; ignored.", - _driverId, - topic.Type, - node); + if (DebugEnabled) + { + _logger!.LogDebug( + "MQTT driver '{DriverId}': {Type} for unauthored edge node '{Node}'; ignored.", + _driverId, + topic.Type, + node); + } + return; } @@ -913,7 +987,11 @@ public sealed class SparkplugIngestor // "the birth established a sequence baseline" are different facts, and conflating them is the // rebirth loop CheckSequence documents. _nodeBirthSeen[node] = 0; - _metadataRebirths.TryRemove(node, out _); + + // NOT a reset of the metadata give-up counter (#988, review M-1): an NBIRTH is exactly what a rebirth + // request provokes, so clearing on it meant the counter never passed 1 for any cause the birth does + // not cure (a device whose DBIRTH never lands, an alias the birth does not declare). The counter is + // re-armed by evidence the request WORKED — clean data for that scope — in OnData. var bdSeq = SequenceTracker.TryReadBdSeq(payload, out var token) ? token : (ulong?)null; if (!TrackerFor(node).AcceptNodeBirth(payload.Seq, bdSeq)) @@ -950,11 +1028,10 @@ public sealed class SparkplugIngestor private void OnDeviceBirth(SparkplugNodeKey node, string deviceId, SparkplugPayload payload) { // A DBIRTH is a sequenced member of the edge node's stream — only the NBIRTH restarts it. - CheckSequence(node, payload, "DBIRTH"); + CheckSequence(node, new SparkplugScope(node.GroupId, node.EdgeNodeId, deviceId), payload, "DBIRTH"); - // Metadata arrived, so the give-up counter re-arms: a device that re-births after a bad patch - // must not stay permanently un-askable because of requests made before it recovered. - _metadataRebirths.TryRemove(node, out _); + // The give-up counter is NOT re-armed here (#988, review M-1): a birth that still does not declare + // the alias the data uses would re-arm the loop. Clean data for this device re-arms it (OnData). var result = Births.ApplyDeviceBirth(node.GroupId, node.EdgeNodeId, deviceId, payload.Metrics); var scope = new SparkplugScope(node.GroupId, node.EdgeNodeId, deviceId); @@ -973,7 +1050,9 @@ public sealed class SparkplugIngestor /// private void OnData(SparkplugNodeKey node, SparkplugScope scope, SparkplugPayload payload) { - CheckSequence(node, payload, scope.IsDevice ? "DDATA" : "NDATA"); + // A late join (no NBIRTH seen) already asked for this message's metadata through the capped path; + // asking again below for the same message would double-count one NCMD against two causes. + var metadataRequested = CheckSequence(node, scope, payload, scope.IsDevice ? "DDATA" : "NDATA"); // Scope-level filtering happens HERE, after the sequence check, never before it: an unauthored // device's DDATA is still a member of its edge node's stream, and skipping it earlier would @@ -999,7 +1078,11 @@ public sealed class SparkplugIngestor + "requesting a rebirth.", _driverId, scope); - RequestMetadataRebirth(node, "data before birth"); + if (!metadataRequested) + { + RequestMetadataRebirth(node, scope, "data before birth"); + } + return; } @@ -1028,8 +1111,17 @@ public sealed class SparkplugIngestor + "declare; requesting a rebirth.", _driverId, scope); - RequestMetadataRebirth(node, "unknown alias"); + if (!metadataRequested) + { + RequestMetadataRebirth(node, scope, "unknown alias"); + } + + return; } + + // Every metric resolved against this scope's birth: the metadata is usable, so any earlier request + // for it worked — the one piece of evidence that re-arms this scope's give-up counter. + _metadataRebirths.TryRemove(scope, out _); } /// @@ -1094,7 +1186,7 @@ public sealed class SparkplugIngestor private void OnDeviceDeath(SparkplugNodeKey node, string deviceId, SparkplugPayload payload) { // A DDEATH IS published by the edge node and IS sequenced — unlike an NDEATH. - CheckSequence(node, payload, "DDEATH"); + CheckSequence(node, new SparkplugScope(node.GroupId, node.EdgeNodeId, deviceId), payload, "DDEATH"); Births.TryForgetDevice(node.GroupId, node.EdgeNodeId, deviceId, out _); @@ -1485,6 +1577,16 @@ public sealed class SparkplugIngestor return BadTypeMismatch(def, binding, target, stamp, serverUtc); } + // The decoded vector is already of the served element type (DoubleArray → Float64, Int32Array → Int32, + // StringArray → String …): the scalar coercion is the identity for every such pair, so the element + // walk below only boxed each element twice on the dispatcher thread (#988, review M-11). Serve a copy — + // one memcpy-sized allocation — so two tags bound to one metric never share a mutable array. + // DateTime is excluded: its wire elements are epoch-ms longs, never DateTime, so it cannot match here. + if (elements.GetType().GetElementType() == clrType) + { + return new DataValueSnapshot(elements.Clone(), StatusGood, stamp, serverUtc); + } + // Element by element through the SCALAR coercion, all-or-nothing: one element that does not fit the // effective type refuses the whole vector (a partial array served as Good is a wrong value). var result = Array.CreateInstance(clrType, elements.Length); @@ -1636,12 +1738,37 @@ public sealed class SparkplugIngestor { for (var i = 0; i < defs.Count; i++) { - var snapshot = Values.Read(defs[i].Name); + var rawPath = defs[i].Name; + var snapshot = Values.Read(rawPath); if (snapshot.StatusCode == StatusBadWaitingForInitialData) continue; - Raise(defs[i].Name, snapshot); + Raise(rawPath, snapshot); + + // The replay runs on the SUBSCRIBING thread with no ordering against the dispatcher thread + // (#988, review M-9): read V1 → ingest stores and raises V2 → this raises V1, and the node holds + // the stale V1 until the item next changes (for a report-by-exception metric, possibly never; and + // plain mode's unchanged-value suppression then swallows an identical republish too). So after + // raising, re-read: if the cache moved on meanwhile, re-raise what it now holds. Bounded — a value + // changing faster than this loop is being delivered by the ingest path anyway. + for (var pass = 0; pass < MaxReplayCatchUpPasses; pass++) + { + var current = Values.Read(rawPath); + if (ReferenceEquals(current, snapshot) || current.StatusCode == StatusBadWaitingForInitialData) + { + break; + } + + snapshot = current; + Raise(rawPath, snapshot); + } } } + /// + /// How many times the initial replay re-raises a reference whose cached value moved while it was + /// being replayed — see . + /// + private const int MaxReplayCatchUpPasses = 3; + /// Marks every authored tag in as no longer communicating. private void FanStale(SparkplugScope scope, DateTime? sourceUtc, string reason) { @@ -1757,7 +1884,11 @@ public sealed class SparkplugIngestor /// against), so a driver that only checked its return value would sit happily behind a stream /// whose birth certificate — and therefore whose entire alias table — it never received. /// - private void CheckSequence(SparkplugNodeKey node, SparkplugPayload payload, string kind) + /// + /// when this message was handled as a late join — a metadata rebirth was asked + /// for (or refused by the cap) on behalf of , so the caller must not ask again. + /// + private bool CheckSequence(SparkplugNodeKey node, SparkplugScope scope, SparkplugPayload payload, string kind) { var tracker = TrackerFor(node); if (!tracker.Accept(payload.Seq)) @@ -1771,13 +1902,16 @@ public sealed class SparkplugIngestor node, payload.Seq, tracker.LastSeq); - RequestRebirth(node, "sequence gap"); - return; + RequestGapRebirth(node); + return false; } + // A contiguous message: the stream is being maintained, so the gap path's escalation re-arms. + _gapRebirths.TryRemove(node, out _); + if (tracker.IsBirthSynchronized) { - return; + return false; } // "Birth-synchronized" in SequenceTracker's sense means a birth established a usable SEQUENCE @@ -1789,7 +1923,7 @@ public sealed class SparkplugIngestor // fact to keep, so it keeps it. if (_nodeBirthSeen.ContainsKey(node)) { - return; + return false; } WarnOnce( @@ -1803,48 +1937,96 @@ public sealed class SparkplugIngestor // The residual loop the birth-seen flag cannot see: an NBIRTH that never reaches Dispatch at // all, because it exceeded MaxPayloadBytes or because the node never sends one. Nothing about // asking again changes that, so it goes through the capped path. - RequestMetadataRebirth(node, "late join (no NBIRTH observed)"); + RequestMetadataRebirth(node, scope, "late join (no NBIRTH observed)"); + return true; + } + + /// + /// Requests a rebirth for a sequence gap: at the debounce rate while gaps are isolated, and at + /// once gap + /// rebirths went out with no contiguous message in between (#988, review M-1 — the gap path had no + /// cap at all, so a node that never maintains seq was commanded every debounce period forever). + /// + /// The edge node. + private void RequestGapRebirth(SparkplugNodeKey node) + { + var consecutive = _gapRebirths.TryGetValue(node, out var n) ? n : 0; + var escalated = consecutive >= MaxConsecutiveMetadataRebirths; + if (escalated) + { + WarnOnce( + $"gap-escalated:{node}", + "MQTT driver '{DriverId}': '{Node}' broke its sequence after {Count} consecutive rebirth requests " + + "without one contiguous message — it does not appear to maintain seq (always 0, or two publishers " + + "under one edge-node id). Further gap rebirths are limited to one per {Floor}.", + _driverId, + node, + consecutive, + EscalatedGapRebirthFloor); + } + + if (RequestRebirth(node, "sequence gap", escalated ? EscalatedGapRebirthFloor : null)) + { + _gapRebirths.AddOrUpdate(node, 1, static (_, c) => c + 1); + } } /// /// Requests a rebirth for a missing-metadata reason — late join, data before birth, or an - /// alias the current birth does not declare — under a per-node cap on consecutive attempts. + /// alias the current birth does not declare — under a per-SCOPE cap on requests sent. /// /// /// - /// Why these three and not a sequence gap. A gap is self-limiting: the tracker + /// Why these three and not a sequence gap. A gap is normally self-limiting: the tracker /// resynchronizes onto the observed value, so the very next message is contiguous and asks - /// for nothing. The three reasons routed here are not — every one of them means "this + /// for nothing (a stream that never is escalates instead — see ). + /// The three reasons routed here are not — every one of them means "this /// driver holds no usable catalog for this node", and if the node cannot supply one (its /// birth is over the payload ceiling, or it ignores NCMD entirely) then every /// subsequent message re-raises the same condition. The debounce caps the rate at one /// request per period; only this caps the lifetime. /// /// - /// Consecutive, not cumulative. Any applied birth clears the counter, so a node that - /// recovers is not permanently penalised for having once been unreachable. + /// Re-armed only by evidence the request worked (#988, review M-1). The counter used to be + /// cleared by ANY birth from the node — and a rebirth request is precisely what makes an NBIRTH + /// arrive, so for every cause the birth does not cure (a DBIRTH over the payload ceiling, an alias + /// the birth never declares, a duplicate alias, a device that never DBIRTHs) it never passed 1 and + /// the node was commanded every debounce period forever, staling every tag under it each time. It + /// is now keyed by the scope whose metadata is missing and cleared only when that scope's data + /// resolves cleanly (or the session resets), so a healthy sibling cannot re-arm a broken device + /// either. Only NCMDs actually sent count — a request the debounce swallowed asked nothing. /// /// /// The edge node to command. + /// The scope whose metadata is missing — the counter's key. /// Why, for the log. - private void RequestMetadataRebirth(SparkplugNodeKey node, string reason) + private void RequestMetadataRebirth(SparkplugNodeKey node, SparkplugScope scope, string reason) { - var attempts = _metadataRebirths.AddOrUpdate(node, 1, static (_, n) => n + 1); - if (attempts > MaxConsecutiveMetadataRebirths) + var sent = _metadataRebirths.TryGetValue(scope, out var n) ? n : 0; + if (sent >= MaxConsecutiveMetadataRebirths) { WarnOnce( - $"metadata-exhausted:{node}", - "MQTT driver '{DriverId}': '{Node}' has not delivered a usable birth certificate after " - + "{Attempts} rebirth request(s); giving up until one arrives on its own. Its tags will " - + "not update. Check the node's birth payload size against maxPayloadBytes, its seq " - + "field, and that it honours NCMD Node Control/Rebirth.", + $"metadata-exhausted:{scope}", + "MQTT driver '{DriverId}': '{Scope}' has still not delivered usable metadata ({Reason}) after " + + "{Attempts} rebirth request(s) to '{Node}'; giving up until its data resolves on its own. " + + "Its unresolved metrics will not update. Check the birth payload size against " + + "maxPayloadBytes, that every DATA alias is declared by the birth (and unique), its seq " + + "field, and that the node honours NCMD Node Control/Rebirth.", _driverId, - node, - MaxConsecutiveMetadataRebirths); + scope, + reason, + MaxConsecutiveMetadataRebirths, + node); return; } - RequestRebirth(node, reason); + // Counted only when an NCMD actually went out: a request swallowed by the debounce asked nothing, and + // counting it let a burst of DATA inside one debounce period exhaust the cap before the node could + // answer the first request. + if (RequestRebirth(node, reason)) + { + _metadataRebirths.AddOrUpdate(scope, 1, static (_, c) => c + 1); + } } /// @@ -1872,7 +2054,14 @@ public sealed class SparkplugIngestor /// policy and the per-node debounce. /// Never blocks the caller and never throws. /// - private void RequestRebirth(SparkplugNodeKey node, string reason) + /// The edge node to command. + /// Why, for the log. + /// + /// A floor longer than the debounce for this request (the escalated gap path), or + /// for the debounce. + /// + /// when an NCMD was dispatched. + private bool RequestRebirth(SparkplugNodeKey node, string reason, TimeSpan? minInterval = null) { if (_options.Sparkplug is { RequestRebirthOnGap: false }) { @@ -1882,7 +2071,7 @@ public sealed class SparkplugIngestor _driverId, node, reason); - return; + return false; } if (_publishTransport is not { } transport) @@ -1893,10 +2082,10 @@ public sealed class SparkplugIngestor _driverId, node, reason); - return; + return false; } - if (!TryAcquireRebirthSlot(node)) + if (!TryAcquireRebirthSlot(node, minInterval ?? _rebirthDebounce)) { _logger?.LogDebug( "MQTT driver '{DriverId}': rebirth request to '{Node}' ({Reason}) suppressed; one was sent " @@ -1904,8 +2093,8 @@ public sealed class SparkplugIngestor _driverId, node, reason, - _rebirthDebounce); - return; + minInterval ?? _rebirthDebounce); + return false; } _logger?.LogInformation( @@ -1934,15 +2123,17 @@ public sealed class SparkplugIngestor node); } })); + + return true; } /// /// Claims this node's rebirth slot, or reports that one was claimed too recently. Lock-free: this /// runs on MQTTnet's dispatcher thread. /// - private bool TryAcquireRebirthSlot(SparkplugNodeKey node) + private bool TryAcquireRebirthSlot(SparkplugNodeKey node, TimeSpan floor) { - if (_rebirthDebounce <= TimeSpan.Zero) + if (floor <= TimeSpan.Zero) { return true; } @@ -1960,7 +2151,7 @@ public sealed class SparkplugIngestor continue; } - if (now - last < _rebirthDebounce.Ticks) + if (now - last < floor.Ticks) { return false; } @@ -2086,8 +2277,16 @@ public sealed class SparkplugIngestor // The ceiling is unreachable by design — see MaxWarnKeys. It exists so that a derivation that // turns out NOT to be bounded (as the oversize path's raw-topic key was) degrades to silence // instead of to unbounded growth on the dispatcher path. - if (_warned.Count < MaxWarnKeys && _warned.TryAdd(key, 0)) + // ContainsKey first and an Interlocked count (#988, review M-12): ConcurrentDictionary.Count takes every + // bucket lock, and a persistently mismatched tag calls this once per message on the dispatcher thread. + if (_warned.ContainsKey(key) || Volatile.Read(ref _warnedCount) >= MaxWarnKeys) { + return; + } + + if (_warned.TryAdd(key, 0)) + { + Interlocked.Increment(ref _warnedCount); #pragma warning disable CA2254 // Template is a compile-time constant at every call site. _logger?.LogWarning(message, args); #pragma warning restore CA2254 @@ -2117,6 +2316,34 @@ public sealed class SparkplugIngestor FrozenDictionary ByScope, FrozenSet EdgeNodes) { + /// + /// The as group/node strings — unambiguous, because neither id can + /// contain '/' — queried by span so the dispatcher's unauthored-node drop allocates nothing. + /// + private readonly FrozenSet.AlternateLookup> _edgeNodeKeys = + EdgeNodes.Select(n => $"{n.GroupId}/{n.EdgeNodeId}") + .ToFrozenSet(StringComparer.Ordinal) + .GetAlternateLookup>(); + + /// Whether (group, node) is an authored edge node, without allocating. + /// The topic's group segment. + /// The topic's edge-node segment. + /// when authored. + public bool ContainsEdgeNode(ReadOnlySpan group, ReadOnlySpan node) + { + var length = group.Length + 1 + node.Length; + if (length > 256) + { + return EdgeNodes.Contains(new SparkplugNodeKey(group.ToString(), node.ToString())); + } + + Span key = stackalloc char[length]; + group.CopyTo(key); + key[group.Length] = '/'; + node.CopyTo(key[(group.Length + 1)..]); + return _edgeNodeKeys.Contains(key); + } + public static readonly AuthoredTable Empty = Build(new Dictionary(StringComparer.Ordinal)); diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs index f5664ebe0..346c11ea2 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt/Sparkplug/SparkplugPrimaryHost.cs @@ -63,6 +63,11 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable /// internal const string ClientIdSuffix = "-spbhost"; + /// + /// Prefix of the generated claim id used when no clientId is configured (#988, review M-3). + /// + internal const string GeneratedClientIdPrefix = "spbhost-"; + /// How often the role gate is sampled. Bounds the failover republish latency. private static readonly TimeSpan RoleSampleInterval = TimeSpan.FromSeconds(1); @@ -81,6 +86,12 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable private readonly ILogger? _logger; private readonly TimeProvider _timeProvider; + /// The options the claim connection is built from — with a blank client id normalised away. + private readonly MqttDriverOptions _claimOptions; + + /// Appended to ' client id; see . + private readonly string _claimClientIdSuffix; + /// /// Serializes claim/release against each other and against . Never /// disposed — see for why. @@ -131,8 +142,50 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable _roleSource = roleSource; _logger = logger; _timeProvider = timeProvider ?? TimeProvider.System; + + // A whitespace-only client id is "unset": the factory would otherwise prefix it verbatim. + _claimOptions = string.IsNullOrWhiteSpace(options.ClientId) ? options with { ClientId = null } : options; + _claimClientIdSuffix = BuildClaimClientIdSuffix(_claimOptions); } + /// + /// The client-id suffix of the claim connection (#988, review M-3). + /// + /// + /// + /// Configured clientId: {clientId}-spbhost, unchanged — stable, so an operator's + /// broker ACL written for it keeps matching, and unique as long as the configured id is (two drivers + /// sharing a configured id already collide on their ingest connections). + /// + /// + /// Blank clientId (the documented default): the id used to be the literal + /// -spbhost — the ONE connection in the driver with a fixed, fleet-wide id (ingest gets a + /// library-generated id, the probe and browser a random suffix). A plant with two Sparkplug groups + /// needs two drivers, both claimed with -spbhost, and each CONNECT evicted the other: both + /// STATE topics flapped ONLINE/OFFLINE about once a second while both drivers reported Healthy. A + /// random per-instance id fixes it, and nothing depends on the id being stable — the claim session + /// is forced clean. 20 characters, inside MQTT 3.1.1's guaranteed 23. + /// + /// + /// The claim connection's options (blank client id already normalised to null). + /// The suffix. + internal static string BuildClaimClientIdSuffix(MqttDriverOptions claimOptions) => + claimOptions.ClientId is null + ? GeneratedClientIdPrefix + Guid.NewGuid().ToString("N")[..12] + : ClientIdSuffix; + + /// Test seam: the client id the claim connection presents. + internal string ClaimClientIdForTests => string.Concat(_claimOptions.ClientId ?? string.Empty, _claimClientIdSuffix); + + /// Test seam: the options the claim connection is built from. + internal MqttDriverOptions ClaimOptionsForTests => _claimOptions; + + /// Test seam: the claim connection's client-id suffix. + internal string ClaimClientIdSuffixForTests => _claimClientIdSuffix; + + /// Test seam: the live claim connection's state, or null when none is held. + internal MqttConnectionState? ClaimConnectionStateForTests => Volatile.Read(ref _connection)?.State; + /// /// Whether asks for — and can support — a primary-host claim: /// Sparkplug mode, actAsPrimaryHost set, and a non-blank hostId. @@ -178,7 +231,17 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable /// Whether the claim is currently held — i.e. a retained ONLINE has been published and a /// Will is armed behind it. /// - public bool IsClaimed => Volatile.Read(ref _connection) is not null; + public bool IsClaimed => Volatile.Read(ref _connection) is { } connection && !IsDead(connection); + + /// + /// Whether a claim connection can never recover by itself: its supervisor stops for good on an + /// unrecoverable reconnect CONNACK (NotAuthorized, BadUserNameOrPassword, Banned, …) or when it faults, + /// and a disposed connection is gone. Such a connection is not a held claim (#988, review M-6). + /// + /// The claim connection. + /// when it is Faulted or Disposed. + private static bool IsDead(MqttConnection connection) => + connection.State is MqttConnectionState.Faulted or MqttConnectionState.Disposed; /// /// Test seam: how many times a claim connect has been attempted, successful or not. @@ -392,7 +455,7 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable private async Task ClaimAsync(CancellationToken cancellationToken) { - if (Volatile.Read(ref _connection) is not null) + if (Volatile.Read(ref _connection) is { } held && !IsDead(held)) { return; // Already held; the connection's own supervisor keeps it that way. } @@ -400,11 +463,34 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); try { - if (_connection is not null || Volatile.Read(ref _disposed) != 0) + if (Volatile.Read(ref _disposed) != 0) { return; } + if (_connection is { } existing) + { + if (!IsDead(existing)) + { + return; + } + + // The supervisor has stopped for good (#988, review M-6) — "a connection object exists" is not + // "the claim is held". The broker has already published the Will (retained OFFLINE), and + // nothing else would ever re-assert ONLINE: the ingest connection, which reconnected fine, keeps + // the driver Healthy, so the watchdog never re-initialises it. Drop the dead claim and claim + // afresh below; a refusal throws into the reconcile loop's backoff like any failed claim. + _logger?.LogWarning( + "MQTT driver '{DriverId}': the Sparkplug primary-host claim connection for '{HostId}' is {State}; " + + "re-claiming.", + _driverId, + _hostId, + existing.State); + Volatile.Write(ref _connection, null); + _session = null; + await existing.DisposeAsync().ConfigureAwait(false); + } + Interlocked.Increment(ref _claimAttempts); // ONE timestamp for both bodies — the Will is built here, before CONNECT, and the birth @@ -413,10 +499,10 @@ public sealed class SparkplugPrimaryHost : IAsyncDisposable _hostId, _timeProvider.GetUtcNow().ToUnixTimeMilliseconds()); var connection = new MqttConnection( - _options, + _claimOptions, _driverId, _logger, - clientIdSuffix: ClientIdSuffix, + clientIdSuffix: _claimClientIdSuffix, lastWill: new MqttLastWill( session.Topic, session.OfflineBody, SparkplugStatePayload.StateQos, Retain: true), // Forced clean, ignoring the driver's configured value: a broker that resumes a prior diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs index fc9f6825b..141046998 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.IntegrationTests/MqttPrimaryHostLiveTests.cs @@ -196,6 +196,45 @@ public sealed class MqttPrimaryHostLiveTests(MqttFixture fixture) await ClearRetainedAsync(hostId, ct); } + /// + /// #988 review M-3, live: two claiming drivers with the recommended blank clientId on one broker + /// (two Sparkplug groups need two drivers). Both used to present the literal -spbhost, so each + /// CONNECT made Mosquitto close the other ("already connected") and both STATE topics flapped about once + /// a second. Both claim connections must now stay Connected throughout. + /// + [Fact] + public async Task Two_claims_with_a_blank_client_id_do_not_evict_each_other() + { + SkipIfUnconfigured(); + + var ct = TestContext.Current.CancellationToken; + var idA = NewHostId(); + var idB = NewHostId(); + await using var a = new SparkplugPrimaryHost(Options(idA) with { ClientId = null }, $"live-{idA}", new MutableRole(true)); + await using var b = new SparkplugPrimaryHost(Options(idB) with { ClientId = null }, $"live-{idB}", new MutableRole(true)); + + await a.StartAsync(ct); + await b.StartAsync(ct); + a.IsClaimed.ShouldBeTrue(); + b.IsClaimed.ShouldBeTrue(); + + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10); + while (DateTime.UtcNow < deadline) + { + a.ClaimConnectionStateForTests.ShouldBe(MqttConnectionState.Connected); + b.ClaimConnectionStateForTests.ShouldBe(MqttConnectionState.Connected); + await Task.Delay(100, ct); + } + + a.ClaimAttemptsForTests.ShouldBe(1); + b.ClaimAttemptsForTests.ShouldBe(1); + + await a.StopAsync(ct); + await b.StopAsync(ct); + await ClearRetainedAsync(idA, ct); + await ClearRetainedAsync(idB, ct); + } + // ---- helpers ----------------------------------------------------------------------------------- /// A per-test host id: the retained STATE outlives the test that wrote it. diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs index 5cb47e49d..0a232f642 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MiniBroker.cs @@ -70,7 +70,13 @@ internal sealed class MiniBroker : IDisposable /// Builds the SUBACK for one SUBSCRIBE packet read whole into , or null when /// the packet is not parseable from one read (the fake handles one packet per read, like CONNECT). /// - private static byte[]? TryBuildSubAck(byte[] buffer, int read) + /// + /// Filters for which the SUBACK carries the MQTT 3.1.1 failure return code (0x80) — a broker ACL + /// denying the subscription. Null (the default) grants everything. + /// + public Func? RefuseSubscribe { get; set; } + + private byte[]? TryBuildSubAck(byte[] buffer, int read) { // Fixed header: type byte, then the variable-length "remaining length". var at = 1; @@ -97,9 +103,10 @@ internal sealed class MiniBroker : IDisposable while (at + 2 <= end) { var length = (buffer[at] << 8) | buffer[at + 1]; + var topic = System.Text.Encoding.UTF8.GetString(buffer, at + 2, Math.Min(length, Math.Max(0, end - at - 2))); at += 2 + length; if (at >= end) return null; - grants.Add((byte)(buffer[at] & 0x03)); + grants.Add(RefuseSubscribe?.Invoke(topic) == true ? (byte)0x80 : (byte)(buffer[at] & 0x03)); at++; } diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs new file mode 100644 index 000000000..55b3a16e4 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/MqttReview20261202Tests.cs @@ -0,0 +1,457 @@ +using System.Text; +using MQTTnet.Exceptions; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Sparkplug; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests; + +/// +/// Regression pins for the 2026-12-02 review's plain-MQTT findings (#988): +/// M-2 (one malformed filter took the whole batched SUBSCRIBE down), M-12 (per-message JSONPath +/// substrings), M-13 (abandoned subscription handles accumulated) and M-15 (Scalar/Raw booleans +/// published as True/False). +/// +public sealed class MqttReview20261202Tests +{ + private const uint Good = 0x00000000u; + private const uint BadNodeIdUnknown = 0x80340000u; + private const uint BadCommunicationError = 0x80050000u; + + private static RawTagEntry Tag(string rawPath, string topic) => + new(rawPath, $$"""{"topic":"{{topic}}","payloadFormat":"Json","jsonPath":"$.v","dataType":"Float64"}""", + WriteIdempotent: false); + + private static MqttDriverOptions BrokerOpts(int port) => new() + { + Host = "127.0.0.1", + Port = port, + UseTls = false, + ProtocolVersion = MqttProtocolVersion.V311, + CleanSession = true, + KeepAliveSeconds = 300, + ConnectTimeoutSeconds = 5, + ReconnectMinBackoffSeconds = 1, + ReconnectMaxBackoffSeconds = 2, + Mode = MqttMode.Plain, + }; + + // --------------------------------------------------------------------------------- + // M-2 — a malformed topic filter is refused at the reader, never sent in the batch + // --------------------------------------------------------------------------------- + + [Theory] + [InlineData("a/#/b")] + [InlineData("a/b+")] + [InlineData("a/#b")] + [InlineData("#/a")] + [InlineData("a/+b/c")] + [InlineData("+a")] + [InlineData("a\0b")] + public void FromTagConfig_rejects_a_malformed_topic_filter(string topic) + { + var blob = $$"""{"topic":{{System.Text.Json.JsonSerializer.Serialize(topic)}},"payloadFormat":"Raw"}"""; + + MqttTagDefinitionFactory.FromTagConfig(blob, "Plant/Mqtt/b/T", out _).ShouldBeFalse(); + + // …and the deploy gate names the cause rather than falling back to the generic backstop. + MqttTagDefinitionFactory.Inspect(blob) + .ShouldContain(w => w.Contains("not a legal MQTT topic filter", StringComparison.Ordinal)); + } + + /// Positive control: every WELL-FORMED wildcard still reads (it is only advised about). + [Theory] + [InlineData("#")] + [InlineData("+")] + [InlineData("a/#")] + [InlineData("a/+/b")] + [InlineData("+/+")] + [InlineData("/")] + [InlineData("plain/topic")] + public void FromTagConfig_accepts_a_well_formed_filter(string topic) + => MqttTagDefinitionFactory.FromTagConfig( + $$"""{"topic":"{{topic}}","payloadFormat":"Raw"}""", "Plant/Mqtt/b/T", out _).ShouldBeTrue(); + + /// + /// The rule set never accepts a filter the client library's own SUBSCRIBE validation throws for, + /// checked against a real (minimal) broker. It is deliberately STRICTER than MQTTnet for a '+' that + /// does not fill its level ('a/b+'): MQTTnet sends that, and a conformant broker (Mosquitto) answers + /// the protocol violation by closing the connection — a reconnect loop for the whole driver. + /// + [Theory] + [InlineData("good/a", false)] + [InlineData("a/#", false)] + [InlineData("#", false)] + [InlineData("a/+/b", false)] + [InlineData("+", false)] + [InlineData("a/#/b", true)] + [InlineData("a/#b", true)] + [InlineData("a/b+", false)] + [InlineData("a/+b/c", false)] + public async Task Filter_rules_never_accept_what_the_MQTTnet_client_refuses(string filter, bool mqttnetThrows) + { + using var broker = new MiniBroker(); + await using var conn = new MqttConnection(BrokerOpts(broker.Port), driverId: "t", logger: null); + await conn.ConnectAsync(TestContext.Current.CancellationToken); + + var threw = false; + try + { + await conn.SubscribeAsync( + [new MqttTopicSubscription(filter, 1, true)], TestContext.Current.CancellationToken); + } + catch (MqttProtocolViolationException) + { + threw = true; + } + + threw.ShouldBe(mqttnetThrows, "the library's behaviour this rule set is pinned against"); + if (threw) + { + MqttTopicFilterRules.IsValid(filter).ShouldBeFalse(); + } + } + + /// + /// Found while pinning M-2: on an MQTT 3.1.1 session MQTTnet refuses retain-handling outright + /// ("Feature RetainHandling requires MQTT version 5.0.0"), so ONE plain tag authored + /// "retainSeed": false failed the whole batched SUBSCRIBE — every tag on a 3.1.1 driver dark. + /// Retain handling is a 5.0-only option; on 3.1.1 the manager filters unwanted seeds client-side. + /// + [Fact] + public async Task A_no_seed_filter_subscribes_on_a_3_1_1_session() + { + // MiniBroker speaks 3.1.1 only (BrokerOpts pins V311); the 5.0 path is unchanged and live-gated. + using var broker = new MiniBroker(); + await using var conn = new MqttConnection(BrokerOpts(broker.Port), driverId: "t", logger: null); + await conn.ConnectAsync(TestContext.Current.CancellationToken); + + var outcomes = await conn.SubscribeAsync( + [new MqttTopicSubscription("a/seeded", 1, true), new MqttTopicSubscription("a/unseeded", 1, false)], + TestContext.Current.CancellationToken); + + outcomes.Count.ShouldBe(2); + } + + /// + /// The report's failure scenario end to end, against a real MQTTnet client: one tag authored with + /// line1/#/temp among good ones. Before #988 the whole SUBSCRIBE threw client-side and every tag + /// read BadCommunicationError; now only the malformed tag is dark (BadNodeIdUnknown, the + /// reader refused it) and the rest are established. + /// + [Fact] + public async Task One_malformed_topic_does_not_take_the_other_tags_dark() + { + using var broker = new MiniBroker(); + var opts = BrokerOpts(broker.Port); + await using var conn = new MqttConnection(opts, driverId: "t", logger: null); + var mgr = new MqttSubscriptionManager(opts, "mqtt-1"); + mgr.Register( + [ + Tag("P/a", "line1/a"), Tag("P/b", "line1/b"), Tag("P/c", "line1/c"), Tag("P/d", "line1/d"), + Tag("P/bad", "line1/#/temp"), + ]); + mgr.AttachTo(conn); + await conn.ConnectAsync(TestContext.Current.CancellationToken); + + await Should.NotThrowAsync(() => mgr.SubscribeAsync( + ["P/a", "P/b", "P/c", "P/d", "P/bad"], TimeSpan.Zero, TestContext.Current.CancellationToken)); + + mgr.Values.Read("P/bad").StatusCode.ShouldBe(BadNodeIdUnknown); + foreach (var good in new[] { "P/a", "P/b", "P/c", "P/d" }) + { + mgr.Values.Read(good).StatusCode.ShouldNotBe(BadCommunicationError, good); + } + + // Positive control: the good topics really are live — a message on one of them is delivered. + mgr.HandleMessage("line1/c", """{"v":4.5}"""u8, retained: false); + mgr.Values.Read("P/c").Value.ShouldBe(4.5); + mgr.Values.Read("P/c").StatusCode.ShouldBe(Good); + } + + /// + /// Defence in depth: a filter-specific CLIENT-SIDE refusal the reader did not foresee (a protocol + /// violation is a property of the packet's content, never of the session) bisects the batch, so the + /// other filters are still established and only the offending one degrades — without a throw, because + /// that is a per-filter verdict like a SUBACK refusal. + /// + [Fact] + public async Task A_per_filter_protocol_violation_bisects_instead_of_failing_the_batch() + { + var transport = new PoisonTransport("t/poison"); + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", transport); + mgr.Register([Tag("P/1", "t/1"), Tag("P/2", "t/2"), Tag("P/3", "t/poison"), Tag("P/4", "t/4"), Tag("P/5", "t/5")]); + + await Should.NotThrowAsync(() => mgr.SubscribeAsync( + ["P/1", "P/2", "P/3", "P/4", "P/5"], TimeSpan.Zero, TestContext.Current.CancellationToken)); + + transport.Granted.ShouldBe(["t/1", "t/2", "t/4", "t/5"], ignoreOrder: true); + mgr.Values.Read("P/3").StatusCode.ShouldBe(BadCommunicationError); + transport.Calls.ShouldBeLessThanOrEqualTo(7, "bisection is logarithmic, not one call per filter"); + } + + /// + /// Control for the test above: a SESSION-level failure (no connection, deadline) is NOT bisected — it + /// fails once, throws so the host re-subscribes, and costs no extra round-trips against a dead broker. + /// + [Fact] + public async Task A_transport_failure_is_not_bisected() + { + var transport = new PoisonTransport(poison: null) { SessionFailure = new InvalidOperationException("not connected") }; + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", transport); + mgr.Register([Tag("P/1", "t/1"), Tag("P/2", "t/2"), Tag("P/3", "t/3"), Tag("P/4", "t/4")]); + + await Should.ThrowAsync(() => mgr.SubscribeAsync( + ["P/1", "P/2", "P/3", "P/4"], TimeSpan.Zero, TestContext.Current.CancellationToken)); + + transport.Calls.ShouldBe(1); + } + + // --------------------------------------------------------------------------------- + // M-14 — the address-picker browse honours CONNACK and SUBACK verdicts + // --------------------------------------------------------------------------------- + + private static string BrowseConfig(int port) => + $$"""{"host":"127.0.0.1","port":{{port}},"useTls":false,"protocolVersion":"V311","connectTimeoutSeconds":2,"mode":"Plain"}"""; + + /// + /// MQTTnet 5 returns a refused CONNECT as a result rather than throwing; the browser discarded it, so the + /// operator got a generic "client is not connected" from the following subscribe instead of the cause. + /// + [Fact] + public async Task Browse_open_reports_a_refused_connect_by_its_reason() + { + using var broker = new MiniBroker { ConnAckReturnCode = MiniBroker.ReturnCodeBadUserNameOrPassword }; + var browser = new ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser.MqttDriverBrowser(); + + var ex = await Should.ThrowAsync( + () => browser.OpenAsync(BrowseConfig(broker.Port), TestContext.Current.CancellationToken)); + + ex.Message.ShouldContain("BadUserNameOrPassword"); + } + + /// + /// A broker ACL that denies the browse root (#) used to open "successfully" onto a silently empty + /// tree. The refusal now fails the open with a message naming the filter. + /// + [Fact] + public async Task Browse_open_fails_when_the_root_filter_is_refused() + { + using var broker = new MiniBroker { RefuseSubscribe = filter => filter == "#" }; + var browser = new ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser.MqttDriverBrowser(); + + var ex = await Should.ThrowAsync( + () => browser.OpenAsync(BrowseConfig(broker.Port), TestContext.Current.CancellationToken)); + + ex.Message.ShouldContain("'#'"); + } + + /// Positive control: a granted CONNECT and SUBSCRIBE open normally. + [Fact] + public async Task Browse_open_succeeds_when_the_broker_grants_everything() + { + using var broker = new MiniBroker(); + var browser = new ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Browser.MqttDriverBrowser(); + + var session = await browser.OpenAsync(BrowseConfig(broker.Port), TestContext.Current.CancellationToken); + await session.DisposeAsync(); + } + + // --------------------------------------------------------------------------------- + // M-13 — handles a later subscribe fully took over are retired + // --------------------------------------------------------------------------------- + + [Fact] + public async Task Abandoned_plain_handles_do_not_accumulate() + { + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", new PoisonTransport(null)); + mgr.Register([Tag("P/1", "t/1"), Tag("P/2", "t/2")]); + + ISubscriptionHandle? last = null; + for (var i = 0; i < 10; i++) + { + // The host drops its handle without unsubscribing (watchdog re-init / Force Reconnect). + last = await mgr.SubscribeAsync(["P/1", "P/2"], TimeSpan.Zero, TestContext.Current.CancellationToken); + } + + mgr.LiveHandleCountForTests.ShouldBe(1); + + // Positive control: the surviving handle is the live one — delivery is still attributed to it. + ISubscriptionHandle? raisedOn = null; + mgr.OnDataChange += (_, e) => raisedOn = e.SubscriptionHandle; + mgr.HandleMessage("t/1", """{"v":1.0}"""u8, retained: false); + raisedOn.ShouldBe(last); + } + + /// A handle that still covers a reference no later subscribe took over is kept. + [Fact] + public async Task A_partially_overlapping_handle_is_kept() + { + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", new PoisonTransport(null)); + mgr.Register([Tag("P/1", "t/1"), Tag("P/2", "t/2")]); + + await mgr.SubscribeAsync(["P/1", "P/2"], TimeSpan.Zero, TestContext.Current.CancellationToken); + await mgr.SubscribeAsync(["P/1"], TimeSpan.Zero, TestContext.Current.CancellationToken); + + mgr.LiveHandleCountForTests.ShouldBe(2); + } + + [Fact] + public async Task Abandoned_sparkplug_handles_do_not_accumulate() + { + var options = new MqttDriverOptions + { + Mode = MqttMode.SparkplugB, + Sparkplug = new MqttSparkplugOptions { GroupId = "G", HostId = "h" }, + }; + var ing = new SparkplugIngestor(options, "spb-1", rebirthDebounce: TimeSpan.Zero); + ing.Register( + [ + new RawTagEntry("P/t", """{"groupId":"G","edgeNodeId":"N","deviceId":"D","metricName":"T","dataType":"Float32"}""", false), + ]); + + for (var i = 0; i < 10; i++) + { + await ing.SubscribeAsync(["P/t"], TimeSpan.Zero, TestContext.Current.CancellationToken); + } + + ing.LiveHandleCountForTests.ShouldBe(1); + } + + // --------------------------------------------------------------------------------- + // M-9 — the subscribe-time replay cannot overwrite a newer pushed value + // --------------------------------------------------------------------------------- + + /// + /// Deterministic interleaving: the replay of the cached V1 is in flight when the dispatcher stores and + /// raises V2 (modelled by delivering V2 from inside the handler, before it records V1). Before #988 the + /// node's last notification was the stale V1 while the cache held V2. + /// + [Fact] + public async Task The_initial_replay_never_leaves_a_stale_value_last() + { + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", new PoisonTransport(null)); + mgr.Register([Tag("P/1", "t/1")]); + mgr.HandleMessage("t/1", """{"v":1.0}"""u8, retained: false); // V1 cached before any subscription + + var seen = new List(); + var raced = false; + mgr.OnDataChange += (_, e) => + { + if (!raced && Equals(e.Snapshot.Value, 1.0)) + { + raced = true; + mgr.HandleMessage("t/1", """{"v":2.0}"""u8, retained: false); // the ingest wins the race + } + + seen.Add(e.Snapshot.Value); + }; + + await mgr.SubscribeAsync(["P/1"], TimeSpan.Zero, TestContext.Current.CancellationToken); + + raced.ShouldBeTrue("the interleaving under test must actually have happened"); + mgr.Values.Read("P/1").Value.ShouldBe(2.0); + seen[^1].ShouldBe(2.0); + } + + /// Control: with no concurrent delivery the replay raises exactly once. + [Fact] + public async Task The_initial_replay_raises_once_when_nothing_races_it() + { + var mgr = new MqttSubscriptionManager(new MqttDriverOptions { Mode = MqttMode.Plain }, "mqtt-1", new PoisonTransport(null)); + mgr.Register([Tag("P/1", "t/1")]); + mgr.HandleMessage("t/1", """{"v":1.0}"""u8, retained: false); + + var seen = new List(); + mgr.OnDataChange += (_, e) => seen.Add(e.Snapshot.Value); + await mgr.SubscribeAsync(["P/1"], TimeSpan.Zero, TestContext.Current.CancellationToken); + + seen.ShouldBe([1.0]); + } + + // --------------------------------------------------------------------------------- + // M-12 — JSONPath evaluation allocates nothing per segment + // --------------------------------------------------------------------------------- + + [Fact] + public void JsonPath_evaluation_allocates_no_segment_strings() + { + using var doc = System.Text.Json.JsonDocument.Parse("""{"a":{"b":{"c":[1.5,2.5]}},"x":{"y":1}}"""); + var root = doc.RootElement; + + // Warm up (JIT, statics). + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$.a.b['c'][1]", out _).ShouldBeTrue(); + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 1000; i++) + { + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$.a.b['c'][1]", out _); + } + + (GC.GetAllocatedBytesForCurrentThread() - before).ShouldBeLessThan(1000); + + // Positive control: the span-based walk still selects the right element. + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$.a.b['c'][1]", out var v).ShouldBeTrue(); + v.GetDouble().ShouldBe(2.5); + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$[\"x\"].y", out var y).ShouldBeTrue(); + y.GetInt32().ShouldBe(1); + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$.*", out _).ShouldBeFalse(); + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$..a", out _).ShouldBeFalse(); + MqttSubscriptionManager.TryEvaluateJsonPath(root, "$.a.b.c[ 0 ]", out var c0).ShouldBeTrue(); + c0.GetDouble().ShouldBe(1.5); + } + + // --------------------------------------------------------------------------------- + // M-15 — Scalar/Raw booleans publish the lower-case text every consumer compares against + // --------------------------------------------------------------------------------- + + [Theory] + [InlineData("Scalar", true, "true")] + [InlineData("Scalar", false, "false")] + [InlineData("Raw", true, "true")] + [InlineData("Json", true, "true")] + public void Boolean_writes_publish_lower_case(string format, bool value, string expected) + { + MqttTagDefinitionFactory.FromTagConfig( + $$"""{"topic":"t/b","writeTopic":"t/b/set","payloadFormat":"{{format}}","dataType":"Boolean"}""", + "P/b", + out var def).ShouldBeTrue(); + + MqttWriteEncoder.TryEncode(MqttMode.Plain, def, value, out var encoded).ShouldBe(MqttWriteEncodeError.None); + Encoding.UTF8.GetString(encoded.Payload).ShouldBe(expected); + } + + /// + /// A fake SUBSCRIBE transport that throws a client-side protocol violation for any batch carrying + /// poison — the shape MQTTnet produces for a malformed filter — or a session failure. + /// + private sealed class PoisonTransport(string? poison) : IMqttSubscribeTransport + { + public int Calls { get; private set; } + + public List Granted { get; } = []; + + public Exception? SessionFailure { get; init; } + + public Task> SubscribeAsync( + IReadOnlyList filters, CancellationToken cancellationToken) + { + Calls++; + if (SessionFailure is not null) + { + throw SessionFailure; + } + + if (poison is not null && filters.Any(f => f.Topic == poison)) + { + throw new MqttProtocolViolationException($"'{poison}' is not acceptable"); + } + + Granted.AddRange(filters.Select(f => f.Topic)); + IReadOnlyList outcomes = + [.. filters.Select(f => new MqttSubscribeOutcome(f.Topic, true, "GrantedQoS1"))]; + return Task.FromResult(outcomes); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugArrayIngestTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugArrayIngestTests.cs index 233ff7d4a..e9f3f30a9 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugArrayIngestTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugArrayIngestTests.cs @@ -253,6 +253,74 @@ public sealed class SparkplugArrayIngestTests snapshot.Value.ShouldBeOfType().ShouldBe(new short[] { 1, -1 }); } + // ---- #988 review M-11: a same-type array is not boxed element by element ---- + + /// + /// A 4,096-element DoubleArray onto a Float64 array tag used to be copied through object + /// (a box out of GetValue, another out of the coercion, an unbox in SetValue) — ~200 KB of + /// garbage per delivery on the dispatcher thread for a 32 KB vector. The decoded array is already the + /// answer; allocation must now stay near the vector size (decode + one defensive copy). + /// + [Fact] + public async Task A_same_type_array_delivery_allocates_near_the_vector_size() + { + var (ing, seen) = await SubscribedAsync(ArrayBlob()); + const int count = 4096; + var values = Enumerable.Range(0, count).Select(i => i * 0.5).ToArray(); + Birth(ing, TahuDataType.DoubleArray, Doubles(values)); + + var data = new Payload { Seq = 2UL, Timestamp = 1721822405000UL }; + data.Metrics.Add(new Payload.Types.Metric { Alias = ArrAlias, BytesValue = ByteString.CopyFrom(Doubles(values)) }); + var decoded = Decode(data); + + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), decoded); // warm-up + var data2 = new Payload { Seq = 3UL, Timestamp = 1721822405000UL }; + data2.Metrics.Add(new Payload.Types.Metric { Alias = ArrAlias, BytesValue = ByteString.CopyFrom(Doubles(values)) }); + var decoded2 = Decode(data2); + + var before = GC.GetAllocatedBytesForCurrentThread(); + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), decoded2); + var allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + allocated.ShouldBeLessThan(count * sizeof(double) * 3L); + + // Positive control: the value is still the right vector, typed double[]. + seen[^1].StatusCode.ShouldBe(Good); + seen[^1].Value.ShouldBeOfType().ShouldBe(values); + } + + /// Two tags bound to one array metric never share (and so can never corrupt) one array instance. + [Fact] + public async Task Two_tags_on_one_array_metric_get_distinct_arrays() + { + const string second = "Plant/Mqtt/spb/ProfileMirror"; + var ing = NewIngestor( + [ + new RawTagEntry(ArrPath, ArrayBlob(), WriteIdempotent: false), + new RawTagEntry(second, ArrayBlob(), WriteIdempotent: false), + ]); + await ing.SubscribeAsync([ArrPath, second], TimeSpan.Zero, TestContext.Current.CancellationToken); + + Birth(ing, TahuDataType.Int32Array, Int32s(1, 2, 3)); + + var a = ing.Values.Read(ArrPath).Value.ShouldBeOfType(); + var b = ing.Values.Read(second).Value.ShouldBeOfType(); + a.ShouldBe(new[] { 1, 2, 3 }); + b.ShouldBe(new[] { 1, 2, 3 }); + ReferenceEquals(a, b).ShouldBeFalse(); + } + + private static byte[] Doubles(double[] values) + { + var bytes = new byte[values.Length * 8]; + for (var i = 0; i < values.Length; i++) + { + BinaryPrimitives.WriteDoubleLittleEndian(bytes.AsSpan(i * 8), values[i]); + } + + return bytes; + } + // ---- helpers ---- private static string ArrayBlob(string? dataType = null, uint? arrayLength = null) diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugIngestorTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugIngestorTests.cs index 259554b93..2c0fc6679 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugIngestorTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugIngestorTests.cs @@ -1,4 +1,5 @@ using Google.Protobuf; +using Microsoft.Extensions.Logging; using Org.Eclipse.Tahu.Protobuf; using Shouldly; using Xunit; @@ -1337,6 +1338,283 @@ public sealed class SparkplugIngestorTests publish.Topics.ShouldNotBeEmpty(); } + // --------------------------------------------------------------------------------- + // #988 review M-1 — the give-up counter is not re-armed by the NBIRTH it provoked + // --------------------------------------------------------------------------------- + + private const string Filler3Path = "Plant/Mqtt/spb/Filler3Temp"; + + /// + /// The report's scenario: Filler3 publishes DDATA but its DBIRTH never lands (over the payload ceiling, + /// or never sent). Every rebirth request is answered by an NBIRTH + the healthy siblings' DBIRTHs — + /// which used to reset the counter, so the node was commanded every debounce period forever and every + /// tag under it blipped Bad→Good. Now at most the cap's worth of NCMDs go out and the operator is told + /// once. A clean sibling DDATA each round must not re-arm Filler3 either. + /// + [Fact] + public async Task A_device_whose_birth_never_lands_is_asked_at_most_the_cap_despite_answering_nbirths() + { + var publish = new RecordingPublishTransport(); + var log = new MessageCapturingLogger(); + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var ing = await NewSubscribedIngestorAsync( + publish, + rebirthDebounce: TimeSpan.FromSeconds(10), + extraTags: [Tag(Filler3Path, Blob(Group, Node, "Filler3", "Temperature", "Float32"))], + logger: log, + utcNow: () => now); + + FeedBirths(ing); + for (var round = 0; round < 10; round++) + { + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 2, (TempAlias, TahuDataType.Float, 1f))); + ing.Dispatch(Topic(SparkplugMessageType.DDATA, "Filler3"), Ddata(seq: 3, (TempAlias, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + + now += TimeSpan.FromSeconds(11); + + // The node answers the NCMD — NBIRTH + the healthy device's DBIRTH; Filler3's never arrives. + FeedBirths(ing); + } + + publish.Topics.Count.ShouldBeLessThanOrEqualTo(3); + publish.Topics.ShouldNotBeEmpty("positive control: the first requests really are sent"); + log.Warnings.Count(m => m.Contains("giving up", StringComparison.Ordinal)).ShouldBe(1); + } + + /// The same loop for a DATA alias the (accepted) birth never declares. + [Fact] + public async Task An_undeclared_alias_is_asked_about_at_most_the_cap_despite_answering_births() + { + var publish = new RecordingPublishTransport(); + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var ing = await NewSubscribedIngestorAsync( + publish, rebirthDebounce: TimeSpan.FromSeconds(10), utcNow: () => now); + + FeedBirths(ing); + for (var round = 0; round < 10; round++) + { + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 2, (4242UL, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + now += TimeSpan.FromSeconds(11); + FeedBirths(ing); + } + + publish.Topics.Count.ShouldBeLessThanOrEqualTo(3); + publish.Topics.ShouldNotBeEmpty(); + } + + /// + /// Consecutive, not cumulative: once the scope's data resolves cleanly the request worked, and a + /// later, unrelated metadata gap is asked about again. + /// + [Fact] + public async Task Clean_data_rearms_the_metadata_rebirth_cap() + { + var publish = new RecordingPublishTransport(); + var ing = await NewSubscribedIngestorAsync(publish); + + FeedBirths(ing); + for (var i = 0; i < 5; i++) + { + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: (ulong)(2 + i), (4242UL, TahuDataType.Float, 1f))); + } + + await ing.DrainPendingRebirthsAsync(); + publish.Topics.Count.ShouldBe(3, "capped"); + + // Evidence the metadata is now usable: a DDATA every metric of which resolves. + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 7, (TempAlias, TahuDataType.Float, 1f))); + publish.Topics.Clear(); + + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 8, (4242UL, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + + publish.Topics.ShouldNotBeEmpty(); + } + + /// + /// The gap path had no cap at all: a node that never maintains seq (always 0, or two publishers + /// under one edge-node id) was commanded every debounce period forever. After the cap's worth of + /// consecutive gap rebirths it now escalates to the long floor. + /// + [Fact] + public async Task A_node_that_never_maintains_seq_escalates_the_gap_rebirth_floor() + { + var publish = new RecordingPublishTransport(); + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var ing = await NewSubscribedIngestorAsync( + publish, rebirthDebounce: TimeSpan.FromSeconds(10), utcNow: () => now); + + FeedBirths(ing); + for (var i = 0; i < 20; i++) + { + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 0, (TempAlias, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + now += TimeSpan.FromSeconds(11); + } + + publish.Topics.Count.ShouldBe(3, "three gap rebirths at the debounce rate, then the escalated floor"); + + // …and the floor is a floor, not a permanent stop. + now += TimeSpan.FromMinutes(5); + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 0, (TempAlias, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + publish.Topics.Count.ShouldBe(4); + } + + /// Control: a one-off gap followed by a contiguous stream keeps the plain debounce cadence. + [Fact] + public async Task A_contiguous_message_after_a_gap_rearms_the_plain_debounce() + { + var publish = new RecordingPublishTransport(); + var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc); + var ing = await NewSubscribedIngestorAsync( + publish, rebirthDebounce: TimeSpan.FromSeconds(10), utcNow: () => now); + + FeedBirths(ing); + ulong seq = 2; + for (var i = 0; i < 6; i++) + { + seq += 2; // a gap + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: seq, (TempAlias, TahuDataType.Float, 1f))); + seq += 1; // then contiguous + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: seq, (TempAlias, TahuDataType.Float, 1f))); + await ing.DrainPendingRebirthsAsync(); + now += TimeSpan.FromSeconds(11); + } + + publish.Topics.Count.ShouldBe(6); + } + + // --------------------------------------------------------------------------------- + // #988 review M-12 — an unauthored node's message costs nothing on the dispatcher thread + // --------------------------------------------------------------------------------- + + /// + /// A group where this driver authors 2 of 200 edge nodes pays the discard path for 99% of traffic. It + /// used to split the topic into a record and box the Debug-log arguments even with Debug off. + /// + [Fact] + public async Task An_unauthored_node_message_allocates_nothing_with_debug_off() + { + var log = new MessageCapturingLogger(); // Information and above only + var ing = await NewSubscribedIngestorAsync(new RecordingPublishTransport(), logger: log); + const string topic = "spBv1.0/Plant1/DDATA/SomeOtherNode/Dev7"; + var wire = new Payload { Seq = 1UL }.ToByteArray(); + + ing.HandleMessage(topic, wire, retained: false); // warm-up + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < 1000; i++) + { + ing.HandleMessage(topic, wire, retained: false); + } + + (GC.GetAllocatedBytesForCurrentThread() - before).ShouldBeLessThan(1000); + + // Positive control: an AUTHORED node's message on the same path is still ingested. + var raised = new List(); + ing.OnDataChange += (_, e) => raised.Add(e.FullReference); + ing.HandleMessage("spBv1.0/Plant1/NBIRTH/EdgeA", NbirthBytes(seq: 0, bdSeq: 1), retained: false); + raised.ShouldContain(NodeUptimePath); + } + + [Theory] + [InlineData("spBv1.0/G/NDATA/N", "G", "N")] + [InlineData("spBv1.0/G/DDATA/N/D", "G", "N")] + [InlineData("spBv1.0/STATE/host", null, null)] + [InlineData("STATE/host", null, null)] + [InlineData("spBv1.0/G", null, null)] + [InlineData("spBv1.0/G/NDATA", null, null)] + [InlineData("spBv1.0//NDATA/N", null, null)] + [InlineData("other/G/NDATA/N", null, null)] + public void TryPeekEdgeNode_reads_group_and_node_or_defers(string topic, string? group, string? node) + { + var ok = SparkplugTopic.TryPeekEdgeNode(topic, out var g, out var n); + ok.ShouldBe(group is not null); + if (ok) + { + g.ToString().ShouldBe(group); + n.ToString().ShouldBe(node); + } + } + + /// + /// #988 review M-9 (Sparkplug): the subscribe-time replay of a cached metric must not land after — and so + /// overwrite — a newer DDATA the dispatcher raised while the replay was in flight. + /// + [Fact] + public async Task The_initial_replay_never_leaves_a_stale_metric_last() + { + var ing = NewIngestor(new RecordingPublishTransport()); + FeedBirths(ing); // caches Temperature = 0 from the DBIRTH, before any subscription + + var seen = new List(); + var raced = false; + ing.OnDataChange += (_, e) => + { + if (e.FullReference != TempPath) + { + return; + } + + if (!raced) + { + raced = true; + ing.Dispatch(Topic(SparkplugMessageType.DDATA, Device), Ddata(seq: 2, (TempAlias, TahuDataType.Float, 5f))); + } + + seen.Add(e.Snapshot.Value); + }; + + await ing.SubscribeAsync([TempPath], TimeSpan.Zero, TestContext.Current.CancellationToken); + + raced.ShouldBeTrue(); + ing.Values.Read(TempPath).Value.ShouldBe(5f); + seen[^1].ShouldBe(5f); + } + + /// Captures formatted warning text. + private sealed class MessageCapturingLogger : ILogger + { + private readonly List _warnings = []; + + public IReadOnlyList Warnings + { + get + { + lock (_warnings) + { + return [.. _warnings]; + } + } + } + + public IDisposable? BeginScope(TState state) + where TState : notnull + => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information; + + public void Log( + LogLevel logLevel, + EventId eventId, + TState state, + Exception? exception, + Func formatter) + { + if (logLevel != LogLevel.Warning) + { + return; + } + + lock (_warnings) + { + _warnings.Add(formatter(state, exception)); + } + } + } + // --------------------------------------------------------------------------------- // Value-level gates // --------------------------------------------------------------------------------- @@ -1499,7 +1777,9 @@ public sealed class SparkplugIngestorTests TimeSpan? rebirthDebounce = null, int maxPayloadBytes = MqttSubscriptionManager.DefaultMaxPayloadBytes, RawTagEntry[]? tags = null, - RawTagEntry[]? extraTags = null) + RawTagEntry[]? extraTags = null, + ILogger? logger = null, + Func? utcNow = null) { var options = new MqttDriverOptions { @@ -1517,12 +1797,13 @@ public sealed class SparkplugIngestorTests "mqtt-spb-1", subscribe, publish, - logger: null, + logger: logger, cache: null, maxPayloadBytes: maxPayloadBytes, // Zero by default so a test asserting "these two triggers each produce an NCMD" is not // silently satisfied by the production debounce; the debounce itself has its own tests. - rebirthDebounce: rebirthDebounce ?? TimeSpan.Zero); + rebirthDebounce: rebirthDebounce ?? TimeSpan.Zero, + utcNow: utcNow); ingestor.Register([.. tags ?? DefaultTags(), .. extraTags ?? []]); return ingestor; @@ -1534,14 +1815,18 @@ public sealed class SparkplugIngestorTests FakeSubscribeTransport? subscribe = null, bool requestRebirthOnGap = true, TimeSpan? rebirthDebounce = null, - RawTagEntry[]? extraTags = null) + RawTagEntry[]? extraTags = null, + ILogger? logger = null, + Func? utcNow = null) { var ingestor = NewIngestor( publish, subscribe, requestRebirthOnGap: requestRebirthOnGap, rebirthDebounce: rebirthDebounce, - extraTags: extraTags); + extraTags: extraTags, + logger: logger, + utcNow: utcNow); await ingestor.SubscribeAsync( [.. ingestor.AuthoredRawPaths], diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs index 48657c28b..fe80256f8 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Mqtt.Tests/SparkplugPrimaryHostTests.cs @@ -149,6 +149,85 @@ public sealed class SparkplugPrimaryHostTests claim.ShouldBe("otopcua-spbhost"); } + /// + /// #988 review M-3: with the recommended blank clientId the claim id was the literal + /// -spbhost, the one fixed, fleet-wide id — two drivers claiming on one broker (two Sparkplug + /// groups need two drivers) evicted each other about once a second, flapping both STATE topics. Each + /// claim now presents its own id. + /// + [Fact] + public void Claims_with_a_blank_client_id_present_distinct_ids() + { + var blank = Options() with { ClientId = null }; + var a = new SparkplugPrimaryHost(blank, "drv-1", new FixedRole(true)); + var b = new SparkplugPrimaryHost(blank with { Sparkplug = blank.Sparkplug! with { GroupId = "Other" } }, "drv-2", new FixedRole(true)); + var whitespace = new SparkplugPrimaryHost(Options() with { ClientId = " " }, "drv-3", new FixedRole(true)); + + a.ClaimClientIdForTests.ShouldNotBe(b.ClaimClientIdForTests); + a.ClaimClientIdForTests.ShouldNotBe(SparkplugPrimaryHost.ClientIdSuffix); + a.ClaimClientIdForTests.ShouldStartWith("spbhost-"); + a.ClaimClientIdForTests.Length.ShouldBeLessThanOrEqualTo(23, "MQTT 3.1.1 servers need only accept 23-character ids"); + whitespace.ClaimClientIdForTests.ShouldNotContain(" "); + + // …and the id is what actually reaches the CONNECT. + MqttClientOptionsFactory.BuildClientOptions(a.ClaimOptionsForTests, a.ClaimClientIdSuffixForTests) + .ClientId.ShouldBe(a.ClaimClientIdForTests); + } + + /// Control: an operator-configured client id keeps its stable, ACL-friendly {clientId}-spbhost. + [Fact] + public void A_configured_client_id_keeps_the_stable_claim_id() + => new SparkplugPrimaryHost(Options(), "drv-1", new FixedRole(true)).ClaimClientIdForTests.ShouldBe("otopcua-spbhost"); + + /// + /// #988 review M-6: the claim connection's supervisor stops for good when a reconnect CONNACK carries an + /// unrecoverable code (here NotAuthorized, e.g. a broker whose auth backend is still loading after + /// a restart). The reconcile loop treated "a connection object exists" as "the claim is held", so the + /// host never published ONLINE again while ingest — reconnected fine — kept the driver Healthy. A Faulted + /// claim is now dropped and re-claimed. + /// + [Trait("Category", "SlowUnit")] + [Fact] + public async Task A_claim_whose_connection_faulted_is_reclaimed() + { + using var broker = new MiniBroker { AckPublish = true }; + var options = Options() with + { + Host = "127.0.0.1", + Port = broker.Port, + UseTls = false, + ProtocolVersion = MqttProtocolVersion.V311, + ConnectTimeoutSeconds = 2, + ReconnectMinBackoffSeconds = 1, + ReconnectMaxBackoffSeconds = 1, + }; + var host = new SparkplugPrimaryHost(options, "drv-1", new FixedRole(shouldActAsPrimary: true)); + await host.StartAsync(TestContext.Current.CancellationToken); + host.IsClaimed.ShouldBeTrue(); + OnlinePublishes(broker).ShouldBe(1); + + // The broker refuses the claim's reconnect with an unrecoverable code → the supervisor faults. + broker.ConnAckReturnCode = MiniBroker.ReturnCodeNotAuthorized; + broker.DropAll(); + (await WaitUntilAsync(() => host.ClaimConnectionStateForTests == MqttConnectionState.Faulted, TimeSpan.FromSeconds(15))) + .ShouldBeTrue("the claim connection must fault on the unrecoverable CONNACK"); + host.IsClaimed.ShouldBeFalse("a Faulted claim is not a held claim"); + + // The broker recovers; the reconcile loop must claim afresh and republish ONLINE. + broker.ConnAckReturnCode = MiniBroker.ReturnCodeAccepted; + (await WaitUntilAsync(() => OnlinePublishes(broker) >= 2, TimeSpan.FromSeconds(20))) + .ShouldBeTrue("the host must re-claim and publish ONLINE again"); + host.IsClaimed.ShouldBeTrue(); + + await host.DisposeAsync(); + } + + private static int OnlinePublishes(MiniBroker broker) => + broker.Published.Count(p => + p.Topic == "spBv1.0/STATE/otopcua-primary" + && SparkplugStatePayload.TryDecode(p.Payload, out var online, out _) + && online); + // ---- Whether a claim is attempted at all ----------------------------------------------------- [Fact]