feat(grpc-data): H3 ProjectedHistoryAccess over deployed connections
Resolves, authorizes (HistoryRead demand: mapping bit + local grant on the mapping scope, ACLs on or off) and pins each projected node, groups the batch per connection / details / issuing endpoint and forwards through IDataHistoryService. Remote cursors bind caller, mapping id+revision, connection route, projection generation, origin view and serving identity, and resend the ORIGINAL details; any change => BadContinuationPointInvalid with the origin token released. Shared per-request assembly budget (min mapping MaxHistoryAssemblyBytesPerRequest) => BadTooManyOperations for the remaining nodes. Releases coalesce per connection. Replaces the H2 refusal pin with the intended behaviour (granted => served, no grant => BadUserAccessDenied).
This commit is contained in:
@@ -118,6 +118,13 @@ public static class DataConnectionRegistration
|
||||
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
|
||||
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
|
||||
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
|
||||
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
|
||||
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
|
||||
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
|
||||
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
|
||||
? bytes : null,
|
||||
sp.GetRequiredService<TimeProvider>()));
|
||||
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
|
||||
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
|
||||
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
|
||||
sp.GetRequiredService<ProjectedNamespaceApplier>(), sp.GetRequiredService<IProjectedNodeLookup>(),
|
||||
|
||||
@@ -60,6 +60,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
private readonly DriverWriteBounds _writeBounds;
|
||||
private readonly IProjectedBrowseAccess? _projectedBrowseAccess;
|
||||
private readonly IProjectedDataAccess? _projectedDataAccess;
|
||||
private readonly IProjectedHistoryAccess? _projectedHistoryAccess;
|
||||
private readonly IFederatedProjectionCatalog? _projectedCatalog;
|
||||
private readonly DataConnectionOptions _dataConnectionOptions;
|
||||
|
||||
@@ -140,6 +141,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
/// <param name="projectedBrowseAccess">Optional caller-bound mapped browse scheduler.</param>
|
||||
/// <param name="projectedDataAccess">Optional bounded mapped read, write and subscription gateway.</param>
|
||||
/// <param name="projectedCatalog">Optional live projection catalog used for mapped authorization.</param>
|
||||
/// <param name="projectedHistoryAccess">Optional HistoryRead gateway for projected variables (H3).</param>
|
||||
public OtOpcUaServerHostedService(
|
||||
IOptions<OpcUaApplicationHostOptions> options,
|
||||
DeferredAddressSpaceSink deferredSink,
|
||||
@@ -164,8 +166,10 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
DeferredStandbyProjection? deferredStandby = null,
|
||||
IProjectedBrowseAccess? projectedBrowseAccess = null,
|
||||
IProjectedDataAccess? projectedDataAccess = null,
|
||||
IFederatedProjectionCatalog? projectedCatalog = null)
|
||||
IFederatedProjectionCatalog? projectedCatalog = null,
|
||||
IProjectedHistoryAccess? projectedHistoryAccess = null)
|
||||
{
|
||||
_projectedHistoryAccess = projectedHistoryAccess;
|
||||
_dataConnectionOptions = configuration.GetSection(DataConnectionOptions.SectionName).Get<DataConnectionOptions>() ?? new();
|
||||
_projectedBrowseAccess = projectedBrowseAccess;
|
||||
_projectedDataAccess = projectedDataAccess;
|
||||
@@ -264,6 +268,7 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
|
||||
_server.NodeManager.ProjectedBrowseAccess = _projectedBrowseAccess;
|
||||
_server.NodeManager.ProjectedBrowseClock = _time;
|
||||
_server.NodeManager.ProjectedDataAccess = _projectedDataAccess;
|
||||
_server.NodeManager.ProjectedHistoryAccess = _projectedHistoryAccess;
|
||||
if (_projectedCatalog is { } projectedCatalog)
|
||||
_server.NodeManager.MappedSubjectResolver = (realm, identifier) =>
|
||||
projectedCatalog.TryResolveProjected(realm == AddressSpaceRealm.Raw ? DataRealm.Raw : DataRealm.Uns,
|
||||
|
||||
@@ -43,6 +43,9 @@ public sealed partial class LocalDataServices
|
||||
/// <summary>Live history sessions (diagnostics/tests).</summary>
|
||||
internal int HistorySessionCount => _historySessions.Count;
|
||||
|
||||
/// <summary>Open origin continuations (page cursors + chunk remainders) across every session (diagnostics/tests).</summary>
|
||||
internal int HistoryOpenContinuations => _historySessions.OpenContinuations;
|
||||
|
||||
/// <summary>Remainder bytes retained for a principal across its sessions (diagnostics/tests).</summary>
|
||||
internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal);
|
||||
|
||||
|
||||
@@ -194,6 +194,17 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions
|
||||
/// <summary>Live sessions (diagnostics/tests).</summary>
|
||||
public int Count { get { lock (_gate) return _sessions.Count; } }
|
||||
|
||||
/// <summary>Open page cursors plus chunk remainders across every session (diagnostics/tests).</summary>
|
||||
public int OpenContinuations
|
||||
{
|
||||
get
|
||||
{
|
||||
OriginHistorySession[] sessions;
|
||||
lock (_gate) sessions = _sessions.Values.Select(x => x.Session).ToArray();
|
||||
return sessions.Sum(x => x.Cursors.Count + x.ChunkCount);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Remainder bytes retained for <paramref name="principal"/> across its sessions.</summary>
|
||||
public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); }
|
||||
|
||||
|
||||
@@ -130,7 +130,7 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
if (metadata.ValueKind == DataValueKind.Timestamp && value is DateTime timestamp) value = new DateTimeOffset(timestamp.ToUniversalTime());
|
||||
return ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue.FromScalar(metadata.ValueKind, value);
|
||||
}
|
||||
private static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
|
||||
internal static object? DecodeValue(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataValue value, DataMetadata metadata)
|
||||
{
|
||||
if (value.Kind == DataValueKind.Null) return null;
|
||||
if (value.Kind != metadata.ValueKind) throw new ArgumentException("Value kind does not match metadata.");
|
||||
@@ -154,13 +154,15 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand)
|
||||
{
|
||||
demand = null;
|
||||
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
|
||||
if (caller is null || operation is not (DataOperations.Browse or DataOperations.Read or DataOperations.Write or DataOperations.Subscribe or DataOperations.HistoryRead)) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireInvalid); return false; }
|
||||
try
|
||||
{
|
||||
if (!_nodes.TryResolve(nodeId, out var definition) || definition is null || !definition.AuthorityIsCurrent() ||
|
||||
!_catalog.TryResolveProjected(definition.Realm, definition.LocalIdentifier, out var proof) || proof is null ||
|
||||
proof.Generation != definition.ProjectionGeneration || !MetadataMatches(proof.Metadata, definition.Metadata) ||
|
||||
((operation is DataOperations.Read or DataOperations.Subscribe) && proof.MaximumSampleAge <= TimeSpan.Zero) ||
|
||||
// H3: history only on a node projected Historizing (mapping bit AND origin HistoryInfo), whatever the caller holds.
|
||||
(operation == DataOperations.HistoryRead && (!definition.Historizing || !ProjectedHistoryAccess.Advertises(proof))) ||
|
||||
proof.Metadata.View.MappingId is not { } mapping || proof.Lease.Serving.ServingGeneration <= 0 ||
|
||||
_connectionForMapping(mapping) is not { Length: > 0 } connectionId) { ProjectedStreamDiagnostics.Count(ProjectedStreamDiagnostics.Event.AcquireDefinition); return false; }
|
||||
var identity = new DataCallerIdentity(caller.Principal, caller.ApiKeyId, caller.CredentialVersion, caller.CredentialExpiresUtc);
|
||||
@@ -213,12 +215,24 @@ public sealed class ProjectedDataAccess : IProjectedDataAccess, IDisposable
|
||||
if (lease is Demand demand) await demand.Completion.ConfigureAwait(false);
|
||||
}
|
||||
public bool HasLiveDemand(DataRealm realm, string localIdentifier) { lock (_sync) return _demandCounts.ContainsKey((realm, localIdentifier)); }
|
||||
/// <summary>H3: what a HistoryRead demand is bound to — its mapping, revision, deployed connection and the origin's metadata.</summary>
|
||||
internal bool TryDescribeHistoryDemand(IProjectedDemandLease lease, out ProjectedHistoryTarget? target)
|
||||
{
|
||||
target = null;
|
||||
if (lease is not Demand { RequestedOperation: DataOperations.HistoryRead } demand || !demand.IsValid) return false;
|
||||
var binding = demand.CurrentBinding;
|
||||
if (binding.Proof.Metadata.View.MappingId is not { } mapping) return false;
|
||||
target = new ProjectedHistoryTarget(mapping, binding.Proof.Metadata.View.MappingRevision, binding.ConnectionId,
|
||||
binding.Proof.OriginMetadata, binding.Proof.Lease.Serving, binding.Proof.Generation);
|
||||
return true;
|
||||
}
|
||||
private static OpcUaOperation Operation(DataOperations operation) => operation switch
|
||||
{
|
||||
DataOperations.Browse => OpcUaOperation.Browse,
|
||||
DataOperations.Read => OpcUaOperation.Read,
|
||||
DataOperations.Write => OpcUaOperation.WriteOperate,
|
||||
DataOperations.Subscribe => OpcUaOperation.CreateMonitoredItems,
|
||||
DataOperations.HistoryRead => OpcUaOperation.HistoryRead,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(operation))
|
||||
};
|
||||
private sealed class Demand(ProjectedDataAccess owner, NodeId nodeId, ProjectedVariableDefinition definition,
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
using Opc.Ua;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>What a projected HistoryRead demand is bound to (H3).</summary>
|
||||
/// <param name="MappingId">The mapping.</param>
|
||||
/// <param name="MappingRevision">The deployed mapping revision.</param>
|
||||
/// <param name="ConnectionId">The deployed connection the mapping reads through.</param>
|
||||
/// <param name="OriginMetadata">The origin's metadata (origin view, value kind).</param>
|
||||
/// <param name="Serving">The origin serving identity the projection was built under.</param>
|
||||
/// <param name="ProjectionGeneration">The projection generation.</param>
|
||||
internal sealed record ProjectedHistoryTarget(string MappingId, long MappingRevision, string ConnectionId, DataMetadata OriginMetadata,
|
||||
ServingIdentity Serving, long ProjectionGeneration);
|
||||
|
||||
/// <summary>
|
||||
/// H3 — consumer OPC UA projection of remote history (gRPC data history plan §2.1, §3.2, §3.3). For each projected node:
|
||||
/// resolve + authorize + pin it through <see cref="ProjectedDataAccess"/> (a <see cref="DataOperations.HistoryRead"/>
|
||||
/// demand: the mapping's HistoryRead bit and a local HistoryRead grant on the mapping scope, ACLs on or off), group the
|
||||
/// batch per deployed connection and per details, and forward through <see cref="IDataHistoryService"/>.
|
||||
/// <list type="bullet">
|
||||
/// <item>A fresh read may move endpoint within its deadline (the connection decides); a RESUMED read never moves —
|
||||
/// its origin token pins the issuing endpoint and serving incarnation, and its cursor re-checks the caller, the
|
||||
/// mapping revision, the projection generation, the serving identity and the connection lease (route) before any
|
||||
/// call. Any mismatch ⇒ <c>BadContinuationPointInvalid</c> and the origin token is released.</item>
|
||||
/// <item>A resume resends the ORIGINAL details verbatim (the origin binds their hash); local SDK resumes ignore details,
|
||||
/// so the consumer does too.</item>
|
||||
/// <item>The per-request assembly budget (min <c>MaxHistoryAssemblyBytesPerRequest</c> of the batch's mappings) is shared
|
||||
/// across the batch; once spent, the remaining nodes are <c>BadTooManyOperations</c>.</item>
|
||||
/// <item>Deadline per call = min(the consumer's remaining <c>HistoryReadDeadline</c>, the connection's
|
||||
/// <c>HistoryTimeoutMilliseconds</c>) ⇒ <c>BadTimeout</c>; a cancelled read is never an origin fault.</item>
|
||||
/// <item>Releases (<c>releaseContinuationPoints</c>, session close, eviction) are coalesced per connection into one
|
||||
/// best-effort <c>ReleaseHistoryAsync</c>; the origin's idle expiry is the backstop.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposable
|
||||
{
|
||||
internal const uint Good = 0, BadContinuationPointInvalid = 0x804A0000u, BadTooManyOperations = 0x80100000u, BadTimeout = 0x800A0000u,
|
||||
BadNoCommunication = 0x80310000u, BadTypeMismatch = 0x80740000u, BadHistoryOperationUnsupported = 0x80720000u;
|
||||
internal const long DefaultAssemblyBudget = 16L * 1024 * 1024;
|
||||
|
||||
private readonly ProjectedDataAccess _access;
|
||||
private readonly IGrpcDataAdapterConnectionSource _connections;
|
||||
private readonly Func<string, long?> _assemblyBudget;
|
||||
private readonly TimeProvider _clock;
|
||||
private readonly object _releaseGate = new();
|
||||
private readonly Dictionary<string, List<byte[]>> _pendingReleases = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private Task _releaseFlush = Task.CompletedTask;
|
||||
private int _disposed;
|
||||
|
||||
/// <summary>Creates the gateway.</summary>
|
||||
/// <param name="access">The projected data access that resolves, authorizes and pins projected nodes.</param>
|
||||
/// <param name="connections">The deployed connection registry.</param>
|
||||
/// <param name="assemblyBudget">A mapping's <c>MaxHistoryAssemblyBytesPerRequest</c>; null = not deployed.</param>
|
||||
/// <param name="clock">The clock.</param>
|
||||
public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections,
|
||||
Func<string, long?> assemblyBudget, TimeProvider clock)
|
||||
{
|
||||
_access = access ?? throw new ArgumentNullException(nameof(access));
|
||||
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
|
||||
_assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget));
|
||||
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
||||
}
|
||||
|
||||
/// <summary>How long a release waits to coalesce with others for the same connection (a session close disposes one by one).</summary>
|
||||
internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25);
|
||||
|
||||
/// <summary>Releases queued and not yet sent (tests).</summary>
|
||||
internal int PendingReleasesForTests { get { lock (_releaseGate) return _pendingReleases.Values.Sum(x => x.Count); } }
|
||||
|
||||
/// <summary>Release calls sent (tests): one per connection per coalesced flush.</summary>
|
||||
internal int ReleaseCallsForTests => Volatile.Read(ref _releaseCalls);
|
||||
private int _releaseCalls;
|
||||
|
||||
/// <summary>Waits for the queued releases to be sent (tests).</summary>
|
||||
internal async Task FlushReleasesForTestsAsync()
|
||||
{
|
||||
Task flush;
|
||||
lock (_releaseGate) flush = _releaseFlush;
|
||||
await flush.ConfigureAwait(false);
|
||||
lock (_releaseGate) flush = _releaseFlush;
|
||||
await flush.ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a projected node is advertised as historizing: the mapping (masked by the export) grants HistoryRead AND the
|
||||
/// origin's negotiated metadata (<c>HistoryInfo</c>, bit 32) says historizing.
|
||||
/// </summary>
|
||||
public static bool Advertises(ProjectedNodeProof proof) =>
|
||||
proof is not null && (proof.Subject.AllowedOperations & DataOperations.HistoryRead) != 0
|
||||
&& (proof.OriginMetadata.AllowedOperations & DataOperations.HistoryRead) != 0
|
||||
&& proof.OriginMetadata.History is { Historizing: true } && proof.OriginMetadata.NodeKind is "Variable" or "Tag";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<ProjectedHistoryOutcome>> ReadAsync(RoleCarryingUserIdentity caller, DataHistoryDetails details,
|
||||
IReadOnlyList<ProjectedHistoryNode> nodes, TimeSpan deadline, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(caller); ArgumentNullException.ThrowIfNull(details); ArgumentNullException.ThrowIfNull(nodes);
|
||||
var started = _clock.GetTimestamp();
|
||||
var outcomes = new ProjectedHistoryOutcome?[nodes.Count];
|
||||
var demands = new IProjectedDemandLease?[nodes.Count];
|
||||
var targets = new ProjectedHistoryTarget?[nodes.Count];
|
||||
var callerKey = CallerKey(caller);
|
||||
long budget = DefaultAssemblyBudget;
|
||||
try
|
||||
{
|
||||
// 1. Resolve, authorize and pin every node; check each resumed cursor against what it was issued under.
|
||||
for (var i = 0; i < nodes.Count; i++)
|
||||
{
|
||||
var node = nodes[i];
|
||||
var cursor = node.Resume as RemoteCursor;
|
||||
if (node.Resume is not null && (cursor is null || !ReferenceEquals(cursor.Owner, this)))
|
||||
{
|
||||
node.Resume.Release();
|
||||
outcomes[i] = Fail(BadContinuationPointInvalid);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!_access.TryAcquire(node.NodeId, caller, DataOperations.HistoryRead, out var demand) || demand is null
|
||||
|| !_access.TryDescribeHistoryDemand(demand, out var target) || target is null)
|
||||
{
|
||||
demand?.Dispose();
|
||||
cursor?.ReleaseOrigin();
|
||||
// The node manager already authorized the node: a projection that cannot be pinned now is not servable.
|
||||
outcomes[i] = Fail(cursor is null ? BadNoCommunication : BadContinuationPointInvalid);
|
||||
continue;
|
||||
}
|
||||
|
||||
demands[i] = demand;
|
||||
targets[i] = target;
|
||||
if (cursor is not null && !cursor.StillMatches(callerKey, target, demand))
|
||||
{
|
||||
// Mapping revision change, failover, projection rebuild, another caller: the cursor never resumes.
|
||||
cursor.ReleaseOrigin();
|
||||
outcomes[i] = Fail(BadContinuationPointInvalid);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. The per-request assembly budget, shared across the batch: the tightest mapping's.
|
||||
budget = long.MaxValue;
|
||||
foreach (var target in targets)
|
||||
if (target is not null) budget = Math.Min(budget, _assemblyBudget(target.MappingId) is { } b and > 0 ? b : DefaultAssemblyBudget);
|
||||
if (budget == long.MaxValue) budget = DefaultAssemblyBudget;
|
||||
|
||||
// 3. One call per (connection, details, resumed endpoint): a resumed item pins its issuing endpoint, so cursors of
|
||||
// different endpoints, and fresh items (which may move), never share a call.
|
||||
var groups = Enumerable.Range(0, nodes.Count).Where(i => outcomes[i] is null)
|
||||
.GroupBy(i => new GroupKey(targets[i]!.ConnectionId, DetailsOf(nodes[i], details), ResumeKey(nodes[i])))
|
||||
.ToArray();
|
||||
foreach (var group in groups)
|
||||
{
|
||||
var indices = group.ToArray();
|
||||
if (cancellationToken.IsCancellationRequested) { FailAll(indices, BadTimeout); continue; }
|
||||
TimeSpan remaining;
|
||||
if (deadline > TimeSpan.Zero)
|
||||
{
|
||||
remaining = deadline - _clock.GetElapsedTime(started);
|
||||
if (remaining <= TimeSpan.Zero) { FailAll(indices, BadTimeout); continue; }
|
||||
}
|
||||
else remaining = TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
|
||||
if (budget <= 0) { FailAll(indices, BadTooManyOperations); continue; }
|
||||
await ReadGroupAsync(group.Key, indices, remaining, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var demand in demands) demand?.Dispose();
|
||||
}
|
||||
|
||||
async Task ReadGroupAsync(GroupKey key, int[] indices, TimeSpan remaining, CancellationToken ct)
|
||||
{
|
||||
IGrpcDataAdapterConnectionLease? lease = null;
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(remaining, _clock);
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
|
||||
lease = await _connections.AcquireAsync(key.ConnectionId, linked.Token).ConfigureAwait(false);
|
||||
if (lease is null || lease.Connection is not IDataHistoryService history || lease.CancellationToken.IsCancellationRequested)
|
||||
{
|
||||
foreach (var i in indices)
|
||||
{
|
||||
if (nodes[i].Resume is RemoteCursor c) { c.ReleaseOrigin(); outcomes[i] = Fail(BadContinuationPointInvalid); }
|
||||
else outcomes[i] = Fail(BadNoCommunication);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var route = lease.RouteIdentity;
|
||||
var items = new List<DataHistoryReadItem>(indices.Length);
|
||||
var sent = new List<int>(indices.Length);
|
||||
foreach (var i in indices)
|
||||
{
|
||||
if (nodes[i].Resume is RemoteCursor cursor)
|
||||
{
|
||||
// The connection lease moved (expiry, redeployment, credential change): its tokens are gone.
|
||||
if (!Equals(cursor.RouteIdentity, route))
|
||||
{
|
||||
cursor.ReleaseOrigin();
|
||||
outcomes[i] = Fail(BadContinuationPointInvalid);
|
||||
continue;
|
||||
}
|
||||
|
||||
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
targets[i]!.OriginMetadata.View, cursor.AggregateId, cursor.Token));
|
||||
}
|
||||
else
|
||||
{
|
||||
items.Add(new DataHistoryReadItem(sent.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
|
||||
targets[i]!.OriginMetadata.View, nodes[i].AggregateId));
|
||||
}
|
||||
|
||||
sent.Add(i);
|
||||
}
|
||||
|
||||
if (items.Count == 0) return;
|
||||
IReadOnlyList<DataHistoryReadResult> answers;
|
||||
try
|
||||
{
|
||||
answers = await history.ReadAsync(new DataHistoryReadRequest(key.Details, items,
|
||||
new DataBudget(remaining, items.Count, (int)Math.Min(int.MaxValue, budget))), linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// Our deadline or the SDK request ending: a timeout, never an origin fault (the connection records none).
|
||||
foreach (var i in sent) outcomes[i] = Fail(BadTimeout);
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (answers.Count != items.Count)
|
||||
{
|
||||
foreach (var i in sent) outcomes[i] = Fail(BadNoCommunication);
|
||||
return;
|
||||
}
|
||||
|
||||
for (var k = 0; k < answers.Count; k++)
|
||||
{
|
||||
var i = sent[k];
|
||||
var answer = answers[k];
|
||||
if (answer.CorrelationId != items[k].CorrelationId)
|
||||
{
|
||||
outcomes[i] = Fail(BadNoCommunication);
|
||||
continue;
|
||||
}
|
||||
|
||||
// The per-request assembly budget, in request order across the whole batch: once a node does not fit,
|
||||
// it and every later node is BadTooManyOperations (never a partial answer; its origin cursor released).
|
||||
long nodeBytes = 0;
|
||||
foreach (var sample in answer.Samples) nodeBytes += sample.Value.EstimatedRetainedBytes;
|
||||
if (nodeBytes > budget)
|
||||
{
|
||||
budget = 0;
|
||||
if (answer.Continuation is { } dropped) EnqueueRelease(key.ConnectionId, dropped);
|
||||
outcomes[i] = Fail(BadTooManyOperations);
|
||||
continue;
|
||||
}
|
||||
|
||||
budget -= nodeBytes;
|
||||
|
||||
var target = targets[i]!;
|
||||
RemoteCursor? next = null;
|
||||
if (answer.Continuation is { } token)
|
||||
{
|
||||
next = new RemoteCursor(this, target.OriginMetadata.View.Realm, demands[i]!.LocalIdentifier, token, key.ConnectionId, route,
|
||||
target, callerKey, key.Details, nodes[i].Resume is RemoteCursor prior ? prior.AggregateId : nodes[i].AggregateId);
|
||||
}
|
||||
|
||||
outcomes[i] = new ProjectedHistoryOutcome(answer.StatusCode, Convert(answer.Samples, target.OriginMetadata), next);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var answer in answers) answer.Dispose();
|
||||
}
|
||||
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
foreach (var i in indices)
|
||||
{
|
||||
if (outcomes[i] is not null) continue;
|
||||
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
|
||||
outcomes[i] = Fail(BadTimeout);
|
||||
}
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidOperationException or UnauthorizedAccessException or ArgumentException or ObjectDisposedException)
|
||||
{
|
||||
foreach (var i in indices) outcomes[i] ??= Fail(nodes[i].Resume is null ? BadNoCommunication : BadContinuationPointInvalid);
|
||||
return;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lease is not null) await lease.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
void FailAll(int[] indices, uint status)
|
||||
{
|
||||
foreach (var i in indices)
|
||||
{
|
||||
if (nodes[i].Resume is RemoteCursor c) c.ReleaseOrigin();
|
||||
outcomes[i] = Fail(status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ProjectedHistoryOutcome Fail(uint status) => new(status, []);
|
||||
|
||||
private static DataHistoryDetails DetailsOf(ProjectedHistoryNode node, DataHistoryDetails request) =>
|
||||
node.Resume is RemoteCursor cursor ? cursor.Details : request;
|
||||
|
||||
private static string ResumeKey(ProjectedHistoryNode node)
|
||||
{
|
||||
if (node.Resume is not RemoteCursor cursor) return "fresh";
|
||||
return GrpcDataConnection.TryUnwrap(cursor.Token, out var endpoint, out var serving, out _)
|
||||
? FormattableString.Invariant($"{endpoint}|{serving}") : "resume";
|
||||
}
|
||||
|
||||
private static string CallerKey(RoleCarryingUserIdentity caller) =>
|
||||
string.Join('\0', caller.Principal ?? "", caller.ApiKeyId ?? "", caller.CredentialVersion ?? "");
|
||||
|
||||
/// <summary>Values verbatim (status, absent timestamps); a value kind that disagrees with the catalog is <c>BadTypeMismatch</c>.</summary>
|
||||
private static OriginHistorySample[] Convert(IReadOnlyList<DataHistorySample> samples, DataMetadata metadata)
|
||||
{
|
||||
var converted = new OriginHistorySample[samples.Count];
|
||||
for (var i = 0; i < samples.Count; i++)
|
||||
{
|
||||
var sample = samples[i];
|
||||
object? value;
|
||||
var status = sample.StatusCode;
|
||||
try { value = ProjectedDataAccess.DecodeValue(sample.Value, metadata); }
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidCastException or InvalidOperationException)
|
||||
{
|
||||
value = null;
|
||||
status = BadTypeMismatch;
|
||||
}
|
||||
|
||||
converted[i] = new OriginHistorySample(value, status, sample.SourceTimestampUtc?.UtcDateTime, sample.ServerTimestampUtc?.UtcDateTime);
|
||||
}
|
||||
|
||||
return converted;
|
||||
}
|
||||
|
||||
/// <summary>Queues an origin token for a coalesced best-effort release on its connection.</summary>
|
||||
private void EnqueueRelease(string connectionId, byte[] token)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) return;
|
||||
lock (_releaseGate)
|
||||
{
|
||||
if (!_pendingReleases.TryGetValue(connectionId, out var list)) _pendingReleases[connectionId] = list = [];
|
||||
list.Add(token);
|
||||
if (!_releaseFlush.IsCompleted) return;
|
||||
_releaseFlush = Task.Run(FlushReleasesAsync);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FlushReleasesAsync()
|
||||
{
|
||||
try { await Task.Delay(ReleaseCoalesce, _stop.Token).ConfigureAwait(false); }
|
||||
catch (OperationCanceledException) { return; }
|
||||
Dictionary<string, List<byte[]>> batch;
|
||||
lock (_releaseGate)
|
||||
{
|
||||
batch = new(_pendingReleases, StringComparer.OrdinalIgnoreCase);
|
||||
_pendingReleases.Clear();
|
||||
}
|
||||
|
||||
foreach (var (connectionId, tokens) in batch)
|
||||
{
|
||||
IGrpcDataAdapterConnectionLease? lease = null;
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, _stop.Token);
|
||||
lease = await _connections.AcquireAsync(connectionId, linked.Token).ConfigureAwait(false);
|
||||
if (lease?.Connection is not IDataHistoryService history) continue;
|
||||
Interlocked.Increment(ref _releaseCalls);
|
||||
await history.ReleaseAsync(tokens, linked.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException) { } // best effort; the origin's idle expiry is the backstop
|
||||
finally
|
||||
{
|
||||
if (lease is not null) try { await lease.DisposeAsync().ConfigureAwait(false); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
lock (_releaseGate)
|
||||
if (_pendingReleases.Count > 0 && Volatile.Read(ref _disposed) == 0) _releaseFlush = Task.Run(FlushReleasesAsync);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_stop.Cancel();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a cursor issued under <paramref name="issued"/> for <paramref name="issuedCaller"/> may resume now: same caller
|
||||
/// (principal, key, credential version), mapping and revision, deployed connection, projection generation, origin view
|
||||
/// and serving identity (node, incarnation, serving generation, role — a failover or restart changes it).
|
||||
/// </summary>
|
||||
internal static bool CursorMatches(ProjectedHistoryTarget issued, string issuedCaller, ProjectedHistoryTarget now, string caller) =>
|
||||
string.Equals(caller, issuedCaller, StringComparison.Ordinal)
|
||||
&& string.Equals(now.MappingId, issued.MappingId, StringComparison.Ordinal) && now.MappingRevision == issued.MappingRevision
|
||||
&& string.Equals(now.ConnectionId, issued.ConnectionId, StringComparison.OrdinalIgnoreCase)
|
||||
&& now.ProjectionGeneration == issued.ProjectionGeneration && now.OriginMetadata.View == issued.OriginMetadata.View
|
||||
&& string.Equals(now.Serving.NodeId, issued.Serving.NodeId, StringComparison.Ordinal)
|
||||
&& string.Equals(now.Serving.Incarnation, issued.Serving.Incarnation, StringComparison.Ordinal)
|
||||
&& now.Serving.ServingGeneration == issued.Serving.ServingGeneration
|
||||
&& string.Equals(now.Serving.Role, issued.Serving.Role, StringComparison.Ordinal);
|
||||
|
||||
private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume);
|
||||
|
||||
/// <summary>The remote cursor in the consumer's SDK session store (<see cref="HistoryCursorKind"/> <c>Remote</c>).</summary>
|
||||
private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
|
||||
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
|
||||
: ProjectedHistoryContinuation(realm, localIdentifier)
|
||||
{
|
||||
private int _originReleased;
|
||||
internal ProjectedHistoryAccess Owner => owner;
|
||||
internal byte[] Token => token;
|
||||
internal object? RouteIdentity => routeIdentity;
|
||||
internal DataHistoryDetails Details => details;
|
||||
internal uint? AggregateId => aggregateId;
|
||||
|
||||
/// <summary>The caller, mapping revision, projection generation, serving identity and connection still match.</summary>
|
||||
internal bool StillMatches(string caller, ProjectedHistoryTarget now, IProjectedDemandLease demand) =>
|
||||
demand.Realm == Realm && string.Equals(demand.LocalIdentifier, LocalIdentifier, StringComparison.Ordinal)
|
||||
&& CursorMatches(target, callerKey, now, caller);
|
||||
|
||||
/// <summary>Releases the origin token (once), whether the cursor was claimed for a resume or not.</summary>
|
||||
internal void ReleaseOrigin()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token);
|
||||
}
|
||||
|
||||
protected override void OnRelease() => ReleaseOrigin();
|
||||
}
|
||||
}
|
||||
+13
@@ -122,6 +122,19 @@ public sealed class ProjectedMappingDeploymentRuntime : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>H3: the mapping's per-request history assembly budget, while its activated authority is current.</summary>
|
||||
public bool TryGetHistoryAssemblyBudget(string mappingId, out long bytes)
|
||||
{
|
||||
bytes = 0;
|
||||
if (!TryGetConnectionId(mappingId, out _)) return false;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_byMapping.TryGetValue(mappingId, out var placement)) return false;
|
||||
bytes = placement.Mapping.MaxHistoryAssemblyBytesPerRequest;
|
||||
return bytes > 0;
|
||||
}
|
||||
}
|
||||
|
||||
public void Stage(CatalogAttempt attempt, IReadOnlyList<RemoteNamespaceMapping> mappings, IReadOnlyList<DataConnection> connections)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(attempt);
|
||||
|
||||
@@ -95,7 +95,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
|
||||
if (!PageCurrent() || guards.Any(guard => !guard.IsCurrent()) || root is not null && !root.IsCurrent())
|
||||
return ProjectionPageStatus.Unavailable;
|
||||
var definitions = guards.Select(guard => new ProjectedVariableDefinition(guard.Proof.Metadata.View.Realm,
|
||||
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)).ToArray();
|
||||
guard.Proof.LocalIdentifier, exactParent, guard.Proof.Metadata, guard.Proof.Generation, guard.IsCurrent)
|
||||
{ Historizing = ProjectedHistoryAccess.Advertises(guard.Proof) }).ToArray();
|
||||
var rootLeaf = root is not null && ProjectedCatalogCache.IsValueNode(root.Proof.Metadata);
|
||||
if (rootLeaf && (definitions.Length != 0 || !page.Complete)) return ProjectionPageStatus.Unavailable;
|
||||
var attempted = 0;
|
||||
@@ -112,7 +113,8 @@ public sealed class ProjectedNamespaceApplier : IDisposable
|
||||
{
|
||||
accepted = rootLeaf
|
||||
? _sink.TryApplyRootLeaf(exactParent, new ProjectedVariableDefinition(root!.Proof.Metadata.View.Realm,
|
||||
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent), Commit)
|
||||
root.Proof.LocalIdentifier, exactParent, root.Proof.Metadata, root.Proof.Generation, root.IsCurrent)
|
||||
{ Historizing = ProjectedHistoryAccess.Advertises(root.Proof) }, Commit)
|
||||
: _sink.TryApply(exactParent, definitions, Commit);
|
||||
return accepted && committed && PageCurrent() ? ProjectionPageStatus.Ready : ProjectionPageStatus.Unavailable;
|
||||
}
|
||||
|
||||
@@ -380,7 +380,7 @@ public sealed class RemoteNamespaceResolver : IFederatedProjectionCatalog, IDisp
|
||||
if (!guard.IsCurrent() || caller is not null && !_policy.AuthorizeMapped(caller, OpcUaOperation.CreateMonitoredItems,
|
||||
mapped.View, serving, subject, resolver, lease)) return false;
|
||||
var newDefinition = new ProjectedVariableDefinition(definition.Realm, definition.LocalIdentifier, definition.Parent,
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime };
|
||||
mapped, generation, guard.IsCurrent) { Lifetime = definition.Lifetime, Historizing = ProjectedHistoryAccess.Advertises(renewed) };
|
||||
return sink.TryRenewExact(nodeId, definition, newDefinition, () =>
|
||||
{
|
||||
var duration = Clock.GetElapsedTime(started, Clock.GetTimestamp());
|
||||
|
||||
+9
-1
@@ -362,7 +362,9 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
bool restrictToPlant = false, Action<ProjectedValueUpdate>? onPublished = null, bool mountAtRealmRoot = false,
|
||||
long maxUnaryBytes = 8_000_000, bool allowWrite = false, IGrpcDataAdapterConnectionSource? connectionSource = null,
|
||||
int? staleTimeoutMilliseconds = null, Func<IProjectedNamespacePageSink, IProjectedNamespacePageSink>? renewalSinkFactory = null,
|
||||
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false)
|
||||
Action<LocalCatalogCoordinator>? onCoordinator = null, int? localPermissions = null, bool allowHistory = false,
|
||||
Action<ProjectedHistoryAccess, OtOpcUaNodeManager>? onHistory = null,
|
||||
Action<ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping>? configureMapping = null)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var pki = Path.Combine(Path.GetTempPath(), $"composed-projection-{Guid.NewGuid():N}");
|
||||
@@ -401,6 +403,7 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
mapping.AllowedOperations |= DataOperations.Read | DataOperations.Metadata;
|
||||
if (allowWrite) { mapping.AllowedOperations |= DataOperations.Write; mapping.WriteThrough = true; }
|
||||
if (allowHistory) mapping.AllowedOperations |= DataOperations.HistoryRead;
|
||||
configureMapping?.Invoke(mapping);
|
||||
placements.Stage(attempt, [mapping], [Connection()]);
|
||||
coordinator.Complete(attempt, true).ShouldBeTrue();
|
||||
var manager = started.Server.NodeManager!;
|
||||
@@ -427,6 +430,11 @@ public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
new DataBudget(TimeSpan.FromSeconds(5), 32, 128_000), 8);
|
||||
manager.ProjectedBrowseAccess = browse;
|
||||
manager.ProjectedDataAccess = access;
|
||||
// H3: projected HistoryRead through the same deployed connections.
|
||||
using var history = new ProjectedHistoryAccess(access, connections,
|
||||
id => placements.TryGetHistoryAssemblyBudget(id, out var bytes) ? bytes : null, origin.Clock);
|
||||
manager.ProjectedHistoryAccess = history;
|
||||
onHistory?.Invoke(history, manager);
|
||||
var identifier = ProjectedDataIds.Identifier("map", root.Address);
|
||||
((IProjectedNodeLookup)sink).TryGetNodeId(ProjectedDataIds.NamespaceUri(root.Realm), identifier, out var node).ShouldBeTrue();
|
||||
var anchor = node.ShouldNotBeNull();
|
||||
|
||||
+6
-2
@@ -7,6 +7,8 @@ using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||||
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P04")]
|
||||
@@ -131,7 +133,8 @@ internal sealed class LocalDataFixture : IDisposable
|
||||
Func<DataAuthenticatedContext, DataTarget, IDataSubscriptionService>? targetSubscriptions = null,
|
||||
bool advanceAuthority = false, string role = "Primary", long servingGeneration = 0, bool nestedCatalog = false, bool nestedUnsCatalog = false,
|
||||
Func<DataAuthenticatedContext, IDataWriteService>? writes = null, bool denyReadExport = false,
|
||||
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1")
|
||||
ManualTimeProvider? clock = null, string servingNode = "node-a", string servingIncarnation = "serving-1",
|
||||
IOriginHistoryPort? history = null)
|
||||
{
|
||||
if (clock is not null) Clock = clock;
|
||||
Serving = Serving with { NodeId = servingNode, Incarnation = servingIncarnation, Role = role, ServingGeneration = servingGeneration };
|
||||
@@ -158,6 +161,7 @@ internal sealed class LocalDataFixture : IDisposable
|
||||
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
|
||||
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe;
|
||||
if (denyReadExport) operations &= ~DataOperations.Read;
|
||||
if (history is not null) operations |= DataOperations.HistoryRead;
|
||||
var rootMetadata = new DataMetadata(Root, "Plant", "Folder", DataValueKind.Null, -1, [], false, operations, 1, null, null, false);
|
||||
var rawMetadata = new DataMetadata(Raw, "Speed", "Variable", DataValueKind.Int32, -1, [], true, operations, 1, Ticket.Key.StableSourceId, "rpm", false);
|
||||
var unsMetadata = rawMetadata with { View = Uns };
|
||||
@@ -192,7 +196,7 @@ internal sealed class LocalDataFixture : IDisposable
|
||||
var capabilities = new DataCapabilitiesProvider("cluster", () => Serving, () => Catalog.IsActive, limits);
|
||||
Services = new LocalDataServices(() => Catalog, Hub, new DataOperationPolicy(Authority,
|
||||
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock, writes: writes, subscriptions: subscriptions,
|
||||
targetSubscriptions: targetSubscriptions);
|
||||
targetSubscriptions: targetSubscriptions, history: history);
|
||||
}
|
||||
|
||||
internal IDataConnection Connection() => Services.Create(Context, new(DataTargetMode.Node, "cluster", Serving.NodeId));
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// H3 — the resume rule of a consumer Remote cursor: it resumes only under the caller, mapping revision, deployed
|
||||
/// connection, projection generation, origin view and serving identity it was issued under. A mapping revision change,
|
||||
/// a failover / origin restart (serving node, incarnation, generation or role), a projection rebuild or another caller
|
||||
/// ⇒ the cursor never resumes (<c>BadContinuationPointInvalid</c>, origin token released).
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H3")]
|
||||
public sealed class GrpcDataProjectedHistoryCursorTests
|
||||
{
|
||||
private static readonly DataView View = new(new DataAddress("origin", "urn:raw", "string", "Plant/Speed"), DataRealm.Raw, null, 0, "Plant/Speed");
|
||||
private static readonly DataMetadata Metadata = new(View, "Speed", "Tag", DataValueKind.Int32, -1, [], false,
|
||||
DataOperations.Read | DataOperations.HistoryRead, 1, null, null, false, History: new DataHistoryInfo(true));
|
||||
private static readonly ProjectedHistoryTarget Issued = new("map", 3, "link", Metadata, new ServingIdentity("node-a", "boot-1", "Primary", 5, 6, 2), 7);
|
||||
private const string Caller = "peer\0key\0v1";
|
||||
|
||||
private static readonly Dictionary<string, (ProjectedHistoryTarget Now, string Caller)> ChangeMap = new()
|
||||
{
|
||||
["mapping revision change"] = (Issued with { MappingRevision = 4 }, Caller),
|
||||
["another mapping"] = (Issued with { MappingId = "other" }, Caller),
|
||||
["another connection"] = (Issued with { ConnectionId = "link-2" }, Caller),
|
||||
["projection rebuild"] = (Issued with { ProjectionGeneration = 8 }, Caller),
|
||||
["failover to the pair member"] = (Issued with { Serving = Issued.Serving with { NodeId = "node-b" } }, Caller),
|
||||
["origin restart"] = (Issued with { Serving = Issued.Serving with { Incarnation = "boot-2" } }, Caller),
|
||||
["serving generation bump"] = (Issued with { Serving = Issued.Serving with { ServingGeneration = 3 } }, Caller),
|
||||
["role change"] = (Issued with { Serving = Issued.Serving with { Role = "Secondary" } }, Caller),
|
||||
["another origin view"] = (Issued with { OriginMetadata = Metadata with { View = View with { Subject = "Plant/Other" } } }, Caller),
|
||||
["another caller"] = (Issued, "intruder\0key\0v1"),
|
||||
["a rotated credential"] = (Issued, "peer\0key\0v2"),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void The_same_binding_resumes_even_when_only_the_catalog_or_authority_epoch_moved()
|
||||
{
|
||||
ProjectedHistoryAccess.CursorMatches(Issued, Caller, Issued, Caller).ShouldBeTrue();
|
||||
// A metadata renewal or ACL redeploy at the origin moves epochs, not the serving identity the token is bound to
|
||||
// (the origin itself still refuses a token its own history epoch no longer matches).
|
||||
ProjectedHistoryAccess.CursorMatches(Issued, Caller,
|
||||
Issued with { Serving = Issued.Serving with { CatalogEpoch = 9, AuthorityEpoch = 9 } }, Caller).ShouldBeTrue();
|
||||
}
|
||||
|
||||
public static TheoryData<string> Changes => new(ChangeMap.Keys);
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(Changes))]
|
||||
public void Any_binding_change_refuses_the_resume(string change) =>
|
||||
ProjectedHistoryAccess.CursorMatches(Issued, Caller, ChangeMap[change].Now, ChangeMap[change].Caller).ShouldBeFalse(change);
|
||||
}
|
||||
+371
-20
@@ -1,39 +1,390 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
|
||||
using SdkDataValue = Opc.Ua.DataValue;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
||||
|
||||
/// <summary>
|
||||
/// H3 — a real consumer OPC UA session HistoryReads a projected node through the real projection stack
|
||||
/// (<see cref="ProjectedDataAccess"/> + <see cref="ProjectedHistoryAccess"/>) and a real in-process origin
|
||||
/// (<see cref="LocalDataServices"/> over a real <see cref="OtOpcUaNodeManager"/> history port and its
|
||||
/// <c>PeerHistoryContinuationStore</c>). Replaces the H2 pin that a projected node refused HistoryRead "until H3".
|
||||
/// </summary>
|
||||
public sealed partial class GrpcDataConfiguredDiscoveryWireTests
|
||||
{
|
||||
/// <summary>
|
||||
/// H2 review 7: <c>DataOperationPolicy</c> now maps OPC UA HistoryRead to the mapping's HistoryRead bit, so a mapped
|
||||
/// HistoryRead is AUTHORISABLE before H3 projects history. Pin that a projected node with the mapping bit AND a local
|
||||
/// HistoryRead grant still answers a clean refusal — never data, never a fault — until H3.
|
||||
/// </summary>
|
||||
private static readonly DateTime HistoryT0 = new(2026, 11, 20, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H2")]
|
||||
public async Task HistoryRead_on_a_projected_node_stays_a_clean_refusal_until_H3()
|
||||
[Trait("Phase", "H3")]
|
||||
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
|
||||
public async Task Granted_projected_HistoryRead_is_served_verbatim_and_pages_to_completion_through_the_origin()
|
||||
{
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1);
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
var connections = new PersistentConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var details = new ReadRawModifiedDetails
|
||||
var values = new List<SdkDataValue>();
|
||||
var cp = default(ByteString);
|
||||
var pages = 0;
|
||||
do
|
||||
{
|
||||
StartTime = DateTime.UtcNow.AddHours(-1), EndTime = DateTime.UtcNow, NumValuesPerNode = 10,
|
||||
IsReadModified = false, ReturnBounds = false,
|
||||
};
|
||||
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
|
||||
[new HistoryReadValueId { NodeId = anchor }], TestContext.Current.CancellationToken);
|
||||
var result = response.Results.ToArray()!.Single();
|
||||
// Pinned: the projected variable carries no HistoryRead access-level bit, so the SDK refuses before any history code.
|
||||
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
|
||||
(result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData { DataValues.Count: > 0 })
|
||||
.ShouldBeTrue("no data is served from a projected node before H3");
|
||||
var result = await RawHistory(client, anchor, 3, cp);
|
||||
StatusCode.IsGood(result.StatusCode).ShouldBeTrue(result.StatusCode.ToString());
|
||||
values.AddRange(Values(result));
|
||||
cp = result.ContinuationPoint;
|
||||
pages++;
|
||||
} while (!cp.IsEmpty && pages < 10);
|
||||
|
||||
values.Select(v => SdkValueBoundary.ToClr(v.WrappedValue)).ShouldBe(Enumerable.Range(0, 7).Cast<object?>());
|
||||
values.Select(v => v.SourceTimestamp.ToDateTime()).ShouldBe(Enumerable.Range(0, 7).Select(i => HistoryT0.AddSeconds(i)));
|
||||
pages.ShouldBe(3);
|
||||
origin.Services.HistoryOpenContinuations.ShouldBe(0, "a page-through to completion leaves nothing open at the origin");
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
[Trait("Phase", "H2")] // replaces the H2 pin "a projected node refuses HistoryRead until H3"
|
||||
public async Task Without_the_local_HistoryRead_grant_on_the_mapping_scope_it_is_BadUserAccessDenied_and_unsent()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var result = await RawHistory(client, anchor, 3, default);
|
||||
result.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code);
|
||||
result.ContinuationPoint.IsEmpty.ShouldBeTrue();
|
||||
}, localPermissions: 15, allowHistory: true);
|
||||
originServer.Source.Calls.ShouldBe(0);
|
||||
}, localPermissions: 7, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
public async Task Consumer_session_close_releases_the_origin_continuations()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
ProjectedHistoryAccess? history = null;
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var page = await RawHistory(client, anchor, 2, default);
|
||||
page.ContinuationPoint.IsEmpty.ShouldBeFalse();
|
||||
origin.Services.HistoryOpenContinuations.ShouldBe(1);
|
||||
await session.CloseAsync(TestContext.Current.CancellationToken);
|
||||
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
|
||||
origin.Services.HistoryOpenContinuations.ShouldBe(0, "the SDK disposed the Remote point and the release reached the origin");
|
||||
history!.ReleaseCallsForTests.ShouldBe(1);
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
|
||||
onHistory: (h, _) => history = h);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
public async Task ReleaseContinuationPoints_forwards_one_release_and_the_point_is_then_invalid()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
ProjectedHistoryAccess? history = null;
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var page = await RawHistory(client, anchor, 2, default);
|
||||
origin.Services.HistoryOpenContinuations.ShouldBe(1);
|
||||
var released = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(2)), TimestampsToReturn.Both, true,
|
||||
[new HistoryReadValueId { NodeId = anchor, ContinuationPoint = page.ContinuationPoint }], TestContext.Current.CancellationToken);
|
||||
StatusCode.IsGood(released.Results[0].StatusCode).ShouldBeTrue();
|
||||
await AwaitReleases(history!, () => origin.Services.HistoryOpenContinuations == 0);
|
||||
origin.Services.HistoryOpenContinuations.ShouldBe(0);
|
||||
var resumed = await RawHistory(client, anchor, 2, page.ContinuationPoint);
|
||||
resumed.StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin), onHistory: (h, _) => history = h);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
public async Task A_resume_after_lease_expiry_or_an_origin_rebuild_epoch_bump_is_invalid_and_a_fresh_read_succeeds()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
var connections = new PersistentConnections(origin);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
|
||||
// Lease expiry / redeployment: the deployed connection (route) is replaced — its tokens never resume.
|
||||
var page = await RawHistory(client, anchor, 2, default);
|
||||
connections.Rotate();
|
||||
(await RawHistory(client, anchor, 2, page.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
var fresh = await RawHistory(client, anchor, 2, default);
|
||||
StatusCode.IsGood(fresh.StatusCode).ShouldBeTrue();
|
||||
|
||||
// Origin rebuild: its history epoch moves (a removal), so the origin itself refuses the resumed token.
|
||||
originServer.BumpEpoch();
|
||||
(await RawHistory(client, anchor, 2, fresh.ContinuationPoint)).StatusCode.Code.ShouldBe(StatusCodes.BadContinuationPointInvalid.Code);
|
||||
StatusCode.IsGood((await RawHistory(client, anchor, 2, default)).StatusCode).ShouldBeTrue();
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: connections);
|
||||
}
|
||||
|
||||
[Fact(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
public async Task Uncapped_raw_returns_the_origin_continuation_and_aggregates_are_refused_both_ways()
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(25, maxRawPerRead: 10);
|
||||
originServer.Source.Aggregates = new HashSet<HistoryAggregateType> { HistoryAggregateType.Average };
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
// NumValuesPerNode = 0: the origin pages at its ceiling and the consumer hands back its continuation (Part 11).
|
||||
var uncapped = await RawHistory(client, anchor, 0, default);
|
||||
StatusCode.IsGood(uncapped.StatusCode).ShouldBeTrue();
|
||||
uncapped.ContinuationPoint.IsEmpty.ShouldBeFalse();
|
||||
Values(uncapped).Count.ShouldBeLessThan(25);
|
||||
|
||||
// The origin refuses an aggregate its backend does not serve.
|
||||
var refused = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Count);
|
||||
refused.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
|
||||
// The consumer refuses an aggregate it cannot name, unsent.
|
||||
var calls = originServer.Source.Calls;
|
||||
var unknown = await ProcessedHistory(client, anchor, new NodeId("no-such-aggregate", 1));
|
||||
unknown.StatusCode.Code.ShouldBe(StatusCodes.BadAggregateNotSupported.Code);
|
||||
originServer.Source.Calls.ShouldBe(calls);
|
||||
// A served aggregate passes through.
|
||||
var average = await ProcessedHistory(client, anchor, ObjectIds.AggregateFunction_Average);
|
||||
StatusCode.IsGood(average.StatusCode).ShouldBeTrue(average.StatusCode.ToString());
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
[Theory(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
[InlineData(1_000_000, 3)]
|
||||
[InlineData(25_000, 2)] // ≈ 288 B a value × 40 per node: two nodes fit, the third is refused
|
||||
[InlineData(15_000, 1)]
|
||||
[InlineData(1_200, 0)]
|
||||
public async Task The_per_request_assembly_budget_is_shared_across_the_batch(int budget, int expectedGood)
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7, extra: 2);
|
||||
using var origin = new LocalDataFixture(additionalRawNodes: 2, servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Root, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
var children = (await BrowseAll(client, anchor, 10))
|
||||
.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray();
|
||||
children.Length.ShouldBe(3);
|
||||
var details = new ReadAtTimeDetails { ReqTimes = Enumerable.Range(0, 40).Select(i => (DateTimeUtc)HistoryT0.AddSeconds(i)).ToArray() };
|
||||
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
|
||||
children.Select(c => new HistoryReadValueId { NodeId = c }).ToArray(), TestContext.Current.CancellationToken);
|
||||
var results = response.Results.ToArray()!;
|
||||
var statuses = results.Select(r => r.StatusCode.Code).ToArray();
|
||||
statuses.Count(s => StatusCode.IsGood(s)).ShouldBe(expectedGood, string.Join(",", statuses.Select(x => x.ToString("X8"))));
|
||||
foreach (var r in results.Where(r => !StatusCode.IsGood(r.StatusCode)))
|
||||
{
|
||||
r.StatusCode.Code.ShouldBe(StatusCodes.BadTooManyOperations.Code);
|
||||
Values(r).ShouldBeEmpty("never a partial answer under an error status");
|
||||
}
|
||||
foreach (var r in results.Where(r => StatusCode.IsGood(r.StatusCode))) Values(r).Count.ShouldBe(40);
|
||||
// The budget is consumed in request order: once a node does not fit, every later node is refused too.
|
||||
statuses.TakeWhile(x => StatusCode.IsGood(x)).Count().ShouldBe(expectedGood);
|
||||
}, localPermissions: 15, allowHistory: true, connectionSource: new PersistentConnections(origin),
|
||||
configureMapping: m => m.MaxHistoryAssemblyBytesPerRequest = budget);
|
||||
}
|
||||
|
||||
[Theory(Timeout = 90000)]
|
||||
[Trait("Phase", "H3")]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Historizing_and_the_HistoryRead_bit_follow_the_mapping_grant_and_never_HistoryWrite(bool granted)
|
||||
{
|
||||
await using var originServer = await HistoryOrigin.StartAsync(7);
|
||||
using var origin = new LocalDataFixture(servingGeneration: 1, history: originServer.Port);
|
||||
await WithComposedServer(origin, origin.Raw, async (session, _, _, _, _, _, anchor) =>
|
||||
{
|
||||
var client = (SessionClient)session;
|
||||
await BrowseAll(client, anchor, 1);
|
||||
var read = await client.ReadAsync(new RequestHeader(), 0, TimestampsToReturn.Neither,
|
||||
[new ReadValueId { NodeId = anchor, AttributeId = Attributes.Historizing },
|
||||
new ReadValueId { NodeId = anchor, AttributeId = Attributes.AccessLevel }], TestContext.Current.CancellationToken);
|
||||
read.Results[0].WrappedValue.TryGetValue(out bool historizing).ShouldBeTrue();
|
||||
historizing.ShouldBe(granted);
|
||||
read.Results[1].WrappedValue.TryGetValue(out byte level).ShouldBeTrue();
|
||||
((level & AccessLevels.HistoryRead) != 0).ShouldBe(granted);
|
||||
(level & AccessLevels.HistoryWrite).ShouldBe((byte)0);
|
||||
if (granted) return;
|
||||
var result = await RawHistory(client, anchor, 3, default);
|
||||
result.StatusCode.Code.ShouldBe(StatusCodes.BadHistoryOperationUnsupported.Code);
|
||||
originServer.Source.Calls.ShouldBe(0);
|
||||
}, localPermissions: 15, allowHistory: granted, connectionSource: new PersistentConnections(origin));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static ReadRawModifiedDetails RawDetails(uint count) => new()
|
||||
{
|
||||
StartTime = HistoryT0.AddSeconds(-1), EndTime = HistoryT0.AddHours(1), NumValuesPerNode = count, IsReadModified = false, ReturnBounds = false,
|
||||
};
|
||||
|
||||
private static async Task<Opc.Ua.HistoryReadResult> RawHistory(SessionClient client, NodeId node, uint count, ByteString cp)
|
||||
{
|
||||
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(RawDetails(count)), TimestampsToReturn.Both, false,
|
||||
[new HistoryReadValueId { NodeId = node, ContinuationPoint = cp }], TestContext.Current.CancellationToken);
|
||||
return response.Results.ToArray()!.Single();
|
||||
}
|
||||
|
||||
private static async Task<Opc.Ua.HistoryReadResult> ProcessedHistory(SessionClient client, NodeId node, NodeId aggregate)
|
||||
{
|
||||
var details = new ReadProcessedDetails
|
||||
{
|
||||
StartTime = HistoryT0, EndTime = HistoryT0.AddMinutes(1), ProcessingInterval = 10_000, AggregateType = [aggregate],
|
||||
AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true },
|
||||
};
|
||||
var response = await client.HistoryReadAsync(new RequestHeader(), new ExtensionObject(details), TimestampsToReturn.Both, false,
|
||||
[new HistoryReadValueId { NodeId = node }], TestContext.Current.CancellationToken);
|
||||
return response.Results.ToArray()!.Single();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<SdkDataValue> Values(Opc.Ua.HistoryReadResult result) =>
|
||||
result.HistoryData.IsNull || ExtensionObject.ToEncodeable(result.HistoryData) is not HistoryData data ? [] : data.DataValues.ToArray() ?? [];
|
||||
|
||||
private static async Task AwaitReleases(ProjectedHistoryAccess history, Func<bool> done)
|
||||
{
|
||||
for (var i = 0; i < 200 && !done(); i++)
|
||||
{
|
||||
await history.FlushReleasesForTestsAsync();
|
||||
if (!done()) await Task.Delay(10, TestContext.Current.CancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One long-lived origin connection, as a deployed gRPC connection is; <see cref="Rotate"/> replaces it (a redeploy).</summary>
|
||||
private sealed class PersistentConnections(LocalDataFixture peer) : IGrpcDataAdapterConnectionSource
|
||||
{
|
||||
private (IDataConnection Connection, object Route)? _current;
|
||||
private readonly object _gate = new();
|
||||
|
||||
public void Rotate()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_current is { } old) _ = old.Connection.DisposeAsync();
|
||||
_current = null;
|
||||
}
|
||||
}
|
||||
|
||||
public ValueTask<IGrpcDataAdapterConnectionLease?> AcquireAsync(string connectionId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (connectionId != "link") return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(null);
|
||||
lock (_gate)
|
||||
{
|
||||
_current ??= (peer.Connection(), new object());
|
||||
return ValueTask.FromResult<IGrpcDataAdapterConnectionLease?>(new Borrowed(_current.Value.Connection, _current.Value.Route));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Borrowed(IDataConnection connection, object route) : IGrpcDataAdapterConnectionLease
|
||||
{
|
||||
public IDataConnection Connection => connection;
|
||||
public CancellationToken CancellationToken => CancellationToken.None;
|
||||
public object? RouteIdentity => route;
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask; // non-owning, like a deployment lease
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A real origin node manager with a historized raw <c>Plant/Driver/Device/Speed</c> behind a real history port.</summary>
|
||||
private sealed class HistoryOrigin : IAsyncDisposable
|
||||
{
|
||||
private readonly OpcUaApplicationHost _host;
|
||||
private readonly string _pki;
|
||||
private readonly OtOpcUaNodeManager _nm;
|
||||
public SeriesSource Source { get; }
|
||||
public OriginHistoryPort Port { get; }
|
||||
|
||||
private HistoryOrigin(OpcUaApplicationHost host, string pki, OtOpcUaNodeManager nm, SeriesSource source)
|
||||
{ _host = host; _pki = pki; _nm = nm; Source = source; Port = new OriginHistoryPort(nm); }
|
||||
|
||||
public static async Task<HistoryOrigin> StartAsync(int samples, int maxRawPerRead = 0, int extra = 0)
|
||||
{
|
||||
var pki = Path.Combine(Path.GetTempPath(), $"h3-origin-{Guid.NewGuid():N}");
|
||||
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
|
||||
{
|
||||
ApplicationName = "H3Origin", ApplicationUri = $"urn:h3-origin:{Guid.NewGuid():N}", OpcUaPort = port,
|
||||
PublicHostname = "127.0.0.1", PkiStoreRoot = pki, EnabledSecurityProfiles = [OpcUaSecurityProfile.None],
|
||||
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
|
||||
var nm = started.Server.NodeManager!;
|
||||
var source = new SeriesSource(Enumerable.Range(0, samples)
|
||||
.Select(i => new DataValueSnapshot(i, 0, HistoryT0.AddSeconds(i), HistoryT0.AddSeconds(i))).ToArray()) { MaxRawValuesPerRead = maxRawPerRead };
|
||||
nm.HistorianDataSource = source;
|
||||
nm.EnsureVariable("Plant/Driver/Device/Speed", null, "Speed", "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed");
|
||||
nm.EnsureVariable("Plant/Driver/Device/Other", null, "Other", "Int32", false, AddressSpaceRealm.Raw);
|
||||
for (var i = 0; i < extra; i++)
|
||||
nm.EnsureVariable("Plant/Driver/Device/Speed" + i, null, "Speed" + i, "Int32", false, AddressSpaceRealm.Raw, historianTagname: "speed" + i);
|
||||
return new HistoryOrigin(started.Host, pki, nm, source);
|
||||
}
|
||||
|
||||
public void BumpEpoch() => _nm.RemoveVariableNode("Plant/Driver/Device/Other", AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _host.DisposeAsync();
|
||||
if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SeriesSource(IReadOnlyList<DataValueSnapshot> series) : IHistorianDataSource
|
||||
{
|
||||
private int _calls;
|
||||
public int Calls => Volatile.Read(ref _calls);
|
||||
public int MaxRawValuesPerRead { get; init; }
|
||||
public IReadOnlySet<HistoryAggregateType> Aggregates { get; set; } = HistoryAggregateTypes.All;
|
||||
public IReadOnlySet<HistoryAggregateType> SupportedAggregates => Aggregates;
|
||||
public bool SupportsReverseRaw => true;
|
||||
|
||||
public Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
IEnumerable<DataValueSnapshot> window = startUtc <= endUtc
|
||||
? series.Where(s => s.SourceTimestampUtc >= startUtc && s.SourceTimestampUtc < endUtc)
|
||||
: series.Where(s => s.SourceTimestampUtc <= startUtc && s.SourceTimestampUtc > endUtc).Reverse();
|
||||
return Task.FromResult(new HistorianRead((maxValuesPerNode == 0 ? window : window.Take((int)maxValuesPerNode)).ToList(), null));
|
||||
}
|
||||
|
||||
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
|
||||
HistoryAggregateType aggregate, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult(new HistorianRead([new DataValueSnapshot(3.0, 0, startUtc, startUtc)], null));
|
||||
}
|
||||
|
||||
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _calls);
|
||||
return Task.FromResult(new HistorianRead(timestampsUtc.Select(t => new DataValueSnapshot(1, 0, t, t)).ToList(), null));
|
||||
}
|
||||
|
||||
public Task<HistoricalEventsResult> ReadEventsAsync(
|
||||
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HistoricalEventsResult(Array.Empty<HistoricalEvent>(), null));
|
||||
|
||||
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user