fix(dcl): separator-aware alarm routing, typed reply for browse/search while disconnected, server-timestamp fallback (DCL-5, DCL-6, DCL-7, WP3 task 3.4)
This commit is contained in:
@@ -300,7 +300,7 @@ Three subscribe paths, deliberately paced differently:
|
|||||||
| **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. |
|
| **Reconnect re-subscribe** (`ReSubscribeAll`) | **Sequential** chunks of `SubscribeBatchSize` with `SubscribeBatchDelay` between them, all inside ONE background task; each chunk reports its per-tag results back to the actor as its own message. Replaces a tight loop that fired one fire-and-forget task per tag. |
|
||||||
| **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. |
|
| **Tag-resolution probe** | The whole not-in-flight unresolved set, chunked at `SubscribeBatchSize`, as one probe round per timer tick. |
|
||||||
|
|
||||||
Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed **and the reconnect re-subscribe loop** are additionally bound to their session (one shared token, created before either starts): entering Reconnecting, an adapter swap or actor stop cancels them, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21), and a re-subscribe loop whose chunk wedged across a reconnect stops at that chunk instead of issuing its remaining chunks against the same adapter's new client (2026-12-02 review DCL-4 — previously duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results were dropped unreleased). The adapters dereference their session client once per batch call. **The MxGateway per-handle supervisory advise is shared by concurrent callers and runs under the client's lifetime (bounded at 60 s), not the token of the caller that created it** (DCL-9) — each caller applies its own deadline to its wait only, so a write timing out no longer cancels the advise a concurrent subscribe awaits; a faulted/timed-out shared advise is evicted and retried by the next caller. **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed.
|
Seeding (the initial-value read that keeps a STATIC tag from staying Uncertain) issues chunked bulk reads — `SeedReadBatchSize` per chunk, `SeedReadMaxParallelism` chunks in flight, `SeedReadTimeout` per chunk — under a single `SeedOverallTimeout` deadline covering every chunk and retry round. The reconnect re-seed **and the reconnect re-subscribe loop** are additionally bound to their session (one shared token, created before either starts): entering Reconnecting, an adapter swap or actor stop cancels them, so a flapping link no longer stacks one full-tag-set seed read per flap (review 2026-10-21), and a re-subscribe loop whose chunk wedged across a reconnect stops at that chunk instead of issuing its remaining chunks against the same adapter's new client (2026-12-02 review DCL-4 — previously duplicate OPC UA monitored items / MxGateway subscribes whose stale-generation results were dropped unreleased). The adapters dereference their session client once per batch call. **The MxGateway per-handle supervisory advise is shared by concurrent callers and runs under the client's lifetime (bounded at 60 s), not the token of the caller that created it** (DCL-9) — each caller applies its own deadline to its wait only, so a write timing out no longer cancels the advise a concurrent subscribe awaits; a faulted/timed-out shared advise is evicted and retried by the next caller. **Value timestamps (DCL-7):** OPC UA reads and subscription notifications stamp a value with its source timestamp, falling back to the server timestamp and then to now — a connection configured for `TimestampsToReturn = Server` (or a server that omits source timestamps) used to stamp every seeded/read value `0001-01-01T00:00:00Z`. **Browse/search while disconnected (DCL-6)** always reply with a typed `ConnectionNotConnected` failure: the actor turns an adapter that throws before returning a task into a faulted task, and the OPC UA adapter's browse/search are `async` so a missing client faults the task. **A connection-level failure row in a reconnect re-subscribe or probe batch (DCL-8)** now puts the tag into the resolution retry set (previously it was only logged, and with `_subscriptionIds`/`_unresolvedTags` already cleared by `ReSubscribeAll` the tag sat in no retry set until an unrelated reconnect when the session stayed up). **A seed never overwrites a newer live value (2026-12-02 review DCL-1).** The subscription is live before the seed read starts, and a seed is held until its whole seed operation finishes, so a live change inside that window used to be regressed to the older seed value (Good quality, indefinitely for a rarely-changing tag). Seed values now travel as `TagValueReceived` marked with their origin, and the actor keeps the latest live value per tag for the current adapter generation (cleared when the generation advances on reconnect/swap, dropped when the tag loses its last subscriber). A reconnect or tag-resolution re-seed for a tag that has already delivered a live value in that generation is **dropped**; an initial-subscribe seed for such a tag is **replaced by the latest live value** (the joining instance may have registered after the tag's earlier live values were fanned out, and a static tag would otherwise never give it a value). The rule is generation-based, not a timestamp comparison, which would depend on device/server clocks and the configured timestamp mode. **On re-entering Connected after a reconnect the actor tells every subscriber `ConnectionQualityChanged(Good)`** (SRT-6) — a restore signal the Instance Actor uses only to reset its tag-subscribe backoff; per-tag quality is restored by the re-subscribe and re-seed.
|
||||||
|
|
||||||
**OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered.
|
**OPC UA subscription sharding.** `RealOpcUaClient` places monitored items on the first subscription shard with free capacity (`MaxMonitoredItemsPerSubscription`), creating a shard when all are full and deleting one once it empties. A batch is N × `AddItem` plus **one** `ApplyChanges` per touched shard. Alarms & Conditions event items are pinned to a **dedicated event shard**, so `ConditionRefresh` has a single subscription id to target and `QueueSize:1000` event items never consume data-shard capacity. Every structural mutation (AddItem / RemoveItem / ApplyChanges / Create / Delete) and every shard-list mutation serializes behind ONE per-client gate — the SDK `Subscription` is not safe under concurrent structural mutation, and the subscribe task, resolution probe and alarm subscribe are otherwise unordered.
|
||||||
|
|
||||||
@@ -378,7 +378,7 @@ Other/custom protocols do not implement the capability; a subscribe request agai
|
|||||||
|
|
||||||
### Connection Actor Behavior
|
### Connection Actor Behavior
|
||||||
|
|
||||||
The `DataConnectionActor` opens **one alarm feed per source** (not per subscriber) and routes incoming transitions to instance subscribers by **source-object reference** — a prefix match of the transition's `SourceObjectReference` (falling back to `SourceReference`) against each subscriber's registered `SourceReference`. Subscribers (the Site Runtime's `NativeAlarmActor` instances) are **ref-counted per source**, so the underlying feed is opened once and torn down only when the last subscriber for that source unsubscribes.
|
The `DataConnectionActor` opens **one alarm feed per source** (not per subscriber) and routes incoming transitions to instance subscribers by **source-object reference** — a **separator-aware** prefix match of the transition's `SourceObjectReference` (falling back to `SourceReference`) against each subscriber's registered `SourceReference`: the reference must be the source itself or continue at a `.` or `/` separator (an empty source — the OPC UA Server-object feed — still covers everything). A raw string prefix used to let `Tank1` / `ns=2;s=Tank1` also receive, cache and mirror every alarm of `Tank10` / `ns=2;s=Tank10` (2026-12-02 review DCL-5). Subscribers (the Site Runtime's `NativeAlarmActor` instances) are **ref-counted per source**, so the underlying feed is opened once and torn down only when the last subscriber for that source unsubscribes.
|
||||||
|
|
||||||
The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and config all store NodeIds), so the transition's routing identity must live in the same space or nothing matches. **Gitea #17**: the OPC UA adapter previously set `SourceObjectReference` from the event's `SourceName` (a plain name — the RawPath for OtOpcUa), which never prefix-matches a NodeId binding, so every native OPC UA alarm transition was silently dropped. Because each OPC UA feed is opened for exactly one binding, the adapter now tags every transition on that feed with the **binding string verbatim** (via the pure `OpcUaAlarmMapper.BuildIdentity`), making the routing key an exact match independent of whether the binding is stored as `ns=<index>` or the durable `nsu=<uri>` form. The Server-object aggregate feed (empty binding) keeps an empty routing identity, so it reaches only "mirror everything" subscribers and never leaks into a specific-node binding. The per-condition `SourceReference` key stays the human-readable `SourceName.ConditionName`, so persistence and display are unchanged — with one exception, below. MxGateway is unaffected — its bindings are object names and its mapper already emits matching names.
|
The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and config all store NodeIds), so the transition's routing identity must live in the same space or nothing matches. **Gitea #17**: the OPC UA adapter previously set `SourceObjectReference` from the event's `SourceName` (a plain name — the RawPath for OtOpcUa), which never prefix-matches a NodeId binding, so every native OPC UA alarm transition was silently dropped. Because each OPC UA feed is opened for exactly one binding, the adapter now tags every transition on that feed with the **binding string verbatim** (via the pure `OpcUaAlarmMapper.BuildIdentity`), making the routing key an exact match independent of whether the binding is stored as `ns=<index>` or the durable `nsu=<uri>` form. The Server-object aggregate feed (empty binding) keeps an empty routing identity, so it reaches only "mirror everything" subscribers and never leaks into a specific-node binding. The per-condition `SourceReference` key stays the human-readable `SourceName.ConditionName`, so persistence and display are unchanged — with one exception, below. MxGateway is unaffected — its bindings are object names and its mapper already emits matching names.
|
||||||
|
|
||||||
@@ -395,7 +395,7 @@ The registered `SourceReference` is a **NodeId** for OPC UA (the picker, CSV and
|
|||||||
- **Server-initiated refresh**: a RefreshStart/RefreshEnd pair the server sends on its own on an existing feed (OtOpcUa's promotion refresh under Warm redundancy, #138) takes the same snapshot path — forwarded in order under its own epoch, and it replaces the cached state for the source.
|
- **Server-initiated refresh**: a RefreshStart/RefreshEnd pair the server sends on its own on an existing feed (OtOpcUa's promotion refresh under Warm redundancy, #138) takes the same snapshot path — forwarded in order under its own epoch, and it replaces the cached state for the source.
|
||||||
- **RefreshRequired (Gitea #148)**: an OPC UA server sends `RefreshRequiredEventType` (`SourceNode = Server`, no condition fields) when the client's view can no longer be trusted — OtOpcUa sends it on an incomplete condition snapshot, a removed imported condition, and a resync that left pre-failover EventIds un-ackable (`BadEventIdUnknown`). Part 9 says the client must call ConditionRefresh. `RealOpcUaClient.HandleAlarmEvent` therefore never maps it as an alarm (it used to fall through as a phantom condition keyed `Server`); it hands the item's handle to `ConditionRefreshCoalescer`, which runs off the SDK publish thread, debounces 500 ms so a burst (the server sends one event per item that may see the condition) costs one refresh, and never overlaps refreshes (a request during an in-flight refresh is served by the next one). The refresh is a targeted `ConditionRefresh2(eventSubscription, item)` per asking item, or one subscription-wide `ConditionRefresh` when every live alarm item asked, an item has no server id yet, or `ConditionRefresh2` fails. Failures are logged, never thrown, and leave the mirror on its last-known state until the next RefreshRequired or reconnect; a disconnect drops pending requests. The replay is the ordinary RefreshStart → conditions → RefreshEnd frame, so the Native Alarm Actor's snapshot swap clears every condition the refreshed snapshot no longer lists (a removed condition gets its return-to-normal). Because the server queues RefreshRequired through the item's WhereClause, the server-side `OfType` clause built from a condition filter always ORs in `OfType(RefreshRequiredEventType)`. Covered by `RealOpcUaRefreshRequiredTests` and `RealOpcUaClientAlarmFilterTests`.
|
- **RefreshRequired (Gitea #148)**: an OPC UA server sends `RefreshRequiredEventType` (`SourceNode = Server`, no condition fields) when the client's view can no longer be trusted — OtOpcUa sends it on an incomplete condition snapshot, a removed imported condition, and a resync that left pre-failover EventIds un-ackable (`BadEventIdUnknown`). Part 9 says the client must call ConditionRefresh. `RealOpcUaClient.HandleAlarmEvent` therefore never maps it as an alarm (it used to fall through as a phantom condition keyed `Server`); it hands the item's handle to `ConditionRefreshCoalescer`, which runs off the SDK publish thread, debounces 500 ms so a burst (the server sends one event per item that may see the condition) costs one refresh, and never overlaps refreshes (a request during an in-flight refresh is served by the next one). The refresh is a targeted `ConditionRefresh2(eventSubscription, item)` per asking item, or one subscription-wide `ConditionRefresh` when every live alarm item asked, an item has no server id yet, or `ConditionRefresh2` fails. Failures are logged, never thrown, and leave the mirror on its last-known state until the next RefreshRequired or reconnect; a disconnect drops pending requests. The replay is the ordinary RefreshStart → conditions → RefreshEnd frame, so the Native Alarm Actor's snapshot swap clears every condition the refreshed snapshot no longer lists (a removed condition gets its return-to-normal). Because the server queues RefreshRequired through the item's WhereClause, the server-side `OfType` clause built from a condition filter always ORs in `OfType(RefreshRequiredEventType)`. Covered by `RealOpcUaRefreshRequiredTests` and `RealOpcUaClientAlarmFilterTests`.
|
||||||
- **Shared condition filter (last-subscriber-wins)**: because the feed is opened once per source, it carries a single condition filter. A second subscriber that registers a *different* filter for the same source overwrites it (last writer wins) and the actor logs a warning — co-subscribers to one source are expected to agree on the filter.
|
- **Shared condition filter (last-subscriber-wins)**: because the feed is opened once per source, it carries a single condition filter. A second subscriber that registers a *different* filter for the same source overwrites it (last writer wins) and the actor logs a warning — co-subscribers to one source are expected to agree on the filter.
|
||||||
- **Routing index**: subscribed sources are bucketed by the **first path segment** of their reference (everything before the first `.`), and a transition is matched only against the bucket for its own first segment, plus a residue list of sources that carry no separator at all (a prefix shorter than one segment, which can match other buckets). This is sound because a source reference containing a separator can only prefix a reference sharing its entire first segment. The per-source `StartsWith` test and the condition-type gate inside the bucket are unchanged, so routing decisions are identical to the previous linear scan over every subscribed source; snapshot boundaries bypass the condition filter, but OPC UA boundaries are sent only to the exact source binding. Connection-wide Mx boundaries broadcast to all subscribers while preserving their refresh epoch.
|
- **Routing index**: subscribed sources are bucketed by the **first path segment** of their reference (everything before the first `.`), and a transition is matched only against the bucket for its own first segment, plus a residue list of sources that carry no separator at all (a prefix shorter than one segment, which can match other buckets). This is sound because a source reference containing a separator can only prefix a reference sharing its entire first segment. The per-source separator-aware containment test and the condition-type gate inside the bucket are applied as in a linear scan, so routing decisions are identical to a linear scan over every subscribed source; snapshot boundaries bypass the condition filter, but OPC UA boundaries are sent only to the exact source binding. Connection-wide Mx boundaries broadcast to all subscribers while preserving their refresh epoch.
|
||||||
- **Gateway union filter (MxGateway)**: `StreamAlarms` carries a single `alarm_filter_prefix`, so the adapter opens the stream on the **longest common prefix** of the currently subscribed source references and restarts it for each new source, including one covered by the existing prefix, so every newly bound source receives standing state. Restarts are **coalesced** (review 2026-10-21): subscribes arriving within `MxAlarmStreamReopenDebounce` (200 ms) of the first share ONE restart on the union prefix, so a staggered deploy batch of N alarm-bound instances costs one close/reopen and one connection-wide snapshot replay instead of N (each of which was broadcast to every already-subscribed source — O(N·M) boundary messages). A reconnect, teardown or last unsubscribe invalidates a pending restart. Each transport refresh has connection-wide start/end markers and a distinct epoch. An unsubscribe never restarts the stream — the prefix it leaves behind is at worst too broad, which may increase bandwidth. Correctness also depends on the epoch-scoped snapshot cache merging concurrent live updates and rejecting stale snapshot ends (DC-5); a broad filter alone provides no such guarantee. The prefix is a bandwidth optimisation only; the actor's per-source + condition-type gate remains authoritative, mirroring the OPC UA server-side WhereClause stance.
|
- **Gateway union filter (MxGateway)**: `StreamAlarms` carries a single `alarm_filter_prefix`, so the adapter opens the stream on the **longest common prefix** of the currently subscribed source references and restarts it for each new source, including one covered by the existing prefix, so every newly bound source receives standing state. Restarts are **coalesced** (review 2026-10-21): subscribes arriving within `MxAlarmStreamReopenDebounce` (200 ms) of the first share ONE restart on the union prefix, so a staggered deploy batch of N alarm-bound instances costs one close/reopen and one connection-wide snapshot replay instead of N (each of which was broadcast to every already-subscribed source — O(N·M) boundary messages). A reconnect, teardown or last unsubscribe invalidates a pending restart. Each transport refresh has connection-wide start/end markers and a distinct epoch. An unsubscribe never restarts the stream — the prefix it leaves behind is at worst too broad, which may increase bandwidth. Correctness also depends on the epoch-scoped snapshot cache merging concurrent live updates and rejecting stale snapshot ends (DC-5); a broad filter alone provides no such guarantee. The prefix is a bandwidth optimisation only; the actor's per-source + condition-type gate remains authoritative, mirroring the OPC UA server-side WhereClause stance.
|
||||||
|
|
||||||
### Protocol-Neutral Types & Messages
|
### Protocol-Neutral Types & Messages
|
||||||
|
|||||||
@@ -2278,7 +2278,20 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
|||||||
|
|
||||||
_log.Debug("[{0}] Browsing children of {1}", _connectionName, command.ParentNodeId ?? "(root)");
|
_log.Debug("[{0}] Browsing children of {1}", _connectionName, command.ParentNodeId ?? "(root)");
|
||||||
|
|
||||||
browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken).ContinueWith(t =>
|
// DCL-6: an adapter that throws BEFORE returning a task (not yet connected, a null client)
|
||||||
|
// must still produce a typed reply — the mapping below only sees a faulted task, so a
|
||||||
|
// synchronous throw used to escape on the actor thread and leave the caller to time out.
|
||||||
|
Task<BrowseChildrenResult> browseTask;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
browseTask = browsable.BrowseChildrenAsync(command.ParentNodeId, command.ContinuationToken);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
browseTask = Task.FromException<BrowseChildrenResult>(ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
browseTask.ContinueWith(t =>
|
||||||
{
|
{
|
||||||
if (t.IsCompletedSuccessfully)
|
if (t.IsCompletedSuccessfully)
|
||||||
{
|
{
|
||||||
@@ -2359,7 +2372,18 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
|||||||
_log.Debug("[{0}] Searching address space for '{1}' (maxDepth={2}, maxResults={3})",
|
_log.Debug("[{0}] Searching address space for '{1}' (maxDepth={2}, maxResults={3})",
|
||||||
_connectionName, command.Query, command.MaxDepth, command.MaxResults);
|
_connectionName, command.Query, command.MaxDepth, command.MaxResults);
|
||||||
|
|
||||||
searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults).ContinueWith(t =>
|
// DCL-6: see HandleBrowse — a synchronous throw must still reply.
|
||||||
|
Task<AddressSpaceSearchResult> searchTask;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
searchTask = searchable.SearchAddressSpaceAsync(command.Query, command.MaxDepth, command.MaxResults);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
searchTask = Task.FromException<AddressSpaceSearchResult>(ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
searchTask.ContinueWith(t =>
|
||||||
{
|
{
|
||||||
if (t.IsCompletedSuccessfully)
|
if (t.IsCompletedSuccessfully)
|
||||||
{
|
{
|
||||||
@@ -3521,9 +3545,10 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
// A subscriber bound to source S receives a transition whose source
|
// A subscriber bound to source S receives a transition whose source
|
||||||
// object (or full reference) falls under S.
|
// object (or full reference) falls under S — S itself or a descendant
|
||||||
var match = transition.SourceObjectReference.StartsWith(sourceRef, StringComparison.Ordinal)
|
// separated by a path separator, never a mere string prefix (DCL-5).
|
||||||
|| transition.SourceReference.StartsWith(sourceRef, StringComparison.Ordinal);
|
var match = IsUnderAlarmSource(transition.SourceObjectReference, sourceRef)
|
||||||
|
|| IsUnderAlarmSource(transition.SourceReference, sourceRef);
|
||||||
if (!match)
|
if (!match)
|
||||||
continue;
|
continue;
|
||||||
|
|
||||||
@@ -3603,6 +3628,29 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
|
|||||||
/// full StartsWith test and the condition-type gate, so routing is identical to the
|
/// full StartsWith test and the condition-type gate, so routing is identical to the
|
||||||
/// previous linear scan.
|
/// previous linear scan.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
/// <summary>
|
||||||
|
/// True when <paramref name="reference"/> is the alarm source <paramref name="source"/> itself or
|
||||||
|
/// lies beneath it: the prefix must end at a path separator (<c>.</c> or <c>/</c>). A raw string
|
||||||
|
/// prefix let <c>Tank1</c> (or <c>ns=2;s=Tank1</c>) also receive — and mirror as its own —
|
||||||
|
/// every alarm of <c>Tank10</c> (DCL-5). An empty source (the OPC UA Server-object aggregate
|
||||||
|
/// feed) covers everything, as before.
|
||||||
|
/// </summary>
|
||||||
|
internal static bool IsUnderAlarmSource(string reference, string source)
|
||||||
|
{
|
||||||
|
if (source.Length == 0)
|
||||||
|
return true;
|
||||||
|
if (!reference.StartsWith(source, StringComparison.Ordinal))
|
||||||
|
return false;
|
||||||
|
if (reference.Length == source.Length)
|
||||||
|
return true;
|
||||||
|
// The source already ends in a separator (an explicit area prefix such as "Area1.").
|
||||||
|
var last = source[^1];
|
||||||
|
if (last is '.' or '/')
|
||||||
|
return true;
|
||||||
|
var next = reference[source.Length];
|
||||||
|
return next is '.' or '/';
|
||||||
|
}
|
||||||
|
|
||||||
private IEnumerable<string> CandidateAlarmSources(NativeAlarmTransition transition)
|
private IEnumerable<string> CandidateAlarmSources(NativeAlarmTransition transition)
|
||||||
{
|
{
|
||||||
var objectSegment = FirstSegment(transition.SourceObjectReference);
|
var objectSegment = FirstSegment(transition.SourceObjectReference);
|
||||||
|
|||||||
@@ -448,23 +448,33 @@ public class OpcUaDataConnection
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public Task<BrowseChildrenResult> BrowseChildrenAsync(
|
public async Task<BrowseChildrenResult> BrowseChildrenAsync(
|
||||||
string? parentNodeId,
|
string? parentNodeId,
|
||||||
string? continuationToken = null,
|
string? continuationToken = null,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
=> _client!.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken);
|
{
|
||||||
|
// async so a not-connected adapter FAULTS the task instead of throwing synchronously
|
||||||
|
// (DCL-6): a freshly swapped failover adapter has no client until the reconnect timer
|
||||||
|
// fires, and the old `_client!` dereference threw a NullReferenceException on the actor
|
||||||
|
// thread, so the caller got no reply at all.
|
||||||
|
var client = _client
|
||||||
|
?? throw new ConnectionNotConnectedException("OPC UA client is not connected.");
|
||||||
|
return await client.BrowseChildrenAsync(parentNodeId, continuationToken, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
|
public async Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
|
||||||
string query, int maxDepth, int maxResults, CancellationToken cancellationToken = default)
|
string query, int maxDepth, int maxResults, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
// Guard connection state with the typed ConnectionNotConnectedException so
|
// Guard connection state with the typed ConnectionNotConnectedException so
|
||||||
// the site-side handler can map it uniformly (mirrors BrowseChildrenAsync,
|
// the site-side handler can map it uniformly (mirrors BrowseChildrenAsync,
|
||||||
// whose underlying client throws the same type when the session is down).
|
// whose underlying client throws the same type when the session is down).
|
||||||
if (_client == null || !_client.IsConnected)
|
// async so the guard faults the task rather than throwing synchronously (DCL-6).
|
||||||
|
var client = _client;
|
||||||
|
if (client == null || !client.IsConnected)
|
||||||
throw new ConnectionNotConnectedException("OPC UA client is not connected.");
|
throw new ConnectionNotConnectedException("OPC UA client is not connected.");
|
||||||
|
|
||||||
return _client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
|
return await client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void StopHeartbeatMonitor()
|
private void StopHeartbeatMonitor()
|
||||||
|
|||||||
@@ -56,6 +56,26 @@ internal static class OpcUaValueBoundary
|
|||||||
internal static DateTime ToClrTimestamp(DateTimeUtc value) =>
|
internal static DateTime ToClrTimestamp(DateTimeUtc value) =>
|
||||||
value == DateTimeUtc.MinValue ? DateTime.MinValue : value.ToDateTime();
|
value == DateTimeUtc.MinValue ? DateTime.MinValue : value.ToDateTime();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The timestamp to stamp on a value read or notified from the server: the SOURCE timestamp
|
||||||
|
/// when present, else the SERVER timestamp, else now (DCL-7). A connection configured for
|
||||||
|
/// <c>TimestampsToReturn = Server</c> gets no source timestamp at all, and a server may omit it
|
||||||
|
/// on notifications; taking <c>SourceTimestamp</c> unconditionally stamped such values
|
||||||
|
/// <c>0001-01-01T00:00:00Z</c>, which was stored, streamed and shown until the tag next changed.
|
||||||
|
/// One helper for both the read and the notification path.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">The DataValue's source timestamp.</param>
|
||||||
|
/// <param name="server">The DataValue's server timestamp.</param>
|
||||||
|
/// <returns>The effective UTC timestamp, never <see cref="DateTime.MinValue"/>.</returns>
|
||||||
|
internal static DateTime EffectiveTimestamp(DateTimeUtc source, DateTimeUtc server)
|
||||||
|
{
|
||||||
|
var fromSource = ToClrTimestamp(source);
|
||||||
|
if (fromSource != DateTime.MinValue)
|
||||||
|
return fromSource;
|
||||||
|
var fromServer = ToClrTimestamp(server);
|
||||||
|
return fromServer != DateTime.MinValue ? fromServer : DateTime.UtcNow;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The SDK value to write for a CLR payload, with SDK 1.5's <c>new Variant(object)</c>
|
/// The SDK value to write for a CLR payload, with SDK 1.5's <c>new Variant(object)</c>
|
||||||
/// semantics: a <c>byte[]</c> is a ByteString scalar, other supported scalars and
|
/// semantics: a <c>byte[]</c> is a ByteString scalar, other supported scalars and
|
||||||
|
|||||||
@@ -772,7 +772,7 @@ public class RealOpcUaClient : IOpcUaClient
|
|||||||
// SDK 2: DataValue is a struct; restore the SDK 1.5 CLR payload shapes.
|
// SDK 2: DataValue is a struct; restore the SDK 1.5 CLR payload shapes.
|
||||||
var dataValue = notification.Value;
|
var dataValue = notification.Value;
|
||||||
var value = OpcUaValueBoundary.ToClr(dataValue.WrappedValue);
|
var value = OpcUaValueBoundary.ToClr(dataValue.WrappedValue);
|
||||||
var timestamp = OpcUaValueBoundary.ToClrTimestamp(dataValue.SourceTimestamp);
|
var timestamp = OpcUaValueBoundary.EffectiveTimestamp(dataValue.SourceTimestamp, dataValue.ServerTimestamp);
|
||||||
var statusCode = dataValue.StatusCode.Code;
|
var statusCode = dataValue.StatusCode.Code;
|
||||||
|
|
||||||
if (_callbacks.TryGetValue(handle, out var cb))
|
if (_callbacks.TryGetValue(handle, out var cb))
|
||||||
@@ -1609,7 +1609,8 @@ public class RealOpcUaClient : IOpcUaClient
|
|||||||
var result = results[i];
|
var result = results[i];
|
||||||
outcomes[index] = new OpcUaReadOutcome(
|
outcomes[index] = new OpcUaReadOutcome(
|
||||||
nodeId, OpcUaValueBoundary.ToClr(result.WrappedValue),
|
nodeId, OpcUaValueBoundary.ToClr(result.WrappedValue),
|
||||||
OpcUaValueBoundary.ToClrTimestamp(result.SourceTimestamp), result.StatusCode.Code, null);
|
OpcUaValueBoundary.EffectiveTimestamp(result.SourceTimestamp, result.ServerTimestamp),
|
||||||
|
result.StatusCode.Code, null);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
|
|||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
using Akka.Actor;
|
||||||
|
using Akka.TestKit.Xunit2;
|
||||||
|
using NSubstitute;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Actors;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
|
||||||
|
using ZB.MOM.WW.ScadaBridge.HealthMonitoring;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Actors;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DCL-6 (2026-12-02 review, WP3 task 3.4): browse/search while the connection has no session must
|
||||||
|
/// REPLY with a typed <c>ConnectionNotConnected</c> failure. An adapter that threw synchronously
|
||||||
|
/// (before returning a task) escaped the actor's faulted-task mapping, so the node-browser dialog
|
||||||
|
/// waited out its whole Ask timeout and the site logged a "threw exception, resuming" warning.
|
||||||
|
/// </summary>
|
||||||
|
public class DataConnectionDisconnectedBrowseTests : TestKit
|
||||||
|
{
|
||||||
|
private readonly ISiteHealthCollector _health = Substitute.For<ISiteHealthCollector>();
|
||||||
|
private readonly IDataConnectionFactory _factory = Substitute.For<IDataConnectionFactory>();
|
||||||
|
|
||||||
|
private readonly DataConnectionOptions _options = new()
|
||||||
|
{
|
||||||
|
ReconnectInterval = TimeSpan.FromSeconds(30),
|
||||||
|
WriteTimeout = TimeSpan.FromSeconds(5),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>An adapter that throws synchronously still yields a typed reply, in the Connecting state.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void SynchronousThrowWhileConnecting_RepliesConnectionNotConnected()
|
||||||
|
{
|
||||||
|
var adapter = Substitute.For<IDataConnection, IBrowsableDataConnection, IAddressSpaceSearchable>();
|
||||||
|
// Never connects: the actor stays in Connecting.
|
||||||
|
adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(new TaskCompletionSource().Task);
|
||||||
|
((IBrowsableDataConnection)adapter)
|
||||||
|
.BrowseChildrenAsync(Arg.Any<string?>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns<Task<BrowseChildrenResult>>(_ => throw new ConnectionNotConnectedException("not connected"));
|
||||||
|
((IAddressSpaceSearchable)adapter)
|
||||||
|
.SearchAddressSpaceAsync(Arg.Any<string>(), Arg.Any<int>(), Arg.Any<int>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns<Task<AddressSpaceSearchResult>>(_ => throw new ConnectionNotConnectedException("not connected"));
|
||||||
|
|
||||||
|
var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor(
|
||||||
|
"conn", adapter, _options, _health, _factory, "OpcUa")));
|
||||||
|
|
||||||
|
actor.Tell(new SearchAddressSpaceCommand("conn", "Tag", 5, 100));
|
||||||
|
var search = ExpectMsg<SearchAddressSpaceResult>(TimeSpan.FromSeconds(5)); // pre-fix: no reply
|
||||||
|
Assert.Equal(BrowseFailureKind.ConnectionNotConnected, search.Failure?.Kind);
|
||||||
|
|
||||||
|
actor.Tell(new BrowseNodeCommand("conn", null));
|
||||||
|
var browse = ExpectMsg<BrowseNodeResult>(TimeSpan.FromSeconds(5));
|
||||||
|
Assert.Equal(BrowseFailureKind.ConnectionNotConnected, browse.Failure?.Kind);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The OPC UA adapter with no client yet faults the task (typed) instead of throwing.</summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task OpcUaAdapterWithoutClient_FaultsTheTask_WithTypedException()
|
||||||
|
{
|
||||||
|
var clientFactory = Substitute.For<IOpcUaClientFactory>();
|
||||||
|
await using var adapter = new OpcUaDataConnection(clientFactory,
|
||||||
|
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaDataConnection>.Instance);
|
||||||
|
|
||||||
|
// Calling the method must not throw synchronously (pre-fix: NullReferenceException /
|
||||||
|
// ConnectionNotConnectedException thrown before a task existed) — it returns a faulted task.
|
||||||
|
Task<BrowseChildrenResult> browse;
|
||||||
|
try { browse = adapter.BrowseChildrenAsync(null); }
|
||||||
|
catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Browse threw synchronously: {ex.GetType().Name}"); }
|
||||||
|
await Assert.ThrowsAsync<ConnectionNotConnectedException>(() => browse);
|
||||||
|
|
||||||
|
Task<AddressSpaceSearchResult> search;
|
||||||
|
try { search = adapter.SearchAddressSpaceAsync("x", 3, 10); }
|
||||||
|
catch (Exception ex) { throw new Xunit.Sdk.XunitException($"Search threw synchronously: {ex.GetType().Name}"); }
|
||||||
|
await Assert.ThrowsAsync<ConnectionNotConnectedException>(() => search);
|
||||||
|
}
|
||||||
|
}
|
||||||
+29
@@ -92,4 +92,33 @@ public class OpcUaValueBoundaryTests
|
|||||||
Assert.Throws<ArgumentException>(() => OpcUaValueBoundary.ToVariant(new object()));
|
Assert.Throws<ArgumentException>(() => OpcUaValueBoundary.ToVariant(new object()));
|
||||||
Assert.Throws<ArgumentException>(() => OpcUaValueBoundary.ToVariant(new int[2, 2]));
|
Assert.Throws<ArgumentException>(() => OpcUaValueBoundary.ToVariant(new int[2, 2]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>DCL-7: the source timestamp wins when present.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void EffectiveTimestamp_PrefersTheSourceTimestamp()
|
||||||
|
{
|
||||||
|
var source = new DateTime(2026, 11, 12, 10, 30, 0, DateTimeKind.Utc);
|
||||||
|
var server = source.AddSeconds(2);
|
||||||
|
Assert.Equal(source, OpcUaValueBoundary.EffectiveTimestamp(source, server));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DCL-7: with <c>TimestampsToReturn = Server</c> (or a server that omits it) there is no source
|
||||||
|
/// timestamp — fall back to the server timestamp, never 0001-01-01.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void EffectiveTimestamp_FallsBackToTheServerTimestamp()
|
||||||
|
{
|
||||||
|
var server = new DateTime(2026, 11, 12, 10, 30, 2, DateTimeKind.Utc);
|
||||||
|
Assert.Equal(server, OpcUaValueBoundary.EffectiveTimestamp(DateTimeUtc.MinValue, server));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>DCL-7: with neither timestamp, the value is stamped now rather than DateTime.MinValue.</summary>
|
||||||
|
[Fact]
|
||||||
|
public void EffectiveTimestamp_WithNeither_IsNow()
|
||||||
|
{
|
||||||
|
var before = DateTime.UtcNow;
|
||||||
|
var ts = OpcUaValueBoundary.EffectiveTimestamp(DateTimeUtc.MinValue, DateTimeUtc.MinValue);
|
||||||
|
Assert.InRange(ts, before, DateTime.UtcNow);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+67
-10
@@ -13,9 +13,11 @@ namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests;
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The alarm subscriber first-segment bucket index must make EXACTLY the routing
|
/// The alarm subscriber first-segment bucket index must make EXACTLY the routing
|
||||||
/// decisions the previous linear scan made. The expectation in each case is computed with
|
/// decisions a linear scan over every subscribed source makes. The expectation in each case
|
||||||
/// the original rule (plain <c>StartsWith</c> against every subscribed source), so the
|
/// is computed with an independent oracle — since the 2026-12-02 review (DCL-5) the rule is
|
||||||
/// test pins equivalence rather than restating the new implementation.
|
/// "the reference is the source itself or lies beneath it at a separator", no longer a raw
|
||||||
|
/// string <c>StartsWith</c> that let <c>Tank1</c> receive <c>Tank10</c>'s alarms — so the test
|
||||||
|
/// pins equivalence rather than restating the implementation.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class DataConnectionActorAlarmIndexTests : TestKit
|
public class DataConnectionActorAlarmIndexTests : TestKit
|
||||||
{
|
{
|
||||||
@@ -37,9 +39,10 @@ public class DataConnectionActorAlarmIndexTests : TestKit
|
|||||||
|
|
||||||
private static readonly (string SourceRef, string SourceObjectRef)[] Transitions =
|
private static readonly (string SourceRef, string SourceObjectRef)[] Transitions =
|
||||||
[
|
[
|
||||||
("Area1.Tank1.Hi", "Area1.Tank1"), // Area1 (residue) + Area1.Tank
|
("Area1.Tank1.Hi", "Area1.Tank1"), // Area1 (residue) ONLY — "Area1.Tank" is a sibling, not a parent (DCL-5)
|
||||||
("Area1.Tank1.Sub.Hi", "Area1.Tank1.Sub"), // + Area1.Tank1.Sub
|
("Area1.Tank1.Sub.Hi", "Area1.Tank1.Sub"), // Area1 + Area1.Tank1.Sub
|
||||||
("Area1X.Pump.Hi", "Area1X.Pump"), // sub-segment prefix: Area1 ONLY
|
("Area1.Tank.Hi", "Area1.Tank"), // Area1 + Area1.Tank
|
||||||
|
("Area1X.Pump.Hi", "Area1X.Pump"), // sub-segment prefix of Area1: nobody (DCL-5)
|
||||||
("Area2.Tank9.Hi", "Area2.Tank9"), // Area2.Tank only
|
("Area2.Tank9.Hi", "Area2.Tank9"), // Area2.Tank only
|
||||||
("Zone.A.Hi", "Zone.A"), // nobody
|
("Zone.A.Hi", "Zone.A"), // nobody
|
||||||
];
|
];
|
||||||
@@ -49,10 +52,12 @@ public class DataConnectionActorAlarmIndexTests : TestKit
|
|||||||
new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500),
|
new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 500),
|
||||||
"Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90");
|
"Process", "hi", "hi", "", "", null, DateTimeOffset.UtcNow, "92", "90");
|
||||||
|
|
||||||
/// <summary>The ORIGINAL linear-scan rule, kept here as the oracle.</summary>
|
/// <summary>The linear-scan oracle: the source itself, or a descendant at a '.' separator.</summary>
|
||||||
private static bool LinearScanMatches(string sourceRef, string transitionSourceRef, string transitionSourceObjectRef) =>
|
private static bool LinearScanMatches(string sourceRef, string transitionSourceRef, string transitionSourceObjectRef) =>
|
||||||
transitionSourceObjectRef.StartsWith(sourceRef, StringComparison.Ordinal)
|
Under(transitionSourceObjectRef, sourceRef) || Under(transitionSourceRef, sourceRef);
|
||||||
|| transitionSourceRef.StartsWith(sourceRef, StringComparison.Ordinal);
|
|
||||||
|
private static bool Under(string reference, string source) =>
|
||||||
|
reference == source || reference.StartsWith(source + ".", StringComparison.Ordinal);
|
||||||
|
|
||||||
/// <summary>Verifies that the bucket index routes exactly as the previous linear scan did.</summary>
|
/// <summary>Verifies that the bucket index routes exactly as the previous linear scan did.</summary>
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -164,7 +169,59 @@ public class DataConnectionActorAlarmIndexTests : TestKit
|
|||||||
Thread.Sleep(200);
|
Thread.Sleep(200);
|
||||||
|
|
||||||
Assert.NotNull(cb);
|
Assert.NotNull(cb);
|
||||||
cb!(Transition("Area1.Tank1.Hi", "Area1.Tank1"));
|
cb!(Transition("Area1.Tank.Hi", "Area1.Tank"));
|
||||||
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
|
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// DCL-5: sibling sources whose names share a prefix (<c>ns=2;s=Tank1</c> / <c>ns=2;s=Tank10</c>,
|
||||||
|
/// MxGateway <c>Pump1</c> / <c>Pump10</c>) must not receive each other's alarms. Pre-fix every
|
||||||
|
/// <c>Tank10</c> transition was also delivered to — and mirrored by — the <c>Tank1</c> instance.
|
||||||
|
/// </summary>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ns=2;s=Tank1", "ns=2;s=Tank10")]
|
||||||
|
[InlineData("Pump1", "Pump10")]
|
||||||
|
public void SiblingSourcesSharingAPrefix_DoNotReceiveEachOthersAlarms(string shortSource, string longSource)
|
||||||
|
{
|
||||||
|
AlarmTransitionCallback? cb = null;
|
||||||
|
var adapter = Substitute.For<IDataConnection, IAlarmSubscribableConnection>();
|
||||||
|
adapter.ConnectAsync(Arg.Any<IDictionary<string, string>>(), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
((IAlarmSubscribableConnection)adapter)
|
||||||
|
.SubscribeAlarmsAsync(Arg.Any<string>(), Arg.Any<string?>(),
|
||||||
|
Arg.Do<AlarmTransitionCallback>(c => cb = c), Arg.Any<CancellationToken>())
|
||||||
|
.Returns(ci => Task.FromResult("alarm-" + ci.ArgAt<string>(0)));
|
||||||
|
|
||||||
|
var actor = Sys.ActorOf(Props.Create(() => new DataConnectionActor(
|
||||||
|
"conn", adapter, _options, _health, _factory, "OpcUa")));
|
||||||
|
|
||||||
|
var shortProbe = CreateTestProbe();
|
||||||
|
var longProbe = CreateTestProbe();
|
||||||
|
actor.Tell(new SubscribeAlarmsRequest("c1", "inst-short", "conn", shortSource, null, DateTimeOffset.UtcNow), shortProbe.Ref);
|
||||||
|
shortProbe.ExpectMsg<SubscribeAlarmsResponse>(m => m.Success, TimeSpan.FromSeconds(5));
|
||||||
|
actor.Tell(new SubscribeAlarmsRequest("c2", "inst-long", "conn", longSource, null, DateTimeOffset.UtcNow), longProbe.Ref);
|
||||||
|
longProbe.ExpectMsg<SubscribeAlarmsResponse>(m => m.Success, TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
cb!(Transition(longSource + ".Hi", longSource));
|
||||||
|
longProbe.ExpectMsg<NativeAlarmTransitionUpdate>(TimeSpan.FromSeconds(5));
|
||||||
|
shortProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(300)); // pre-fix: delivered here too
|
||||||
|
|
||||||
|
// The short source still gets its own alarms.
|
||||||
|
cb!(Transition(shortSource + ".Hi", shortSource));
|
||||||
|
shortProbe.ExpectMsg<NativeAlarmTransitionUpdate>(TimeSpan.FromSeconds(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The separator-aware containment rule behind alarm routing.</summary>
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Tank1", "Tank1", true)]
|
||||||
|
[InlineData("Tank1.Hi", "Tank1", true)]
|
||||||
|
[InlineData("Area/Tank1", "Area", true)]
|
||||||
|
[InlineData("Tank10", "Tank1", false)]
|
||||||
|
[InlineData("Tank10.Hi", "Tank1", false)]
|
||||||
|
[InlineData("ns=2;s=Tank10", "ns=2;s=Tank1", false)]
|
||||||
|
[InlineData("Area1.Tank", "Area1.", true)]
|
||||||
|
[InlineData("anything", "", true)]
|
||||||
|
[InlineData("Tank", "Tank1", false)]
|
||||||
|
public void IsUnderAlarmSource_IsSeparatorAware(string reference, string source, bool expected) =>
|
||||||
|
Assert.Equal(expected, DataConnectionActor.IsUnderAlarmSource(reference, source));
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user