491df111ea
Closes arch-review remediation residual #1 (DCL unsubscribe-during-reconnect
count staleness).
DataConnectionActor tracked TotalSubscribedTags/ResolvedTags as two int fields
incremented and decremented at five independent sites. ReSubscribeAll clears the
very maps those decrements key off (_subscriptionIds, _unresolvedTags) while
deliberately preserving _subscriptionsByInstance, so an unsubscribe landing
inside a reconnect window matched NEITHER decrement branch: the total leaked +1
per subscribe/reconnect/unsubscribe churn cycle, permanently and cumulatively.
The 37f13e2e discard gate stopped the orphan-handle half of that race; it could
not stop the counters drifting, because they were state of their own.
Both counts are now DERIVED at report time from the authoritative per-tag
collections, which makes the drift unrepresentable rather than merely guarded:
total = _instancesByTag.Count (the per-tag counted set the residual
called for — distinct tags with at least
one subscribing instance)
resolved = _subscriptionIds.Count (tags for which the adapter holds a handle)
Two semantic corrections fall out of the derivation:
- A tag whose subscribe failed at CONNECTION level now counts toward the total.
It was excluded before, yet the reconnect re-subscribe re-issued it from
_subscriptionsByInstance and booked it as resolved — resolved above total, and
a total driven negative by the eventual unsubscribe.
- _tagSubscriberCount is deleted. It duplicated _instancesByTag exactly, so
HandleUnsubscribe's last-subscriber test is now "did UnindexTag drop the key?"
— still O(1), with no parallel count that can disagree about when a handle is
released. The subscribe-success promotion split (fresh vs. unresolved→resolved)
also goes: it existed only to pick which scalar to bump; set sizes get
DataConnectionLayer-020's double-count cases right for free.
Behavior is otherwise unchanged — same logging, same handle release, same
unresolved-tag probing, same in-flight-unsubscribe discard semantics (the long
comment block there is updated for the mechanics that changed).
Tests: five TagResolutionCounts_* cases in DataConnectionActorBatchTests
covering the churn repro (3 cycles), a shared tag losing one instance mid
reconnect, connection-level failure then recovery, plain subscribe/unsubscribe
cycles, and a completed reconnect re-subscribe. Verified failing against the
pre-fix actor (churn: total 1 not 0; connection-level: total 0 not 1) and
passing after. Full DCL suite 319/319; solution builds with 0 warnings.
Docs: Component-DataConnectionLayer.md health-reporting section describes the
derived counts; residuals register item 1 marked RESOLVED.
177 lines
7.7 KiB
C#
177 lines
7.7 KiB
C#
using System.Collections.Concurrent;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;
|
|
|
|
/// <summary>
|
|
/// In-memory batch-capable <see cref="IDataConnection"/> for the WP2.1b seam tests. It
|
|
/// records every batch call (so "one round trip per chunk, not per tag" is assertable),
|
|
/// can fail individual tags or a whole batch, and can hang its bulk read so the seed
|
|
/// deadline is observable.
|
|
/// </summary>
|
|
public sealed class FakeBatchDataConnection
|
|
: IDataConnection, IBatchSubscribableConnection, IAlarmSubscribableConnection
|
|
{
|
|
private int _nextId;
|
|
|
|
/// <summary>Tag lists handed to <see cref="SubscribeBatchAsync"/>, one entry per call.</summary>
|
|
public readonly ConcurrentQueue<IReadOnlyList<string>> SubscribeBatches = new();
|
|
/// <summary>Id lists handed to <see cref="UnsubscribeBatchAsync"/>, one entry per call.</summary>
|
|
public readonly ConcurrentQueue<IReadOnlyList<string>> UnsubscribeBatches = new();
|
|
/// <summary>Tag lists handed to <see cref="ReadBatchAsync"/>, one entry per call.</summary>
|
|
public readonly ConcurrentQueue<IReadOnlyList<string>> ReadBatches = new();
|
|
/// <summary>Count of SINGLE-tag subscribe calls; must stay 0 on a batch-capable adapter.</summary>
|
|
public int SingleSubscribeCalls;
|
|
/// <summary>Count of SINGLE-tag read calls; must stay 0 on a batch-capable adapter.</summary>
|
|
public int SingleReadCalls;
|
|
/// <summary>Wall-clock instant of each <see cref="SubscribeBatchAsync"/> call.</summary>
|
|
public readonly ConcurrentQueue<DateTimeOffset> SubscribeBatchTimes = new();
|
|
|
|
/// <summary>Tags reported as failed rows (per-tag resolution failure).</summary>
|
|
public readonly HashSet<string> FailingTags = new(StringComparer.Ordinal);
|
|
/// <summary>
|
|
/// When set, a batch subscribe throws whatever this returns — a batch-level fault.
|
|
/// Returning <c>null</c> lets that call through, so a test can make the fault TRANSIENT
|
|
/// (e.g. fail the initial subscribe at connection level, then let the reconnect
|
|
/// re-subscribe succeed).
|
|
/// </summary>
|
|
public Func<Exception?>? BatchSubscribeThrows;
|
|
/// <summary>When true, bulk reads never return until the caller's token cancels.</summary>
|
|
public bool HangReads;
|
|
/// <summary>
|
|
/// When set, <see cref="SubscribeBatchAsync"/> records the call and then parks until this
|
|
/// task completes, before producing its result rows. Lets a test hold a subscribe batch
|
|
/// in flight while it drives other messages into the actor (e.g. an unsubscribe that
|
|
/// races the completion).
|
|
/// </summary>
|
|
public Task? SubscribeGate;
|
|
/// <summary>Value returned for every readable tag.</summary>
|
|
public object? SeedValue = 42;
|
|
|
|
/// <summary>Callback the last batch subscribe registered; drives value pushes in tests.</summary>
|
|
public SubscriptionCallback? ValueCallback;
|
|
/// <summary>Callback the last alarm subscribe registered.</summary>
|
|
public AlarmTransitionCallback? AlarmCallback;
|
|
|
|
/// <inheritdoc />
|
|
public ConnectionHealth Status { get; private set; } = ConnectionHealth.Disconnected;
|
|
|
|
/// <inheritdoc />
|
|
public event Action? Disconnected;
|
|
|
|
/// <summary>Raises <see cref="Disconnected"/> as a real adapter would on a transport fault.</summary>
|
|
public void RaiseDisconnected() => Disconnected?.Invoke();
|
|
|
|
/// <inheritdoc />
|
|
public Task ConnectAsync(IDictionary<string, string> connectionDetails, CancellationToken cancellationToken = default)
|
|
{
|
|
Status = ConnectionHealth.Connected;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task DisconnectAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
Status = ConnectionHealth.Disconnected;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<TagSubscribeResult>> SubscribeBatchAsync(
|
|
IReadOnlyList<string> tagPaths, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
|
{
|
|
SubscribeBatches.Enqueue(tagPaths.ToList());
|
|
SubscribeBatchTimes.Enqueue(DateTimeOffset.UtcNow);
|
|
ValueCallback = callback;
|
|
|
|
if (BatchSubscribeThrows?.Invoke() is { } fault)
|
|
throw fault;
|
|
|
|
if (SubscribeGate is { } gate)
|
|
await gate;
|
|
|
|
IReadOnlyList<TagSubscribeResult> rows = tagPaths
|
|
.Select(t => FailingTags.Contains(t)
|
|
? new TagSubscribeResult(t, false, null, "node not found")
|
|
: new TagSubscribeResult(t, true, $"sub-{Interlocked.Increment(ref _nextId)}", null))
|
|
.ToList();
|
|
return rows;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task UnsubscribeBatchAsync(IReadOnlyList<string> subscriptionIds, CancellationToken cancellationToken = default)
|
|
{
|
|
UnsubscribeBatches.Enqueue(subscriptionIds.ToList());
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<string> SubscribeAsync(string tagPath, SubscriptionCallback callback, CancellationToken cancellationToken = default)
|
|
{
|
|
Interlocked.Increment(ref SingleSubscribeCalls);
|
|
ValueCallback = callback;
|
|
return Task.FromResult($"sub-{Interlocked.Increment(ref _nextId)}");
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task UnsubscribeAsync(string subscriptionId, CancellationToken cancellationToken = default)
|
|
=> Task.CompletedTask;
|
|
|
|
/// <inheritdoc />
|
|
public async Task<ReadResult> ReadAsync(string tagPath, CancellationToken cancellationToken = default)
|
|
{
|
|
Interlocked.Increment(ref SingleReadCalls);
|
|
if (HangReads)
|
|
await Task.Delay(Timeout.Infinite, cancellationToken);
|
|
return new ReadResult(true, new TagValue(SeedValue, QualityCode.Good, DateTimeOffset.UtcNow), null);
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyDictionary<string, ReadResult>> ReadBatchAsync(
|
|
IEnumerable<string> tagPaths, CancellationToken cancellationToken = default)
|
|
{
|
|
var tags = tagPaths.ToList();
|
|
ReadBatches.Enqueue(tags);
|
|
if (HangReads)
|
|
await Task.Delay(Timeout.Infinite, cancellationToken);
|
|
|
|
return tags.ToDictionary(
|
|
t => t,
|
|
t => new ReadResult(true, new TagValue(SeedValue, QualityCode.Good, DateTimeOffset.UtcNow), null));
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task<WriteResult> WriteAsync(string tagPath, object? value, CancellationToken cancellationToken = default)
|
|
=> Task.FromResult(new WriteResult(true, null));
|
|
|
|
/// <inheritdoc />
|
|
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)));
|
|
|
|
/// <inheritdoc />
|
|
public Task<bool> WriteBatchAndWaitAsync(
|
|
IDictionary<string, object?> values, string flagPath, object? flagValue, string responsePath,
|
|
object? responseValue, TimeSpan timeout, CancellationToken cancellationToken = default)
|
|
=> Task.FromResult(true);
|
|
|
|
/// <inheritdoc />
|
|
public Task<string> SubscribeAlarmsAsync(
|
|
string sourceReference, string? conditionFilter, AlarmTransitionCallback callback,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
AlarmCallback = callback;
|
|
return Task.FromResult($"alarm-{Interlocked.Increment(ref _nextId)}");
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Task UnsubscribeAlarmsAsync(string subscriptionId, CancellationToken cancellationToken = default)
|
|
=> Task.CompletedTask;
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|