mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-23 02:00:00 +08:00
5bc8a9d705
## Stacked on #4197 Base is `marcschier/server-bind-phase`. The full stack is **#4188 → #4193 → #4197 → this**. GitHub retargets each base automatically as the stack merges. **Review the earlier three first.** **#4217 has been merged into this branch** (squash `53dd4b618`), so the last remaining item from the issue — `ISession.SessionDiagnostics` — is now part of this PR. Closes #4187. Refs #4203 — **does not close it.** #4217 swapped `OnUpdateDiagnostics` onto `m_diagnosticsLock`, but it still calls `Variant.FromStructure(ServerDiagnostics)` with the default `copy: false`, which wraps the *live* structure in the `ExtensionObject`. The caller reads its fields after the lock is released, so the lock currently excludes nothing. #4222 adds `copy: true` and is what actually closes #4203. ## The finding that changed the approach `ISession` has **exactly one production adapter**: `src/Opc.Ua.Server/Session/Session.cs`. The other `ISession` implementations in the tree are the unrelated **client** interface (`src/Opc.Ua.Client/Session/Session.cs`, `RedundantClientSession`) and a migration-analyzer test stub. One adapter means the seam is hypothetical; two means it is real. The issue proposed splitting `ISession` into five concern-interfaces — that would turn one hypothetical seam into five. The interface earns its keep for testability and because node managers receive it through `OperationContext`, but that argues for making it **smaller**, not for multiplying it. **So: reduce, don't split.** Reasoning posted to the issue as [comment 5226712936](https://github.com/OPCFoundation/UA-.NETStandard/issues/4187#issuecomment-5226712936) so the five-way framing does not get re-proposed later. ## Measurement 38 members, 368 references. External production consumers are **4 files using 5 members**: | Consumer | Members used | |---|---| | `Opc.Ua.Redundancy.Server/Sessions/DistributedSessionManager.cs` | `Id`, `InitializeAsync`, `Dispose` | | `Opc.Ua.Di.Server/Locking/DefaultLockService.cs` | `Id` | | `samples/ConsoleReferenceServer/UAServer.cs` | `Id`, `Identity`, `ReadDiagnostics` | | `samples/Quickstarts.Servers/.../DataChangeMonitoredItem.cs` | type reference only | Every production caller of the five continuation-point members is inside `Opc.Ua.Server` (`MasterNodeManager`, `NodeManagerLifecycle`, `HistorianDispatcher`). **`ISession` is 38 → 32 members.** ## Commits ### `882b2937` Type the history continuation point `ISession` leaked `object` twice, against the repository rule: ```csharp void SaveHistoryContinuationPoint(Guid id, object continuationPoint); object? RestoreHistoryContinuationPoint(ByteString continuationPoint); ``` The erasure was **not** hiding a genuinely opaque plugin token. `HistorianDispatcher` is the only production caller, it always passes a `HistorianContinuationState`, and it casts straight back to that type on restore. The `object` was a round trip through the type system that bought nothing. `HistorianContinuationState` is `internal`, so it cannot appear on a public interface. `IHistoryContinuationPoint` names the concept instead: it carries an `Id` and extends `IDisposable`. Two latent bugs fell out of typing it: - The session disposed only those points that **happened** to implement `IDisposable` and **silently leaked the rest**. Every point is now disposable by construction, and three `as IDisposable` probes are gone. - Carrying the `Id` on the point removes the separate `Guid` parameter, which could disagree with the payload it was filed under. The mock stores in the historian tests had the same latent inconsistency. ### `0d020b77` Delete the obsolete synchronous `ValidateBeforeActivate` **Zero production callers** — the nine references were all tests written for it. `[Obsolete]` since 1.5.378, which the repository rules allow removing in master. It is also the divergent-signature problem the runtime analysis flagged: the async form returns the validated handler and policy as a tuple, while the sync one took the same two values as trailing `out` parameters, so a caller had to learn two shapes for one operation. The overload could not verify a user token requiring decryption, so on a secure endpoint it failed closed and told the caller to use the async path anyway. The one test asserting that fail-closed behaviour goes with the method it described; the path it pointed at is already covered by `ActivationValidationDecodesBinaryEncodedUserIdentityToken`. The other eight tests are **converted, not deleted** — the channel, signature, security-policy and token-policy validation they cover is still asserted, now against the path the server actually uses. ### `821e8302` Route the continuation points behind one member Five `ISession` members were one-line pass-throughs to `SessionContinuationPoints`, a 419-line module that already owns the behaviour and already has its own `IContinuationPointStore` seam. The interface restated the module's surface without adding anything. ```csharp // was session.SaveContinuationPoint(cp); session.RestoreHistoryContinuationPoint(bytes); // now session.ContinuationPoints.SaveBrowse(cp); session.ContinuationPoints.RestoreHistory(bytes); ``` The holder is `internal sealed`, so `ISessionContinuationPoints` is what makes it addressable. **This is composition, not the service locator `IServerContext` refused to be.** A subsystem with an independent lifetime should be injected; continuation points belong to the session and cannot exist without it. `InvalidateContinuationPoints` called `RemoveBrowseForManager` and `RemoveHistoryForManager` in sequence, so the pair becomes `RemoveForManager` — the caller's intent is that a node manager is going away, not that two collections need visiting. ## Tests Three harnesses had hand-rolled a `Dictionary<Guid, object>` to stand in for the holder. They now use the **real** one, so the dispatcher and `BrowseNext` meet the eviction and disposal rules a live session actually applies. **One hazard worth recording for future interface work.** A Moq member that is never stubbed returns `null`. Where the old code called a method straight on `ISession`, that `null` was harmless. Reaching *through* a property means an unstubbed `ContinuationPoints` null-derefs instead. Three tests failed exactly that way; they are wired to a real holder, not restubbed. | Suite | net10.0 | net48 | |---|---|---| | `Opc.Ua.Server.Tests` | 4032 passed, 1 failed | builds clean | | Touched areas (continuation points, historian, master node manager, session) | 898 passed | — | The single failure is `ConfigureApplicationBuildsSharedClientAndServerConfigurationAsync`, a local certificate-store problem verified to reproduce unchanged at HEAD with these changes stashed. Not caused by this PR. `Opc.Ua.Redundancy.Server`, `Opc.Ua.Di.Server`, `Quickstarts.Servers` and `ConsoleReferenceServer` all build clean. ## Docs `docs/MigrationGuide.md` gains a "Removed members on ISession" section covering the `ValidateBeforeActivate` removal with the async replacement, and the `IHistoryContinuationPoint` change with before/after. ## The SessionDiagnostics removal (folded in from #4217) `ISession.SessionDiagnostics` handed out the whole mutable `SessionDiagnosticsDataType` — the structure the session's diagnostics lock protects — so a caller could read a field while the owner was writing it. Every server-side reader wanted exactly one value out of it, so the interface now exposes those two values (`SessionName`, `ClientApplicationUri`) directly and the structure stays behind the lock. That work landed here as #4217 rather than as a separate PR, and it also fixes #4203: `OnUpdateDiagnostics` now takes `m_diagnosticsLock` instead of locking the diagnostics payload it was handed. ## Reviewer questions - `ISessionContinuationPoints` exposes `MaxBrowse` as read-only while the concrete holder keeps a setter (the test framework adjusts it to exercise limits). Should the setter be on the interface, or is test-only mutation better left to the concrete type? - `RemoveForManager` collapses two removal methods. The concrete `RemoveBrowseForManager`/`RemoveHistoryForManager` remain public on the holder — worth making them private now that nothing outside calls them individually? --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: e9c13dd0-a6e3-4ad2-8ad6-1c3fe6323041
808 lines
36 KiB
C#
808 lines
36 KiB
C#
/* ========================================================================
|
|
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
|
|
*
|
|
* OPC Foundation MIT License 1.00
|
|
*
|
|
* Permission is hereby granted, free of charge, to any person
|
|
* obtaining a copy of this software and associated documentation
|
|
* files (the "Software"), to deal in the Software without
|
|
* restriction, including without limitation the rights to use,
|
|
* copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
* copies of the Software, and to permit persons to whom the
|
|
* Software is furnished to do so, subject to the following
|
|
* conditions:
|
|
*
|
|
* The above copyright notice and this permission notice shall be
|
|
* included in all copies or substantial portions of the Software.
|
|
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
* OTHER DEALINGS IN THE SOFTWARE.
|
|
*
|
|
* The complete license agreement can be found here:
|
|
* http://opcfoundation.org/License/MIT/1.00/
|
|
* ======================================================================*/
|
|
|
|
// CA2000: test code; disposables are ownership-transferred to test fixtures or are short-lived,
|
|
// making CA2000 noisy without a real leak risk. Disabled file-level for the suite.
|
|
#pragma warning disable CA2000
|
|
|
|
#nullable enable
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
using Opc.Ua.Server.Historian;
|
|
using Opc.Ua.Server.Historian.InMemory;
|
|
|
|
namespace Opc.Ua.Server.Tests.NodeManager
|
|
{
|
|
[TestFixture]
|
|
[Category("Historian")]
|
|
[Category("NodeManager")]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public class AsyncCustomNodeManagerHistoryRoutingTests
|
|
{
|
|
private static readonly DateTime BaseTime
|
|
= new(2025, 6, 1, 0, 0, 0, DateTimeKind.Utc);
|
|
|
|
private const string TestNamespaceUri = "http://test.org/UA/HistoryRouting/";
|
|
|
|
[Test]
|
|
public async Task HistoryReadWithReleaseContinuationPointsCallsReleaseAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryReadVariable(h, "RelCp");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var nodesToRead = new List<HistoryReadValueId>
|
|
{
|
|
new()
|
|
{
|
|
NodeId = variable.NodeId,
|
|
ContinuationPoint = new ByteString(new byte[] { 0xAB, 0xCD })
|
|
}
|
|
};
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext,
|
|
new ReadRawModifiedDetails { StartTime = BaseTime, EndTime = BaseTime.AddMinutes(1) },
|
|
TimestampsToReturn.Source,
|
|
releaseContinuationPoints: true,
|
|
nodesToRead,
|
|
results,
|
|
errors).ConfigureAwait(false);
|
|
|
|
Assert.That(errors[0].StatusCode, Is.EqualTo(StatusCodes.BadContinuationPointInvalid));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadRawOnHistorizedVariableRoutesToProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryReadVariable(h, "RawRead");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
DateTime t1 = BaseTime;
|
|
DateTime t2 = BaseTime.AddSeconds(1);
|
|
DateTime t3 = BaseTime.AddSeconds(2);
|
|
await provider.InsertAsync(
|
|
h.CreateHistorianOpContext(),
|
|
variable.NodeId,
|
|
[
|
|
new DataValue(new Variant(10.0), StatusCodes.Good, t1, t1),
|
|
new DataValue(new Variant(20.0), StatusCodes.Good, t2, t2),
|
|
new DataValue(new Variant(30.0), StatusCodes.Good, t3, t3)
|
|
],
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = BaseTime.AddSeconds(-1),
|
|
EndTime = BaseTime.AddSeconds(10)
|
|
};
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = variable.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details, TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
Assert.That(results[0], Is.Not.Null);
|
|
|
|
var historyData = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
|
|
Assert.That(historyData, Is.Not.Null);
|
|
Assert.That(historyData!.DataValues, Has.Count.EqualTo(3));
|
|
Assert.That(historyData.DataValues[0].GetValue<double>(0), Is.EqualTo(10.0));
|
|
Assert.That(historyData.DataValues[1].GetValue<double>(0), Is.EqualTo(20.0));
|
|
Assert.That(historyData.DataValues[2].GetValue<double>(0), Is.EqualTo(30.0));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadAnnotationsPropertyRoutesToParentProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
ushort nsIdx = h.Manager.NamespaceIndexes[0];
|
|
var parent = new BaseDataVariableState(null);
|
|
parent.CreateAsPredefinedNode(h.Context);
|
|
parent.NodeId = new NodeId("AnnotParent", nsIdx);
|
|
parent.BrowseName = new QualifiedName("AnnotParent", nsIdx);
|
|
parent.DataType = DataTypeIds.Int32;
|
|
parent.ValueRank = ValueRanks.Scalar;
|
|
parent.AccessLevel = AccessLevels.HistoryRead;
|
|
parent.UserAccessLevel = AccessLevels.HistoryRead;
|
|
parent.Historizing = true;
|
|
|
|
var annotProp = new PropertyState(parent);
|
|
annotProp.CreateAsPredefinedNode(h.Context);
|
|
annotProp.NodeId = new NodeId("AnnotParent_Annotations", nsIdx);
|
|
annotProp.BrowseName = new QualifiedName(BrowseNames.Annotations, 0);
|
|
annotProp.DataType = DataTypeIds.BaseDataType;
|
|
annotProp.ValueRank = ValueRanks.Scalar;
|
|
annotProp.AccessLevel = AccessLevels.HistoryRead;
|
|
annotProp.UserAccessLevel = AccessLevels.HistoryRead;
|
|
|
|
await h.Manager.AddNodeAsync(h.Context, default, parent).ConfigureAwait(false);
|
|
await h.Manager.AddNodeAsync(h.Context, default, annotProp).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(parent.NodeId, provider);
|
|
provider.Register(parent.NodeId);
|
|
|
|
DateTime annotTime = BaseTime.AddSeconds(5);
|
|
await provider.InsertAnnotationsAsync(
|
|
h.CreateHistorianOpContext(),
|
|
parent.NodeId,
|
|
[new Annotation { AnnotationTime = annotTime, UserName = "tester", Message = "note1" }],
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1)
|
|
};
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = annotProp.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details, TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
Assert.That(results[0], Is.Not.Null);
|
|
|
|
var historyData = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
|
|
Assert.That(historyData, Is.Not.Null);
|
|
Assert.That(historyData!.DataValues, Has.Count.EqualTo(1));
|
|
|
|
ExtensionObject annotExt = historyData.DataValues[0].GetValue<ExtensionObject>(default);
|
|
var annotation = ExtensionObject.ToEncodeable(annotExt) as Annotation;
|
|
Assert.That(annotation, Is.Not.Null);
|
|
Assert.That(annotation!.Message, Is.EqualTo("note1"));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadOnUnownedNodeLeavesDefaultErrorAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
var unknownNodeId = new NodeId("DoesNotExist", h.Manager.NamespaceIndexes[0]);
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = unknownNodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext,
|
|
new ReadRawModifiedDetails { StartTime = BaseTime, EndTime = BaseTime.AddMinutes(1) },
|
|
TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false);
|
|
|
|
// GetManagerHandleAsync returns null for unknown nodes — the loop
|
|
// continues without modifying errors[0], so it stays null.
|
|
Assert.That(errors[0], Is.Null);
|
|
Assert.That(results[0], Is.Null);
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadEventsOnNotifierObjectRoutesToProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
ushort nsIdx = h.Manager.NamespaceIndexes[0];
|
|
|
|
var notifier = new BaseObjectState(null);
|
|
notifier.CreateAsPredefinedNode(h.Context);
|
|
notifier.NodeId = new NodeId("EventNotifier", nsIdx);
|
|
notifier.BrowseName = new QualifiedName("EventNotifier", nsIdx);
|
|
notifier.EventNotifier = EventNotifiers.HistoryRead | EventNotifiers.SubscribeToEvents;
|
|
|
|
await h.Manager.AddNodeAsync(h.Context, default, notifier).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(notifier.NodeId, provider);
|
|
|
|
var eventId = new ByteString(Encoding.UTF8.GetBytes("evt-1"));
|
|
var record = new HistorianEventRecord(
|
|
eventId,
|
|
ObjectTypeIds.BaseEventType,
|
|
BaseTime.AddSeconds(10),
|
|
new Dictionary<string, Variant>(StringComparer.Ordinal)
|
|
{
|
|
[BrowseNames.EventId] = new Variant(eventId),
|
|
[BrowseNames.EventType] = new Variant(ObjectTypeIds.BaseEventType),
|
|
[BrowseNames.Time] = new Variant((DateTimeUtc)BaseTime.AddSeconds(10)),
|
|
[BrowseNames.Message] = new Variant(new LocalizedText("test event"))
|
|
});
|
|
|
|
await provider.InsertEventsAsync(
|
|
h.CreateHistorianOpContext(),
|
|
notifier.NodeId,
|
|
[record],
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
var filter = new EventFilter();
|
|
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Message, Attributes.Value);
|
|
|
|
var details = new ReadEventDetails
|
|
{
|
|
NumValuesPerNode = 100,
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1),
|
|
Filter = filter
|
|
};
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = notifier.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details, TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
Assert.That(results[0], Is.Not.Null);
|
|
|
|
var historyEvent = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryEvent;
|
|
Assert.That(historyEvent, Is.Not.Null);
|
|
Assert.That(historyEvent!.Events, Has.Count.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadWithInvalidTimestampsToReturnThrowsAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryReadVariable(h, "TsInvalid");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1)
|
|
};
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = variable.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
ServiceResultException? ex = Assert.ThrowsAsync<ServiceResultException>(async () =>
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details,
|
|
(TimestampsToReturn)99,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false));
|
|
|
|
Assert.That(ex!.StatusCode, Is.EqualTo(StatusCodes.BadTimestampsToReturnInvalid));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadRawWithMissingTimestampsAndZeroMaxThrowsAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryReadVariable(h, "NoTs");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
var details = new ReadRawModifiedDetails
|
|
{
|
|
StartTime = DateTime.MinValue,
|
|
EndTime = DateTime.MinValue,
|
|
NumValuesPerNode = 0
|
|
};
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = variable.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
ServiceResultException? ex = Assert.ThrowsAsync<ServiceResultException>(async () =>
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details,
|
|
TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false));
|
|
|
|
Assert.That(ex!.StatusCode, Is.EqualTo(StatusCodes.BadHistoryOperationInvalid));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadProcessedAggregateMismatchThrowsAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryReadVariable(h, "AggMismatch");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
var details = new ReadProcessedDetails
|
|
{
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1),
|
|
ProcessingInterval = 1000,
|
|
AggregateType = [ObjectIds.AggregateFunction_Average, ObjectIds.AggregateFunction_Count]
|
|
};
|
|
// Only 1 node but 2 aggregate types.
|
|
var nodesToRead = new List<HistoryReadValueId> { new() { NodeId = variable.NodeId } };
|
|
var results = new List<HistoryReadResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
ServiceResultException? ex = Assert.ThrowsAsync<ServiceResultException>(async () =>
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details,
|
|
TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false));
|
|
|
|
Assert.That(ex!.StatusCode, Is.EqualTo(StatusCodes.BadAggregateListMismatch));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryReadProcessedWithEqualStartAndEndTimeReturnsBadInvalidArgumentPerNodeAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState node1 = CreateHistoryReadVariable(h, "EqualTimesA");
|
|
BaseDataVariableState node2 = CreateHistoryReadVariable(h, "EqualTimesB");
|
|
await h.Manager.AddNodeAsync(h.Context, default, node1).ConfigureAwait(false);
|
|
await h.Manager.AddNodeAsync(h.Context, default, node2).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(node1.NodeId, provider);
|
|
h.RegisterProvider(node2.NodeId, provider);
|
|
provider.Register(node1.NodeId);
|
|
provider.Register(node2.NodeId);
|
|
|
|
// Part 11 v1.05.07 §6.5.4.2: startTime == endTime is a zero-width time domain that
|
|
// "has no meaningful way to interpret", so the Server shall return Bad_InvalidArgument.
|
|
// This reproduces CTT aggregate_002_01 (multi-node): each per-node operation result
|
|
// must carry Bad_InvalidArgument while the HistoryRead service call itself succeeds.
|
|
var details = new ReadProcessedDetails
|
|
{
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime,
|
|
ProcessingInterval = 1000,
|
|
AggregateType = [ObjectIds.AggregateFunction_Average, ObjectIds.AggregateFunction_Average]
|
|
};
|
|
|
|
var nodesToRead = new List<HistoryReadValueId>
|
|
{
|
|
new() { NodeId = node1.NodeId },
|
|
new() { NodeId = node2.NodeId }
|
|
};
|
|
var results = new List<HistoryReadResult> { null!, null! };
|
|
var errors = new List<ServiceResult> { null!, null! };
|
|
|
|
await h.Manager.HistoryReadAsync(
|
|
h.OperationContext, details, TimestampsToReturn.Source,
|
|
false, nodesToRead, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(errors, Has.Count.EqualTo(2));
|
|
Assert.That(errors[0].StatusCode, Is.EqualTo(StatusCodes.BadInvalidArgument));
|
|
Assert.That(errors[1].StatusCode, Is.EqualTo(StatusCodes.BadInvalidArgument));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryUpdateInsertDataDispatchesToProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryWriteVariable(h, "InsertData");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
DateTime ts = BaseTime.AddSeconds(1);
|
|
var updateDetails = new UpdateDataDetails
|
|
{
|
|
NodeId = variable.NodeId,
|
|
PerformInsertReplace = PerformUpdateType.Insert,
|
|
UpdateValues =
|
|
[
|
|
new DataValue(new Variant(42.0), StatusCodes.Good, ts, ts)
|
|
]
|
|
};
|
|
|
|
var nodesToUpdate = new List<HistoryUpdateDetails> { updateDetails };
|
|
var results = new List<HistoryUpdateResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryUpdateAsync(
|
|
h.OperationContext, typeof(UpdateDataDetails),
|
|
nodesToUpdate, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
Assert.That(results[0], Is.Not.Null);
|
|
Assert.That(results[0]!.OperationResults, Has.Count.EqualTo(1));
|
|
Assert.That(StatusCode.IsGood(results[0].OperationResults[0]), Is.True);
|
|
|
|
// Verify data actually stored.
|
|
HistorianPage<HistoricalDataValue> page = await provider.ReadRawAsync(
|
|
h.CreateHistorianOpContext(),
|
|
new HistorianRawReadRequest
|
|
{
|
|
NodeId = variable.NodeId,
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1),
|
|
IsForward = true
|
|
},
|
|
default,
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(page.Values, Has.Count.EqualTo(1));
|
|
Assert.That(page.Values[0].Value.GetValue<double>(0), Is.EqualTo(42.0));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryUpdateDeleteRawDispatchesToProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryWriteVariable(h, "DeleteRaw");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(variable.NodeId, provider);
|
|
provider.Register(variable.NodeId);
|
|
|
|
// Seed 3 values.
|
|
for (int i = 0; i < 3; i++)
|
|
{
|
|
DateTime t = BaseTime.AddSeconds(i);
|
|
await provider.InsertAsync(
|
|
h.CreateHistorianOpContext(),
|
|
variable.NodeId,
|
|
[new DataValue(new Variant((double)i), StatusCodes.Good, t, t)],
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
|
|
var deleteDetails = new DeleteRawModifiedDetails
|
|
{
|
|
NodeId = variable.NodeId,
|
|
StartTime = BaseTime.AddSeconds(-1),
|
|
EndTime = BaseTime.AddSeconds(10),
|
|
IsDeleteModified = false
|
|
};
|
|
var nodesToUpdate = new List<HistoryUpdateDetails> { deleteDetails };
|
|
var results = new List<HistoryUpdateResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryUpdateAsync(
|
|
h.OperationContext, typeof(DeleteRawModifiedDetails),
|
|
nodesToUpdate, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
|
|
// Verify all deleted.
|
|
HistorianPage<HistoricalDataValue> page = await provider.ReadRawAsync(
|
|
h.CreateHistorianOpContext(),
|
|
new HistorianRawReadRequest
|
|
{
|
|
NodeId = variable.NodeId,
|
|
StartTime = BaseTime.AddSeconds(-1),
|
|
EndTime = BaseTime.AddSeconds(10),
|
|
IsForward = true
|
|
},
|
|
default,
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(page.Values, Has.Count.EqualTo(0));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryUpdateUpdateEventDispatchesToProviderAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
ushort nsIdx = h.Manager.NamespaceIndexes[0];
|
|
|
|
var notifier = new BaseObjectState(null);
|
|
notifier.CreateAsPredefinedNode(h.Context);
|
|
notifier.NodeId = new NodeId("EventUpdNotifier", nsIdx);
|
|
notifier.BrowseName = new QualifiedName("EventUpdNotifier", nsIdx);
|
|
notifier.EventNotifier = EventNotifiers.HistoryRead | EventNotifiers.HistoryWrite;
|
|
|
|
await h.Manager.AddNodeAsync(h.Context, default, notifier).ConfigureAwait(false);
|
|
|
|
var provider = new InMemoryHistorianProvider();
|
|
h.RegisterProvider(notifier.NodeId, provider);
|
|
|
|
var eventId = new ByteString(Encoding.UTF8.GetBytes("upd-evt-1"));
|
|
var filter = new EventFilter();
|
|
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventId, Attributes.Value);
|
|
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Message, Attributes.Value);
|
|
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.Time, Attributes.Value);
|
|
filter.AddSelectClause(ObjectTypeIds.BaseEventType, BrowseNames.EventType, Attributes.Value);
|
|
|
|
var eventFieldList = new HistoryEventFieldList
|
|
{
|
|
EventFields =
|
|
[
|
|
new Variant(eventId),
|
|
new Variant(new LocalizedText("update event")),
|
|
new Variant((DateTimeUtc)BaseTime.AddSeconds(20)),
|
|
new Variant(ObjectTypeIds.BaseEventType)
|
|
]
|
|
};
|
|
|
|
var updateDetails = new UpdateEventDetails
|
|
{
|
|
NodeId = notifier.NodeId,
|
|
PerformInsertReplace = PerformUpdateType.Insert,
|
|
EventData = [eventFieldList],
|
|
Filter = filter
|
|
};
|
|
|
|
var nodesToUpdate = new List<HistoryUpdateDetails> { updateDetails };
|
|
var results = new List<HistoryUpdateResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryUpdateAsync(
|
|
h.OperationContext, typeof(UpdateEventDetails),
|
|
nodesToUpdate, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(ServiceResult.IsGood(errors[0]), Is.True);
|
|
Assert.That(results[0], Is.Not.Null);
|
|
Assert.That(results[0]!.OperationResults, Has.Count.EqualTo(1));
|
|
Assert.That(StatusCode.IsGood(results[0].OperationResults[0]), Is.True);
|
|
|
|
// Verify stored via provider.
|
|
HistorianPage<HistorianEventRecord> page = await provider.ReadEventsAsync(
|
|
h.CreateHistorianOpContext(),
|
|
new HistorianEventReadRequest
|
|
{
|
|
NodeId = notifier.NodeId,
|
|
StartTime = BaseTime,
|
|
EndTime = BaseTime.AddMinutes(1),
|
|
IsForward = true,
|
|
Filter = filter
|
|
},
|
|
default,
|
|
CancellationToken.None).ConfigureAwait(false);
|
|
|
|
Assert.That(page.Values, Has.Count.EqualTo(1));
|
|
Assert.That(page.Values[0].EventId, Is.EqualTo(eventId));
|
|
}
|
|
|
|
[Test]
|
|
public async Task HistoryUpdateOnVariableWithoutProviderReturnsBadHistoryOperationUnsupportedAsync()
|
|
{
|
|
using Harness h = await CreateHarnessAsync().ConfigureAwait(false);
|
|
|
|
BaseDataVariableState variable = CreateHistoryWriteVariable(h, "NoProvider");
|
|
await h.Manager.AddNodeAsync(h.Context, default, variable).ConfigureAwait(false);
|
|
|
|
// Intentionally do NOT register a provider.
|
|
|
|
DateTime ts = BaseTime.AddSeconds(1);
|
|
var updateDetails = new UpdateDataDetails
|
|
{
|
|
NodeId = variable.NodeId,
|
|
PerformInsertReplace = PerformUpdateType.Insert,
|
|
UpdateValues =
|
|
[
|
|
new DataValue(new Variant(1.0), StatusCodes.Good, ts, ts)
|
|
]
|
|
};
|
|
|
|
var nodesToUpdate = new List<HistoryUpdateDetails> { updateDetails };
|
|
var results = new List<HistoryUpdateResult> { null! };
|
|
var errors = new List<ServiceResult> { null! };
|
|
|
|
await h.Manager.HistoryUpdateAsync(
|
|
h.OperationContext, typeof(UpdateDataDetails),
|
|
nodesToUpdate, results, errors).ConfigureAwait(false);
|
|
|
|
Assert.That(errors[0].StatusCode, Is.EqualTo(StatusCodes.BadHistoryOperationUnsupported));
|
|
}
|
|
|
|
private static BaseDataVariableState CreateHistoryReadVariable(Harness h, string name)
|
|
{
|
|
ushort nsIdx = h.Manager.NamespaceIndexes[0];
|
|
var variable = new BaseDataVariableState(null);
|
|
variable.CreateAsPredefinedNode(h.Context);
|
|
variable.NodeId = new NodeId(name, nsIdx);
|
|
variable.BrowseName = new QualifiedName(name, nsIdx);
|
|
variable.DataType = DataTypeIds.Double;
|
|
variable.ValueRank = ValueRanks.Scalar;
|
|
variable.AccessLevel = AccessLevels.HistoryRead;
|
|
variable.UserAccessLevel = AccessLevels.HistoryRead;
|
|
variable.Historizing = true;
|
|
return variable;
|
|
}
|
|
|
|
private static BaseDataVariableState CreateHistoryWriteVariable(Harness h, string name)
|
|
{
|
|
ushort nsIdx = h.Manager.NamespaceIndexes[0];
|
|
var variable = new BaseDataVariableState(null);
|
|
variable.CreateAsPredefinedNode(h.Context);
|
|
variable.NodeId = new NodeId(name, nsIdx);
|
|
variable.BrowseName = new QualifiedName(name, nsIdx);
|
|
variable.DataType = DataTypeIds.Double;
|
|
variable.ValueRank = ValueRanks.Scalar;
|
|
variable.AccessLevel = AccessLevels.HistoryRead | AccessLevels.HistoryWrite;
|
|
variable.UserAccessLevel = AccessLevels.HistoryRead | AccessLevels.HistoryWrite;
|
|
variable.Historizing = true;
|
|
return variable;
|
|
}
|
|
|
|
private static async ValueTask<Harness> CreateHarnessAsync()
|
|
{
|
|
var mockServer = new Mock<IServerInternal>();
|
|
var mockLogger = new Mock<ILogger>();
|
|
var mockMasterNodeManager = new Mock<IMasterNodeManager>();
|
|
var mockConfigurationNodeManager = new Mock<IConfigurationNodeManager>();
|
|
|
|
var mockSession = new Mock<ISession>();
|
|
mockSession.Setup(s => s.EffectiveIdentity).Returns(new Mock<IUserIdentity>().Object);
|
|
mockSession.Setup(s => s.PreferredLocales).Returns([]);
|
|
mockSession.Setup(s => s.ContinuationPoints).Returns(
|
|
new SessionContinuationPoints(
|
|
() => NodeId.Null, maxBrowse: 10, maxHistory: 10, store: null));
|
|
|
|
var namespaceTable = new NamespaceTable();
|
|
namespaceTable.Append(TestNamespaceUri);
|
|
|
|
mockServer.Setup(s => s.NamespaceUris).Returns(namespaceTable);
|
|
mockServer.Setup(s => s.ServerUris).Returns(new StringTable());
|
|
mockServer.Setup(s => s.TypeTree).Returns(new TypeTable(namespaceTable));
|
|
mockServer.Setup(s => s.Factory).Returns(EncodeableFactory.Create());
|
|
mockServer.Setup(s => s.NodeManager).Returns(mockMasterNodeManager.Object);
|
|
mockMasterNodeManager.Setup(m => m.ConfigurationNodeManager).Returns(mockConfigurationNodeManager.Object);
|
|
|
|
var mockTelemetry = new Mock<ITelemetryContext>();
|
|
mockServer.Setup(s => s.Telemetry).Returns(mockTelemetry.Object);
|
|
|
|
var monitoredItemQueueFactory = new MonitoredItemQueueFactory(mockTelemetry.Object);
|
|
mockServer.Setup(s => s.MonitoredItemQueueFactory).Returns(monitoredItemQueueFactory);
|
|
|
|
var serverSystemContext = new ServerSystemContext(mockServer.Object);
|
|
mockServer.Setup(s => s.DefaultSystemContext).Returns(serverSystemContext);
|
|
|
|
var configuration = new ApplicationConfiguration
|
|
{
|
|
ServerConfiguration = new ServerConfiguration
|
|
{
|
|
MaxNotificationQueueSize = 100,
|
|
MaxDurableNotificationQueueSize = 200
|
|
}
|
|
};
|
|
|
|
var manager = new HistoryRoutingTestNodeManager(
|
|
mockServer.Object, configuration, mockLogger.Object, TestNamespaceUri);
|
|
|
|
mockMasterNodeManager
|
|
.Setup(m => m.GetManagerHandleAsync(It.IsAny<NodeId>(), It.IsAny<CancellationToken>()))
|
|
.Returns<NodeId, CancellationToken>((nodeId, _) =>
|
|
{
|
|
NodeState? nodeState = manager.Find(nodeId);
|
|
if (nodeState == null)
|
|
{
|
|
return new ValueTask<(object? handle, IAsyncNodeManager? nodeManager)>((null, null));
|
|
}
|
|
|
|
var handle = new NodeHandle(nodeId, nodeState);
|
|
return new ValueTask<(object? handle, IAsyncNodeManager? nodeManager)>((handle, manager));
|
|
});
|
|
|
|
var opContext = new OperationContext(
|
|
new RequestHeader(), null!, RequestType.HistoryRead, RequestLifetime.None, mockSession.Object);
|
|
|
|
await Task.CompletedTask.ConfigureAwait(false);
|
|
return new Harness(manager, serverSystemContext, opContext, mockServer.Object, monitoredItemQueueFactory);
|
|
}
|
|
|
|
private sealed class Harness : IDisposable
|
|
{
|
|
public HistoryRoutingTestNodeManager Manager { get; }
|
|
public ServerSystemContext Context { get; }
|
|
public OperationContext OperationContext { get; }
|
|
|
|
private readonly IServerInternal m_server;
|
|
private readonly MonitoredItemQueueFactory m_queueFactory;
|
|
|
|
public Harness(
|
|
HistoryRoutingTestNodeManager manager,
|
|
ServerSystemContext context,
|
|
OperationContext operationContext,
|
|
IServerInternal server,
|
|
MonitoredItemQueueFactory queueFactory)
|
|
{
|
|
Manager = manager;
|
|
Context = context;
|
|
OperationContext = operationContext;
|
|
m_server = server;
|
|
m_queueFactory = queueFactory;
|
|
}
|
|
|
|
public void RegisterProvider(NodeId nodeId, IHistorianProvider provider)
|
|
{
|
|
Manager.ProviderMap[nodeId] = provider;
|
|
}
|
|
|
|
public HistorianOperationContext CreateHistorianOpContext()
|
|
{
|
|
var systemContext = new ServerSystemContext(m_server, OperationContext);
|
|
return new HistorianOperationContext(
|
|
systemContext, OperationContext, null, HistoryUpdateType.Insert);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
m_queueFactory.Dispose();
|
|
Manager.Dispose();
|
|
}
|
|
}
|
|
|
|
private sealed class HistoryRoutingTestNodeManager : AsyncCustomNodeManager
|
|
{
|
|
public NodeIdDictionary<IHistorianProvider> ProviderMap { get; } = [];
|
|
|
|
public HistoryRoutingTestNodeManager(
|
|
IServerInternal server,
|
|
ApplicationConfiguration configuration,
|
|
ILogger logger,
|
|
params string[] namespaceUris)
|
|
: base(server, configuration, logger, namespaceUris)
|
|
{
|
|
}
|
|
|
|
public new NodeIdDictionary<NodeState> PredefinedNodes => base.PredefinedNodes;
|
|
|
|
protected override IHistorianProvider? GetHistorianProvider(NodeState node)
|
|
{
|
|
if (ProviderMap.TryGetValue(node.NodeId, out IHistorianProvider? provider))
|
|
{
|
|
return provider;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
}
|