docs: fill missing XML docs and strip tracking IDs from src comments

Clears CommentChecker findings in src/ (3,280 -> 209, the remainder being false
positives like PLC-5/IEEE-754/M0.0) by adding missing summaries/params/returns,
normalising inheritdoc usage, and removing Gitea/review tracking IDs while keeping
the rationale they annotated. Comment-only: comment-stripped sources are identical
to the parent commit.
This commit is contained in:
Joseph Doherty
2026-10-15 06:14:58 -04:00
parent ebcbd81fca
commit 826312befe
430 changed files with 4434 additions and 3923 deletions
@@ -34,7 +34,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.S7;
public sealed class S7Driver
: IDriver, ITagDiscovery, IReadable, IWritable, IBatchSubscribable, IHostConnectivityProbe, ISkippedTagReporter, IDriverDiagnostics, IDisposable, IAsyncDisposable
{
/// <summary>Authored tags this driver could not build into its poll table (Gitea #541).</summary>
/// <summary>Authored tags this driver could not build into its poll table.</summary>
private readonly SkippedTagLedger _skippedTags = new();
/// <inheritdoc />
@@ -60,7 +60,7 @@ public sealed class S7Driver
_logger = logger ?? NullLogger<S7Driver>.Instance;
_resolver = new EquipmentTagRefResolver<S7TagDefinition>(
r => _tagsByRawPath.TryGetValue(r, out var t) ? t : null);
// CONV-1: the polling overlay runs on the shared PollGroupEngine (structural array diff +
// The polling overlay runs on the shared PollGroupEngine (structural array diff +
// drain-before-dispose + capped-exponential failure backoff + caller-token-filtered OCE),
// retiring the bespoke S7 poll fork. minInterval 100 ms matches the S7 scan-mailbox floor;
// backoffCap 30 s matches the retired fork's PollBackoffCap.
@@ -197,7 +197,7 @@ public sealed class S7Driver
}
/// <summary>
/// Per-device connect-attempt throttle (STAB-21): a dead PLC costs one connect attempt per
/// Per-device connect-attempt throttle: a dead PLC costs one connect attempt per
/// backoff window (1 s doubling to 30 s) instead of one per data call / poll tick / probe tick.
/// Not internally synchronized — only touched from <see cref="EnsureConnectedAsync"/> (under
/// <see cref="_gate"/>) and from init/shutdown, which run with every loop drained.
@@ -225,7 +225,7 @@ public sealed class S7Driver
/// <inheritdoc />
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
// #630: InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract
// InitializeAsync is reachable on a live driver with no teardown first (the IDriver contract
// allows it, and a reconnect retry can overlap a running attempt). Stop the previous probe loop and drop the previous connection
// before they are overwritten below. Deliberately NOT ShutdownAsync: that also drops _poll and the
// subscriptions, which are owned by the shutdown path (the actor re-subscribes after every successful init).
@@ -287,7 +287,7 @@ public sealed class S7Driver
{
// The linked CancelAfter fired — a connect TIMEOUT, not a caller cancellation.
// Surface it as a TimeoutException so init-time and reconnect-time timeouts report
// the same exception type (STAB-14 consistency); the outer catch still faults health.
// the same exception type (for consistency); the outer catch still faults health.
try { plc.Dispose(); } catch { }
throw new TimeoutException(
$"S7 connect to {_options.Host}:{_options.Port} timed out after " +
@@ -365,7 +365,7 @@ public sealed class S7Driver
// and CTS objects. Without the drain, a loop iteration mid-_gate would call Release()
// on (or WaitAsync against) a disposed semaphore.
// Drain the polling overlay first — the engine cancels each loop and awaits it before
// disposing its CTS (drain-before-dispose, STAB-6-S7), so no poll iteration touches _gate
// disposing its CTS (drain-before-dispose), so no poll iteration touches _gate
// after this returns.
await _poll.DisposeAsync().ConfigureAwait(false);
await ReleaseConnectionAsync().ConfigureAwait(false);
@@ -463,11 +463,9 @@ public sealed class S7Driver
["S7.NegotiatedPduSize"] = NegotiatedPduSize,
};
/// <summary>
/// <see cref="IDriverDiagnostics"/> view of the same facts, as strings, for the <c>/hosts</c> page
/// (Gitea #640). Empty before the first connect (PDU size 0 is "not negotiated yet", not a size).
/// </summary>
/// <returns>The diagnostics bag.</returns>
// IDriverDiagnostics view of the same facts, as strings, for the /hosts page. Empty before the
// first connect (PDU size 0 is "not negotiated yet", not a size).
/// <inheritdoc />
IReadOnlyDictionary<string, string> IDriverDiagnostics.GetDiagnostics()
{
var pdu = NegotiatedPduSize;
@@ -567,7 +565,7 @@ public sealed class S7Driver
// element, mirroring the read), so a write would overwrite the 7 neighbouring bits of
// every byte it touches; a safe bit-packed write needs read-modify-write and is not
// implemented. Every other supported element type (Byte/Int16/UInt16/Int32/UInt32/
// Float32) writes as ONE contiguous block (EncodeArrayBlock) — S7-016. Wide-type arrays
// Float32) writes as ONE contiguous block (EncodeArrayBlock). Wide-type arrays
// are already rejected above (guard-a).
if (t.ArrayCount is >= 1 && t.Writable && t.DataType == S7DataType.Bool)
{
@@ -615,34 +613,24 @@ public sealed class S7Driver
// ---- IReadable ----
// The batch is served in two passes under ONE gate acquisition. First S7ReadSpanPlanner groups
// the resolved tags into contiguous (area, DB) byte spans and each span is read with a single
// ReadBytesAsync, its members decoded by slicing the returned block - this is what turns one wire
// request per tag into one per contiguous block. Whatever the planner declines (Timer/Counter,
// whose offsets are device numbers) plus any span not worth issuing (see PrefersPerTagRead) falls
// to the leftover list.
//
// Those leftovers get a SECOND grouping pass: the ones a S7DataItem expresses cleanly - the narrow
// scalars, which is what a demoted single-member span is - are batched into multi-var requests by
// ReadLeftoversByMultiVarAsync, which crosses (area, DB) boundaries a block read cannot. Whatever
// remains (Timer/Counter, unparseable addresses, and any chunk whose multi-var request faulted)
// goes through the unchanged per-tag ReadOneAsync path.
//
// Setting SpanReadMaxGapBytes below zero skips BOTH passes, which restores the pre-grouping
// behaviour exactly. Either way the result array is written by original index, so the caller sees
// its own ordering regardless of how the batch was partitioned, and both passes share
// RecordReadFailure so a fault stamps the same status whichever path observed it.
/// <inheritdoc />
/// <remarks>
/// <para>
/// The batch is served in two passes under ONE gate acquisition. First
/// <see cref="S7ReadSpanPlanner"/> groups the resolved tags into contiguous
/// <c>(area, DB)</c> byte spans and each span is read with a single
/// <c>ReadBytesAsync</c>, its members decoded by slicing the returned block — this is
/// what turns one wire request per tag into one per contiguous block. Whatever the
/// planner declines (Timer/Counter, whose offsets are device numbers) plus any span not
/// worth issuing (see <see cref="PrefersPerTagRead"/>) falls to the leftover list.
/// </para>
/// <para>
/// Those leftovers get a SECOND grouping pass: the ones a
/// <see cref="S7DataItem"/> expresses cleanly — the narrow scalars, which is what a
/// demoted single-member span is — are batched into multi-var requests by
/// <see cref="ReadLeftoversByMultiVarAsync"/>, which crosses <c>(area, DB)</c>
/// boundaries a block read cannot. Whatever remains (Timer/Counter, unparseable
/// addresses, and any chunk whose multi-var request faulted) goes through the unchanged
/// per-tag <see cref="ReadOneAsync"/> path.
/// </para>
/// <para>
/// Setting <c>SpanReadMaxGapBytes</c> below zero skips BOTH passes, which
/// restores the pre-grouping behaviour exactly. Either way the result array is written
/// by original index, so the caller sees its own ordering regardless of how the batch
/// was partitioned, and both passes share <see cref="RecordReadFailure"/> so a fault
/// stamps the same status whichever path observed it.
/// </para>
/// </remarks>
public async Task<IReadOnlyList<DataValueSnapshot>> ReadAsync(
IReadOnlyList<string> fullReferences, CancellationToken cancellationToken)
{
@@ -670,7 +658,7 @@ public sealed class S7Driver
}
// Rethrow ONLY caller cancellation. A timeout-born OCE (none expected after the
// EnsureConnectedAsync conversion, but e.g. an S7.Net-internal CTS) must degrade the
// batch below, not escape as teardown (STAB-14).
// batch below, not escape as teardown.
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
@@ -761,7 +749,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Cancellation observed mid-PDU abandons a half-read ISO-on-TCP response on the
// single gated stream — the handle must be reopened, not reused (STAB-15a). Mark
// single gated stream — the handle must be reopened, not reused. Mark
// dead (we hold _gate) and propagate: the caller cancelled, nobody consumes the
// batch. Marking is unconditional on OCE (not routed through the type classifier):
// whether bytes moved is unknowable, and a false positive costs one cheap reopen
@@ -1045,7 +1033,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Same reasoning as the per-tag and span paths: a cancelled read abandons a half-read
// response on the single gated stream, so the handle must be reopened (STAB-15a).
// response on the single gated stream, so the handle must be reopened.
_plcDead = true;
throw;
}
@@ -1164,7 +1152,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Same reasoning as the per-tag path: a cancelled block read leaves the single gated
// stream at an untrustworthy position, so the handle must be reopened (STAB-15a).
// stream at an untrustworthy position, so the handle must be reopened.
_plcDead = true;
throw;
}
@@ -1477,7 +1465,7 @@ public sealed class S7Driver
// S7.Net Counter.FromByteArray returns the raw big-endian word ((bytes[0]<<8)|bytes[1]),
// without BCD reinterpretation. This preserves the raw value, not a verified PLC count:
// S7comm C-area response encoding still needs independent raw bytes and PLC-side
// count/binary/BCD references (#616). CPU family alone does not prove that encoding.
// count/binary/BCD references. CPU family alone does not prove that encoding.
// IEC counter integers in DB memory take the DB type codec, not this C-area path;
// S7-1500 also has legacy SIMATIC counters. See docs/drivers/S7.md for the evidence gate.
return (object)(int)global::S7.Net.Types.Counter.FromByteArray(block);
@@ -1569,7 +1557,7 @@ public sealed class S7Driver
// ReadScalarBlockAsync read, so WriteBytesAsync writes the whole reserved STRING. A value
// longer than StringLength throws ArgumentException (S7.Net rejects overflow; we do NOT
// silently truncate). A null value encodes as the empty string.
// #632: surfaced as S7ValueRangeException (→ BadOutOfRange) like the WSTRING codec — a
// Surfaced as S7ValueRangeException (→ BadOutOfRange) like the WSTRING codec — a
// client value error, not a comms fault (the raw ArgumentException used to land in the
// generic catch as BadCommunicationError + Degraded).
try { return global::S7.Net.Types.S7String.ToByteArray(Convert.ToString(value) ?? "", tag.StringLength); }
@@ -1580,7 +1568,7 @@ public sealed class S7Driver
// 1990–2089 DT range and throws ArgumentOutOfRangeException for an out-of-range year —
// we surface that (no silent clamp). Value coerced via Convert.ToDateTime (accepts a
// System.DateTime or a parseable timestamp string).
// #632: the range refusal maps to BadOutOfRange (see STRING above).
// The range refusal maps to BadOutOfRange (see STRING above).
var dt = Convert.ToDateTime(value);
try { return global::S7.Net.Types.DateTime.ToByteArray(dt); }
catch (ArgumentOutOfRangeException ex) { throw new S7ValueRangeException($"S7 DATE_AND_TIME value {dt:O} is outside the DT range (1990–2089): {ex.Message}"); }
@@ -1871,7 +1859,7 @@ public sealed class S7Driver
plc = await EnsureConnectedAsync(cancellationToken).ConfigureAwait(false);
}
// Rethrow ONLY caller cancellation — a timeout-born OCE degrades the batch below rather
// than escaping as teardown (STAB-14 defense-in-depth, mirrors ReadAsync).
// than escaping as teardown (defense-in-depth, mirrors ReadAsync).
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception ex)
{
@@ -1919,7 +1907,7 @@ public sealed class S7Driver
catch (OperationCanceledException)
{
// Cancellation observed mid-PDU abandons a half-written ISO-on-TCP request on
// the single gated stream — the handle must be reopened, not reused (STAB-15a).
// the single gated stream — the handle must be reopened, not reused.
// Mark dead (we hold _gate) and propagate: the caller cancelled, nobody consumes
// the batch, and Release() still runs in finally. Marking is unconditional on
// OCE — a false positive costs one cheap reopen versus permanent desync.
@@ -1983,7 +1971,7 @@ public sealed class S7Driver
}
/// <summary>
/// Publishes one write batch's verdict (STAB-22): worst state wins over every outcome the
/// Publishes one write batch's verdict: worst state wins over every outcome the
/// batch recorded, so a Faulted access-denied item is not erased by a later Degraded or
/// successful sibling. Maintains <see cref="_writeFault"/>, the sticky Faulted a read pass
/// must not erase. Caller holds <see cref="_gate"/>.
@@ -2058,7 +2046,7 @@ public sealed class S7Driver
? parsed
: S7AddressParser.Parse(tag.Address);
// Array path (S7-016): ONE contiguous WriteBytesAsync of count × element-bytes — the inverse
// Array path: ONE contiguous WriteBytesAsync of count × element-bytes — the inverse
// of ReadArrayAsync. Bool / wide-type arrays throw NotSupportedException (→ BadNotSupported);
// a wrong-shaped value throws S7WriteValueException (→ BadTypeMismatch, no health impact).
if (tag.ArrayCount is >= 1)
@@ -2246,9 +2234,9 @@ public sealed class S7Driver
/// enforces. The read / write / probe paths all take the gate before calling it.
/// <para>
/// While the PLC is down every data call and probe tick would pay a full connect attempt
/// bounded only by <c>_options.Timeout</c> (STAB-8). This method is the single
/// bounded only by <c>_options.Timeout</c>. This method is the single
/// choke-point all S7 reconnects flow through (already gate-serialized), so the
/// connect-attempt throttle lives here (STAB-21): the shared <see cref="ConnectionBackoff"/>
/// connect-attempt throttle lives here: the shared <see cref="ConnectionBackoff"/>
/// primitive is consulted with <c>ShouldAttempt(now)</c> at the top of the slow path —
/// inside the window the call fails fast with no connect attempt, which every caller
/// already degrades on — with <c>RecordFailure</c>/<c>RecordSuccess</c> around the connect.
@@ -2271,7 +2259,7 @@ public sealed class S7Driver
}
_plcDead = false;
// STAB-21: inside the backoff window fail fast WITHOUT a connect attempt. A plain
// Inside the backoff window fail fast WITHOUT a connect attempt. A plain
// InvalidOperationException (not an OCE) so the read/write/probe catch ladders degrade on it.
if (!_connectBackoff.ShouldAttempt(BackoffClock()))
throw new InvalidOperationException(
@@ -2290,7 +2278,7 @@ public sealed class S7Driver
// The linked CancelAfter fired — a connect TIMEOUT, not a caller cancellation.
// Surface it as a connection FAILURE (TimeoutException) so callers route it through
// their degrade paths: an escaping OCE reads as teardown and permanently killed the
// subscription poll loops (STAB-14, the unreachable-host regression in the Crit-3 fix).
// subscription poll loops (the unreachable-host regression).
try { plc.Dispose(); } catch { /* best-effort */ }
throw new TimeoutException(
$"S7 connect to {_options.Host}:{_options.Port} timed out after " +
@@ -2330,13 +2318,13 @@ public sealed class S7Driver
/// <see cref="System.Net.Sockets.SocketException"/> / <see cref="System.IO.IOException"/> /
/// <see cref="ObjectDisposedException"/>; a <see cref="TimeoutException"/> from a wire op that
/// blew its <see cref="S7OperationDeadline"/> wall-clock ceiling (an unresponsive but still
/// TCP-established peer — the READ-leg sibling of the connect-timeout fix, STAB-14); an S7.Net framing violation
/// TCP-established peer — the READ-leg sibling of the connect-timeout fix); an S7.Net framing violation
/// (<see cref="TPKTInvalidException"/> / <see cref="TPDUInvalidException"/> /
/// <see cref="WrongNumberOfBytesException"/>); or a <see cref="PlcException"/> carrying
/// <see cref="ErrorCode.ConnectionError"/> or <see cref="ErrorCode.WrongNumberReceivedBytes"/>.
/// A framing violation means the single serialized stream's position is untrustworthy — a
/// half-read PDU left by a timeout/cancellation makes every later response mis-frame, so only
/// a reopen recovers (STAB-15a: the Modbus STAB-3 desync mode rebuilt in S7).
/// a reopen recovers (the Modbus desync mode, rebuilt in S7).
/// <para>
/// Deliberately NOT <see cref="System.IO.InvalidDataException"/>: the driver's own decode
/// backstop (<see cref="ReinterpretRawValue"/> / <see cref="DecodeScalarBlock"/>) throws
@@ -2360,11 +2348,11 @@ public sealed class S7Driver
// A wire op that blew its wall-clock deadline (S7OperationDeadline — the async read/write
// ceiling S7.Net's ignored socket ReadTimeout/WriteTimeout can't provide) means the
// connection is unresponsive: discard + reopen. This is the READ-leg sibling of the
// connect-timeout fix (STAB-14) — without it a frozen-but-established peer wedges the
// connect-timeout fix — without it a frozen-but-established peer wedges the
// poll loop forever instead of surfacing Bad + reconnecting.
if (e is TimeoutException)
return true;
// ISO-on-TCP framing/desync surface (STAB-15a): the stream position is untrustworthy —
// ISO-on-TCP framing/desync surface: the stream position is untrustworthy —
// a half-read PDU left by a timeout/cancellation makes every later response mis-frame.
// NOTE: deliberately NOT System.IO.InvalidDataException — ReinterpretRawValue throws it
// for a declared-type/address-size CONFIG mismatch on a healthy socket.
@@ -2385,6 +2373,8 @@ public sealed class S7Driver
/// no typed error code for it, so the inner message is the only discriminator
/// S7.Net exposes.
/// </summary>
/// <param name="pex">The exception raised by S7.Net.</param>
/// <returns><see langword="true"/> when the PLC refused access to the object.</returns>
internal static bool IsAccessDenied(PlcException pex)
{
for (Exception? e = pex; e is not null; e = e.InnerException)
@@ -2465,7 +2455,7 @@ public sealed class S7Driver
}
/// <summary>
/// 05/STAB-9 — routes a poll-loop reader failure (surfaced by the shared
/// Routes a poll-loop reader failure (surfaced by the shared
/// <see cref="PollGroupEngine"/>'s onError sink) to the driver health surface: logs it and
/// degrades to <see cref="DriverState.Degraded"/> preserving <c>LastSuccessfulRead</c>. Never
/// downgrades a <see cref="DriverState.Faulted"/> state (e.g. PUT/GET-denied set by ReadAsync)
@@ -2518,7 +2508,7 @@ public sealed class S7Driver
// marked the handle dead (or the socket dropped between ticks), the probe
// reopens it here so recovery doesn't wait for the next data call.
// It runs on the LOOP token, not the (shorter) probe deadline: the connect is bounded by
// _options.Timeout inside, and a timeout there must count as a failure so STAB-21's
// _options.Timeout inside, and a timeout there must count as a failure so the
// backoff window opens — cutting it with the probe deadline looked like a caller cancel,
// recorded nothing, and let a black-holed host cost a connect attempt every probe tick.
var plc = await EnsureConnectedAsync(ct).ConfigureAwait(false);
@@ -2537,12 +2527,12 @@ public sealed class S7Driver
{
// Probe deadline fired mid-PDU: the CPU-status response may still be in
// flight, so the handle can't be reused (half-read ⇒ desync). We hold _gate
// here, keeping _plcDead gate-guarded (STAB-15b).
// here, keeping _plcDead gate-guarded.
_plcDead = true;
}
catch (Exception ex)
{
// STAB-15b: classify + mark while holding _gate so a wire-dead/desynced
// Classify + mark while holding _gate so a wire-dead/desynced
// handle whose TcpClient still claims Connected is reopened by the NEXT
// tick's EnsureConnectedAsync instead of being re-probed forever.
MarkConnectionDeadIfFatal(ex);
@@ -2607,7 +2597,7 @@ public sealed class S7Driver
/// </summary>
private void SynchronousTeardown()
{
// Drain the polling overlay (drain-before-dispose, STAB-6-S7).
// Drain the polling overlay (drain-before-dispose).
try { _poll.DisposeAsync().AsTask().Wait(DrainTimeout); }
catch { /* timeouts/loop faults are tolerated — teardown continues */ }