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:
Joseph Doherty
2026-12-03 10:04:02 -05:00
parent d52aff1bee
commit c000ee3203
8 changed files with 267 additions and 25 deletions
@@ -2278,7 +2278,20 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
_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)
{
@@ -2359,7 +2372,18 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
_log.Debug("[{0}] Searching address space for '{1}' (maxDepth={2}, maxResults={3})",
_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)
{
@@ -3521,9 +3545,10 @@ public partial class DataConnectionActor : UntypedActor, IWithTimers
continue;
// A subscriber bound to source S receives a transition whose source
// object (or full reference) falls under S.
var match = transition.SourceObjectReference.StartsWith(sourceRef, StringComparison.Ordinal)
|| transition.SourceReference.StartsWith(sourceRef, StringComparison.Ordinal);
// object (or full reference) falls under S — S itself or a descendant
// separated by a path separator, never a mere string prefix (DCL-5).
var match = IsUnderAlarmSource(transition.SourceObjectReference, sourceRef)
|| IsUnderAlarmSource(transition.SourceReference, sourceRef);
if (!match)
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
/// previous linear scan.
/// </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)
{
var objectSegment = FirstSegment(transition.SourceObjectReference);
@@ -448,23 +448,33 @@ public class OpcUaDataConnection
}
/// <inheritdoc />
public Task<BrowseChildrenResult> BrowseChildrenAsync(
public async Task<BrowseChildrenResult> BrowseChildrenAsync(
string? parentNodeId,
string? continuationToken = null,
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 />
public Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
public async Task<AddressSpaceSearchResult> SearchAddressSpaceAsync(
string query, int maxDepth, int maxResults, CancellationToken cancellationToken = default)
{
// Guard connection state with the typed ConnectionNotConnectedException so
// the site-side handler can map it uniformly (mirrors BrowseChildrenAsync,
// 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.");
return _client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
return await client.SearchAddressSpaceAsync(query, maxDepth, maxResults, cancellationToken);
}
private void StopHeartbeatMonitor()
@@ -56,6 +56,26 @@ internal static class OpcUaValueBoundary
internal static DateTime ToClrTimestamp(DateTimeUtc value) =>
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>
/// 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
@@ -772,7 +772,7 @@ public class RealOpcUaClient : IOpcUaClient
// SDK 2: DataValue is a struct; restore the SDK 1.5 CLR payload shapes.
var dataValue = notification.Value;
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;
if (_callbacks.TryGetValue(handle, out var cb))
@@ -1609,7 +1609,8 @@ public class RealOpcUaClient : IOpcUaClient
var result = results[i];
outcomes[index] = new OpcUaReadOutcome(
nodeId, OpcUaValueBoundary.ToClr(result.WrappedValue),
OpcUaValueBoundary.ToClrTimestamp(result.SourceTimestamp), result.StatusCode.Code, null);
OpcUaValueBoundary.EffectiveTimestamp(result.SourceTimestamp, result.ServerTimestamp),
result.StatusCode.Code, null);
}
else
{