diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md
index 39742d64..842f97ef 100644
--- a/docs/GatewayConfiguration.md
+++ b/docs/GatewayConfiguration.md
@@ -511,7 +511,7 @@ behavior.
| `MxGateway:Alarms:DefaultArea` | _(empty)_ | Area name used to compose a default subscription when `SubscriptionExpression` is empty. If both are empty while `Enabled` is `true`, the monitor faults with a configuration diagnostic. |
| `MxGateway:Alarms:ReconcileIntervalSeconds` | `30` | How often the monitor re-resolves and, on material change, hot-swaps the subtag fallback watch-list, then reconciles its in-process alarm cache against the worker's authoritative active-alarm snapshot. The acknowledged watch-list fingerprint advances only after an OK worker reply. Floored at 5 seconds. |
| `MxGateway:Alarms:PollIntervalMilliseconds` | `500` | Cadence at which the worker's STA polls the AVEVA alarm consumer (`GetXmlCurrentAlarms2`) for the active-alarm snapshot the live feed diffs. Must be between `100` and `3600000` (one hour): every poll is a COM call plus an XML parse on the same STA that serves reads and writes, so a tighter cadence starves the command path, while a value above an hour stops being a cadence and silently disables alarm polling. The gateway conveys the value to the worker via the `MXGATEWAY_ALARM_POLL_INTERVAL_MS` environment variable; a missing or out-of-range value leaves the worker on the 500 ms default rather than failing the session. |
-| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR plus a full `XmlDocument`, so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
+| `MxGateway:Alarms:MaxAlarmsPerFetch` | `1024` | Cap the worker passes to `GetXmlCurrentAlarms2`'s `maxAlmCnt`. Must be between `64` and `65536` — the worker is a 32-bit process that materializes each reply as one BSTR (streamed into one record per alarm, not a DOM), so an unbounded cap faults the STA with an out-of-memory rather than merely slowing it. It doubles as the **truncation threshold**: a fetch returning exactly this many records is treated as truncated, because the COM API caps its reply with no "more available" flag. On a truncated poll the worker retains the alarms the capped reply could not mention instead of letting their absence read as a clear, and logs a rate-limited `AlarmSnapshotTruncated` warning to its stderr (identifiers and counts only). **Remediation when you see that warning: raise this value** so the steady-state active-alarm count fits inside one fetch. A galaxy permanently above the cap holds stale entries in the snapshot until a sub-cap poll, and loses clear→re-raise cycles that happen entirely out of window (see `docs/DesignDecisions.md`). Conveyed to the worker via the `MXGATEWAY_ALARM_MAX_ALARMS_PER_FETCH` environment variable; a missing or out-of-range value leaves the worker on the 1024 default. |
| `MxGateway:Alarms:AckClientName` | `MxGateway` | MXAccess client name the alarm worker's ack writer registers with; the Historian records it as each acknowledgement's OperatorNode. 1-64 printable characters. Conveyed via `MXGATEWAY_ALARM_ACK_CLIENT_NAME`. |
The alarm monitor is independent of client sessions: `AcknowledgeAlarm` and
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerFrameProtocolTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerFrameProtocolTests.cs
index 75bbe1e9..0d60d9d9 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerFrameProtocolTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Ipc/WorkerFrameProtocolTests.cs
@@ -912,6 +912,146 @@ public sealed class WorkerFrameProtocolTests
Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerEvent, f4.BodyCase);
}
+ ///
+ /// A batch with per-frame rejections surfaces the first failure in batch order, not in
+ /// completion order, and still writes every acceptable frame with contiguous sequences. Run in
+ /// both orders so a writer that reported the last failure, or a fixed failure kind, cannot pass.
+ /// Pins the batch-completion contract the per-frame-TCS removal (#177) must keep.
+ ///
+ /// Whether the oversized frame precedes the body-less one.
+ /// A task that represents the asynchronous operation.
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task WriteBatchAsync_WithPerFrameRejections_SurfacesFirstFailureInBatchOrder(bool oversizedFirst)
+ {
+ WorkerFrameProtocolOptions options = CreateBatchRejectionOptions();
+ using FlushCountingStream stream = new();
+ WorkerFrameWriter writer = new(stream, options);
+
+ WorkerEnvelope[] batch = CreateBatchWithTwoRejections(oversizedFirst);
+
+ WorkerFrameProtocolException exception = await Assert.ThrowsAsync(
+ async () => await writer.WriteBatchAsync(batch, WorkerFrameWritePriority.Event));
+
+ Assert.Equal(
+ oversizedFirst ? WorkerFrameProtocolErrorCode.MessageTooLarge : WorkerFrameProtocolErrorCode.InvalidEnvelope,
+ exception.ErrorCode);
+ await AssertBatchSurvivorsWrittenAsync(stream, options);
+ Assert.Equal(1, stream.FlushCount);
+ }
+
+ ///
+ /// The batch caller does not have to drain its own frames: when a concurrent single-frame caller
+ /// holds the write lock as the batch is queued, that caller's pass claims and writes the batch.
+ /// The batch call must still report the first rejection in batch order and return only after
+ /// its frames are on the wire — the case that relies on every claimed frame being terminal before
+ /// its drainer releases the lock (#177).
+ ///
+ /// Whether the oversized frame precedes the body-less one.
+ /// A task that represents the asynchronous operation.
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public async Task WriteBatchAsync_DrainedByAnotherLockHolder_StillSurfacesFirstFailureInBatchOrder(bool oversizedFirst)
+ {
+ WorkerFrameProtocolOptions options = CreateBatchRejectionOptions();
+ using GatedWriteStream stream = new();
+ WorkerFrameWriter writer = new(stream, options);
+
+ // A control writer takes the lock and parks inside its stream write.
+ Task controlWrite = writer.WriteAsync(CreateGatewayHelloEnvelope(), WorkerFrameWritePriority.Control);
+ await AwaitWithTimeoutAsync(stream.FirstWriteStarted);
+
+ Task batchWrite = writer.WriteBatchAsync(
+ CreateBatchWithTwoRejections(oversizedFirst),
+ WorkerFrameWritePriority.Event);
+ await Task.Delay(50);
+ Assert.False(batchWrite.IsCompleted);
+
+ stream.ReleaseFirstWrite();
+ await AwaitWithTimeoutAsync(controlWrite);
+
+ WorkerFrameProtocolException exception = await Assert.ThrowsAsync(
+ async () => await AwaitWithTimeoutAsync(batchWrite));
+ Assert.Equal(
+ oversizedFirst ? WorkerFrameProtocolErrorCode.MessageTooLarge : WorkerFrameProtocolErrorCode.InvalidEnvelope,
+ exception.ErrorCode);
+
+ stream.Position = 0;
+ WorkerFrameReader reader = new(stream, options);
+ WorkerEnvelope hello = await reader.ReadAsync();
+ Assert.Equal(WorkerEnvelope.BodyOneofCase.GatewayHello, hello.BodyCase);
+ WorkerEnvelope first = await reader.ReadAsync();
+ WorkerEnvelope second = await reader.ReadAsync();
+ Assert.Equal(new ulong[] { 1, 2, 3 }, new[] { hello.Sequence, first.Sequence, second.Sequence });
+ Assert.Equal(11UL, first.WorkerEvent.Event.WorkerSequence);
+ Assert.Equal(12UL, second.WorkerEvent.Event.WorkerSequence);
+ Assert.Equal(stream.Length, stream.Position);
+ }
+
+ ///
+ /// A batch cancelled while waiting for the write lock is tombstoned whole: none of its frames
+ /// reach the wire and the sequence stays contiguous for the next writer.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task WriteBatchAsync_CancelledWhileWaitingForLock_WritesNoneOfTheBatch()
+ {
+ WorkerFrameProtocolOptions options = CreateOptions();
+ using GatedWriteStream stream = new();
+ WorkerFrameWriter writer = new(stream, options);
+
+ Task firstWrite = writer.WriteAsync(CreateGatewayHelloEnvelope(), WorkerFrameWritePriority.Control);
+ await AwaitWithTimeoutAsync(stream.FirstWriteStarted);
+
+ using CancellationTokenSource cts = new();
+ Task cancelledBatch = writer.WriteBatchAsync(
+ new[] { CreateEventEnvelope(1), CreateEventEnvelope(2), CreateEventEnvelope(3) },
+ WorkerFrameWritePriority.Event,
+ cts.Token);
+ await Task.Delay(50);
+ cts.Cancel();
+ await Assert.ThrowsAnyAsync(async () => await cancelledBatch);
+
+ stream.ReleaseFirstWrite();
+ await AwaitWithTimeoutAsync(firstWrite);
+ await writer.WriteAsync(CreateShutdownAckEnvelope(), WorkerFrameWritePriority.Control);
+
+ stream.Position = 0;
+ WorkerFrameReader reader = new(stream, options);
+ WorkerEnvelope frame1 = await reader.ReadAsync();
+ WorkerEnvelope frame2 = await reader.ReadAsync();
+ Assert.Equal(WorkerEnvelope.BodyOneofCase.GatewayHello, frame1.BodyCase);
+ Assert.Equal(WorkerEnvelope.BodyOneofCase.WorkerShutdownAck, frame2.BodyCase);
+ Assert.Equal(new ulong[] { 1, 2 }, new[] { frame1.Sequence, frame2.Sequence });
+ Assert.Equal(stream.Length, stream.Position);
+ }
+
+ ///
+ /// A batch whose end-of-pass flush fails surfaces that stream failure — not success and not a
+ /// different frame's outcome — because no frame of an unflushed batch may count as delivered.
+ ///
+ /// A task that represents the asynchronous operation.
+ [Fact]
+ public async Task WriteBatchAsync_WhenFlushFails_SurfacesTheStreamFailure()
+ {
+ string marker = $"batch-flush-{Guid.NewGuid():N}";
+ WorkerFrameProtocolOptions options = CreateOptions();
+ using FlushFaultingGatedStream stream = new(marker);
+ WorkerFrameWriter writer = new(stream, options);
+
+ Task batchWrite = writer.WriteBatchAsync(
+ new[] { CreateEventEnvelope(1), CreateEventEnvelope(2), CreateEventEnvelope(3) },
+ WorkerFrameWritePriority.Event);
+ await AwaitWithTimeoutAsync(stream.FirstWriteStarted);
+ stream.ReleaseFirstWrite();
+
+ IOException exception = await Assert.ThrowsAsync(
+ async () => await AwaitWithTimeoutAsync(batchWrite));
+ Assert.Equal(marker, exception.Message);
+ }
+
///
/// Frame-writer lock-parking, closed. The class-boundary flush made a control frame's delivery
/// point honest, but the caller that lost the write-lock race still could not observe it: it
@@ -1155,6 +1295,48 @@ public sealed class WorkerFrameProtocolTests
};
}
+ private static WorkerFrameProtocolOptions CreateBatchRejectionOptions()
+ {
+ return new WorkerFrameProtocolOptions(
+ SessionId,
+ GatewayContractInfo.WorkerProtocolVersion,
+ Nonce,
+ maxMessageBytes: 512);
+ }
+
+ // Two acceptable events (worker sequences 11 and 12) around two per-frame rejections: one
+ // oversized frame (MessageTooLarge) and one body-less frame (InvalidEnvelope), in either order.
+ private static WorkerEnvelope[] CreateBatchWithTwoRejections(bool oversizedFirst)
+ {
+ WorkerEnvelope oversized = CreateEventEnvelope(99);
+ oversized.WorkerEvent.Event.RawStatus = new string('x', 2048);
+ WorkerEnvelope bodyless = new()
+ {
+ ProtocolVersion = GatewayContractInfo.WorkerProtocolVersion,
+ SessionId = SessionId,
+ };
+
+ return new[]
+ {
+ CreateEventEnvelope(11),
+ oversizedFirst ? oversized : bodyless,
+ CreateEventEnvelope(12),
+ oversizedFirst ? bodyless : oversized,
+ };
+ }
+
+ private static async Task AssertBatchSurvivorsWrittenAsync(Stream stream, WorkerFrameProtocolOptions options)
+ {
+ stream.Position = 0;
+ WorkerFrameReader reader = new(stream, options);
+ WorkerEnvelope first = await reader.ReadAsync();
+ WorkerEnvelope second = await reader.ReadAsync();
+ Assert.Equal(11UL, first.WorkerEvent.Event.WorkerSequence);
+ Assert.Equal(12UL, second.WorkerEvent.Event.WorkerSequence);
+ Assert.Equal(new ulong[] { 1, 2 }, new[] { first.Sequence, second.Sequence });
+ Assert.Equal(stream.Length, stream.Position);
+ }
+
// net48 has no Task.WaitAsync(TimeSpan); fail the test rather than hang if the writer misbehaves.
private static async Task AwaitWithTimeoutAsync(Task task)
{
diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlParityTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlParityTests.cs
new file mode 100644
index 00000000..fa6bd6bc
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/WnWrapAlarmConsumerXmlParityTests.cs
@@ -0,0 +1,344 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Reflection;
+using System.Text;
+using System.Xml;
+using ZB.MOM.WW.MxGateway.Worker.MxAccess;
+
+namespace ZB.MOM.WW.MxGateway.Worker.Tests.MxAccess;
+
+///
+/// Differential tests for :
+/// the streaming parser that replaced the per-poll (#177) must
+/// produce exactly what the DOM-based parser produced — same records, same field text, same
+/// raw ALARM count, and an exception of the same type for a payload the DOM rejected.
+/// is a verbatim copy of the replaced implementation and is the
+/// oracle; it must not be "tidied" to match the production code, or the comparison proves
+/// nothing.
+///
+public sealed class WnWrapAlarmConsumerXmlParityTests
+{
+ private const string Guid1 = "BCC4705395424D65BDAABCDEA6A32A73";
+ private const string Guid2 = "0123456789ABCDEF0123456789ABCDEF";
+
+ /// Gets the payload corpus, each case named so a divergence points at its shape.
+ public static IEnumerable
public bool IsControl { get; }
- /// Gets the completion source signaled once the frame has been written or has failed.
- public TaskCompletionSource Completion { get; }
+ ///
+ /// Gets the task signaled once the frame has been written or has failed. Only an awaitable
+ /// (single-frame) frame has one; reading it on a batch frame is a programming error.
+ ///
+ public Task Completion => _completion?.Task
+ ?? throw new InvalidOperationException("A batch frame has no awaitable completion.");
+
+ /// Gets a value indicating whether the frame has an awaitable .
+ public bool HasCompletion => _completion is not null;
+
+ /// Gets a value indicating whether a cancelled caller tombstoned this frame.
+ public bool IsCanceled => Volatile.Read(ref _state) == StateCanceled;
+
+ /// Gets a value indicating whether the frame has reached a terminal state.
+ public bool IsCompleted => Volatile.Read(ref _state) != StatePending;
///
/// Set to true by — under _gate — at the instant the
@@ -60,6 +96,63 @@ public sealed class WorkerFrameWriter
/// Mutated only under _gate.
///
public bool Claimed;
+
+ /// Marks the frame written and flushed; a no-op once terminal.
+ public void TrySetResult()
+ {
+ if (TryTransition(StateSucceeded))
+ {
+ _completion?.TrySetResult(true);
+ }
+ }
+
+ /// Marks the frame failed; a no-op once terminal.
+ /// Failure to surface to the frame's caller.
+ public void TrySetException(Exception exception)
+ {
+ // _fault is published before the state flips, so a reader that observes StateFaulted
+ // (through the Interlocked fence) also observes the exception.
+ if (Volatile.Read(ref _state) != StatePending)
+ {
+ return;
+ }
+
+ Exception? previous = Interlocked.CompareExchange(ref _fault, exception, null);
+ if (previous is not null)
+ {
+ return;
+ }
+
+ if (TryTransition(StateFaulted))
+ {
+ _completion?.TrySetException(exception);
+ }
+ }
+
+ /// Tombstones the frame; a no-op once terminal.
+ /// Token whose cancellation tombstoned the frame.
+ public void TrySetCanceled(CancellationToken cancellationToken)
+ {
+ if (TryTransition(StateCanceled))
+ {
+ _completion?.TrySetCanceled(cancellationToken);
+ }
+ }
+
+ ///
+ /// Returns the failure a terminal batch frame ended with, or when it
+ /// succeeded or was tombstoned.
+ ///
+ /// The frame's failure, or .
+ public Exception? TryGetFault()
+ {
+ return Volatile.Read(ref _state) == StateFaulted ? Volatile.Read(ref _fault) : null;
+ }
+
+ private bool TryTransition(int terminalState)
+ {
+ return Interlocked.CompareExchange(ref _state, terminalState, StatePending) == StatePending;
+ }
}
private readonly WorkerFrameProtocolOptions _options;
@@ -132,7 +225,7 @@ public sealed class WorkerFrameWriter
throw new ArgumentNullException(nameof(envelope));
}
- PendingFrame frame = new PendingFrame(envelope, priority);
+ PendingFrame frame = new PendingFrame(envelope, priority, awaitable: true);
lock (_gate)
{
if (priority == WorkerFrameWritePriority.Event)
@@ -153,7 +246,7 @@ public sealed class WorkerFrameWriter
// the winner's release; the acquisition it then walks away from is detached, never dropped, so
// no drain responsibility leaves with it.
Task lockWait = _writeLock.WaitAsync(cancellationToken);
- Task completion = frame.Completion.Task;
+ Task completion = frame.Completion;
await Task.WhenAny(completion, lockWait).ConfigureAwait(false);
if (lockWait.Status != TaskStatus.RanToCompletion)
@@ -253,7 +346,7 @@ public sealed class WorkerFrameWriter
{
WorkerEnvelope envelope = envelopes[index]
?? throw new ArgumentException("Batch envelopes must not contain null.", nameof(envelopes));
- frames[index] = new PendingFrame(envelope, priority);
+ frames[index] = new PendingFrame(envelope, priority, awaitable: false);
}
lock (_gate)
@@ -284,19 +377,21 @@ public sealed class WorkerFrameWriter
_writeLock.Release();
}
- // Await every completion so no per-frame rejection faults unobserved, but surface the first
- // failure (in batch order) to the caller — the drain loop maps it back to the offending event.
+ // Surface the first failure (in batch order) to the caller — the drain loop maps it back to
+ // the offending event. Every batch frame is terminal here without waiting: this caller's own
+ // pass drained whatever of the batch was still queued, and any frame an earlier lock-holder
+ // claimed was completed or failed inside that holder's pass, before it released the lock this
+ // caller then acquired. Batch frames carry no Task, so there is nothing left to observe.
Exception? firstFailure = null;
foreach (PendingFrame frame in frames)
{
- try
+ if (!frame.IsCompleted)
{
- await frame.Completion.Task.ConfigureAwait(false);
- }
- catch (Exception exception)
- {
- firstFailure ??= exception;
+ throw new InvalidOperationException(
+ "A batch frame was still pending after its caller's drain pass released the write lock.");
}
+
+ firstFailure ??= frame.TryGetFault();
}
if (firstFailure is not null)
@@ -311,7 +406,7 @@ public sealed class WorkerFrameWriter
{
if (!frame.Claimed)
{
- frame.Completion.TrySetCanceled(cancellationToken);
+ frame.TrySetCanceled(cancellationToken);
}
}
@@ -326,7 +421,7 @@ public sealed class WorkerFrameWriter
{
if (!frame.Claimed)
{
- frame.Completion.TrySetCanceled(cancellationToken);
+ frame.TrySetCanceled(cancellationToken);
}
}
}
@@ -349,7 +444,11 @@ public sealed class WorkerFrameWriter
/// Frame whose completion may fault without an awaiter.
private static void ObserveAbandonedFault(PendingFrame frame)
{
- ObserveFault(frame.Completion.Task);
+ // A batch frame has no Task, so a later failure has nothing to go unobserved on.
+ if (frame.HasCompletion)
+ {
+ ObserveFault(frame.Completion);
+ }
}
///
@@ -497,7 +596,7 @@ public sealed class WorkerFrameWriter
// flush that guarantees delivery failed, so the pipe is broken. Fail the frame just
// claimed (it is out of its queue and nothing else will ever complete it), every
// written-but-unflushed frame, and everything still queued, then stop draining.
- frame.Completion.TrySetException(exception);
+ frame.TrySetException(exception);
FailFrames(written, exception);
FailAllQueued(exception);
return;
@@ -520,14 +619,14 @@ public sealed class WorkerFrameWriter
// Validation, empty-payload, and oversized-frame errors are specific to this frame and
// do not damage the stream; fail only this frame and keep draining the rest. Nothing was
// written for it, so it needs no flush.
- frame.Completion.TrySetException(exception);
+ frame.TrySetException(exception);
}
catch (Exception exception)
{
// A stream write failure means the pipe is broken; fail this frame, every frame already
// written this batch but not yet flushed, and every frame still queued so no caller
// awaits forever, then stop draining.
- frame.Completion.TrySetException(exception);
+ frame.TrySetException(exception);
FailFrames(written, exception);
FailAllQueued(exception);
return;
@@ -560,7 +659,7 @@ public sealed class WorkerFrameWriter
{
foreach (PendingFrame frame in frames)
{
- frame.Completion.TrySetResult(true);
+ frame.TrySetResult();
}
}
@@ -568,7 +667,7 @@ public sealed class WorkerFrameWriter
{
foreach (PendingFrame frame in frames)
{
- frame.Completion.TrySetException(exception);
+ frame.TrySetException(exception);
}
}
@@ -591,7 +690,7 @@ public sealed class WorkerFrameWriter
while (_controlFrames.Count > 0)
{
PendingFrame frame = _controlFrames.Dequeue();
- if (frame.Completion.Task.IsCanceled)
+ if (frame.IsCanceled)
{
continue;
}
@@ -603,7 +702,7 @@ public sealed class WorkerFrameWriter
while (_eventFrames.Count > 0)
{
PendingFrame frame = _eventFrames.Dequeue();
- if (frame.Completion.Task.IsCanceled)
+ if (frame.IsCanceled)
{
continue;
}
@@ -622,12 +721,12 @@ public sealed class WorkerFrameWriter
{
while (_controlFrames.Count > 0)
{
- _controlFrames.Dequeue().Completion.TrySetException(exception);
+ _controlFrames.Dequeue().TrySetException(exception);
}
while (_eventFrames.Count > 0)
{
- _eventFrames.Dequeue().Completion.TrySetException(exception);
+ _eventFrames.Dequeue().TrySetException(exception);
}
}
}
diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs
index ed998d98..fe2fdfc4 100644
--- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs
+++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/WnWrapAlarmConsumer.cs
@@ -2,7 +2,9 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.IO;
using System.Runtime.InteropServices;
+using System.Text;
using System.Xml;
using WNWRAPCONSUMERLib;
using ZB.MOM.WW.MxGateway.Contracts;
@@ -73,7 +75,7 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
/// Ceiling on the resolved per-fetch cap. Mirrors the gateway-side
/// MxGateway:Alarms:MaxAlarmsPerFetch maximum. The worker is a
/// 32-bit process: every poll materializes the whole reply as one BSTR
- /// and then a full over it, so an unbounded
+ /// and then streams it into one record per alarm, so an unbounded
/// cap ( passed startup validation before
/// this existed) is an out-of-memory fault on the STA, not a slow poll.
///
@@ -685,22 +687,58 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
if (string.IsNullOrWhiteSpace(xml)) return records;
- XmlDocument doc = new XmlDocument();
- doc.LoadXml(xml);
- XmlNodeList? alarmNodes = doc.SelectNodes("/ALARM_RECORDS/ALARM");
- if (alarmNodes is null) return records;
-
- alarmRecordCount = alarmNodes.Count;
-
- foreach (XmlNode alarmNode in alarmNodes)
+ // Streamed with a forward-only XmlTextReader instead of materializing a
+ // full XmlDocument: the poll runs every 500 ms on the STA and at the
+ // per-fetch cap the DOM was the dominant steady allocation (#177).
+ //
+ // Parity with the XmlDocument + XPath reading this replaces, which the
+ // differential tests in WnWrapAlarmConsumerXmlTests pin against a copy
+ // of the old code:
+ // * XmlDocument.LoadXml reads through an XmlTextReader with its
+ // defaults (DTDs parsed, Normalization off — so CRLF inside a
+ // comment field survives — and no character checking); this reader
+ // keeps those defaults and only nulls the resolver, which
+ // XmlDocument also leaves unset. The whole document is read to its
+ // end, so a malformed payload still throws XmlException rather than
+ // returning the records before the fault.
+ // * "/ALARM_RECORDS/ALARM" is an unprefixed XPath name test: local
+ // name match in the empty namespace, document element then its
+ // direct children only.
+ // * XmlDocument (PreserveWhitespace off) drops insignificant
+ // whitespace nodes and keeps significant ones; WhitespaceHandling
+ // .Significant makes the reader do the same, so InnerText
+ // concatenation below sees the same text nodes the DOM held.
+ using StringReader textReader = new StringReader(xml);
+ using XmlTextReader reader = new XmlTextReader(textReader)
{
+ XmlResolver = null,
+ DtdProcessing = DtdProcessing.Parse,
+ EntityHandling = EntityHandling.ExpandEntities,
+ WhitespaceHandling = WhitespaceHandling.Significant,
+ };
+
+ bool rootIsAlarmRecords = false;
+ while (reader.Read())
+ {
+ if (reader.NodeType != XmlNodeType.Element) continue;
+
+ if (reader.Depth == 0)
+ {
+ rootIsAlarmRecords = IsUnqualified(reader, "ALARM_RECORDS");
+ continue;
+ }
+
+ if (!rootIsAlarmRecords || reader.Depth != 1 || !IsUnqualified(reader, "ALARM")) continue;
+
+ alarmRecordCount++;
+
// One pass over the child elements instead of 17 SelectSingleNode
// XPath evaluations per record. At the 1024-record cap that is the
// difference between ~17k XPath expression compilations plus child
// walks and one walk per record, on the STA that also serves reads
// and writes.
//
- // Parity with the XPath it replaces: SelectSingleNode(name) picks
+ // Parity with the XPath this replaced: SelectSingleNode(name) picks
// the FIRST child ELEMENT of that name (ordinal, case-sensitive)
// and yields its InnerText; an absent child yields string.Empty,
// and so does a present-but-empty one. Hence: element nodes only,
@@ -708,12 +746,14 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
// coalesce to string.Empty at the end — which keeps the absent and
// empty cases indistinguishable exactly as before.
//
- // One theoretical divergence: XmlNode.Name is the QName, so a child
- // carrying its own default-namespace declaration ()
- // matches here where the unprefixed XPath name test would not. It is
- // theoretical — wnwrap emits no namespaces, and a namespaced ALARM
- // wrapper makes the outer SelectNodes return nothing either way — and
- // it errs permissive (field populated rather than silently dropped).
+ // One theoretical divergence from that XPath, kept from the DOM
+ // walk that preceded this reader: reader.Name is the QName, so a
+ // child carrying its own default-namespace declaration
+ // () matches here where the unprefixed XPath
+ // name test would not. It is theoretical — wnwrap emits no
+ // namespaces, and a namespaced ALARM wrapper is skipped either
+ // way — and it errs permissive (field populated rather than
+ // silently dropped).
string? guidHex = null;
string? xmlDate = null;
string? xmlTime = null;
@@ -736,33 +776,40 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
string? ackOperatorDomain = null;
string? ackOperatorNode = null;
- foreach (XmlNode child in alarmNode.ChildNodes)
+ if (!reader.IsEmptyElement)
{
- if (child.NodeType != XmlNodeType.Element) continue;
-
- switch (child.Name)
+ while (reader.Read() && !(reader.NodeType == XmlNodeType.EndElement && reader.Depth == 1))
{
- case "GUID": guidHex ??= child.InnerText; break;
- case "DATE": xmlDate ??= child.InnerText; break;
- case "TIME": xmlTime ??= child.InnerText; break;
- case "GMTOFFSET": gmtOffset ??= child.InnerText; break;
- case "DSTADJUST": dstAdjust ??= child.InnerText; break;
- case "PROVIDER_NODE": providerNode ??= child.InnerText; break;
- case "PROVIDER_NAME": providerName ??= child.InnerText; break;
- case "GROUP": group ??= child.InnerText; break;
- case "TAGNAME": tagName ??= child.InnerText; break;
- case "TYPE": type ??= child.InnerText; break;
- case "VALUE": value ??= child.InnerText; break;
- case "LIMIT": limit ??= child.InnerText; break;
- case "PRIORITY": priority ??= child.InnerText; break;
- case "STATE": state ??= child.InnerText; break;
- case "OPERATOR_NODE": operatorNode ??= child.InnerText; break;
- case "OPERATOR_NAME": operatorName ??= child.InnerText; break;
- case "ALARM_COMMENT": alarmComment ??= child.InnerText; break;
- case "ACK_COMMENT": ackComment ??= child.InnerText; break;
- case "ACK_OPERATOR_NAME": ackOperatorName ??= child.InnerText; break;
- case "ACK_DOMAIN_NAME": ackOperatorDomain ??= child.InnerText; break;
- case "ACK_OPERATOR_NODE": ackOperatorNode ??= child.InnerText; break;
+ if (reader.NodeType != XmlNodeType.Element || reader.Depth != 2) continue;
+
+ // Read the name before the text: reading the text moves the
+ // reader to the element's end tag.
+ string name = reader.Name;
+ string text = ReadElementInnerText(reader);
+ switch (name)
+ {
+ case "GUID": guidHex ??= text; break;
+ case "DATE": xmlDate ??= text; break;
+ case "TIME": xmlTime ??= text; break;
+ case "GMTOFFSET": gmtOffset ??= text; break;
+ case "DSTADJUST": dstAdjust ??= text; break;
+ case "PROVIDER_NODE": providerNode ??= text; break;
+ case "PROVIDER_NAME": providerName ??= text; break;
+ case "GROUP": group ??= text; break;
+ case "TAGNAME": tagName ??= text; break;
+ case "TYPE": type ??= text; break;
+ case "VALUE": value ??= text; break;
+ case "LIMIT": limit ??= text; break;
+ case "PRIORITY": priority ??= text; break;
+ case "STATE": state ??= text; break;
+ case "OPERATOR_NODE": operatorNode ??= text; break;
+ case "OPERATOR_NAME": operatorName ??= text; break;
+ case "ALARM_COMMENT": alarmComment ??= text; break;
+ case "ACK_COMMENT": ackComment ??= text; break;
+ case "ACK_OPERATOR_NAME": ackOperatorName ??= text; break;
+ case "ACK_DOMAIN_NAME": ackOperatorDomain ??= text; break;
+ case "ACK_OPERATOR_NODE": ackOperatorNode ??= text; break;
+ }
}
}
@@ -799,6 +846,55 @@ public sealed class WnWrapAlarmConsumer : IMxAccessAlarmConsumer
return records;
}
+ private static bool IsUnqualified(XmlReader reader, string localName)
+ {
+ return reader.NamespaceURI.Length == 0
+ && string.Equals(reader.LocalName, localName, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Returns what returned for the
+ /// element the reader is on — every text, CDATA and significant
+ /// whitespace node in its subtree, concatenated in document order,
+ /// comments and processing instructions excluded — and leaves the
+ /// reader on the element's end tag (or on the element itself when it
+ /// is empty). The single-text-node case, which is every wnwrap field,
+ /// returns the reader's string without a builder.
+ ///
+ /// Reader positioned on an element start tag.
+ /// The concatenated inner text, or .
+ private static string ReadElementInnerText(XmlReader reader)
+ {
+ if (reader.IsEmptyElement) return string.Empty;
+
+ int depth = reader.Depth;
+ string? first = null;
+ StringBuilder? builder = null;
+ while (reader.Read())
+ {
+ XmlNodeType nodeType = reader.NodeType;
+ if (nodeType == XmlNodeType.EndElement && reader.Depth == depth) break;
+
+ if (nodeType is XmlNodeType.Text
+ or XmlNodeType.CDATA
+ or XmlNodeType.Whitespace
+ or XmlNodeType.SignificantWhitespace)
+ {
+ if (first is null)
+ {
+ first = reader.Value;
+ }
+ else
+ {
+ builder ??= new StringBuilder(first);
+ builder.Append(reader.Value);
+ }
+ }
+ }
+
+ return builder?.ToString() ?? first ?? string.Empty;
+ }
+
private static int ParseInt(string text)
{
return int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)