fix(dcl): seeds never overwrite a newer live value; Good on reconnect resets only the subscribe backoff (DCL-1, SRT-6, WP3 tasks 3.1 + 3.8)
3.1: seed values are flagged on TagValueReceived; a reconnect/resolution re-seed for a tag that already delivered a live value in the current adapter generation is dropped, an initial-subscribe seed is replaced by the latest live value (a joining instance may have missed earlier live values). 3.8: the connection actor tells subscribers ConnectionQualityChanged(Good) on re-entering Connected; InstanceActor's Good branch only resets the Lever-1 backoff and no longer stamps bound attributes Good.
This commit is contained in:
@@ -300,7 +300,7 @@ Three subscribe paths, deliberately paced differently:
|
||||
| **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. |
|
||||
| **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. |
|
||||
|
||||
Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21).
|
||||
Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed is additionally bound to its session: entering Reconnecting, an adapter swap or actor stop cancels it, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed.
|
||||
|
||||
**OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered.
|
||||
|
||||
|
||||
@@ -219,7 +219,7 @@ flowchart TD
|
||||
2. Set quality to **uncertain** for all attributes that have a data source reference. Static attributes (no data source reference) have quality **good**. The uncertain quality persists until the first value update arrives from the Data Connection Layer, distinguishing "not yet received" from "known good" or "connection lost."
|
||||
3. Register data source references with the Data Connection Layer for subscriptions.
|
||||
|
||||
> **Tag-subscribe retry (S4/UA6, hardened by Lever 1 of the MxGateway subscribe-storm design, 2026-08-28).** The Instance Actor groups its data-sourced tag paths by connection and sends one `SubscribeTagsRequest` per connection, arming a per-connection watchdog *on send* so both a failed reply and a lost reply are retried. **At most one request per connection is outstanding:** a watchdog tick while the in-flight request is younger than `TagSubscribeInFlightCeilingMs` (45 s, sized above the gateway's 30 s command deadline) only re-arms — it never issues a duplicate — so a gateway that is slow to answer is not handed a fresh N-tag subscribe every interval on top of the one it is still processing (the amplifier behind the 2026-08-26 QA freeze). Past the ceiling the reply is presumed lost and a new request goes out; a late reply for the superseded id is ignored. The retry interval is exponential: floor `TagSubscribeRetryIntervalMs` (5 s), ×2 with ±20 % jitter per failed/lost attempt, capped at `TagSubscribeRetryMaxIntervalMs` (60 s); a `Success` reply or the connection returning to `Good` quality resets it to the floor — but the `Good` reset does **not** release an outstanding request (it still owns the connection until the ceiling), so it shortens the wait only when nothing is in flight; and once the backed-off interval exceeds the ceiling the guard is inert on ticks and the interval itself is the rate limit (one re-send per 60 s at the defaults). All three keys are startup-validated (`SiteRuntimeOptionsValidator`). Design: `docs/plans/2026-08-28-mxgateway-subscribe-storm-prevention-design.md` §3; plan: `docs/plans/2026-08-28-tag-subscribe-inflight-guard-backoff.md`.
|
||||
> **Tag-subscribe retry (S4/UA6, hardened by Lever 1 of the MxGateway subscribe-storm design, 2026-08-28).** The Instance Actor groups its data-sourced tag paths by connection and sends one `SubscribeTagsRequest` per connection, arming a per-connection watchdog *on send* so both a failed reply and a lost reply are retried. **At most one request per connection is outstanding:** a watchdog tick while the in-flight request is younger than `TagSubscribeInFlightCeilingMs` (45 s, sized above the gateway's 30 s command deadline) only re-arms — it never issues a duplicate — so a gateway that is slow to answer is not handed a fresh N-tag subscribe every interval on top of the one it is still processing (the amplifier behind the 2026-08-26 QA freeze). Past the ceiling the reply is presumed lost and a new request goes out; a late reply for the superseded id is ignored. The retry interval is exponential: floor `TagSubscribeRetryIntervalMs` (5 s), ×2 with ±20 % jitter per failed/lost attempt, capped at `TagSubscribeRetryMaxIntervalMs` (60 s); a `Success` reply or the connection returning to `Good` quality (the DCL connection actor sends `ConnectionQualityChanged(Good)` to its subscribers when it re-enters Connected after a reconnect — 2026-12-02 review SRT-6; before that the reset was dead code) resets it to the floor. `Good` is a **restore signal only**: unlike `Bad`, it does **not** stamp the bound attributes `Good` with their pre-outage last-known values — their quality comes back through the DCL's re-subscribe and re-seed as ordinary `TagValueUpdate`s — but the `Good` reset does **not** release an outstanding request (it still owns the connection until the ceiling), so it shortens the wait only when nothing is in flight; and once the backed-off interval exceeds the ceiling the guard is inert on ticks and the interval itself is the rate limit (one re-send per 60 s at the defaults). All three keys are startup-validated (`SiteRuntimeOptionsValidator`). Design: `docs/plans/2026-08-28-mxgateway-subscribe-storm-prevention-design.md` §3; plan: `docs/plans/2026-08-28-tag-subscribe-inflight-guard-backoff.md`.
|
||||
|
||||
4. Create child Script Actors (one per script defined on the instance).
|
||||
5. Create child Alarm Actors (one per alarm defined on the instance).
|
||||
|
||||
@@ -1260,6 +1260,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
ReSubscribeAllAlarms();
|
||||
|
||||
BecomeConnected();
|
||||
PushConnectionRestored();
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -1970,7 +1971,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
foreach (var seed in msg.SeedValues)
|
||||
{
|
||||
if (_subscriptionIds.ContainsKey(seed.TagPath))
|
||||
Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration));
|
||||
Self.Tell(new TagValueReceived(seed.TagPath, seed.Value, _adapterGeneration, SeedKind.InitialSubscribe));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2633,7 +2634,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
{
|
||||
var seeds = await SeedTagsAsync(adapter, resolved);
|
||||
foreach (var seed in seeds)
|
||||
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation));
|
||||
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -2819,6 +2820,27 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
ScheduleTagResolutionRetry();
|
||||
}
|
||||
|
||||
// ── Connection-restored signal ──
|
||||
|
||||
/// <summary>
|
||||
/// SRT-6 / WP3 task 3.8: tells every subscriber <c>ConnectionQualityChanged(Good)</c> when the
|
||||
/// connection re-enters Connected after a reconnect. It is a RESTORE SIGNAL only — the Instance
|
||||
/// Actor uses it to reset its Lever-1 tag-subscribe backoff so a subscribe that failed during
|
||||
/// the outage is retried at the floor instead of up to <c>TagSubscribeRetryMaxIntervalMs</c>
|
||||
/// later. It deliberately says nothing about any tag's value: per-tag quality is restored by
|
||||
/// the re-subscribe and the re-seed, and the Instance Actor must not stamp bound attributes
|
||||
/// Good with their last-known values before the device re-reports.
|
||||
/// </summary>
|
||||
private void PushConnectionRestored()
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
foreach (var instanceName in _subscriptionsByInstance.Keys)
|
||||
{
|
||||
if (_subscribers.TryGetValue(instanceName, out var subscriber))
|
||||
subscriber.Tell(new ConnectionQualityChanged(_connectionName, QualityCode.Good, now));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bad Quality Push ──
|
||||
|
||||
private void PushBadQualityForAllTags()
|
||||
@@ -2993,7 +3015,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
{
|
||||
var seeds = await SeedTagsAsync(reseedAdapter, allTags, reseedToken);
|
||||
foreach (var seed in seeds)
|
||||
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation));
|
||||
self.Tell(new TagValueReceived(seed.TagPath, seed.Value, generation, SeedKind.Reseed));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -3041,9 +3063,24 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
private void UnindexTag(string tag, string instance)
|
||||
{
|
||||
if (_instancesByTag.TryGetValue(tag, out var insts) && insts.Remove(instance) && insts.Count == 0)
|
||||
{
|
||||
_instancesByTag.Remove(tag);
|
||||
_lastLiveValue.Remove(tag);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DCL-1: the latest LIVE (subscription-delivered, non-seed) value per tag in the generation
|
||||
/// recorded in <see cref="_liveValuesGeneration"/>. A tag present here has already delivered a
|
||||
/// live value in the current subscribe generation, so a later seed for it is stale. Cleared
|
||||
/// lazily when the adapter generation advances (every reconnect / adapter swap); an entry is
|
||||
/// dropped when the tag loses its last subscriber.
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, TagValue> _lastLiveValue = new();
|
||||
|
||||
/// <summary>The adapter generation <see cref="_lastLiveValue"/> belongs to.</summary>
|
||||
private int _liveValuesGeneration = -1;
|
||||
|
||||
private void HandleTagValueReceived(TagValueReceived msg)
|
||||
{
|
||||
// Drop values delivered by a disposed adapter. After a
|
||||
@@ -3064,6 +3101,38 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
if (!_instancesByTag.TryGetValue(msg.TagPath, out var interestedInstances))
|
||||
return;
|
||||
|
||||
// DCL-1: a seed must never overwrite a newer live value. The subscription is live
|
||||
// before the seed read starts, and a seed is held until its whole seed operation
|
||||
// completes, so a live change inside that window would otherwise be regressed to the
|
||||
// older seed value — with Good quality, indefinitely, for a tag that changes rarely.
|
||||
// The rule is generation-based (decided 2026-12-03), NOT a timestamp comparison,
|
||||
// which would depend on device/server clocks and the configured timestamp mode.
|
||||
if (_liveValuesGeneration != _adapterGeneration)
|
||||
{
|
||||
_lastLiveValue.Clear();
|
||||
_liveValuesGeneration = _adapterGeneration;
|
||||
}
|
||||
var value = msg.Value;
|
||||
if (msg.Seed == SeedKind.None)
|
||||
{
|
||||
_lastLiveValue[msg.TagPath] = value;
|
||||
}
|
||||
else if (_lastLiveValue.TryGetValue(msg.TagPath, out var latestLive))
|
||||
{
|
||||
if (msg.Seed == SeedKind.Reseed)
|
||||
{
|
||||
// Every interested instance was registered while the subscription was live,
|
||||
// so each already holds the live value: drop the seed outright.
|
||||
_log.Debug("[{0}] Dropping seed for {1}: a live value already arrived in generation {2}",
|
||||
_connectionName, msg.TagPath, _adapterGeneration);
|
||||
return;
|
||||
}
|
||||
|
||||
// Initial subscribe: the joining instance may have missed live values delivered
|
||||
// before it registered, so re-deliver the LATEST live value instead of the seed.
|
||||
value = latestLive;
|
||||
}
|
||||
|
||||
// Fan out to exactly the instances subscribed to this tag via the reverse index —
|
||||
// O(subscribers of this tag) instead of scanning every instance's tag set per update.
|
||||
foreach (var instanceName in interestedInstances)
|
||||
@@ -3071,7 +3140,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
if (_subscribers.TryGetValue(instanceName, out var subscriber))
|
||||
{
|
||||
subscriber.Tell(new TagValueUpdate(
|
||||
_connectionName, msg.TagPath, msg.Value.Value, msg.Value.Quality, msg.Value.Timestamp));
|
||||
_connectionName, msg.TagPath, value.Value, value.Quality, value.Timestamp));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3082,7 +3151,7 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
// 30s. Now: unchanged quality is a no-op; a genuine transition updates the buckets
|
||||
// and arms the coalescing flush timer.
|
||||
var hadPrevious = _lastTagQuality.TryGetValue(msg.TagPath, out var prevQuality);
|
||||
if (hadPrevious && prevQuality == msg.Value.Quality)
|
||||
if (hadPrevious && prevQuality == value.Quality)
|
||||
return;
|
||||
|
||||
if (hadPrevious)
|
||||
@@ -3096,13 +3165,13 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
}
|
||||
}
|
||||
// Increment new quality bucket
|
||||
switch (msg.Value.Quality)
|
||||
switch (value.Quality)
|
||||
{
|
||||
case QualityCode.Good: _tagsGoodQuality++; break;
|
||||
case QualityCode.Bad: _tagsBadQuality++; break;
|
||||
case QualityCode.Uncertain: _tagsUncertainQuality++; break;
|
||||
}
|
||||
_lastTagQuality[msg.TagPath] = msg.Value.Quality;
|
||||
_lastTagQuality[msg.TagPath] = value.Quality;
|
||||
MarkQualityDirty();
|
||||
}
|
||||
|
||||
@@ -3593,7 +3662,35 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
||||
/// swapped-out adapter can be dropped (<see cref="IsStaleDisconnect"/>).
|
||||
/// </summary>
|
||||
internal record AdapterDisconnected(int AdapterGeneration);
|
||||
internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration);
|
||||
/// <summary>
|
||||
/// A tag value marshalled onto the actor thread. <paramref name="Seed"/> marks a value that
|
||||
/// came from a seed READ rather than the live subscription (DCL-1): a seed is held until its
|
||||
/// whole seed operation completes (up to <see cref="DataConnectionOptions.SeedOverallTimeout"/>),
|
||||
/// so it can be older than a live value the subscription has already delivered.
|
||||
/// </summary>
|
||||
internal record TagValueReceived(string TagPath, TagValue Value, int AdapterGeneration, SeedKind Seed = SeedKind.None);
|
||||
|
||||
/// <summary>Origin of a <see cref="TagValueReceived"/> (DCL-1).</summary>
|
||||
internal enum SeedKind
|
||||
{
|
||||
/// <summary>A live subscription notification.</summary>
|
||||
None,
|
||||
|
||||
/// <summary>
|
||||
/// A seed read for tags every interested instance was already registered for while the
|
||||
/// subscription was live: the reconnect re-seed and the tag-resolution re-seed. Dropped
|
||||
/// when the tag already delivered a live value in the current generation.
|
||||
/// </summary>
|
||||
Reseed,
|
||||
|
||||
/// <summary>
|
||||
/// The seed read of an initial <see cref="SubscribeTagsRequest"/>. The requesting instance
|
||||
/// may have joined a tag that was ALREADY live for another instance, so it never saw the
|
||||
/// earlier live values; when the tag has delivered a live value in the current generation
|
||||
/// the stale seed is replaced by that latest live value rather than dropped outright.
|
||||
/// </summary>
|
||||
InitialSubscribe,
|
||||
}
|
||||
internal record RetryTagResolution;
|
||||
|
||||
/// <summary>Coalescing-timer tick for the tag-quality counter push.</summary>
|
||||
|
||||
@@ -1415,11 +1415,16 @@ public class InstanceActor : ReceiveActor
|
||||
|
||||
private void HandleConnectionQualityChanged(ConnectionQualityChanged qualityChanged)
|
||||
{
|
||||
_logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}",
|
||||
qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName);
|
||||
if (qualityChanged.Quality == QualityCode.Good)
|
||||
_logger.LogInformation("Connection {Connection} restored for instance {Instance}",
|
||||
qualityChanged.ConnectionName, _instanceUniqueName);
|
||||
else
|
||||
_logger.LogWarning("Connection {Connection} quality changed to {Quality} for instance {Instance}",
|
||||
qualityChanged.ConnectionName, qualityChanged.Quality, _instanceUniqueName);
|
||||
|
||||
// Lever 1 (2026-08-28): a connection returning to Good is the Instance Actor's
|
||||
// only restore signal (the DCL re-subscribes transparently). If our own subscribe
|
||||
// only restore signal (the DCL re-subscribes transparently; it sends Good when the
|
||||
// connection re-enters Connected — SRT-6, WP3 task 3.8). If our own subscribe
|
||||
// on it is still unconfirmed, retry at the floor now rather than in up to
|
||||
// TagSubscribeRetryMaxIntervalMs — recovery must be prompt. Timer != null ⇔ the
|
||||
// subscribe is unconfirmed (it is only nulled by a Success); if a request is in
|
||||
@@ -1436,6 +1441,12 @@ public class InstanceActor : ReceiveActor
|
||||
ArmTagSubscribeWatchdog(qualityChanged.ConnectionName, subState);
|
||||
}
|
||||
|
||||
// Good is a restore signal ONLY (decided 2026-12-03, SRT-6): it must NOT stamp the
|
||||
// bound attributes Good with their last-known values — those values are from before
|
||||
// the outage, and the device has not re-reported yet. Per-tag quality comes back
|
||||
// through the DCL's re-subscribe and re-seed as ordinary TagValueUpdates.
|
||||
if (qualityChanged.Quality == QualityCode.Good) return;
|
||||
|
||||
if (_configuration == null) return;
|
||||
|
||||
// Mark all attributes bound to this connection with the new quality
|
||||
|
||||
+2
@@ -188,6 +188,8 @@ public class DataConnectionReconfigureTests : TestKit
|
||||
ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
||||
|
||||
AwaitCondition(() => Subscribed(newAdapter), TimeSpan.FromSeconds(5));
|
||||
// Re-entering Connected tells the subscriber Good (SRT-6 restore signal).
|
||||
ExpectMsg<ConnectionQualityChanged>(m => m.Quality == QualityCode.Good, TimeSpan.FromSeconds(5));
|
||||
ExpectNoMsg(TimeSpan.FromMilliseconds(300));
|
||||
|
||||
oldCallback!("sensor/temp", new TagValue(999, QualityCode.Good, DateTimeOffset.UtcNow));
|
||||
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Akka.Actor;
|
||||
using Akka.TestKit.Xunit2;
|
||||
using NSubstitute;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors;
|
||||
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;
|
||||
|
||||
/// <summary>
|
||||
/// DCL-1 (2026-12-02 review, WP3 task 3.1): a seed read is held until its whole seed operation
|
||||
/// completes, while the subscription is already live, so a seed can arrive AFTER a newer live value.
|
||||
/// Decided rule: a seed for a tag that has already delivered a live value in the current subscribe
|
||||
/// generation never overwrites it. Also covers SRT-6 / task 3.8 — the connection actor tells its
|
||||
/// subscribers <c>ConnectionQualityChanged(Good)</c> when it re-enters Connected.
|
||||
/// </summary>
|
||||
[Collection("DataConnectionManagerActor")]
|
||||
public class DataConnectionSeedOrderingTests : TestKit
|
||||
{
|
||||
private const string Tag = "Mixer.State";
|
||||
private const string OtherTag = "Mixer.Speed";
|
||||
|
||||
private readonly ISiteHealthCollector _health = Substitute.For<ISiteHealthCollector>();
|
||||
private readonly IDataConnectionFactory _factory = Substitute.For<IDataConnectionFactory>();
|
||||
|
||||
private readonly DataConnectionOptions _options = new()
|
||||
{
|
||||
ReconnectInterval = TimeSpan.FromMilliseconds(100),
|
||||
TagResolutionRetryInterval = TimeSpan.FromSeconds(30),
|
||||
WriteTimeout = TimeSpan.FromSeconds(5),
|
||||
SeedReadMaxAttempts = 1,
|
||||
SeedReadRetryDelay = TimeSpan.FromMilliseconds(10),
|
||||
SubscribeBatchDelay = TimeSpan.Zero
|
||||
};
|
||||
|
||||
private IActorRef CreateConnectionActor(string name, SeedGatedAdapter adapter)
|
||||
{
|
||||
var config = new Dictionary<string, string> { ["Endpoint"] = "opc.tcp://plc:4840" };
|
||||
return Sys.ActorOf(Props.Create(() =>
|
||||
new DataConnectionActor(
|
||||
name, adapter, _options, _health, _factory, "OpcUa", config, null, 3)), name);
|
||||
}
|
||||
|
||||
private void AwaitConnectedCount(string name, int count) =>
|
||||
AwaitCondition(() => _health.ReceivedCalls().Count(c =>
|
||||
c.GetMethodInfo().Name == nameof(ISiteHealthCollector.UpdateConnectionHealth) &&
|
||||
c.GetArguments() is [string n, ConnectionHealth reported, ..] &&
|
||||
n == name && reported == ConnectionHealth.Connected) >= count,
|
||||
TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(10));
|
||||
|
||||
private static TagValue Good(object value) => new(value, QualityCode.Good, DateTimeOffset.UtcNow);
|
||||
|
||||
/// <summary>
|
||||
/// Initial subscribe: the live "Running" arrives while the seed read is still out; the seed
|
||||
/// then returns the older "Idle". The instance must end on "Running" — the stale seed is
|
||||
/// replaced by the latest live value (pre-fix it regressed the attribute to "Idle", Good).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void InitialSubscribe_SeedArrivingAfterLiveValue_DoesNotRegressIt()
|
||||
{
|
||||
const string name = "seed-initial";
|
||||
var adapter = new SeedGatedAdapter();
|
||||
var actor = CreateConnectionActor(name, adapter);
|
||||
AwaitConnectedCount(name, 1);
|
||||
|
||||
var seedGate = adapter.GateNextRead();
|
||||
var instance = CreateTestProbe();
|
||||
instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow));
|
||||
|
||||
// The subscription is live before the seed read returns.
|
||||
adapter.AwaitCallback(Tag)(Tag, Good("Running"));
|
||||
var live = instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Running", live.Value);
|
||||
|
||||
// The seed read (taken before the change) now completes with the older value.
|
||||
seedGate.Release(new Dictionary<string, object> { [Tag] = "Idle" });
|
||||
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
var afterSeed = instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Running", afterSeed.Value); // pre-fix: "Idle"
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A seed for a tag that has delivered NO live value is still delivered — the seed is the
|
||||
/// only value a static tag will ever produce.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void InitialSubscribe_SeedForTagWithNoLiveValue_IsDelivered()
|
||||
{
|
||||
const string name = "seed-static";
|
||||
var adapter = new SeedGatedAdapter();
|
||||
var actor = CreateConnectionActor(name, adapter);
|
||||
AwaitConnectedCount(name, 1);
|
||||
|
||||
var seedGate = adapter.GateNextRead();
|
||||
var instance = CreateTestProbe();
|
||||
instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag], DateTimeOffset.UtcNow));
|
||||
adapter.AwaitCallback(Tag);
|
||||
|
||||
seedGate.Release(new Dictionary<string, object> { [Tag] = "Idle" });
|
||||
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Idle", instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reconnect: the re-subscribe goes live and delivers "Running" while the re-seed is still out;
|
||||
/// the re-seed then returns "Idle" for that tag (dropped) and a value for a tag that has not
|
||||
/// re-reported (delivered). The connection also signals Good on re-entering Connected (3.8).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Reconnect_ReseedArrivingAfterLiveValue_IsDropped_AndGoodIsSignalled()
|
||||
{
|
||||
const string name = "seed-reconnect";
|
||||
var adapter = new SeedGatedAdapter();
|
||||
var actor = CreateConnectionActor(name, adapter);
|
||||
AwaitConnectedCount(name, 1);
|
||||
|
||||
var instance = CreateTestProbe();
|
||||
instance.Send(actor, new SubscribeTagsRequest("c1", "inst1", name, [Tag, OtherTag], DateTimeOffset.UtcNow));
|
||||
instance.ExpectMsg<SubscribeTagsResponse>(r => r.Success, TimeSpan.FromSeconds(5));
|
||||
adapter.ClearCallbacks();
|
||||
|
||||
var reseedGate = adapter.GateNextRead();
|
||||
adapter.RaiseDisconnected();
|
||||
var bad = instance.ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(QualityCode.Bad, bad.Quality);
|
||||
AwaitConnectedCount(name, 2);
|
||||
var good = instance.ExpectMsg<ConnectionQualityChanged>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal(QualityCode.Good, good.Quality); // pre-fix: Good was never sent
|
||||
|
||||
// The new subscription delivers a live change before the re-seed returns.
|
||||
adapter.AwaitCallback(Tag)(Tag, Good("Running"));
|
||||
Assert.Equal("Running", instance.ExpectMsg<TagValueUpdate>(TimeSpan.FromSeconds(5)).Value);
|
||||
|
||||
reseedGate.Release(new Dictionary<string, object> { [Tag] = "Idle", [OtherTag] = 7 });
|
||||
|
||||
// OtherTag never re-reported live, so its seed is delivered; Tag's seed must not be.
|
||||
var seen = new List<TagValueUpdate>();
|
||||
instance.FishForMessage<TagValueUpdate>(u =>
|
||||
{
|
||||
seen.Add(u);
|
||||
return u.TagPath == OtherTag;
|
||||
}, TimeSpan.FromSeconds(5));
|
||||
instance.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
|
||||
Assert.DoesNotContain(seen, u => u.TagPath == Tag); // pre-fix: Tag = "Idle"
|
||||
Assert.Equal(7, seen.Single(u => u.TagPath == OtherTag).Value);
|
||||
}
|
||||
|
||||
/// <summary>One held <c>ReadBatchAsync</c> call.</summary>
|
||||
internal sealed class ReadGate
|
||||
{
|
||||
private readonly TaskCompletionSource<Dictionary<string, object>> _tcs =
|
||||
new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public Task<Dictionary<string, object>> Values => _tcs.Task;
|
||||
|
||||
public void Release(Dictionary<string, object> values) => _tcs.SetResult(values);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Batch-capable adapter whose subscribes succeed at once (capturing each tag's live
|
||||
/// callback) and whose seed reads can be held until the test releases them.
|
||||
/// </summary>
|
||||
internal sealed class SeedGatedAdapter : IDataConnection, IBatchSubscribableConnection
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, SubscriptionCallback> _callbacks = new();
|
||||
private readonly ConcurrentQueue<ReadGate> _readGates = new();
|
||||
private int _handle;
|
||||
|
||||
public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected;
|
||||
|
||||
public event Action? Disconnected;
|
||||
|
||||
public ReadGate GateNextRead()
|
||||
{
|
||||
var gate = new ReadGate();
|
||||
_readGates.Enqueue(gate);
|
||||
return gate;
|
||||
}
|
||||
|
||||
public void ClearCallbacks() => _callbacks.Clear();
|
||||
|
||||
public SubscriptionCallback AwaitCallback(string tag)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (_callbacks.TryGetValue(tag, out var cb))
|
||||
return cb;
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
|
||||
throw new TimeoutException($"No subscription for {tag}.");
|
||||
}
|
||||
|
||||
public void RaiseDisconnected()
|
||||
{
|
||||
Status = ConnectionHealth.Disconnected;
|
||||
Disconnected?.Invoke();
|
||||
}
|
||||
|
||||
public Task ConnectAsync(IDictionary<string, string> connectionDetails, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Status = ConnectionHealth.Connected;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task DisconnectAsync(CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||
|
||||
public Task<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
|
||||
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var rows = new List<TagSubscribeResult>();
|
||||
foreach (var tag in tagPaths)
|
||||
{
|
||||
_callbacks[tag] = callback;
|
||||
rows.Add(new TagSubscribeResult(tag, true, $"h{Interlocked.Increment(ref _handle)}", null));
|
||||
}
|
||||
return Task.FromResult<IReadOnlyList<TagSubscribeResult>>(rows);
|
||||
}
|
||||
|
||||
public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default) =>
|
||||
Task.CompletedTask;
|
||||
|
||||
public Task<string> SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default) =>
|
||||
throw new NotSupportedException("batch-capable adapter");
|
||||
|
||||
public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default) => Task.CompletedTask;
|
||||
|
||||
public Task<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(new ReadResult(false, null, "no value"));
|
||||
|
||||
public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
|
||||
IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var values = _readGates.TryDequeue(out var gate)
|
||||
? await gate.Values
|
||||
: new Dictionary<string, object>();
|
||||
return tagPaths
|
||||
.Where(values.ContainsKey)
|
||||
.ToDictionary(t => t, t => new ReadResult(true,
|
||||
new TagValue(values[t], QualityCode.Good, DateTimeOffset.UtcNow), null));
|
||||
}
|
||||
|
||||
public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(new WriteResult(true, null));
|
||||
|
||||
public Task<IReadOnlyDictionary<string, WriteResult>> WriteBatchAsync(
|
||||
IDictionary<string, object?> values, CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult<IReadOnlyDictionary<string, WriteResult>>(
|
||||
values.ToDictionary(kv => kv.Key, _ => new WriteResult(true, null)));
|
||||
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -1476,6 +1476,8 @@ public class DataConnectionActorTests : TestKit
|
||||
AwaitCondition(() =>
|
||||
backupAdapter.ReceivedCalls().Any(c => c.GetMethodInfo().Name == "SubscribeAsync"),
|
||||
TimeSpan.FromSeconds(5));
|
||||
// Re-entering Connected on the backup tells the subscriber Good (SRT-6 restore signal).
|
||||
ExpectMsg<ConnectionQualityChanged>(m => m.Quality == QualityCode.Good, TimeSpan.FromSeconds(5));
|
||||
await Task.Delay(300); // actor is Connected on backup
|
||||
|
||||
// Drain any value updates produced by the re-subscribe path.
|
||||
|
||||
@@ -1638,6 +1638,34 @@ public class InstanceActorTests : TestKit, IDisposable
|
||||
Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(1000), $"retry took {sw.Elapsed} — backoff not reset");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SRT-6 / WP3 task 3.8: the DCL's <c>ConnectionQualityChanged(Good)</c> on reconnect is a
|
||||
/// restore signal only. It must NOT stamp the bound attributes Good with their pre-outage
|
||||
/// last-known values — they stay Bad until the device re-reports through a TagValueUpdate.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ConnectionBackToGood_DoesNotStampBoundAttributesGood()
|
||||
{
|
||||
var (instance, dclProbe) = CreateInstanceWithDataSourcedAttribute(new SiteRuntimeOptions());
|
||||
dclProbe.ExpectMsg<SubscribeTagsRequest>();
|
||||
|
||||
instance.Tell(new TagValueUpdate("conn-1", "ns=2;s=Motor.Temp", 42, QualityCode.Good, DateTimeOffset.UtcNow));
|
||||
instance.Tell(new ConnectionQualityChanged("conn-1", QualityCode.Bad, DateTimeOffset.UtcNow));
|
||||
instance.Tell(new ConnectionQualityChanged("conn-1", QualityCode.Good, DateTimeOffset.UtcNow));
|
||||
|
||||
instance.Tell(new GetAttributeRequest("q1", "Sub-1", "Motor.Temp", DateTimeOffset.UtcNow));
|
||||
var stillBad = ExpectMsg<GetAttributeResponse>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Bad", stillBad.Quality); // pre-fix: "Good"
|
||||
Assert.Equal(42, stillBad.Value);
|
||||
|
||||
// The device re-reports: quality returns through the ordinary value path.
|
||||
instance.Tell(new TagValueUpdate("conn-1", "ns=2;s=Motor.Temp", 43, QualityCode.Good, DateTimeOffset.UtcNow));
|
||||
instance.Tell(new GetAttributeRequest("q2", "Sub-1", "Motor.Temp", DateTimeOffset.UtcNow));
|
||||
var good = ExpectMsg<GetAttributeResponse>(TimeSpan.FromSeconds(5));
|
||||
Assert.Equal("Good", good.Quality);
|
||||
Assert.Equal(43, good.Value);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a late reply for a failed and re-issued request is ignored.</summary>
|
||||
[Fact]
|
||||
public void LateReplyForFailedAndReissuedRequest_IsIgnored()
|
||||
|
||||
Reference in New Issue
Block a user