fix(mtconnect): close Java-driver parity gaps found by the #804 review
- Lift an Agent's MTConnectError body under a non-2xx status (cppagent 2.x serves OUT_OF_RANGE as HTTP 400, NO_DEVICE as 404) into the refusal-marked InvalidDataException, reading at most 64 KiB. The 400 used to be a transport fault, so the OUT_OF_RANGE re-baseline never ran against a real 2.x Agent. - Run the instanceId restart test on every re-baseline snapshot: on 2.x a restart is first seen there (the old cursor gets a 400), and was adopted silently. - Report the stream Degraded after 3 consecutive re-baselines with no /sample chunk (it read Healthy for ever); LastSuccessfulRead keeps advancing. - Prohibit DTDs on the /probe and write-answer parses; bound the streams walk to 64 levels (unbounded recursion = uncatchable StackOverflowException). - Skip structural elements under <Components>/<Devices> instead of failing the probe. - Never serve a non-finite float as Good; serve integer-valued decimals on integral tags losslessly (a real fraction stays BadOutOfRange). - Merge sibling browse containers that resolve to one folder name. Unit 678 -> 714, integration 18 -> 20 (live fixture); every gap test failed first.
This commit is contained in:
@@ -161,6 +161,17 @@ public sealed partial class MTConnectDriver
|
||||
/// </remarks>
|
||||
private static readonly TimeSpan TeardownWait = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// How many consecutive <c>/current</c> re-baselines with no <c>/sample</c> chunk delivered between them
|
||||
/// report the stream Degraded (#804; the Java driver's <c>MAX_REBASELINES_WITHOUT_PROGRESS</c>). One
|
||||
/// re-baseline is a genuine ring-buffer overrun resolving; three in a row is an Agent and a cursor/count
|
||||
/// that cannot agree.
|
||||
/// </summary>
|
||||
internal const int MaxRebaselinesWithoutProgress = 3;
|
||||
|
||||
/// <summary>The type-only <c>LastError</c> a stalled stream (<see cref="MaxRebaselinesWithoutProgress"/>) reports.</summary>
|
||||
internal const string StalledStreamReason = "repeated /sample re-baselines with no observations in between";
|
||||
|
||||
/// <summary>
|
||||
/// Config-JSON reader options, mirroring the sibling driver factories. Note there is
|
||||
/// deliberately <b>no</b> <c>JsonStringEnumConverter</c>: enum-carrying DTO fields stay
|
||||
@@ -1433,6 +1444,9 @@ public sealed partial class MTConnectDriver
|
||||
var devices = 0;
|
||||
var variables = 0;
|
||||
|
||||
// Siblings that resolve to one folder name share ONE folder (#804) — see SiblingFolders.
|
||||
var deviceFolders = new SiblingFolders(builder);
|
||||
|
||||
foreach (var device in model.Devices)
|
||||
{
|
||||
if (device is null || !InDeviceScope(device, deviceScope))
|
||||
@@ -1454,7 +1468,7 @@ public sealed partial class MTConnectDriver
|
||||
}
|
||||
|
||||
devices++;
|
||||
variables += StreamContainer(device, builder.Folder(name, name), writeEnabled);
|
||||
variables += StreamContainer(device, deviceFolders.Get(name), writeEnabled);
|
||||
}
|
||||
|
||||
// A configured scope that matches NO device is an authoring error — almost always a typo or
|
||||
@@ -1555,6 +1569,8 @@ public sealed partial class MTConnectDriver
|
||||
streamed++;
|
||||
}
|
||||
|
||||
var componentFolders = new SiblingFolders(scope);
|
||||
|
||||
foreach (var component in container.Components)
|
||||
{
|
||||
if (component is null)
|
||||
@@ -1574,12 +1590,42 @@ public sealed partial class MTConnectDriver
|
||||
continue;
|
||||
}
|
||||
|
||||
streamed += StreamContainer(component, scope.Folder(name, name), writeEnabled);
|
||||
streamed += StreamContainer(component, componentFolders.Get(name), writeEnabled);
|
||||
}
|
||||
|
||||
return streamed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One builder folder per distinct name under one parent scope: two sibling containers that resolve to the
|
||||
/// same folder name (two components named alike, or one's <c>name</c> equal to another's <c>id</c>) are
|
||||
/// streamed into a SINGLE shared folder, deterministically, rather than as two same-named folders.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Why (#804, Java-driver parity).</b> A browse picker keys a folder by its path, so two same-named sibling
|
||||
/// folders share one key: the universal browser's capture (<c>CapturingAddressSpaceBuilder</c>) indexes the
|
||||
/// FIRST and every expand of that path returns the first one's children — the second container's data items
|
||||
/// were listed in the tree but unreachable. Merging is what the Java driver does for the same collision, and
|
||||
/// it loses nothing: every data item is still streamed, keyed by its own DataItem id. A data item whose name
|
||||
/// equals a sibling folder's is NOT a collision here — a leaf is keyed by its DataItem id, never its path.
|
||||
/// </remarks>
|
||||
private sealed class SiblingFolders(IAddressSpaceBuilder parent)
|
||||
{
|
||||
private readonly Dictionary<string, IAddressSpaceBuilder> _folders = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The folder named <paramref name="name"/> under the parent, created on first use.</summary>
|
||||
public IAddressSpaceBuilder Get(string name)
|
||||
{
|
||||
if (!_folders.TryGetValue(name, out var folder))
|
||||
{
|
||||
folder = parent.Folder(name, name);
|
||||
_folders[name] = folder;
|
||||
}
|
||||
|
||||
return folder;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether <see cref="WriteAsync"/> would accept a write to <paramref name="dataItem"/> — the
|
||||
/// browse-time answer, asked of the same two facts the runtime asks of.
|
||||
@@ -2186,6 +2232,9 @@ public sealed partial class MTConnectDriver
|
||||
var counts = new SampleCountState(options.SampleCount);
|
||||
Volatile.Write(ref _effectiveSampleCount, counts.Count);
|
||||
|
||||
// #804 (Java-driver parity) — consecutive re-baselines with no /sample chunk delivered in between.
|
||||
var rebaselinesWithoutProgress = 0;
|
||||
|
||||
try
|
||||
{
|
||||
if (republishOnStart)
|
||||
@@ -2215,7 +2264,15 @@ public sealed partial class MTConnectDriver
|
||||
}
|
||||
}
|
||||
|
||||
var outcome = await ConsumeStreamAsync(client, options, cursor, instanceId, generation, counts, ct).ConfigureAwait(false);
|
||||
var outcome = await ConsumeStreamAsync(
|
||||
client, options, cursor, instanceId, generation, counts,
|
||||
holdStalled: rebaselinesWithoutProgress >= MaxRebaselinesWithoutProgress, ct)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
if (outcome.DeliveredAny)
|
||||
{
|
||||
rebaselinesWithoutProgress = 0;
|
||||
}
|
||||
cursor = outcome.Cursor;
|
||||
instanceId = outcome.InstanceId;
|
||||
|
||||
@@ -2291,6 +2348,25 @@ public sealed partial class MTConnectDriver
|
||||
attempt = outcome.DeliveredAny ? 0 : attempt + 1;
|
||||
_reconnectAttempts = attempt;
|
||||
|
||||
// #804 — the backoff above PACES a stream that only ever re-baselines, but each /current
|
||||
// also marked the stream delivered, so it read Healthy for ever while no /sample chunk
|
||||
// arrived (a SampleCount at or above the Agent's bufferSize is refused OUT_OF_RANGE on
|
||||
// EVERY open). After MaxRebaselinesWithoutProgress in a row it is reported Degraded, and
|
||||
// stays so (holdStalled) until a chunk is delivered.
|
||||
if (!outcome.DeliveredAny &&
|
||||
++rebaselinesWithoutProgress == MaxRebaselinesWithoutProgress)
|
||||
{
|
||||
if (!TryHoldStreamStalled(generation, StalledStreamReason))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogWarning(
|
||||
outcome.Error,
|
||||
"MTConnect driver {DriverInstanceId}: {Count} consecutive /current re-baselines of {AgentUri} without a single /sample chunk in between; reporting the stream Degraded until one is delivered. Values are re-baselined, not streamed. An Agent answering every /sample with OUT_OF_RANGE usually means SampleCount is at or above its bufferSize.",
|
||||
_driverInstanceId, rebaselinesWithoutProgress, AgentDisplay(options));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -2354,6 +2430,7 @@ public sealed partial class MTConnectDriver
|
||||
long instanceId,
|
||||
long generation,
|
||||
SampleCountState counts,
|
||||
bool holdStalled,
|
||||
CancellationToken ct)
|
||||
{
|
||||
// The RUNNING cursor the gap check is made against: the previous chunk's nextSequence, equal
|
||||
@@ -2402,23 +2479,13 @@ public sealed partial class MTConnectDriver
|
||||
// Dropped BEFORE the re-baseline, and the subscribers are told: if the /current
|
||||
// then fails, holding stale values from a dead device model would be worse than
|
||||
// holding none.
|
||||
if (!TryCaptureSessionState(generation, out var restartIndex, out var restartTracker))
|
||||
if (!TryDropForAgentRestart(generation, chunk.InstanceId, options))
|
||||
{
|
||||
return new StreamOutcome(StreamVerdict.Cancelled, expected, instanceId, delivered, null);
|
||||
}
|
||||
|
||||
// Not live while the index is empty (review m2): reads go to /current until the re-baseline lands.
|
||||
_pumpLive = false;
|
||||
restartIndex.Clear();
|
||||
restartTracker.Clear();
|
||||
FanOut(SubscribedReferences(), restartIndex);
|
||||
|
||||
// The driver's own state is consistent by this point, so it is safe to hand the
|
||||
// restart to arbitrary caller code — which may call straight back into
|
||||
// DiscoverAsync.
|
||||
AnnounceAgentRestart(chunk.InstanceId, options);
|
||||
|
||||
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, ct)
|
||||
return await RebaselineAsync(
|
||||
client, options, expected, chunk.InstanceId, delivered, generation, holdStalled, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -2428,7 +2495,7 @@ public sealed partial class MTConnectDriver
|
||||
"MTConnect driver {DriverInstanceId} fell out of {AgentUri}'s buffer (expected sequence {Expected}, oldest retained {FirstSequence}); re-baselining from /current.",
|
||||
_driverInstanceId, AgentDisplay(options), expected, chunk.FirstSequence);
|
||||
|
||||
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, ct)
|
||||
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, holdStalled, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
@@ -2501,7 +2568,7 @@ public sealed partial class MTConnectDriver
|
||||
"MTConnect driver {DriverInstanceId} could not resume {AgentUri}'s /sample stream at sequence {Cursor} (the Agent rejected it as out of range); re-baselining from /current.",
|
||||
_driverInstanceId, AgentDisplay(options), cursor);
|
||||
|
||||
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, ct)
|
||||
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, holdStalled, ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -2532,6 +2599,7 @@ public sealed partial class MTConnectDriver
|
||||
long fallbackInstanceId,
|
||||
bool deliveredAny,
|
||||
long generation,
|
||||
bool holdStalled,
|
||||
CancellationToken ct)
|
||||
{
|
||||
try
|
||||
@@ -2545,8 +2613,31 @@ public sealed partial class MTConnectDriver
|
||||
StreamVerdict.Cancelled, fallbackCursor, fallbackInstanceId, deliveredAny, null);
|
||||
}
|
||||
|
||||
// #804 — the restart test runs on the SNAPSHOT too (the Java driver's rule). On a real 2.x Agent this
|
||||
// is how a restart is usually first seen: the restarted process refuses the dead one's cursor with
|
||||
// HTTP 400 OUT_OF_RANGE, so no chunk ever reaches the in-stream instanceId check above, and the
|
||||
// re-baseline used to adopt the new instanceId silently — no rediscovery prompt, and the dead model's
|
||||
// held values (data items the new Agent may not declare) kept being served.
|
||||
if (current.InstanceId != fallbackInstanceId)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"MTConnect driver {DriverInstanceId} saw {AgentUri} restart while re-baselining (instanceId {Previous} -> {Current}); dropping every held observation.",
|
||||
_driverInstanceId, AgentDisplay(options), fallbackInstanceId, current.InstanceId);
|
||||
|
||||
if (!TryDropForAgentRestart(generation, current.InstanceId, options))
|
||||
{
|
||||
return new StreamOutcome(
|
||||
StreamVerdict.Cancelled, fallbackCursor, fallbackInstanceId, deliveredAny, null);
|
||||
}
|
||||
}
|
||||
|
||||
PublishAgentCursor(generation, current.InstanceId, current.NextSequence);
|
||||
if (!ApplyAndFanOut(current, generation, baseline: true) || !TryMarkStreamDelivered(generation))
|
||||
// A stalled stream (#804) keeps its Degraded verdict across the re-baseline: the /current answered, but
|
||||
// it is not the /sample progress the verdict is about. Only a delivered chunk clears it.
|
||||
if (!ApplyAndFanOut(current, generation, baseline: true) ||
|
||||
!(holdStalled && !deliveredAny
|
||||
? TryHoldStreamStalled(generation, StalledStreamReason)
|
||||
: TryMarkStreamDelivered(generation)))
|
||||
{
|
||||
return new StreamOutcome(
|
||||
StreamVerdict.Cancelled, fallbackCursor, fallbackInstanceId, deliveredAny, null);
|
||||
@@ -2732,6 +2823,63 @@ public sealed partial class MTConnectDriver
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An Agent restart (a changed <c>instanceId</c>) seen by the pump started under <paramref name="generation"/>:
|
||||
/// drop every held observation and condition state — the device model they describe may no longer exist —
|
||||
/// tell the subscribers, and raise rediscovery (once per distinct id).
|
||||
/// </summary>
|
||||
/// <returns><see langword="false"/> when the pump's session has been replaced (nothing dropped).</returns>
|
||||
private bool TryDropForAgentRestart(long generation, long newInstanceId, MTConnectDriverOptions options)
|
||||
{
|
||||
if (!TryCaptureSessionState(generation, out var restartIndex, out var restartTracker))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Not live while the index is empty (review m2): reads go to /current until the re-baseline lands.
|
||||
_pumpLive = false;
|
||||
restartIndex.Clear();
|
||||
restartTracker.Clear();
|
||||
FanOut(SubscribedReferences(), restartIndex);
|
||||
|
||||
// The driver's own state is consistent by this point, so it is safe to hand the restart to arbitrary
|
||||
// caller code — which may call straight back into DiscoverAsync.
|
||||
AnnounceAgentRestart(newInstanceId, options);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #804: the pump started under <paramref name="generation"/> has re-baselined
|
||||
/// <see cref="MaxRebaselinesWithoutProgress"/> times in a row without one <c>/sample</c> chunk: degrade the
|
||||
/// stream — generation-checked, like <see cref="TryDegradeStream"/> — but stamp
|
||||
/// <c>LastSuccessfulRead</c> now, because each <c>/current</c> it re-baselined from IS the Agent answering.
|
||||
/// That is deliberate: the comms-loss watchdog reconnects on non-Healthy AND a frozen stamp, and a reconnect
|
||||
/// cannot fix an Agent that refuses the count or cursor — it would only reconnect-loop the driver (the
|
||||
/// "an Agent refusal is a reply" health contract).
|
||||
/// </summary>
|
||||
/// <param name="generation">The pump's session generation.</param>
|
||||
/// <param name="message">The type-only reason.</param>
|
||||
/// <returns><see langword="false"/> when the pump's session has been replaced (nothing written).</returns>
|
||||
private bool TryHoldStreamStalled(long generation, string message)
|
||||
{
|
||||
lock (_subscriptionLock)
|
||||
{
|
||||
if (_sessionGeneration != generation)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_streamDegraded = true;
|
||||
if (ReadHealth().State != DriverState.Faulted)
|
||||
{
|
||||
WriteHealth(new DriverHealth(DriverState.Degraded, DateTime.UtcNow, message));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Review I-1: the stream of the pump started under <paramref name="generation"/> delivered — clear its
|
||||
/// degradation, mark it live and publish Healthy, all under the generation check and in one critical section,
|
||||
|
||||
Reference in New Issue
Block a user