fix(grpc-data): A1 review S3 + S4 + nits — snapshot start cursor, readiness cut with the snapshot, failed applies
- S3a: SnapshotConditions reads a start cursor under Lock before enumerating keys; every slice carries it, so a condition materialised and activated between the enumeration and slice 1's hold is covered by deltas after it. - S3b: each hold captures the apply generation (bumped when a rebuild begins) and the complete flag; slices carry them and ConditionSnapshotSlice.IsCompleteSnapshot / ConditionStateHub.IsSnapshotCompleteFor detect a rebuild that straddles a multi-slice snapshot. An empty scope still takes one hold. - S3c: maxConditionsPerHold is clamped to MaxConditionsPerHoldLimit (5,000). - S4: CompleteAddressSpaceApply(bool succeeded) (new default sink member, forwarded by the deferred and SDK sinks); the publish actor passes !Degraded. A failed/degraded rebuild keeps readiness false and its pending removals, emitting no removal records; the next successful apply completes it. - Nits: ConditionStateRecord.UnshelveTimeUtc (timed-shelve expiry); ConditionStateHub.Read has a bounded default.
This commit is contained in:
@@ -88,6 +88,9 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _inner.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply(bool succeeded) => _inner.CompleteAddressSpaceApply(succeeded);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _inner.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
@@ -213,6 +213,15 @@ public interface IOpcUaAddressSpaceSink
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="CompleteAddressSpaceApply()"/> with the apply's outcome (A1 review S4): <paramref name="succeeded"/>
|
||||
/// is false for a throwing or degraded apply, and an SDK-backed sink then keeps a rebuild's condition-set
|
||||
/// readiness withheld and emits no removal records for conditions the failed pass did not re-materialise. The
|
||||
/// default forwards to the parameterless overload.
|
||||
/// </summary>
|
||||
/// <param name="succeeded">Whether the apply completed cleanly.</param>
|
||||
void CompleteAddressSpaceApply(bool succeeded) => CompleteAddressSpaceApply();
|
||||
|
||||
/// <summary>
|
||||
/// A1 (plan §5.1 T1/T2): the state of <paramref name="conditionIds"/> has been ESTABLISHED by
|
||||
/// <paramref name="source"/> (a driver's <c>InitialAlarmStateDelivered</c>, its backstop timer, or a scripted
|
||||
|
||||
@@ -39,6 +39,8 @@ public readonly record struct ConditionActivationMarker(string Incarnation, ulon
|
||||
/// <param name="Activation">The origin-owned activation marker (T3).</param>
|
||||
/// <param name="Comment">The condition's Comment text, if any.</param>
|
||||
/// <param name="ClientUserId">Who left that comment, if recorded.</param>
|
||||
/// <param name="UnshelveTimeUtc">For a timed shelve, the absolute UTC expiry (A2 projects the remaining time from it);
|
||||
/// otherwise null.</param>
|
||||
public sealed record ConditionStateRecord(
|
||||
AddressSpaceRealm Realm,
|
||||
string ConditionId,
|
||||
@@ -59,7 +61,8 @@ public sealed record ConditionStateRecord(
|
||||
bool Retain,
|
||||
ConditionActivationMarker Activation,
|
||||
string? Comment = null,
|
||||
string? ClientUserId = null);
|
||||
string? ClientUserId = null,
|
||||
DateTime? UnshelveTimeUtc = null);
|
||||
|
||||
/// <summary>
|
||||
/// The node manager's SDK-free delta callback (plan §5.1). Implemented by the Runtime's <c>ConditionStateHub</c>.
|
||||
@@ -95,4 +98,34 @@ public interface IConditionStateSink
|
||||
/// </summary>
|
||||
/// <param name="Watermark">The sink's watermark taken under the same hold.</param>
|
||||
/// <param name="Records">The copied records (each carries <see cref="Watermark"/> as its version).</param>
|
||||
public sealed record ConditionSnapshotSlice(long Watermark, IReadOnlyList<ConditionStateRecord> Records);
|
||||
/// <param name="StartCursor">
|
||||
/// The watermark read BEFORE the snapshot enumerated its keys (the same for every slice of one snapshot). A condition
|
||||
/// no slice holds — materialised after the enumeration — is covered by its deltas after this cursor.
|
||||
/// </param>
|
||||
/// <param name="ApplyGeneration">The node manager's apply generation (bumped when a rebuild begins) under this hold.</param>
|
||||
/// <param name="ApplyComplete">Whether the address-space apply was complete under this hold.</param>
|
||||
public sealed record ConditionSnapshotSlice(
|
||||
long Watermark,
|
||||
IReadOnlyList<ConditionStateRecord> Records,
|
||||
long StartCursor = 0,
|
||||
long ApplyGeneration = 0,
|
||||
bool ApplyComplete = false)
|
||||
{
|
||||
/// <summary>
|
||||
/// Whether the slices form a complete snapshot of the condition SET: every hold saw a completed apply of ONE
|
||||
/// generation (review S3b — readiness atomic with the cut). False when a rebuild began during, or straddled, a
|
||||
/// multi-slice snapshot: the caller retakes it (and keeps sending <c>NotReady</c>). The Primary verdict is the
|
||||
/// caller's to combine.
|
||||
/// </summary>
|
||||
/// <param name="slices">One snapshot's slices.</param>
|
||||
/// <returns><see langword="true"/> when complete and consistent.</returns>
|
||||
public static bool IsCompleteSnapshot(IReadOnlyList<ConditionSnapshotSlice> slices)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(slices);
|
||||
if (slices.Count == 0) return false; // SnapshotConditions always returns at least one slice
|
||||
var generation = slices[0].ApplyGeneration;
|
||||
foreach (var s in slices)
|
||||
if (!s.ApplyComplete || s.ApplyGeneration != generation) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,12 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>The default most conditions one snapshot <c>Lock</c> hold copies (§5.5 <c>MaxConditions</c>).</summary>
|
||||
public const int DefaultMaxConditionsPerHold = 1000;
|
||||
|
||||
/// <summary>
|
||||
/// The upper bound a caller's <c>maxConditionsPerHold</c> is clamped to (review S3c): at the measured
|
||||
/// ≈ 1.7–2.9 µs per condition (§5.1) one hold stays ≈ 9–15 ms, whatever a mapping configures.
|
||||
/// </summary>
|
||||
public const int MaxConditionsPerHoldLimit = 5000;
|
||||
|
||||
/// <summary>Per-condition activation bookkeeping: the occurrence sequence plus the Active/Acked basis it was
|
||||
/// last compared against. Mutable, only touched under <c>Lock</c>.</summary>
|
||||
private sealed class ActivationEntry
|
||||
@@ -35,6 +41,11 @@ public sealed partial class OtOpcUaNodeManager
|
||||
// a consumer retire a condition that is still active at the origin).
|
||||
private readonly HashSet<RealmKey> _rebuildPendingRemoval = new();
|
||||
private bool _conditionApplyComplete;
|
||||
// Bumped when a rebuild begins; captured under each snapshot hold so a caller can detect a rebuild that
|
||||
// straddles a multi-slice snapshot (review S3b).
|
||||
private long _conditionApplyGeneration;
|
||||
// The absolute expiry of each timed-shelved condition (set by WriteAlarmCondition), for the record's UnshelveTimeUtc.
|
||||
private readonly Dictionary<RealmKey, DateTime> _conditionUnshelveAt = new();
|
||||
|
||||
/// <summary>The serving incarnation the activation markers are minted under (one per node-manager lifetime).</summary>
|
||||
internal string ConditionIncarnation { get; set; } = Guid.NewGuid().ToString("N");
|
||||
@@ -42,6 +53,9 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>Test seam: invoked after each snapshot <c>Lock</c> hold (outside it) with the records that hold copied.</summary>
|
||||
internal Action<int>? OnConditionSnapshotHold { get; set; }
|
||||
|
||||
/// <summary>Test seam: invoked after a snapshot enumerated its keys and before its first hold (outside <c>Lock</c>).</summary>
|
||||
internal Action? OnConditionSnapshotKeysEnumerated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// The SDK-free condition-state delta callback (the Runtime's <c>ConditionStateHub</c>). Null = no hub; the
|
||||
/// known flags and activation markers are still maintained. Set once at host start.
|
||||
@@ -149,29 +163,45 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// snapshot defines the SET), never more than <paramref name="maxConditionsPerHold"/> per <c>Lock</c> hold.
|
||||
/// Each slice carries the sink's watermark taken under the same hold, so a delta is either inside the slice or
|
||||
/// after its watermark. A consumer must register for deltas before snapshotting.
|
||||
/// <para>Review S3: every slice also carries <see cref="ConditionSnapshotSlice.StartCursor"/> — the watermark
|
||||
/// read under <c>Lock</c> BEFORE the keys are enumerated — so a condition materialised (and activated) after
|
||||
/// that point, which no slice holds, is covered by the deltas after the start cursor; and the apply generation +
|
||||
/// complete flag captured under that slice's hold, so a caller can tell a snapshot cut during or across a
|
||||
/// rebuild (<see cref="ConditionSnapshotSlice.IsCompleteSnapshot"/>).</para>
|
||||
/// </summary>
|
||||
/// <param name="scope">Realm + id filter (an export's root); evaluated outside <c>Lock</c>.</param>
|
||||
/// <param name="maxConditionsPerHold">The most conditions one hold copies (≥ 1).</param>
|
||||
/// <param name="maxConditionsPerHold">The most conditions one hold copies (≥ 1; clamped to
|
||||
/// <see cref="MaxConditionsPerHoldLimit"/>).</param>
|
||||
/// <returns>The slices in ascending (realm, id) order.</returns>
|
||||
public IReadOnlyList<ConditionSnapshotSlice> SnapshotConditions(
|
||||
Func<AddressSpaceRealm, string, bool> scope, int maxConditionsPerHold = DefaultMaxConditionsPerHold)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(scope);
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(maxConditionsPerHold, 1);
|
||||
maxConditionsPerHold = Math.Min(maxConditionsPerHold, MaxConditionsPerHoldLimit);
|
||||
|
||||
long startCursor;
|
||||
lock (Lock) startCursor = _conditionStateSink?.Watermark ?? 0;
|
||||
|
||||
// Key enumeration and the scope filter run OFF Lock (the map is concurrent and keys are immutable); a
|
||||
// condition added after this point is not in the snapshot but its materialise record is a delta.
|
||||
var keys = _alarmConditions.Keys.Where(k => scope(k.Realm, k.Id))
|
||||
.OrderBy(k => k.Realm).ThenBy(k => k.Id, StringComparer.Ordinal).ToList();
|
||||
var slices = new List<ConditionSnapshotSlice>((keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold);
|
||||
for (var start = 0; start < keys.Count; start += maxConditionsPerHold)
|
||||
OnConditionSnapshotKeysEnumerated?.Invoke();
|
||||
// At least one hold even for an empty scope: an empty SET is a snapshot too, and its readiness must be cut.
|
||||
var sliceCount = Math.Max(1, (keys.Count + maxConditionsPerHold - 1) / maxConditionsPerHold);
|
||||
var slices = new List<ConditionSnapshotSlice>(sliceCount);
|
||||
for (var start = 0; slices.Count < sliceCount; start += maxConditionsPerHold)
|
||||
{
|
||||
var end = Math.Min(start + maxConditionsPerHold, keys.Count);
|
||||
var records = new List<ConditionStateRecord>(end - start);
|
||||
long watermark;
|
||||
long watermark, generation;
|
||||
bool applyComplete;
|
||||
lock (Lock)
|
||||
{
|
||||
watermark = _conditionStateSink?.Watermark ?? 0;
|
||||
generation = _conditionApplyGeneration;
|
||||
applyComplete = _conditionApplyComplete;
|
||||
for (var i = start; i < end; i++)
|
||||
{
|
||||
if (_alarmConditions.TryGetValue(keys[i], out var condition))
|
||||
@@ -180,7 +210,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
}
|
||||
|
||||
OnConditionSnapshotHold?.Invoke(records.Count);
|
||||
slices.Add(new ConditionSnapshotSlice(watermark, records));
|
||||
slices.Add(new ConditionSnapshotSlice(watermark, records, startCursor, generation, applyComplete));
|
||||
}
|
||||
|
||||
return slices;
|
||||
@@ -205,6 +235,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private void ForgetConditionState(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_conditionUnshelveAt.Remove(key);
|
||||
_activation.Remove(key, out var entry);
|
||||
_conditionStateSink?.Append(BuildConditionRecord(key, condition, 0, removed: true, entry));
|
||||
}
|
||||
@@ -213,8 +244,10 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private void CaptureConditionStateForRebuild()
|
||||
{
|
||||
_conditionApplyComplete = false;
|
||||
_conditionApplyGeneration++;
|
||||
_conditionStateSink?.OnApplyStateChanged(false);
|
||||
_rebuildScriptedActivation.Clear();
|
||||
_conditionUnshelveAt.Clear();
|
||||
foreach (var key in _alarmConditions.Keys)
|
||||
{
|
||||
_rebuildPendingRemoval.Add(key);
|
||||
@@ -228,8 +261,23 @@ public sealed partial class OtOpcUaNodeManager
|
||||
|
||||
/// <summary>Under <c>Lock</c>, at <c>CompleteAddressSpaceApply</c>: announce the conditions the rebuild dropped
|
||||
/// for good, forget the rebuild memory and mark the apply complete.</summary>
|
||||
private void CompleteConditionApply()
|
||||
/// <param name="succeeded">
|
||||
/// Review S4: false for a throwing or degraded apply. Then a rebuild in progress is NOT completed: readiness
|
||||
/// stays false and the pending-removal set is kept, so no removal record is emitted for a condition the failed
|
||||
/// pass simply did not re-materialise (a consumer would retire a condition that may still be active). The
|
||||
/// next successful apply completes it.
|
||||
/// </param>
|
||||
private void CompleteConditionApply(bool succeeded)
|
||||
{
|
||||
if (!succeeded)
|
||||
{
|
||||
if (!_conditionApplyComplete)
|
||||
_logger.LogWarning(
|
||||
"OtOpcUaNodeManager: the address-space apply failed or was degraded — condition snapshot readiness withheld and {Pending} pending removal(s) kept until an apply succeeds",
|
||||
_rebuildPendingRemoval.Count);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var key in _rebuildPendingRemoval)
|
||||
{
|
||||
if (_alarmConditions.ContainsKey(key)) continue;
|
||||
@@ -305,6 +353,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
c.Retain?.Value == true,
|
||||
new ConditionActivationMarker(ConditionIncarnation, entry?.Sequence ?? 0),
|
||||
c.Comment?.Value.Text,
|
||||
c.ClientUserId?.Value);
|
||||
c.ClientUserId?.Value,
|
||||
delta.Shelving == AlarmShelvingKind.Timed && _conditionUnshelveAt.TryGetValue(key, out var unshelveAt) ? unshelveAt : null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,6 +1373,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
{
|
||||
condition.SetConfirmedState(SystemContext, state.Confirmed);
|
||||
}
|
||||
// A1 review nit: the absolute timed-shelve expiry rides the condition-state record (A2 projects it).
|
||||
if (state.Shelving == AlarmShelvingKind.Timed && state.UnshelveAtUtc is { } unshelveAt) _conditionUnshelveAt[key] = unshelveAt;
|
||||
else _conditionUnshelveAt.Remove(key);
|
||||
if (condition.ShelvingState is not null)
|
||||
{
|
||||
// SetShelvingState(shelved, oneShot, shelvingTime): map our 3-way kind onto the SDK's
|
||||
@@ -5683,7 +5686,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
// re-assert does), then discards whatever captured state no materialise claimed. A condition the apply
|
||||
// replaced again after restoring it is skipped: the instance reported must be the one restored.
|
||||
/// <inheritdoc cref="IOpcUaAddressSpaceSink.CompleteAddressSpaceApply"/>
|
||||
public void CompleteAddressSpaceApply()
|
||||
public void CompleteAddressSpaceApply() => CompleteAddressSpaceApply(succeeded: true);
|
||||
|
||||
/// <inheritdoc cref="IOpcUaAddressSpaceSink.CompleteAddressSpaceApply(bool)"/>
|
||||
public void CompleteAddressSpaceApply(bool succeeded)
|
||||
{
|
||||
int reported = 0, discarded;
|
||||
lock (Lock)
|
||||
@@ -5701,7 +5707,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
|
||||
discarded = _rebuildCarryOver.Count;
|
||||
_restoredConditionReports.Clear();
|
||||
_rebuildCarryOver.Clear();
|
||||
CompleteConditionApply();
|
||||
CompleteConditionApply(succeeded);
|
||||
}
|
||||
|
||||
if (reported > 0 || discarded > 0)
|
||||
|
||||
@@ -141,6 +141,9 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply() => _nodeManager.CompleteAddressSpaceApply();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void CompleteAddressSpaceApply(bool succeeded) => _nodeManager.CompleteAddressSpaceApply(succeeded);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void MarkConditionsKnown(string source, IReadOnlyList<string> conditionIds, AddressSpaceRealm realm)
|
||||
=> _nodeManager.MarkConditionsKnown(source, conditionIds, realm);
|
||||
|
||||
@@ -41,6 +41,9 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <summary>Default per-partition buffer capacity (records).</summary>
|
||||
public const int DefaultPartitionCapacity = 8192;
|
||||
|
||||
/// <summary>The default most records one <see cref="Read"/> returns (review nit: bounded, not <c>int.MaxValue</c>).</summary>
|
||||
public const int DefaultReadMax = 1024;
|
||||
|
||||
private sealed class Partition
|
||||
{
|
||||
public readonly object Gate = new();
|
||||
@@ -82,6 +85,16 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <summary><c>snapshot_complete</c> may be sent: apply complete AND this node is Primary.</summary>
|
||||
public bool IsSnapshotComplete => _applyComplete && _primary?.ShouldActAsPrimary == true;
|
||||
|
||||
/// <summary>
|
||||
/// <c>snapshot_complete</c> for ONE taken snapshot (review S3b): readiness read atomically with the cut — every
|
||||
/// slice's hold saw a completed apply of one generation — AND this node is Primary. Prefer this over
|
||||
/// <see cref="IsSnapshotComplete"/>, which a rebuild can flip between the read and the snapshot.
|
||||
/// </summary>
|
||||
/// <param name="slices">The snapshot's slices (<c>OtOpcUaNodeManager.SnapshotConditions</c>).</param>
|
||||
/// <returns>Whether that snapshot may be sent as complete.</returns>
|
||||
public bool IsSnapshotCompleteFor(IReadOnlyList<ConditionSnapshotSlice> slices) =>
|
||||
ConditionSnapshotSlice.IsCompleteSnapshot(slices) && _primary?.ShouldActAsPrimary == true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public long Append(ConditionStateRecord record)
|
||||
{
|
||||
@@ -134,8 +147,9 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
/// <param name="afterVersion">The reader's cursor (the slice watermark or the last version it applied).</param>
|
||||
/// <param name="max">The most records to return.</param>
|
||||
/// <returns>The read.</returns>
|
||||
public ConditionDeltaRead Read(int partition, long afterVersion, int max = int.MaxValue)
|
||||
public ConditionDeltaRead Read(int partition, long afterVersion, int max = DefaultReadMax)
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfLessThan(max, 1);
|
||||
var p = _partitions[partition];
|
||||
lock (p.Gate)
|
||||
{
|
||||
@@ -160,7 +174,7 @@ public sealed class ConditionStateHub : IConditionStateSink
|
||||
var all = new List<ConditionStateRecord>();
|
||||
for (var i = 0; i < _partitions.Length; i++)
|
||||
{
|
||||
var read = Read(i, afterVersion);
|
||||
var read = Read(i, afterVersion, DefaultPartitionCapacity);
|
||||
if (read.ResetRequired) return null;
|
||||
all.AddRange(read.Records);
|
||||
}
|
||||
|
||||
@@ -1345,7 +1345,9 @@ public sealed class OpcUaPublishActor : ReceiveActor, IWithTimers
|
||||
/// </summary>
|
||||
private void FinishRebuild(RebuildAddressSpace msg, IActorRef requester, (bool Degraded, string? Reason) outcome)
|
||||
{
|
||||
try { _sink.CompleteAddressSpaceApply(); }
|
||||
// A1 review S4: a degraded/throwing apply must not complete a rebuild's condition set (no removal records for
|
||||
// conditions it failed to re-materialise, readiness stays withheld).
|
||||
try { _sink.CompleteAddressSpaceApply(succeeded: !outcome.Degraded); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Error(ex, "OpcUaPublish: sink.CompleteAddressSpaceApply threw (correlation={Correlation})", msg.Correlation);
|
||||
|
||||
@@ -302,6 +302,118 @@ public sealed class ConditionStateNodeManagerTests : IDisposable
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Review S3a: a condition materialised and activated between the key enumeration and slice 1's hold is in
|
||||
/// no slice, and its records are after the snapshot's START cursor — the slice watermark alone would hide them.</summary>
|
||||
[Fact]
|
||||
public async Task S3a_A_condition_materialised_after_the_enumeration_is_covered_by_deltas_after_the_start_cursor()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
const string Late = Device + "/Late";
|
||||
nm.OnConditionSnapshotKeysEnumerated = () =>
|
||||
{
|
||||
nm.MaterialiseAlarmCondition(Late, Device, "Late", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
nm.WriteAlarmCondition(Late, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
};
|
||||
|
||||
var slices = nm.SnapshotConditions((_, _) => true);
|
||||
|
||||
slices.SelectMany(x => x.Records).ShouldNotContain(r => r.ConditionId == Late);
|
||||
slices.ShouldAllBe(x => x.StartCursor == slices[0].StartCursor);
|
||||
var late = sink.Records.Where(r => r.ConditionId == Late).ToList();
|
||||
late.ShouldNotBeEmpty();
|
||||
late.ShouldAllBe(r => r.Version > slices[0].StartCursor);
|
||||
late.ShouldAllBe(r => r.Version <= slices[0].Watermark); // why the start cursor is needed
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Review S3b: readiness is cut with the snapshot — a rebuild that straddles a multi-slice snapshot (even one
|
||||
/// that completes before the last hold) makes it incomplete; one inside a single apply generation is complete.</summary>
|
||||
[Fact]
|
||||
public async Task S3b_A_rebuild_straddling_a_multi_slice_snapshot_makes_it_incomplete()
|
||||
{
|
||||
var (host, nm, _) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeFalse(); // not applied yet
|
||||
nm.CompleteAddressSpaceApply();
|
||||
ConditionSnapshotSlice.IsCompleteSnapshot(nm.SnapshotConditions((_, _) => true, 1)).ShouldBeTrue();
|
||||
|
||||
var holds = 0;
|
||||
nm.OnConditionSnapshotHold = _ =>
|
||||
{
|
||||
if (++holds != 1) return;
|
||||
nm.RebuildAddressSpace();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
};
|
||||
var slices = nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: 1);
|
||||
|
||||
slices.Count.ShouldBe(3);
|
||||
slices.ShouldAllBe(x => x.ApplyComplete); // each hold alone looks ready …
|
||||
ConditionSnapshotSlice.IsCompleteSnapshot(slices).ShouldBeFalse(); // … but the cut spans two generations
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Review S3c: a caller's per-hold maximum is clamped to <see cref="OtOpcUaNodeManager.MaxConditionsPerHoldLimit"/>.</summary>
|
||||
[Fact]
|
||||
public async Task S3c_MaxConditions_per_hold_is_clamped()
|
||||
{
|
||||
var (host, nm, _) = await BootAsync();
|
||||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||||
for (var i = 0; i <= OtOpcUaNodeManager.MaxConditionsPerHoldLimit; i++)
|
||||
nm.MaterialiseAlarmCondition($"{Device}/C{i:00000}", Device, $"C{i:00000}", "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true);
|
||||
var holds = new List<int>();
|
||||
nm.OnConditionSnapshotHold = holds.Add;
|
||||
|
||||
nm.SnapshotConditions((_, _) => true, maxConditionsPerHold: int.MaxValue);
|
||||
|
||||
holds.ShouldBe([OtOpcUaNodeManager.MaxConditionsPerHoldLimit, 1]);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Review S4: a failed/degraded rebuild apply neither emits removal records for the conditions it did not
|
||||
/// re-materialise nor flips readiness; the next successful apply completes it.</summary>
|
||||
[Fact]
|
||||
public async Task S4_A_failed_rebuild_apply_emits_no_removals_and_keeps_readiness_withheld()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
nm.RebuildAddressSpace();
|
||||
nm.EnsureFolder(Device, null, "dev1", AddressSpaceRealm.Raw);
|
||||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
var before = sink.Records.Count;
|
||||
|
||||
nm.CompleteAddressSpaceApply(succeeded: false); // the pass threw before re-creating Native2 and the scripted one
|
||||
|
||||
sink.Records.Skip(before).ShouldNotContain(r => r.Removed);
|
||||
sink.ApplyComplete.ShouldBe(false);
|
||||
nm.IsConditionApplyComplete.ShouldBeFalse();
|
||||
|
||||
nm.CompleteAddressSpaceApply(succeeded: true); // a later successful apply (that also dropped them)
|
||||
sink.Records.Skip(before).Where(r => r.Removed).Select(r => r.ConditionId).ShouldBe([Native2, Scripted], ignoreOrder: true);
|
||||
sink.ApplyComplete.ShouldBe(true);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Review nit: a timed shelve's absolute expiry rides the record (A2 projects the remaining time).</summary>
|
||||
[Fact]
|
||||
public async Task A_timed_shelve_record_carries_its_UnshelveTime()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
var at = DateTime.UtcNow.AddMinutes(5);
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false) with { Shelving = AlarmShelvingKind.Timed, UnshelveAtUtc = at },
|
||||
DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
sink.Records.Last().ShouldSatisfyAllConditions(
|
||||
r => r.Shelving.ShouldBe(AlarmShelvingKind.Timed), r => r.UnshelveTimeUtc.ShouldBe(at));
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
sink.Records.Last().UnshelveTimeUtc.ShouldBeNull();
|
||||
AssertParity(nm, sink);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
private static void MaterialiseAll(OtOpcUaNodeManager nm)
|
||||
|
||||
+29
@@ -148,6 +148,27 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Review S4: a throwing apply completes with <c>succeeded: false</c> (the node manager then keeps the
|
||||
/// rebuild's readiness withheld and emits no removals); a clean one with <c>true</c>.</summary>
|
||||
[Fact]
|
||||
public void A_throwing_apply_completes_the_address_space_apply_as_failed()
|
||||
{
|
||||
var sink = new OrderSink();
|
||||
var fail = true;
|
||||
var actor = Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
|
||||
new OpcUaPublishActor.TestHooks { BeforePlan = () => { if (fail) throw new InvalidOperationException("boom"); } }));
|
||||
|
||||
actor.Tell(Rebuild());
|
||||
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitAssert(() => sink.Completions.ShouldBe([false]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
fail = false;
|
||||
actor.Tell(Rebuild());
|
||||
ExpectMsg<OpcUaPublishActor.RebuildCompleted>(PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
AwaitAssert(() => sink.Completions.ShouldBe([false, true]), PlanBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private IActorRef Spawn(OrderSink sink, ManualResetEventSlim gate) =>
|
||||
Sys.ActorOf(OpcUaPublishActor.PropsForTests(
|
||||
sink, new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance),
|
||||
@@ -238,6 +259,14 @@ public sealed class OpcUaPublishActorConditionKnownTests : RuntimeActorTestBase
|
||||
lock (_gate) _conditions.Add(alarmNodeId);
|
||||
}
|
||||
|
||||
public List<bool> Completions { get { lock (_gate) return [.. _completions]; } }
|
||||
private readonly List<bool> _completions = new();
|
||||
|
||||
public void CompleteAddressSpaceApply(bool succeeded)
|
||||
{
|
||||
lock (_gate) _completions.Add(succeeded);
|
||||
}
|
||||
|
||||
public void RebuildAddressSpace()
|
||||
{
|
||||
lock (_gate) { _conditions.Clear(); _known.Clear(); }
|
||||
|
||||
Reference in New Issue
Block a user