feat(historian): #1007 one-time revival of 'max attempts' dead letters; #1034 stalled alarm S&F queue detection (status, log, gauge, Degraded health)
#1007: LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters requeues only rows whose last_error is exactly the pre-#976 'max attempts (N) exceeded' (idempotent, replicates through LocalDb); driven by AlarmHistorian:ReviveMaxAttemptsDeadLetters for one restart. Runbook in docs/AlarmHistorian.md. #1034: AlarmHistorian:StallThresholdHours (default 2, 0 disables) -> HistorianSinkStatus.Stalled/LastProgressUtc, transition logs, otopcua.alarm_historian.queue.* gauges, Degraded 'alarm-historian' readiness check. Both touch the same sink/options/registration files, hence one commit.
This commit is contained in:
+42
-2
@@ -265,8 +265,46 @@ after that, with no automatic retry. Now:
|
||||
dead-lettered. It shows as a queue that does not drain while `LastError` reports the
|
||||
deferral.
|
||||
- Rows dead-lettered as `max attempts (N) exceeded` before #976 may be outage
|
||||
casualties; `RetryDeadLettered()` revives them. Rows dead-lettered by a post-#976 node
|
||||
read `… exceeded while the historian accepted other events`.
|
||||
casualties; see "Reviving rows the old cap dead-lettered (#1007)" below. Rows
|
||||
dead-lettered by a post-#976 node read `… exceeded while the historian accepted other events`.
|
||||
|
||||
### Reviving rows the old cap dead-lettered (#1007)
|
||||
|
||||
A node that ran a pre-#976 build through a historian outage holds dead-lettered rows whose
|
||||
`last_error` is exactly `max attempts (N) exceeded` — outage casualties, not poison. They stay
|
||||
dead for the retention window (default 30 days, then they are purged and unrecoverable), so do
|
||||
this soon after upgrading. One-time, idempotent, safe:
|
||||
|
||||
1. Upgrade to a #976+ build (the revived rows must meet the new outage-aware rule).
|
||||
2. Set `AlarmHistorian__ReviveMaxAttemptsDeadLetters=true` and restart the node (do the Primary,
|
||||
or both nodes of a pair — the second finds nothing left).
|
||||
3. Read the Warning `requeued N alarm event(s) the pre-#976 'max attempts' cap dead-lettered`
|
||||
(N = 0 means nothing to do). The rows rejoin the queue with `attempt_count = 0` and drain in
|
||||
their original enqueue order. The revival goes through LocalDb, so it replicates to the peer.
|
||||
4. Remove the setting. Leaving it on is harmless (it re-runs and revives 0 each boot).
|
||||
|
||||
It touches **only** the exact old reason (`last_error GLOB 'max attempts (*) exceeded'`):
|
||||
`PermanentFail`, corrupt-payload and post-#976 poison dead letters are untouched (use
|
||||
`RetryDeadLettered()` for those). A revived row that is genuinely poison dead-letters again under
|
||||
the current rule with the new-style reason, so it cannot loop. Dead letters are visible as
|
||||
`DeadLetterDepth` before/after. Delivery is at-least-once, so a casualty the historian had in fact
|
||||
stored is simply re-written.
|
||||
|
||||
### Stalled-queue detection (#1034)
|
||||
|
||||
A queue whose head is rows that always answer `RetryPlease` (or a long outage) does not drain, and
|
||||
nothing dead-letters it. `AlarmHistorian:StallThresholdHours` (default `2`, `0` disables) reports
|
||||
the queue **stalled** once rows have been queued on the draining node for that long with no row
|
||||
delivered or dead-lettered:
|
||||
|
||||
- `HistorianSinkStatus.Stalled` / `LastProgressUtc` (AdminUI `/alarms/historian`, actor status),
|
||||
- one Warning on entering the state and one Information on leaving it,
|
||||
- gauge `otopcua.alarm_historian.queue.stalled` (1/0) plus `…queue.depth` / `…queue.dead_letter_depth`,
|
||||
- the readiness check `alarm-historian`: **Degraded** (still 200, never Unhealthy).
|
||||
|
||||
The sink cannot tell an outage from a retry-forever head (both look like "no Ack"), so it also fires
|
||||
on a long genuine outage; `LastError` says which. A node that is not the drain owner is never stalled
|
||||
and promotion restarts the clock.
|
||||
|
||||
### Durability bound (important)
|
||||
|
||||
@@ -352,6 +390,8 @@ node's consolidated `LocalDb:Path` database (see
|
||||
| `Capacity` | long | `1000000` | Max queued rows before the sink evicts the oldest (data-loss signal via `EvictedCount`). |
|
||||
| `DeadLetterRetentionDays` | int | `30` | Days to retain dead-lettered rows before purge. |
|
||||
| `MaxAttempts` | int | `10` | Maximum delivery attempts before a poison (perpetually-retrying) row is dead-lettered automatically. Must be > 0. |
|
||||
| `StallThresholdHours` | double | `2` | Hours of no queue progress (rows queued, none delivered/dead-lettered, on the draining node) before the queue is reported stalled (#1034). `0` disables. |
|
||||
| `ReviveMaxAttemptsDeadLetters` | bool | `false` | One-time recovery (#1007): requeue rows the pre-#976 cap dead-lettered as `max attempts (N) exceeded`. Idempotent; remove after one restart. |
|
||||
|
||||
> The downstream gateway connection lives in `ServerHistorian` (`Endpoint` + env `ServerHistorian__ApiKey`,
|
||||
> `UseTls`, `CaCertificatePath`); alarm-history `ReadEvents` additionally requires the gateway running
|
||||
|
||||
@@ -63,6 +63,12 @@ public sealed class NullAlarmHistorianSink : IAlarmHistorianSink
|
||||
/// its configured capacity. Non-zero values indicate that accepted alarm events
|
||||
/// were dropped before reaching the historian — operator attention required.
|
||||
/// </param>
|
||||
/// <param name="Stalled">
|
||||
/// <c>true</c> when rows are queued on a node that owns the drain and nothing has been delivered or dead-lettered for the
|
||||
/// configured stall threshold (#1034). Fires on both a long historian outage and a queue head of rows that always answer
|
||||
/// retry; <paramref name="LastError"/> says which. Always <c>false</c> when no threshold is configured.
|
||||
/// </param>
|
||||
/// <param name="LastProgressUtc">UTC of the last time the queue made progress (a row delivered or dead-lettered) or was seen empty; <c>null</c> when not tracked (no drain yet, or not the drain owner).</param>
|
||||
public sealed record HistorianSinkStatus(
|
||||
long QueueDepth,
|
||||
long DeadLetterDepth,
|
||||
@@ -70,7 +76,9 @@ public sealed record HistorianSinkStatus(
|
||||
DateTime? LastSuccessUtc,
|
||||
string? LastError,
|
||||
HistorianDrainState DrainState,
|
||||
long EvictedCount = 0);
|
||||
long EvictedCount = 0,
|
||||
bool Stalled = false,
|
||||
DateTime? LastProgressUtc = null);
|
||||
|
||||
/// <summary>Where the drain worker is in its state machine.</summary>
|
||||
public enum HistorianDrainState
|
||||
|
||||
@@ -90,6 +90,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
private readonly int _maxAttempts;
|
||||
private readonly Func<DateTime> _clock;
|
||||
private readonly Func<bool> _drainGate;
|
||||
private readonly TimeSpan? _stallThreshold;
|
||||
|
||||
private readonly SemaphoreSlim _drainGateLock = new(1, 1);
|
||||
private Timer? _drainTimer;
|
||||
@@ -108,6 +109,11 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
// Tracks the last gate decision so a denial is logged on the transition rather than on every
|
||||
// tick. Null until the first drain runs.
|
||||
private bool? _lastGateDecision;
|
||||
// Stall detection (#1034). _progressUtc = the last time the queue made progress (a row Ack'd or dead-lettered) or was
|
||||
// seen empty; null = not tracking (never drained yet, or this node is not the drain owner). _wasStalled drives the
|
||||
// transition-only logging.
|
||||
private DateTime? _progressUtc;
|
||||
private bool _wasStalled;
|
||||
|
||||
private long _queuedRowCount;
|
||||
// Cached dead-letter depth (R05:7). GetStatus used to run a synchronous COUNT(*) table scan per
|
||||
@@ -148,6 +154,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
/// most one node, because the queue replicates — see the class remarks. The default
|
||||
/// (<c>null</c> ⇒ always drain) is the correct single-node and test posture.
|
||||
/// </param>
|
||||
/// <param name="stallThreshold">
|
||||
/// When set (and positive), <see cref="HistorianSinkStatus.Stalled"/> turns true once rows have been queued on a
|
||||
/// draining node for this long with no row Ack'd or dead-lettered (#1034). <c>null</c> (the default) disables it.
|
||||
/// </param>
|
||||
public LocalDbStoreAndForwardSink(
|
||||
ILocalDb db,
|
||||
IAlarmHistorianWriter writer,
|
||||
@@ -157,7 +167,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
TimeSpan? deadLetterRetention = null,
|
||||
int maxAttempts = DefaultMaxAttempts,
|
||||
Func<DateTime>? clock = null,
|
||||
Func<bool>? drainGate = null)
|
||||
Func<bool>? drainGate = null,
|
||||
TimeSpan? stallThreshold = null)
|
||||
{
|
||||
_db = db ?? throw new ArgumentNullException(nameof(db));
|
||||
_writer = writer ?? throw new ArgumentNullException(nameof(writer));
|
||||
@@ -168,6 +179,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
_maxAttempts = maxAttempts > 0 ? maxAttempts : throw new ArgumentOutOfRangeException(nameof(maxAttempts));
|
||||
_clock = clock ?? (() => DateTime.UtcNow);
|
||||
_drainGate = drainGate ?? (static () => true);
|
||||
_stallThreshold = stallThreshold is { } st && st > TimeSpan.Zero ? st : null;
|
||||
|
||||
_queuedRowCount = ProbeRowCount(deadLettered: false);
|
||||
_deadLetterRowCount = ProbeRowCount(deadLettered: true);
|
||||
@@ -357,7 +369,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
{
|
||||
if (!EvaluateDrainGate())
|
||||
{
|
||||
lock (_statusLock) { _drainState = HistorianDrainState.NotPrimary; }
|
||||
lock (_statusLock) { _drainState = HistorianDrainState.NotPrimary; _progressUtc = null; }
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -371,9 +383,10 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
var batch = await ReadBatchAsync(ct).ConfigureAwait(false);
|
||||
if (batch.Count == 0)
|
||||
{
|
||||
lock (_statusLock) { _drainState = HistorianDrainState.Idle; }
|
||||
lock (_statusLock) { _drainState = HistorianDrainState.Idle; _progressUtc = _clock(); }
|
||||
return;
|
||||
}
|
||||
lock (_statusLock) { _progressUtc ??= _clock(); }
|
||||
|
||||
// A null/un-deserializable payload can never succeed — dead-letter it
|
||||
// immediately for its own id so it cannot stall the queue head, and
|
||||
@@ -392,6 +405,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
}
|
||||
Interlocked.Add(ref _queuedRowCount, -corruptIds.Count);
|
||||
Interlocked.Add(ref _deadLetterRowCount, corruptIds.Count);
|
||||
lock (_statusLock) { _progressUtc = _clock(); }
|
||||
_logger.Warning(
|
||||
"Dead-lettered {Count} historian queue row(s) with un-deserializable payload",
|
||||
corruptIds.Count);
|
||||
@@ -511,6 +525,7 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
lock (_statusLock)
|
||||
{
|
||||
if (acks > 0) _lastSuccessUtc = _clock();
|
||||
if (rowsLeavingQueue > 0) _progressUtc = _clock();
|
||||
if (outageMsg is not null) _lastError = outageMsg;
|
||||
|
||||
if (outcomes.Any(o => o == HistorianWriteOutcome.RetryPlease))
|
||||
@@ -528,10 +543,48 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
}
|
||||
finally
|
||||
{
|
||||
_drainGateLock.Release();
|
||||
try { ObserveStall(); }
|
||||
finally { _drainGateLock.Release(); }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether the queue is stalled at <paramref name="now"/> (#1034): rows are queued, this node owns the drain, and
|
||||
/// nothing has left the queue for at least the threshold. Pure over the supplied state.
|
||||
/// </summary>
|
||||
private bool IsStalled(DateTime now, long queued, HistorianDrainState state, DateTime? progressUtc) =>
|
||||
_stallThreshold is { } threshold
|
||||
&& queued > 0
|
||||
&& state is not (HistorianDrainState.NotPrimary or HistorianDrainState.Disabled)
|
||||
&& progressUtc is { } p
|
||||
&& now - p >= threshold;
|
||||
|
||||
/// <summary>Logs a stall once on entering it (and once on leaving it); called after every drain tick.</summary>
|
||||
private void ObserveStall()
|
||||
{
|
||||
if (_stallThreshold is null) return;
|
||||
var queued = Interlocked.Read(ref _queuedRowCount);
|
||||
bool stalled, changed;
|
||||
DateTime? progress;
|
||||
string? lastError;
|
||||
lock (_statusLock)
|
||||
{
|
||||
progress = _progressUtc;
|
||||
lastError = _lastError;
|
||||
stalled = IsStalled(_clock(), queued, _drainState, progress);
|
||||
changed = stalled != _wasStalled;
|
||||
_wasStalled = stalled;
|
||||
}
|
||||
if (!changed) return;
|
||||
if (stalled)
|
||||
_logger.Warning(
|
||||
"Alarm historian queue STALLED: {Queued} event(s) queued and none delivered or dead-lettered since {Since:O} (threshold {Threshold}). "
|
||||
+ "Either the historian has been unreachable that long or the head of the queue is rows that always answer retry; last error: {LastError}",
|
||||
queued, progress, _stallThreshold, lastError ?? "(none)");
|
||||
else
|
||||
_logger.Information("Alarm historian queue is making progress again (no longer stalled)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consults the injected gate, logging only when the decision changes.
|
||||
/// </summary>
|
||||
@@ -591,6 +644,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
string? lastError;
|
||||
HistorianDrainState drainState;
|
||||
long evicted;
|
||||
DateTime? progress;
|
||||
bool stalled;
|
||||
lock (_statusLock)
|
||||
{
|
||||
lastDrain = _lastDrainUtc;
|
||||
@@ -598,6 +653,8 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
lastError = _lastError;
|
||||
drainState = _drainState;
|
||||
evicted = _evictedCount;
|
||||
progress = _progressUtc;
|
||||
stalled = IsStalled(_clock(), queued, drainState, progress);
|
||||
}
|
||||
|
||||
return new HistorianSinkStatus(
|
||||
@@ -607,7 +664,9 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
LastSuccessUtc: lastSuccess,
|
||||
LastError: lastError,
|
||||
DrainState: drainState,
|
||||
EvictedCount: evicted);
|
||||
EvictedCount: evicted,
|
||||
Stalled: stalled,
|
||||
LastProgressUtc: progress);
|
||||
}
|
||||
|
||||
/// <summary>Operator action from Admin UI — retry every dead-lettered row. Non-cascading: they rejoin the regular queue + get a fresh backoff.</summary>
|
||||
@@ -632,6 +691,44 @@ public sealed class LocalDbStoreAndForwardSink : IAlarmHistorianSink, IDisposabl
|
||||
return revived;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One-time recovery (#1007): requeues the rows the PRE-#976 sink dead-lettered with the bare
|
||||
/// <c>"max attempts (N) exceeded"</c> reason — during a historian outage, when that cap counted every retry — so they
|
||||
/// are delivered after all. Idempotent and safe to run on every boot.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Matches ONLY <c>last_error</c> of exactly the old form (<c>max attempts (*) exceeded</c>, nothing after it). The
|
||||
/// current rule's reason carries a suffix (<c>… while the historian accepted other events</c>), so a genuine poison
|
||||
/// row, a <c>PermanentFail</c> row and a corrupt-payload row are never touched — use
|
||||
/// <see cref="RetryDeadLettered"/> for those. A revived row gets <c>attempt_count = 0</c> and no error, and is
|
||||
/// delivered in its original enqueue order. A revived row that is in fact poison dead-letters again under the
|
||||
/// current rule with the new-style reason, so it cannot be revived a second time. Rows past
|
||||
/// <c>DeadLetterRetentionDays</c> were already purged and cannot be recovered.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Runs through the LocalDb connection so the revival replicates to the pair peer (the capture triggers).
|
||||
/// Running it on both nodes is harmless: the second finds nothing left to revive.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
/// <returns>The number of rows revived.</returns>
|
||||
public int ReviveMaxAttemptsDeadLetters()
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(LocalDbStoreAndForwardSink));
|
||||
using var conn = _db.CreateConnection();
|
||||
using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText =
|
||||
"UPDATE alarm_sf_events SET dead_lettered = 0, attempt_count = 0, last_error = NULL "
|
||||
+ "WHERE dead_lettered = 1 AND last_error GLOB 'max attempts (*) exceeded'";
|
||||
var revived = cmd.ExecuteNonQuery();
|
||||
if (revived > 0)
|
||||
{
|
||||
Interlocked.Add(ref _queuedRowCount, revived);
|
||||
Interlocked.Add(ref _deadLetterRowCount, -revived);
|
||||
}
|
||||
return revived;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One queued row paired with its deserialized event. <see cref="Event"/> is
|
||||
/// <c>null</c> when the row's <c>payload_json</c> is corrupt or un-deserializable —
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Health;
|
||||
|
||||
/// <summary>
|
||||
/// Pure decision for the alarm store-and-forward probe (#1034), factored out of <see cref="AlarmHistorianHealthCheck"/>
|
||||
/// so it is table-testable. <b>Never Unhealthy:</b> a stuck alarm-history queue does not stop the node serving driver data
|
||||
/// (and on a redundant pair failing readiness would shift ServiceLevel to a peer that shares the same queue and the same
|
||||
/// historian), so a stall is Degraded — still 200, but visible.
|
||||
/// </summary>
|
||||
public static class AlarmHistorianHealthDecision
|
||||
{
|
||||
/// <summary>Maps the sink's status to a health status.</summary>
|
||||
/// <param name="status">The sink status, or <c>null</c> when no durable sink is registered (alarm history disabled).</param>
|
||||
/// <returns>The status, a description and the queue figures.</returns>
|
||||
public static (HealthStatus Status, string Description, IReadOnlyDictionary<string, object> Data) Evaluate(HistorianSinkStatus? status)
|
||||
{
|
||||
if (status is null)
|
||||
return (HealthStatus.Healthy, "Alarm history store-and-forward is not enabled.", new Dictionary<string, object>());
|
||||
|
||||
var data = new Dictionary<string, object>
|
||||
{
|
||||
["queueDepth"] = status.QueueDepth,
|
||||
["deadLetterDepth"] = status.DeadLetterDepth,
|
||||
["evictedCount"] = status.EvictedCount,
|
||||
["drainState"] = status.DrainState.ToString(),
|
||||
};
|
||||
if (status.LastProgressUtc is { } progress) data["lastProgressUtc"] = progress.ToString("O");
|
||||
if (status.LastError is { } error) data["lastError"] = error;
|
||||
|
||||
return status.Stalled
|
||||
? (HealthStatus.Degraded,
|
||||
$"Alarm history queue stalled: {status.QueueDepth} event(s) queued, none delivered or dead-lettered since "
|
||||
+ $"{status.LastProgressUtc:O}. The historian is unreachable or the queue head is rows that always answer retry"
|
||||
+ (status.LastError is null ? "." : $" (last error: {status.LastError})."),
|
||||
data)
|
||||
: (HealthStatus.Healthy, $"Alarm history queue draining ({status.QueueDepth} queued).", data);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Readiness-tier check (Degraded at worst) over the alarm store-and-forward queue's stall state (#1034).</summary>
|
||||
/// <param name="sink">The registered alarm sink, or <c>null</c> when none is.</param>
|
||||
public sealed class AlarmHistorianHealthCheck(IAlarmHistorianSink? sink) : IHealthCheck
|
||||
{
|
||||
/// <summary>The check's registration name.</summary>
|
||||
public const string Name = "alarm-historian";
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
HistorianSinkStatus? status;
|
||||
try { status = sink?.GetStatus(); }
|
||||
catch (ObjectDisposedException) { status = null; } // shutting down
|
||||
var (health, description, data) = AlarmHistorianHealthDecision.Evaluate(status);
|
||||
return Task.FromResult(health == HealthStatus.Healthy
|
||||
? HealthCheckResult.Healthy(description, data)
|
||||
: HealthCheckResult.Degraded(description, data: data));
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,15 @@ public static class HealthEndpoints
|
||||
sp => new ScriptRunnerHealthCheck(sp.GetService<ScriptRunnerSelection>()),
|
||||
failureStatus: null,
|
||||
tags: new[] { ZbHealthTags.Ready }));
|
||||
|
||||
// #1034: alarm store-and-forward queue stalled (rows queued, none delivered or dead-lettered for
|
||||
// AlarmHistorian:StallThresholdHours). Ready tier, Degraded at worst (still 200): a stuck alarm-history
|
||||
// queue must not take the node out of rotation. Healthy when alarm history is not enabled.
|
||||
checks.Add(new HealthCheckRegistration(
|
||||
AlarmHistorianHealthCheck.Name,
|
||||
sp => new AlarmHistorianHealthCheck(sp.GetService<ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.IAlarmHistorianSink>()),
|
||||
failureStatus: null,
|
||||
tags: new[] { ZbHealthTags.Ready }));
|
||||
}
|
||||
|
||||
// configdb probe is admin-only (per-cluster mesh Phase 4). A driver-only node gets its config
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Diagnostics.Metrics;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Historian;
|
||||
|
||||
/// <summary>
|
||||
/// Observable gauges over the alarm store-and-forward queue (#1034), hung off the central
|
||||
/// <see cref="OtOpcUaTelemetry.Meter"/>. They read the sink's cached <see cref="HistorianSinkStatus"/> (no storage scan,
|
||||
/// no actor Ask), so a scrape is cheap and never blocks the metrics thread.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
/// <item><c>otopcua.alarm_historian.queue.stalled</c> — 1 when rows are queued on the draining node and none has been
|
||||
/// delivered or dead-lettered for <c>AlarmHistorian:StallThresholdHours</c>; else 0. Alert on it.</item>
|
||||
/// <item><c>otopcua.alarm_historian.queue.depth</c> / <c>.dead_letter_depth</c> — rows waiting / dead-lettered.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public static class AlarmHistorianMetrics
|
||||
{
|
||||
/// <summary>Gauge name: 1 while the queue is stalled.</summary>
|
||||
public const string StalledGaugeName = "otopcua.alarm_historian.queue.stalled";
|
||||
|
||||
private static volatile IAlarmHistorianSink? _sink;
|
||||
|
||||
static AlarmHistorianMetrics()
|
||||
{
|
||||
OtOpcUaTelemetry.Meter.CreateObservableGauge(
|
||||
StalledGaugeName, () => Status()?.Stalled == true ? 1 : 0, unit: "{state}",
|
||||
description: "1 when alarm events are queued on the draining node and none was delivered or dead-lettered for AlarmHistorian:StallThresholdHours (a long outage or retry-forever rows at the queue head).");
|
||||
OtOpcUaTelemetry.Meter.CreateObservableGauge(
|
||||
"otopcua.alarm_historian.queue.depth", () => Status()?.QueueDepth ?? 0L, unit: "{event}",
|
||||
description: "Alarm events waiting in the store-and-forward queue.");
|
||||
OtOpcUaTelemetry.Meter.CreateObservableGauge(
|
||||
"otopcua.alarm_historian.queue.dead_letter_depth", () => Status()?.DeadLetterDepth ?? 0L, unit: "{event}",
|
||||
description: "Alarm events dead-lettered in the store-and-forward queue (retained until the retention window expires).");
|
||||
}
|
||||
|
||||
/// <summary>Points the gauges at <paramref name="sink"/> (the process's alarm sink). Re-binding replaces it.</summary>
|
||||
/// <param name="sink">The alarm sink whose status the gauges report.</param>
|
||||
public static void Bind(IAlarmHistorianSink sink) => _sink = sink ?? throw new ArgumentNullException(nameof(sink));
|
||||
|
||||
private static HistorianSinkStatus? Status()
|
||||
{
|
||||
try { return _sink?.GetStatus(); }
|
||||
catch (ObjectDisposedException) { return null; } // a disposed sink (shutdown) reports nothing
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,25 @@ public sealed class AlarmHistorianOptions
|
||||
/// Defaults to 10 (matches <c>LocalDbStoreAndForwardSink</c>'s <c>DefaultMaxAttempts</c>).</summary>
|
||||
public int MaxAttempts { get; init; } = LocalDbStoreAndForwardSink.DefaultMaxAttempts;
|
||||
|
||||
/// <summary>
|
||||
/// Hours of no progress (nothing delivered or dead-lettered while rows are queued on the draining node) after which the
|
||||
/// queue is reported stalled (#1034): a Warning log, the <c>otopcua.alarm_historian.queue.stalled</c> gauge and a
|
||||
/// Degraded <c>alarm-historian</c> readiness check. Defaults to 2; <c>0</c> disables. Fires on a long historian outage
|
||||
/// as well as on a queue head of retry-forever rows — read <c>LastError</c> to tell which.
|
||||
/// </summary>
|
||||
public double StallThresholdHours { get; init; } = 2;
|
||||
|
||||
/// <summary>
|
||||
/// One-time recovery (#1007): when <c>true</c>, every host start requeues the rows the pre-#976 sink dead-lettered with
|
||||
/// the bare "max attempts (N) exceeded" reason during an outage (<c>LocalDbStoreAndForwardSink.ReviveMaxAttemptsDeadLetters</c>).
|
||||
/// Idempotent — safe to leave on, but intended to be turned on for one restart and then removed.
|
||||
/// Defaults to <c>false</c>. See <c>docs/AlarmHistorian.md</c>.
|
||||
/// </summary>
|
||||
public bool ReviveMaxAttemptsDeadLetters { get; init; }
|
||||
|
||||
/// <summary>The stall threshold as a <see cref="TimeSpan"/>, or <c>null</c> when disabled (<see cref="StallThresholdHours"/> <= 0).</summary>
|
||||
public TimeSpan? StallThreshold => StallThresholdHours > 0 ? TimeSpan.FromHours(StallThresholdHours) : null;
|
||||
|
||||
/// <summary>Returns operator-facing misconfiguration warnings for an <c>Enabled</c> historian
|
||||
/// (empty when disabled or correctly configured). Pure — the registration logs each entry.</summary>
|
||||
/// <returns>Zero or more human-readable warning messages.</returns>
|
||||
@@ -56,6 +75,8 @@ public sealed class AlarmHistorianOptions
|
||||
warnings.Add($"AlarmHistorian:DeadLetterRetentionDays is {DeadLetterRetentionDays} — must be > 0; dead-lettered rows would be purged on every drain tick.");
|
||||
if (MaxAttempts <= 0)
|
||||
warnings.Add($"AlarmHistorian:MaxAttempts is {MaxAttempts} — must be > 0; the sink constructor will throw at startup.");
|
||||
if (StallThresholdHours < 0)
|
||||
warnings.Add($"AlarmHistorian:StallThresholdHours is {StallThresholdHours} — negative; stall detection is disabled (use 0 to disable explicitly).");
|
||||
return warnings;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,7 +229,17 @@ public static class ServiceCollectionExtensions
|
||||
capacity: opts.Capacity,
|
||||
deadLetterRetention: TimeSpan.FromDays(opts.DeadLetterRetentionDays),
|
||||
maxAttempts: opts.MaxAttempts,
|
||||
drainGate: () => !replicated || roleView.ShouldDrainAlarmHistory);
|
||||
drainGate: () => !replicated || roleView.ShouldDrainAlarmHistory,
|
||||
stallThreshold: opts.StallThreshold);
|
||||
if (opts.ReviveMaxAttemptsDeadLetters)
|
||||
{
|
||||
var revived = sink.ReviveMaxAttemptsDeadLetters();
|
||||
Serilog.Log.Logger.ForContext<LocalDbStoreAndForwardSink>().Warning(
|
||||
"AlarmHistorian:ReviveMaxAttemptsDeadLetters is on: requeued {Revived} alarm event(s) the pre-#976 'max attempts' cap dead-lettered. "
|
||||
+ "This is a one-time recovery — remove the setting once it reports 0",
|
||||
revived);
|
||||
}
|
||||
AlarmHistorianMetrics.Bind(sink);
|
||||
sink.StartDrainLoop(TimeSpan.FromSeconds(opts.DrainIntervalSeconds));
|
||||
return sink;
|
||||
});
|
||||
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// #1007 (one-time revival of rows the pre-#976 "max attempts" cap dead-lettered during an outage) and #1034
|
||||
/// (a queue that stops making progress is reported as stalled).
|
||||
/// </summary>
|
||||
public sealed partial class LocalDbStoreAndForwardSinkTests
|
||||
{
|
||||
private const string OldCapReason = "max attempts (10) exceeded";
|
||||
|
||||
private async Task SetDeadLetterAsync(string alarmId, string? lastError, int attempts = 10)
|
||||
{
|
||||
// Rewrites a row exactly as the pre-#976 sink left it (dead-lettered with the old reason).
|
||||
var n = await Db.ExecuteAsync(
|
||||
"UPDATE alarm_sf_events SET dead_lettered = 1, attempt_count = @A, last_error = @E, last_attempt_utc = @T WHERE alarm_id = @Id",
|
||||
new { A = attempts, E = lastError, T = DateTime.UtcNow.ToString("O"), Id = alarmId },
|
||||
TestContext.Current.CancellationToken);
|
||||
n.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>The revival touches ONLY rows the old cap dead-lettered; genuine dead letters stay dead.</summary>
|
||||
[Fact]
|
||||
public async Task Revive_requeues_only_rows_the_old_max_attempts_cap_dead_lettered()
|
||||
{
|
||||
var writer = new FakeWriter();
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log);
|
||||
var t = DateTime.UtcNow;
|
||||
foreach (var id in new[] { "old-cap-1", "old-cap-2", "permanent", "poison", "corrupt", "live" })
|
||||
await sink.EnqueueAsync(Event(id, t = t.AddSeconds(1)), CancellationToken.None);
|
||||
|
||||
await SetDeadLetterAsync("old-cap-1", OldCapReason);
|
||||
await SetDeadLetterAsync("old-cap-2", "max attempts (3) exceeded"); // a different MaxAttempts is still the old cap
|
||||
await SetDeadLetterAsync("permanent", "permanent fail at 2026-12-01T00:00:00.0000000Z", 1);
|
||||
await SetDeadLetterAsync("poison", "max attempts (10) exceeded while the historian accepted other events"); // the #976 rule: a REAL poison row
|
||||
await SetDeadLetterAsync("corrupt", "corrupt payload at 2026-12-01T00:00:00.0000000Z", 1);
|
||||
await sink.DebugResyncCountersAsync(CancellationToken.None);
|
||||
sink.GetStatus().DeadLetterDepth.ShouldBe(5);
|
||||
|
||||
var revived = sink.ReviveMaxAttemptsDeadLetters();
|
||||
|
||||
revived.ShouldBe(2);
|
||||
var status = sink.GetStatus();
|
||||
status.DeadLetterDepth.ShouldBe(3, "permanent / poison / corrupt rows stay dead-lettered");
|
||||
status.QueueDepth.ShouldBe(3, "the live row plus the two revived rows");
|
||||
|
||||
var rows = await Db.QueryAsync("SELECT alarm_id, dead_lettered, attempt_count, last_error FROM alarm_sf_events ORDER BY alarm_id",
|
||||
r => (Id: r.GetString(0), Dead: r.GetInt64(1), Attempts: r.GetInt64(2), Err: r.IsDBNull(3) ? null : r.GetString(3)),
|
||||
null, TestContext.Current.CancellationToken);
|
||||
rows.Single(r => r.Id == "old-cap-1").ShouldBe(("old-cap-1", 0L, 0L, null));
|
||||
rows.Single(r => r.Id == "old-cap-2").ShouldBe(("old-cap-2", 0L, 0L, null));
|
||||
rows.Single(r => r.Id == "permanent").Dead.ShouldBe(1);
|
||||
rows.Single(r => r.Id == "poison").Dead.ShouldBe(1);
|
||||
rows.Single(r => r.Id == "corrupt").Dead.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>Running it again (or on every boot) finds nothing: a revived row has no old-cap reason left.</summary>
|
||||
[Fact]
|
||||
public async Task Revive_is_idempotent_and_revived_rows_are_delivered_in_enqueue_order()
|
||||
{
|
||||
var writer = new FakeWriter();
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log);
|
||||
var t = DateTime.UtcNow;
|
||||
await sink.EnqueueAsync(Event("a", t.AddSeconds(1)), CancellationToken.None);
|
||||
await sink.EnqueueAsync(Event("b", t.AddSeconds(2)), CancellationToken.None);
|
||||
await SetDeadLetterAsync("a", OldCapReason);
|
||||
await SetDeadLetterAsync("b", OldCapReason);
|
||||
await sink.DebugResyncCountersAsync(CancellationToken.None);
|
||||
|
||||
sink.ReviveMaxAttemptsDeadLetters().ShouldBe(2);
|
||||
sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "second run is a no-op");
|
||||
sink.GetStatus().QueueDepth.ShouldBe(2);
|
||||
|
||||
await sink.DrainOnceAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
writer.Batches.Single().Select(e => e.AlarmId).ShouldBe(["a", "b"]);
|
||||
sink.GetStatus().QueueDepth.ShouldBe(0);
|
||||
sink.GetStatus().DeadLetterDepth.ShouldBe(0);
|
||||
sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "delivered rows are gone");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A revived row that is genuinely poison goes back to dead-letter under the NEW rule (so the one-time revival
|
||||
/// cannot loop): it needs MaxAttempts drains in which the historian proved reachable, and gets a new-style reason.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_revived_poison_row_dead_letters_again_with_the_new_reason_and_is_then_not_revived()
|
||||
{
|
||||
var writer = new OutageWriter();
|
||||
writer.RetryForever.Add("poison");
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, maxAttempts: 2);
|
||||
var t = DateTime.UtcNow;
|
||||
await sink.EnqueueAsync(Event("poison", t.AddSeconds(1)), CancellationToken.None);
|
||||
await SetDeadLetterAsync("poison", OldCapReason, 2);
|
||||
await sink.DebugResyncCountersAsync(CancellationToken.None);
|
||||
sink.ReviveMaxAttemptsDeadLetters().ShouldBe(1);
|
||||
|
||||
for (var i = 0; i < 2; i++)
|
||||
{
|
||||
await sink.EnqueueAsync(Event($"healthy-{i}", t.AddSeconds(10 + i)), CancellationToken.None);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
sink.GetStatus().DeadLetterDepth.ShouldBe(1);
|
||||
sink.ReviveMaxAttemptsDeadLetters().ShouldBe(0, "the new-rule reason is not the old cap's");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------- #1034 stalled queue
|
||||
|
||||
private static readonly TimeSpan Stall = TimeSpan.FromHours(2);
|
||||
|
||||
/// <summary>No progress for the threshold while rows are queued and this node is draining ⇒ Stalled; recovery clears it.</summary>
|
||||
[Fact]
|
||||
public async Task A_queue_with_no_progress_for_the_threshold_is_reported_stalled_and_recovers_on_the_first_ack()
|
||||
{
|
||||
var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
|
||||
var writer = new OutageWriter();
|
||||
writer.RetryForever.Add("stuck");
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, stallThreshold: Stall);
|
||||
await sink.EnqueueAsync(Event("stuck", now), CancellationToken.None);
|
||||
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse("first drain only starts the clock");
|
||||
|
||||
now += Stall - TimeSpan.FromMinutes(1);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse("just under the threshold");
|
||||
|
||||
now += TimeSpan.FromMinutes(2);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
var stalled = sink.GetStatus();
|
||||
stalled.Stalled.ShouldBeTrue();
|
||||
stalled.QueueDepth.ShouldBe(1);
|
||||
stalled.LastProgressUtc.ShouldBe(new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc));
|
||||
|
||||
writer.RetryForever.Clear();
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse("the row was delivered");
|
||||
}
|
||||
|
||||
/// <summary>Positive control: a queue that keeps draining (some Ack every drain) is never stalled, however old it gets.</summary>
|
||||
[Fact]
|
||||
public async Task A_queue_that_keeps_acking_is_never_stalled_even_with_a_retry_forever_row_at_its_head()
|
||||
{
|
||||
var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
|
||||
var writer = new OutageWriter();
|
||||
writer.RetryForever.Add("stuck");
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, maxAttempts: 100_000, stallThreshold: Stall);
|
||||
await sink.EnqueueAsync(Event("stuck", now), CancellationToken.None);
|
||||
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
now += TimeSpan.FromHours(1);
|
||||
await sink.EnqueueAsync(Event($"ok-{i}", now), CancellationToken.None);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse($"cycle {i}: the historian is accepting events");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Secondary (gate closed) is not draining on purpose: never Stalled, and promotion restarts the clock.</summary>
|
||||
[Fact]
|
||||
public async Task A_node_that_is_not_the_drain_owner_is_never_stalled_and_promotion_restarts_the_clock()
|
||||
{
|
||||
var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
|
||||
var open = false;
|
||||
var writer = new OutageWriter { Down = true };
|
||||
using var sink = new LocalDbStoreAndForwardSink(Db, writer, _log, clock: () => now, stallThreshold: Stall, drainGate: () => open);
|
||||
await sink.EnqueueAsync(Event("a", now), CancellationToken.None);
|
||||
|
||||
now += TimeSpan.FromHours(10);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().DrainState.ShouldBe(HistorianDrainState.NotPrimary);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse();
|
||||
|
||||
open = true; // promoted
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeFalse("the clock starts at promotion, not at enqueue");
|
||||
now += Stall + TimeSpan.FromMinutes(1);
|
||||
await sink.DrainOnceAsync(CancellationToken.None);
|
||||
sink.GetStatus().Stalled.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>An empty queue is never stalled, and the feature is off unless a threshold is configured.</summary>
|
||||
[Fact]
|
||||
public async Task Stall_detection_is_off_without_a_threshold_and_an_empty_queue_is_never_stalled()
|
||||
{
|
||||
var now = new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc);
|
||||
var down = new OutageWriter { Down = true };
|
||||
using (var off = new LocalDbStoreAndForwardSink(Db, down, _log, clock: () => now))
|
||||
{
|
||||
await off.EnqueueAsync(Event("a", now), CancellationToken.None);
|
||||
await off.DrainOnceAsync(CancellationToken.None);
|
||||
now += TimeSpan.FromDays(2);
|
||||
await off.DrainOnceAsync(CancellationToken.None);
|
||||
off.GetStatus().Stalled.ShouldBeFalse("no threshold configured");
|
||||
down.Down = false;
|
||||
await off.DrainOnceAsync(CancellationToken.None);
|
||||
off.GetStatus().QueueDepth.ShouldBe(0);
|
||||
}
|
||||
|
||||
using var on = new LocalDbStoreAndForwardSink(Db, down, _log, clock: () => now, stallThreshold: Stall);
|
||||
await on.DrainOnceAsync(CancellationToken.None);
|
||||
now += TimeSpan.FromDays(2);
|
||||
await on.DrainOnceAsync(CancellationToken.None);
|
||||
on.GetStatus().QueueDepth.ShouldBe(0);
|
||||
on.GetStatus().Stalled.ShouldBeFalse("nothing queued");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -17,7 +17,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian.Tests;
|
||||
/// capacity eviction, and retention-based dead-letter purge.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class LocalDbStoreAndForwardSinkTests : IDisposable
|
||||
public sealed partial class LocalDbStoreAndForwardSinkTests : IDisposable
|
||||
{
|
||||
private readonly string _dbPath;
|
||||
private readonly ILogger _log;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Health;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Health;
|
||||
|
||||
/// <summary>#1034: a stalled alarm store-and-forward queue is Degraded (still ready/200), never Unhealthy.</summary>
|
||||
public sealed class AlarmHistorianHealthCheckTests
|
||||
{
|
||||
private static HistorianSinkStatus Status(bool stalled, string? lastError = null) => new(
|
||||
QueueDepth: 12, DeadLetterDepth: 1, LastDrainUtc: null, LastSuccessUtc: null, LastError: lastError,
|
||||
DrainState: HistorianDrainState.BackingOff, Stalled: stalled,
|
||||
LastProgressUtc: new DateTime(2026, 12, 3, 0, 0, 0, DateTimeKind.Utc));
|
||||
|
||||
[Fact]
|
||||
public void No_sink_is_healthy() =>
|
||||
AlarmHistorianHealthDecision.Evaluate(null).Status.ShouldBe(HealthStatus.Healthy);
|
||||
|
||||
[Fact]
|
||||
public void A_draining_queue_is_healthy_and_reports_its_figures()
|
||||
{
|
||||
var (status, _, data) = AlarmHistorianHealthDecision.Evaluate(Status(stalled: false));
|
||||
status.ShouldBe(HealthStatus.Healthy);
|
||||
data["queueDepth"].ShouldBe(12L);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_stalled_queue_is_degraded_never_unhealthy_and_carries_the_last_error()
|
||||
{
|
||||
var (status, description, data) = AlarmHistorianHealthDecision.Evaluate(Status(stalled: true, "Historian unavailable"));
|
||||
status.ShouldBe(HealthStatus.Degraded);
|
||||
description.ShouldContain("stalled");
|
||||
description.ShouldContain("Historian unavailable");
|
||||
data["lastError"].ShouldBe("Historian unavailable");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_check_maps_a_stalled_sink_to_Degraded()
|
||||
{
|
||||
var result = await new AlarmHistorianHealthCheck(new FixedSink(Status(stalled: true)))
|
||||
.CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken);
|
||||
result.Status.ShouldBe(HealthStatus.Degraded);
|
||||
|
||||
(await new AlarmHistorianHealthCheck(null).CheckHealthAsync(new HealthCheckContext(), TestContext.Current.CancellationToken))
|
||||
.Status.ShouldBe(HealthStatus.Healthy);
|
||||
}
|
||||
|
||||
private sealed class FixedSink(HistorianSinkStatus status) : IAlarmHistorianSink
|
||||
{
|
||||
public Task EnqueueAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
public HistorianSinkStatus GetStatus() => status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using System.Diagnostics.Metrics;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.AlarmHistorian;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Historian;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian;
|
||||
|
||||
/// <summary>#1034: the alarm-queue stall gauge and the options that drive it.</summary>
|
||||
[Collection("AlarmHistorianMetricsBinding")] // the sink gauges bind process-wide state
|
||||
public sealed class AlarmHistorianMetricsTests
|
||||
{
|
||||
[Fact]
|
||||
public void The_stalled_gauge_reads_1_for_a_stalled_sink_and_0_once_it_recovers()
|
||||
{
|
||||
var sink = new SwitchSink();
|
||||
AlarmHistorianMetrics.Bind(sink);
|
||||
|
||||
Observe().ShouldBe(0);
|
||||
sink.Stalled = true;
|
||||
Observe().ShouldBe(1);
|
||||
sink.Stalled = false;
|
||||
Observe().ShouldBe(0);
|
||||
}
|
||||
|
||||
private static int Observe()
|
||||
{
|
||||
var seen = new List<int>();
|
||||
using var listener = new MeterListener
|
||||
{
|
||||
InstrumentPublished = (inst, l) =>
|
||||
{
|
||||
if (ReferenceEquals(inst.Meter, OtOpcUaTelemetry.Meter) && inst.Name == AlarmHistorianMetrics.StalledGaugeName)
|
||||
l.EnableMeasurementEvents(inst);
|
||||
},
|
||||
};
|
||||
listener.SetMeasurementEventCallback<int>((inst, v, _, _) => { if (inst.Name == AlarmHistorianMetrics.StalledGaugeName) seen.Add(v); });
|
||||
listener.Start();
|
||||
listener.RecordObservableInstruments();
|
||||
return seen.Single();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Options_default_to_a_two_hour_stall_threshold_and_no_revival_and_zero_disables()
|
||||
{
|
||||
var o = new AlarmHistorianOptions();
|
||||
o.StallThreshold.ShouldBe(TimeSpan.FromHours(2));
|
||||
o.ReviveMaxAttemptsDeadLetters.ShouldBeFalse();
|
||||
new AlarmHistorianOptions { StallThresholdHours = 0 }.StallThreshold.ShouldBeNull();
|
||||
new AlarmHistorianOptions { StallThresholdHours = 0.5 }.StallThreshold.ShouldBe(TimeSpan.FromMinutes(30));
|
||||
}
|
||||
|
||||
private sealed class SwitchSink : IAlarmHistorianSink
|
||||
{
|
||||
public volatile bool Stalled;
|
||||
public Task EnqueueAsync(AlarmHistorianEvent evt, CancellationToken cancellationToken) => Task.CompletedTask;
|
||||
public HistorianSinkStatus GetStatus() => new(1, 0, null, null, null, HistorianDrainState.BackingOff, Stalled: Stalled);
|
||||
}
|
||||
}
|
||||
+1
@@ -17,6 +17,7 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Historian;
|
||||
/// default survives; when it is enabled a real <see cref="LocalDbStoreAndForwardSink"/> wins
|
||||
/// (last-registration-wins over the <c>TryAddSingleton</c> Null default).
|
||||
/// </summary>
|
||||
[Collection("AlarmHistorianMetricsBinding")] // the sink gauges bind process-wide state
|
||||
public sealed class AlarmHistorianRegistrationTests
|
||||
{
|
||||
/// <summary>A no-op writer the factory hands the sink; never actually invoked in these tests.</summary>
|
||||
|
||||
Reference in New Issue
Block a user