Merge #976: historian outages never dead-letter alarm history; gateway transient codes retry; outbox ack never drops an unindexed append

This commit is contained in:
Joseph Doherty
2026-12-03 10:03:50 -05:00
14 changed files with 639 additions and 93 deletions
@@ -42,6 +42,21 @@ namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
/// <see cref="HistorianWriteOutcome.PermanentFail"/> rows flip the <c>dead_lettered</c> flag
/// on the individual row; neighbors in the batch still retry on their own cadence.
/// </para>
/// <para>
/// <b>An outage never dead-letters (lmxopcua#976 G-16/K-2).</b> Every production writer answers a
/// systemic failure — historian / gateway down, auth blip, failed schema bootstrap — with
/// <see cref="HistorianWriteOutcome.RetryPlease"/> for every event, so a RetryPlease alone cannot tell
/// an outage from a poison row. A RetryPlease therefore counts against <c>MaxAttempts</c> only on a
/// drain that proves the historian is accepting writes: at least one event of the same drain was
/// <see cref="HistorianWriteOutcome.Ack"/>'d. (A <see cref="HistorianWriteOutcome.PermanentFail"/> is not
/// that evidence — writers decide some without contacting anything, e.g. a pre-1970 time on QuestDB.)
/// A drain with no Ack is an outage: it backs off down the capped ladder, still dead-letters its
/// PermanentFail rows, and leaves every RetryPlease row untouched — before this rule an outage
/// longer than ~6.5 minutes dead-lettered the oldest queued alarm history, 100 rows every 10
/// minutes after that. The cost: a batch made up ENTIRELY of rows
/// that always answer RetryPlease is indistinguishable from an outage and is retried (at the 60 s cap)
/// rather than dead-lettered; it is visible as a non-draining queue with <c>LastError</c> set.
/// </para>
/// </remarks>
public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposable
{
@@ -51,7 +66,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
/// <summary>Default window dead-lettered rows are retained for before the sweeper purges them.</summary>
public static readonly TimeSpan DefaultDeadLetterRetention = TimeSpan.FromDays(30);
/// <summary>Default max delivery attempts before a perpetually-retrying (poison) row is dead-lettered.</summary>
/// <summary>
/// Default max delivery attempts before a perpetually-retrying (poison) row is dead-lettered. Only attempts made
/// on a drain that proved the historian reachable count — an outage never consumes them (#976).
/// </summary>
public const int DefaultMaxAttempts = 10;
private static readonly TimeSpan[] BackoffLadder =
@@ -422,8 +440,15 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
return;
}
// #976 G-16/K-2: a RetryPlease is evidence against its row only when the same drain shows the historian
// accepting writes (some event Ack'd). A drain with no Ack is an outage — or a writer that refused events
// without contacting anything (a pre-1970 time, an unmappable event) — and RetryPlease rows are left exactly
// as they were: no attempt counted, nothing dead-lettered. PermanentFail rows dead-letter either way.
var historianReachable = outcomes.Any(o => o == HistorianWriteOutcome.Ack);
int rowsLeavingQueue = 0;
int rowsDeadLettered = 0;
int retriesDeferred = 0;
await using (var tx = await _db.BeginTransactionAsync(ct).ConfigureAwait(false))
{
for (var i = 0; i < outcomes.Count; i++)
@@ -450,9 +475,15 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
// attempt count is the count BEFORE this attempt; +1 accounts for the
// bump this drain represents. At the cap, dead-letter instead of
// bumping — and count it as leaving the live queue like PermanentFail.
if (liveRows[i].AttemptCount + 1 >= _maxAttempts)
// Counted only on a drain that proved the historian reachable (#976):
// during an outage the row is left untouched.
if (!historianReachable)
{
await DeadLetterRowAsync(tx, id, $"max attempts ({_maxAttempts}) exceeded", ct).ConfigureAwait(false);
retriesDeferred++;
}
else if (liveRows[i].AttemptCount + 1 >= _maxAttempts)
{
await DeadLetterRowAsync(tx, id, $"max attempts ({_maxAttempts}) exceeded while the historian accepted other events", ct).ConfigureAwait(false);
rowsLeavingQueue++;
rowsDeadLettered++;
}
@@ -474,9 +505,13 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
Interlocked.Add(ref _deadLetterRowCount, rowsDeadLettered);
var acks = outcomes.Count(o => o == HistorianWriteOutcome.Ack);
string? outageMsg = retriesDeferred > 0
? $"Historian unavailable: {retriesDeferred} event(s) deferred with no write accepted (outage retries never count toward MaxAttempts)"
: null;
lock (_statusLock)
{
if (acks > 0) _lastSuccessUtc = _clock();
if (outageMsg is not null) _lastError = outageMsg;
if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease))
_drainState = HistorianDrainState.BackingOff;
@@ -484,6 +519,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
_drainState = HistorianDrainState.Idle;
}
if (outageMsg is not null) _logger.Debug("{Msg}", outageMsg);
if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease))
BumpBackoff();
else
@@ -39,17 +39,19 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
/// call.
/// </para>
/// <para>
/// <b>Outcome mapping.</b> Success (or store-forward-queued) ack ⇒ <see cref="HistorianWriteOutcome.Ack"/>.
/// Transient gRPC codes (<c>Unavailable</c>, <c>DeadlineExceeded</c>, <c>ResourceExhausted</c>,
/// <c>Aborted</c>, <c>Internal</c>) and the auth codes (<c>Unauthenticated</c>,
/// <c>PermissionDenied</c>) ⇒ <see cref="HistorianWriteOutcome.RetryPlease"/> — an auth fix
/// re-enables the batch, so an auth blip never dead-letters. Permanent codes
/// (<c>InvalidArgument</c>, <c>FailedPrecondition</c>, <c>OutOfRange</c>, <c>Unimplemented</c>) ⇒
/// <see cref="HistorianWriteOutcome.PermanentFail"/> (dead-letter poison — mirrors the Wonderware
/// <c>PerEventStatus==2</c> boundary). The typed client exceptions are classified by type, or by
/// the <see cref="RpcException"/> they wrap; any other or unclassifiable error defaults to
/// <see cref="HistorianWriteOutcome.PermanentFail"/> so the drain worker cannot loop a poison
/// event forever.
/// <b>Outcome mapping (lmxopcua#976 G-8).</b> Success (or store-forward-queued) ack ⇒
/// <see cref="HistorianWriteOutcome.Ack"/>. Only the gRPC codes that prove the EVENT itself is bad
/// (<c>InvalidArgument</c>, <c>FailedPrecondition</c>, <c>OutOfRange</c>, <c>NotFound</c>, <c>AlreadyExists</c>,
/// <c>Unimplemented</c>) — and an event that cannot even be mapped to the wire — are
/// <see cref="HistorianWriteOutcome.PermanentFail"/> (dead-letter poison). EVERYTHING else is
/// <see cref="HistorianWriteOutcome.RetryPlease"/>: the transient codes, the auth codes (an auth fix re-enables
/// the batch), <c>Cancelled</c> (the gateway's answer to a server-side cancellation — shutdown, internal timeout),
/// <c>Unknown</c> (an unmapped server fault), <c>DataLoss</c>, any code not listed, and every non-RPC exception
/// (a dropped channel's <see cref="IOException"/> / <see cref="HttpRequestException"/>, a disposed channel, a
/// client exception with no inner status, an internal timeout's <see cref="OperationCanceledException"/>). The
/// default used to be PermanentFail, which dead-lettered a whole drained batch on a gateway restart. A poison event
/// the classifier cannot recognise is still bounded: the store-and-forward sink counts a RetryPlease against
/// <c>MaxAttempts</c> whenever the same drain proves the historian reachable (another event Ack'd).
/// </para>
/// </remarks>
public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDisposable
@@ -134,17 +136,15 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
var indexes = new List<int>(count);
for (var i = offset; i < offset + count; i++)
{
try
if (TryMap(batch[i], out var mapped))
{
events.Add(AlarmEventMapper.ToHistorianEvent(batch[i]));
events.Add(mapped);
indexes.Add(i);
}
catch (Exception exception)
else
{
// An event that cannot even be mapped is poison: classified exactly as a single send would classify it.
outcomes[i] = Classify(exception);
_logger.LogWarning("Alarm event could not be mapped for SendEvents ({Exception}); dead-lettering it.",
exception.GetType().Name);
// An event that cannot even be mapped is poison: no gateway can ever accept it.
outcomes[i] = HistorianWriteOutcome.PermanentFail;
}
}
if (events.Count == 0) return true;
@@ -241,11 +241,29 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
return null;
}
private async Task<HistorianWriteOutcome> SendOneAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken)
/// <summary>Maps an event to the wire; a mapping failure is poison (logged, never thrown).</summary>
private bool TryMap(AlarmHistorianEvent evt, out HistorianEvent mapped)
{
try
{
var ack = await _client.SendEventAsync(AlarmEventMapper.ToHistorianEvent(evt), cancellationToken)
mapped = AlarmEventMapper.ToHistorianEvent(evt);
return true;
}
catch (Exception exception)
{
_logger.LogWarning("Alarm event could not be mapped to a gateway event ({Exception}); dead-lettering it.",
exception.GetType().Name);
mapped = null!;
return false;
}
}
private async Task<HistorianWriteOutcome> SendOneAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken)
{
if (!TryMap(evt, out var mapped)) return HistorianWriteOutcome.PermanentFail;
try
{
var ack = await _client.SendEventAsync(mapped, cancellationToken)
.ConfigureAwait(false);
return MapAck(ack);
}
@@ -283,37 +301,28 @@ public sealed class GatewayAlarmHistorianWriter : IAlarmHistorianWriter, IDispos
private static HistorianWriteOutcome MapAck(WriteAck ack) =>
ack.Success || ack.Queued ? HistorianWriteOutcome.Ack : HistorianWriteOutcome.RetryPlease;
private static HistorianWriteOutcome Classify(Exception exception) => exception switch
{
// Published client's typed hierarchy (production reality). Unavailable + both auth kinds retry.
HistorianGatewayUnavailableException => HistorianWriteOutcome.RetryPlease,
HistorianGatewayAuthenticationException => HistorianWriteOutcome.RetryPlease,
HistorianGatewayAuthorizationException => HistorianWriteOutcome.RetryPlease,
// A base client exception wrapping a permanent/transient RpcException → classify by inner status.
HistorianGatewayException { InnerException: RpcException inner } => ClassifyStatus(inner.StatusCode),
// Defensive raw RpcException path (the seam type signature permits it).
RpcException rpc => ClassifyStatus(rpc.StatusCode),
// Anything else (incl. a bare base client exception we cannot classify) → dead-letter to avoid
// an infinite drain loop on a poison event.
_ => HistorianWriteOutcome.PermanentFail,
};
/// <summary>
/// Classifies a gateway failure. A failure carrying a gRPC status (the typed client exceptions, the base client
/// exception wrapping an <see cref="RpcException"/>, or a raw one) is classified by that status; anything without
/// one is a transport-level fault and retries. Never dead-letter on what might be an outage (lmxopcua#976 G-8).
/// </summary>
private static HistorianWriteOutcome Classify(Exception exception) =>
StatusOf(exception) is { } code ? ClassifyStatus(code) : HistorianWriteOutcome.RetryPlease;
/// <summary>
/// Only the codes that prove the EVENT is bad dead-letter; every other code — transient, auth, <c>Cancelled</c>
/// (server-side cancellation), <c>Unknown</c> (unmapped server fault), <c>DataLoss</c>, and any code this list does
/// not name — retries.
/// </summary>
private static HistorianWriteOutcome ClassifyStatus(StatusCode code) => code switch
{
StatusCode.Unavailable
or StatusCode.DeadlineExceeded
or StatusCode.ResourceExhausted
or StatusCode.Aborted
or StatusCode.Internal
// An auth fix re-enables the whole batch — never dead-letter on an auth blip.
or StatusCode.Unauthenticated
or StatusCode.PermissionDenied => HistorianWriteOutcome.RetryPlease,
StatusCode.InvalidArgument
or StatusCode.FailedPrecondition
or StatusCode.OutOfRange
or StatusCode.NotFound
or StatusCode.AlreadyExists
or StatusCode.Unimplemented => HistorianWriteOutcome.PermanentFail,
// Unknown/unclassified gRPC code → dead-letter to avoid an infinite drain loop.
_ => HistorianWriteOutcome.PermanentFail,
_ => HistorianWriteOutcome.RetryPlease,
};
/// <summary>
@@ -16,7 +16,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Recorder;
/// policy: when an append would exceed <c>capacity</c>, the head is advanced past the oldest
/// entry (truncate + commit) and <see cref="DroppedCount"/> is incremented. Assumes serialized
/// appends (the recorder actor processes messages sequentially); the lock protects the in-memory
/// index, and FasterLog itself tolerates concurrent enqueue/scan.
/// index, and FasterLog itself tolerates concurrent enqueue/scan. Appends DO run concurrently
/// with the drain's peek/remove, and an append enqueues before it indexes, so neither side may
/// reason from the live tail: a peek returns only indexed records, and a remove truncates to
/// the acked record's own end, never past it (G-7, lmxopcua#976).
/// </remarks>
public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
{
@@ -42,6 +45,11 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
private readonly LinkedList<LiveEntry> _live = new();
private readonly Dictionary<Guid, LinkedListNode<LiveEntry>> _index = new();
private long _nextScanAddress; // authoritative logical head; peeks scan from here
// The last record the most recent peek returned: its start address and the scan's `next` address after it (the
// record's end, a valid truncation point). RemoveAsync of the NEWEST indexed entry truncates to that end — never to
// the live tail, which may already hold an append that is enqueued but not yet indexed (G-7, #976).
private long _lastPeekedStart = -1;
private long _lastPeekedEnd;
private long _droppedCount;
private long _unreadableCount;
@@ -149,6 +157,8 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
HistorizationOutboxEntry entry = entries[i];
byte[] payload = HistorizationOutboxEntrySerializer.Serialize(entry);
long start = await _log.EnqueueAsync(payload, ct).ConfigureAwait(false);
if (AfterEnqueueForTests is { } parked)
await parked().ConfigureAwait(false);
lock (_state)
{
_index[entry.Id] = _live.AddLast(new LiveEntry(entry.Id, start));
@@ -183,7 +193,7 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
while (_capacity > 0 && _live.Count > _capacity)
{
LinkedListNode<LiveEntry> oldest = _live.First!;
truncateTo = oldest.Next?.Value.Start ?? _log.TailAddress;
truncateTo = oldest.Next?.Value.Start ?? EndOfRecordAt(oldest.Value.Start);
_index.Remove(oldest.Value.Id);
_live.RemoveFirst();
_droppedCount++;
@@ -216,29 +226,47 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(max);
long from, tail;
long from, tail, lastIndexed;
lock (_state)
{
from = _nextScanAddress;
tail = _log.TailAddress;
// Only INDEXED records are returned (G-7, #976): a record past the newest indexed one belongs to an append that
// has enqueued but not yet indexed it. Returning it would make its id un-ackable (RemoveAsync no-ops on an
// unknown id) and the whole batch would be re-sent; it is peeked on the next pass, once indexed.
lastIndexed = _live.Last?.Value.Start ?? -1;
}
var batch = new List<HistorizationOutboxEntry>(Math.Min(max, 64));
List<(long Address, long Next, bool LeadsBatch)>? unreadable = null;
using (FasterLogScanIterator iter = _log.Scan(from, tail, recover: false))
long lastStart = -1, lastEnd = 0;
if (lastIndexed >= from)
{
using FasterLogScanIterator iter = _log.Scan(from, tail, recover: false);
while (batch.Count < max && iter.GetNext(out byte[] bytes, out int len, out long address, out long next))
{
if (address > lastIndexed)
break;
ScanStepForTests?.Invoke();
if (HistorizationOutboxEntrySerializer.TryDeserialize(bytes.AsSpan(0, len), out HistorizationOutboxEntry? entry))
{
batch.Add(entry);
(lastStart, lastEnd) = (address, next);
continue;
}
(unreadable ??= []).Add((address, next, batch.Count == 0));
}
}
if (lastStart >= 0)
{
lock (_state)
{
_lastPeekedStart = lastStart;
_lastPeekedEnd = lastEnd;
}
}
long? droppedHeadTo = null;
if (unreadable is not null)
{
@@ -286,6 +314,9 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
return batch;
}
/// <summary>Test seam: awaited after each append's enqueue returns and BEFORE it is indexed (the G-7 window).</summary>
internal Func<Task>? AfterEnqueueForTests { get; set; }
/// <summary>Test seam: invoked once per record the peek scans, OUTSIDE the state lock.</summary>
internal Action? ScanStepForTests { get; set; }
@@ -298,7 +329,9 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
if (!_index.TryGetValue(id, out LinkedListNode<LiveEntry>? node))
return; // unknown / already removed -> defensive no-op
truncateTo = node.Next?.Value.Start ?? _log.TailAddress;
// Never the live tail (G-7, #976): an append may have enqueued past the newest indexed entry and not yet indexed
// it, and truncating to the tail would silently discard that value.
truncateTo = node.Next?.Value.Start ?? EndOfRecordAt(node.Value.Start);
// FIFO ack: remove the target plus any older entries still ahead of it.
while (_live.First is { } first)
{
@@ -316,6 +349,18 @@ public sealed class FasterLogHistorizationOutbox : IHistorizationOutbox
await _log.CommitAsync(ct).ConfigureAwait(false); // make the head advance durable
}
// The address just past the record starting at `start` — a valid truncation point that covers that record and nothing
// after it. Caller holds _state. The newest indexed entry is normally the last record the drain peeked, whose end the
// peek recorded; otherwise a one-record scan finds it. If even that fails, the record's own start is returned: the
// target then stays in the log and may be re-delivered (a duplicate), never lost.
private long EndOfRecordAt(long start)
{
if (start == _lastPeekedStart)
return _lastPeekedEnd;
using FasterLogScanIterator iter = _log.Scan(start, _log.TailAddress, recover: false);
return iter.GetNext(out _, out _, out long address, out long next) && address == start ? next : start;
}
/// <inheritdoc />
public ValueTask<int> CountAsync(CancellationToken ct)
{
@@ -75,6 +75,7 @@ internal sealed class QuestDbAlarmHistorianWriter : IAlarmHistorianWriter
var outcomes2 = await AlarmBatchWrite.RunAsync(slots, ChunkRows,
(indexes, ct) => InsertChunkAsync(batch, indexes, ct),
Classify,
QuestDbConnection.IsTransient,
(ex, outcome) => _log.LogWarning("QuestDB alarm event write failed ({Exception}); outcome {Outcome}.", ex.GetType().Name, outcome),
cancellationToken).ConfigureAwait(false);
@@ -8,12 +8,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common;
/// <list type="bullet">
/// <item>a chunk that succeeds is Ack for every event in it (each was inserted or already present — the writes are
/// insert-if-absent / deduplicated by event id);</item>
/// <item>a chunk failing <see cref="HistorianWriteOutcome.RetryPlease"/>-class (transient: the database is down or
/// <item>a chunk failing with a KNOWN transient error (the caller's <c>isTransient</c>: the database is down or
/// busy) is RetryPlease for all its events — re-sending them one by one during an outage would only multiply
/// the round trips;</item>
/// <item>a chunk failing <see cref="HistorianWriteOutcome.PermanentFail"/>-class (a data error, or anything the
/// caller's classifier wants isolated) is re-sent ONE EVENT AT A TIME, so only the poison event dead-letters and
/// its siblings still Ack;</item>
/// <item>a chunk failing with an error that is neither (RetryPlease-class but not a known transient — an
/// unrecognised error, lmxopcua#976 G-16) is ALSO re-sent one event at a time: retrying the whole chunk tied
/// every sibling to one poison event, and since the store-and-forward sink counts a RetryPlease only when the
/// same drain proves the historian reachable, a chunk that never lands would otherwise pin the queue head. The
/// poison event keeps its RetryPlease and the sink dead-letters it alone once its siblings keep landing;</item>
/// <item>a cancellation of the caller's token makes every event not yet decided RetryPlease (never a dead letter).</item>
/// </list>
/// </summary>
@@ -27,6 +32,10 @@ public static class AlarmBatchWrite
/// <param name="chunkSize">Events per statement (at least 1).</param>
/// <param name="writeChunk">Writes the events at the given batch indexes in ONE statement; throws on failure.</param>
/// <param name="classify">Maps a write failure to the outcome it implies (see the summary for multi-event chunks).</param>
/// <param name="isTransient">
/// Whether a failure is a KNOWN outage-class error (connection / timeout / throttling). A multi-event chunk whose
/// RetryPlease-class failure is not one of these is isolated event by event.
/// </param>
/// <param name="onFailure">Optional diagnostic hook per failure (the exception and its classified outcome).</param>
/// <param name="ct">The drain's cancellation token.</param>
/// <returns>The filled outcomes.</returns>
@@ -34,12 +43,14 @@ public static class AlarmBatchWrite
HistorianWriteOutcome?[] outcomes, int chunkSize,
Func<IReadOnlyList<int>, CancellationToken, Task> writeChunk,
Func<Exception, HistorianWriteOutcome> classify,
Func<Exception, bool> isTransient,
Action<Exception, HistorianWriteOutcome>? onFailure,
CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(outcomes);
ArgumentNullException.ThrowIfNull(writeChunk);
ArgumentNullException.ThrowIfNull(classify);
ArgumentNullException.ThrowIfNull(isTransient);
chunkSize = Math.Max(1, chunkSize);
var pending = new List<int>(outcomes.Length);
@@ -49,12 +60,12 @@ public static class AlarmBatchWrite
for (var start = 0; start < pending.Count; start += chunkSize)
{
var chunk = pending.GetRange(start, Math.Min(chunkSize, pending.Count - start));
var outcome = await TryAsync(chunk).ConfigureAwait(false);
if (outcome == HistorianWriteOutcome.PermanentFail && chunk.Count > 1)
var (outcome, isolate) = await TryAsync(chunk).ConfigureAwait(false);
if (isolate && chunk.Count > 1)
{
// Isolate the poison event: one statement per event, so the siblings still land.
foreach (var index in chunk)
outcomes[index] = await TryAsync([index]).ConfigureAwait(false);
outcomes[index] = (await TryAsync([index]).ConfigureAwait(false)).Outcome;
continue;
}
foreach (var index in chunk) outcomes[index] ??= outcome;
@@ -64,23 +75,24 @@ public static class AlarmBatchWrite
for (var i = 0; i < outcomes.Length; i++) result[i] = outcomes[i] ?? HistorianWriteOutcome.RetryPlease;
return result;
async Task<HistorianWriteOutcome> TryAsync(IReadOnlyList<int> indexes)
// Isolate = the failure is not a known outage: a PermanentFail, or a RetryPlease the caller cannot vouch for.
async Task<(HistorianWriteOutcome Outcome, bool Isolate)> TryAsync(IReadOnlyList<int> indexes)
{
if (ct.IsCancellationRequested) return HistorianWriteOutcome.RetryPlease;
if (ct.IsCancellationRequested) return (HistorianWriteOutcome.RetryPlease, false);
try
{
await writeChunk(indexes, ct).ConfigureAwait(false);
return HistorianWriteOutcome.Ack;
return (HistorianWriteOutcome.Ack, false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
return HistorianWriteOutcome.RetryPlease; // shutdown: never a dead letter
return (HistorianWriteOutcome.RetryPlease, false); // shutdown: never a dead letter
}
catch (Exception ex)
{
var o = classify(ex);
onFailure?.Invoke(ex, o);
return o;
return (o, o == HistorianWriteOutcome.PermanentFail || (o == HistorianWriteOutcome.RetryPlease && !isTransient(ex)));
}
}
}
@@ -71,6 +71,7 @@ internal sealed class SqlServerAlarmHistorianWriter : IAlarmHistorianWriter
var written = await AlarmBatchWrite.RunAsync(slots, ChunkRows,
(indexes, ct) => WriteChunkAsync(batch, ids, indexes, ct),
ClassifyChunk,
SqlHistorianConnection.IsTransient,
(ex, outcome) => _log.LogWarning("SQL alarm event write failed ({Exception}); outcome {Outcome}.", ex.GetType().Name, outcome),
cancellationToken).ConfigureAwait(false);
for (var i = 0; i < batch.Count; i++) outcomes[i] = written[representative[ids[i]]];