mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-20 08:41:51 +08:00
efad0ddeff
# Description Fixes defects found in a spec-grounded audit of the server **Subscription / MonitoredItem** implementation (`src/Opc.Ua.Server/Subscription/**`, `NodeManager/MonitoredItem/**`, `EventManager`, monitored-item service dispatch and filter validation). Each behaviour change was checked against OPC 10000-4 (§5.13, §5.14, §7.21, §7.22), Part 5 (subscription diagnostics) and Part 9 (ConditionRefresh). Every fix has a regression test. The audit found 56 defects (1 Critical, 3 High, 20 Medium, 32 Low). A follow-up max-effort code review of the fix branch found 27 more issues, mostly introduced by the first round of fixes. All but one are fixed here. ### Most important fixes - **Critical — remote hang:** an `AggregateFilter` with `processingInterval = NaN` was not revised, and `AggregateCalculator` looped forever while holding the node-manager lock, so one CreateMonitoredItems request blocked the node manager. Non-finite, ≤0 and sub-tick intervals are now revised (Part 4 §5.13.2.1), and the calculator rejects them as a backstop. - **Monitored-item limits:** new `ServerConfiguration.MaxMonitoredItemCount` / `MaxMonitoredItemsPerSubscription`; Bad_TooManyMonitoredItems is returned when a limit is hit, and ServerCapabilities now report the limits. Both default to `0` (no limit), so existing behaviour is unchanged. - **Sampling groups:** a client could get one dedicated thread per distinct sampling interval above 1 h; intervals above the last rate group are now rounded, and the loop is async. An item could also end up in two sampling groups and keep being sampled after it was deleted. - **Subscription state machine** (Part 4 §5.14.1.2): - the lifetime counter resets while a Publish is queued and counts otherwise; - the lifetime and keep-alive stay within `MaxSubscriptionLifetime`; - LatePublishRequestCount is counted once per entry into LATE; - messages held while publishing is disabled are no longer sent, and are not offered by Transfer/Republish either; - ConditionRefresh returns Bad_RefreshInProgress for any refresh already queued or running on the subscription. - **Triggering** (Part 4 §5.13.1.6): - linked items are triggered by an item still draining a backlog, by the first value after re-enable, and by an item created Disabled; - links are persisted for durable subscriptions; - Disabled/Sampling items follow the publish rules in the shared pipeline, so custom `IMonitoredItem` implementations follow them too. - **Queues** (Part 4 §5.13.1.5, §7.21): - no duplicate value after a queue-size increase; - EventQueueOverflow events are placed where the events were lost, including on queue shrink; - the duplicate-event check scans the newest entries; - EventQueueOverflowCount and MonitoringQueueOverflowCount are maintained correctly; - changing select clauses rebuilds queued events in the new layout, and is safe on durable queues and on failure. - **Filters:** - per-clause EventFilterResult instead of rejecting the whole item (Part 4 §7.22.3); - corrected status codes: Bad_DeadbandFilterInvalid, Bad_MonitoredItemFilterInvalid, Bad_EventFilterInvalid, Bad_MonitoringModeInvalid, Bad_TimestampsToReturnInvalid; - aggregate filter in subscriptions: processing interval at least 2× the revised sampling interval, revised StartTime on the requested grid, ServerTimestamp = end of interval (Part 4 §7.22.4). - **Lifecycle and races:** - expired subscriptions are always cleaned up, even when the session closes during cleanup; - Create/Transfer racing CloseSession returns Bad_SessionClosed; - session diagnostics counts no longer drift; - a large but valid Publish TimeoutHint no longer fails the request; - a ready subscription is served by queued Publish requests instead of going Late; - restored persisted state is validated. - **Access:** a value change notification is checked against each subscriber's UserAccessLevel, not the writer's. - **Redundancy / durable store:** - the first-unsent sequence number is mirrored; - sequence numbers are no longer reused after a second failover; - triggering links are stored (definition format 6, written only when links exist, so older replicas can still read link-less subscriptions). ### Behaviour changes reviewers should know - With the default config, publishing intervals above `MaxSubscriptionLifetime / 3` (1,200,000 ms) are revised down, so lifetime ≥ 3×keep-alive fits the configured maximum. - The revised keep-alive is capped at a third of the max lifetime. - Idle subscriptions expire after exactly MaxLifetimeCount cycles without a queued Publish. - A partly invalid EventFilter select list is accepted with per-clause errors. The public `EventFilter.Validate` keeps Status Good if at least one clause is valid; callers that cannot return per-clause results must also check the new `EventFilter.Result.HasSelectClauseErrors`. There is a migration note in `docs/migrate/2.0.x/sessions-subscriptions.md`. - Aggregate processing intervals may be revised higher (≥ 2× sampling interval); aggregate ServerTimestamp is now the interval end. - Sampling intervals above 3,600,000 ms are rounded to multiples of 900,000 ms (default rate groups). ### Public API Additive only: - `ServerConfiguration.MaxMonitoredItemCount` and `MaxMonitoredItemsPerSubscription`; - `EventFilter.Result.HasSelectClauseErrors`; - `IStoredSubscriptionTriggering`, `ISubscriptionRetransmissionSendStateStore`, `SubscriptionRetransmissionState.FirstUnsentSequenceNumber` (optional store capabilities, detected with `as`); - new `EventQueueHandler` constructor overloads. ### Known open items (not in this PR) - **Part 4 §5.13.2.1:** CreateMonitoredItems should create an item even when the user lacks Read permission and report the error in Publish. This is not done: the create-time RolePermissions check is the only role check on the initial value, so following the spec would leak values until every node manager re-checks per sample. - **Sampling loop:** it runs on thread-pool threads; node managers with blocking synchronous reads should not use sampling groups heavily. The alternative, a dedicated thread per group, was the thread-exhaustion issue fixed here. - **Restarts:** a pending QueueSize-1 value and a pending overflow flag are not kept across a restart; that needs persistence interface extensions. - **Limit defaults:** decide whether the new limits should get finite defaults (currently 0 = unlimited). ## Related Issues - No tracking issue; the findings come from an internal audit of the server subscription code. ## Checklist - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [x] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [ ] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. ### Local verification (net10.0, all green) | Suite | Passed | Failed | |---|---|---| | Opc.Ua.Server.Tests | 7963 | 0 | | Opc.Ua.Subscriptions.Tests | 643 | 0 | | Opc.Ua.Subscriptions.Classic.Tests | 57 | 0 | | Opc.Ua.Subscriptions.Durable.Tests | 36 | 0 | | Opc.Ua.Redundancy.Server.Tests | 847 | 0 | | Opc.Ua.Core.Tests (filter tests) | 283 | 0 | net48 build of `Opc.Ua.Server.Tests`: 0 errors. net48 tests and the full UA.slnx were not run locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
589 lines
23 KiB
C#
589 lines
23 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/
|
|
* ======================================================================*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Moq;
|
|
using NUnit.Framework;
|
|
|
|
// CA2000: test code; disposables are ownership-transferred to the EventManager
|
|
// under test or are torn down with the fixture.
|
|
#pragma warning disable CA2000
|
|
|
|
namespace Opc.Ua.Server.Tests.NodeManager
|
|
{
|
|
/// <summary>
|
|
/// Deterministic, offline unit tests for <see cref="EventManager"/>.
|
|
/// </summary>
|
|
[TestFixture]
|
|
[Category("NodeManager")]
|
|
[Category("EventManager")]
|
|
[Parallelizable(ParallelScope.All)]
|
|
public class EventManagerTests
|
|
{
|
|
[Test]
|
|
public void FailedEventItemConstructionDoesNotPoisonLaterEnumeration()
|
|
{
|
|
Mock<IServerInternal> server = DeterministicServerMock.Create(out MonitoredItemQueueFactory queues);
|
|
using (queues)
|
|
using (var manager = new EventManager(server.Object, 100, 100))
|
|
using (OperationContext context = NewContext())
|
|
{
|
|
var nodeManager = new Mock<IAsyncNodeManager>();
|
|
var ids = new MonitoredItemIdFactory();
|
|
MonitoredItemCreateRequest request = NewCreateRequest(1000, 5);
|
|
ServiceResultException failure = Assert.Throws<ServiceResultException>(() =>
|
|
manager.CreateMonitoredItem(
|
|
context, nodeManager.Object, null!, 1, ids, TimestampsToReturn.Both,
|
|
1000, request, new EventFilter(), createDurable: true));
|
|
Assert.That(failure.StatusCode, Is.EqualTo(StatusCodes.BadInternalError));
|
|
Assert.That(manager.GetMonitoredItems(), Is.Empty);
|
|
Assert.That(manager.GetMonitoredItems().Where(item => item.MonitoringAllEvents), Is.Empty);
|
|
|
|
IEventMonitoredItem recovered = manager.CreateMonitoredItem(
|
|
context, nodeManager.Object, null!, 1, ids, TimestampsToReturn.Both,
|
|
1000, request, new EventFilter(), createDurable: false);
|
|
Assert.That(manager.GetMonitoredItems(), Has.Count.EqualTo(1));
|
|
Assert.That(manager.GetMonitoredItems()[0], Is.SameAs(recovered));
|
|
}
|
|
}
|
|
|
|
private static OperationContext NewContext()
|
|
{
|
|
return new OperationContext(
|
|
new RequestHeader(), null, RequestType.CreateMonitoredItems, RequestLifetime.None);
|
|
}
|
|
|
|
private static MonitoredItemCreateRequest NewCreateRequest(
|
|
double samplingInterval,
|
|
uint queueSize)
|
|
{
|
|
return new MonitoredItemCreateRequest
|
|
{
|
|
ItemToMonitor = new ReadValueId(),
|
|
MonitoringMode = MonitoringMode.Reporting,
|
|
RequestedParameters = new MonitoringParameters
|
|
{
|
|
ClientHandle = 42,
|
|
SamplingInterval = samplingInterval,
|
|
QueueSize = queueSize,
|
|
DiscardOldest = true
|
|
}
|
|
};
|
|
}
|
|
|
|
private static EventManager CreateManager(
|
|
uint maxQueueSize,
|
|
uint maxDurableQueueSize,
|
|
out Mock<IServerInternal> mockServer,
|
|
out Mock<IAsyncNodeManager> mockNodeManager)
|
|
{
|
|
mockServer = DeterministicServerMock.Create(out _);
|
|
mockNodeManager = new Mock<IAsyncNodeManager>();
|
|
return new EventManager(mockServer.Object, maxQueueSize, maxDurableQueueSize);
|
|
}
|
|
|
|
[Test]
|
|
public void ConstructorWithNullServerThrows()
|
|
{
|
|
Assert.That(
|
|
() => new EventManager(null!, 10, 10),
|
|
Throws.TypeOf<ArgumentNullException>());
|
|
}
|
|
|
|
[Test]
|
|
public void CreateMonitoredItemAddsItemToManager()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(),
|
|
nm.Object,
|
|
null!,
|
|
1,
|
|
idFactory,
|
|
TimestampsToReturn.Both,
|
|
1000.0,
|
|
NewCreateRequest(1000.0, 5),
|
|
new EventFilter(),
|
|
false);
|
|
|
|
Assert.That(item, Is.Not.Null);
|
|
Assert.That(manager.GetMonitoredItems(), Has.Count.EqualTo(1));
|
|
Assert.That(manager.GetMonitoredItems()[0].Id, Is.EqualTo(item.Id));
|
|
}
|
|
|
|
[Test]
|
|
public void CreateMonitoredItemClampsQueueSizeToMax()
|
|
{
|
|
EventManager manager = CreateManager(3, 3, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(),
|
|
nm.Object,
|
|
null!,
|
|
1,
|
|
idFactory,
|
|
TimestampsToReturn.Both,
|
|
1000.0,
|
|
NewCreateRequest(1000.0, 1000),
|
|
new EventFilter(),
|
|
false);
|
|
|
|
Assert.That(item, Is.InstanceOf<MonitoredItem>());
|
|
Assert.That(((MonitoredItem)item).QueueSize, Is.EqualTo(3));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Part 4 §7.21: for event monitored items a requested queueSize of 0
|
|
/// means the server default and 1 means the minimum queue size the
|
|
/// server requires for Event Notifications. Neither may be taken
|
|
/// literally, otherwise a burst of events (for example the
|
|
/// OpenSecureChannel, CreateSession and ActivateSession audit events of
|
|
/// one connect) collapses to the last event before the next publish.
|
|
/// </summary>
|
|
[TestCase(0u)]
|
|
[TestCase(1u)]
|
|
public void CreateMonitoredItemRevisesSpecialEventQueueSizes(uint requestedQueueSize)
|
|
{
|
|
EventManager manager = CreateManager(10000, 10000, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, requestedQueueSize),
|
|
new EventFilter(), false);
|
|
|
|
Assert.That(
|
|
((MonitoredItem)item).QueueSize,
|
|
Is.EqualTo(EventManager.DefaultEventQueueSize));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The server default is still limited by the configured maximum, and a
|
|
/// configured maximum of 1 is honored rather than read as another
|
|
/// queueSize 1 request.
|
|
/// </summary>
|
|
[TestCase(0u, 3u)]
|
|
[TestCase(1u, 3u)]
|
|
[TestCase(0u, 1u)]
|
|
[TestCase(1u, 1u)]
|
|
public void CreateMonitoredItemClampsDefaultEventQueueSizeToMax(
|
|
uint requestedQueueSize,
|
|
uint maxQueueSize)
|
|
{
|
|
EventManager manager = CreateManager(
|
|
maxQueueSize,
|
|
10000,
|
|
out _,
|
|
out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, requestedQueueSize),
|
|
new EventFilter(), false);
|
|
|
|
Assert.That(((MonitoredItem)item).QueueSize, Is.EqualTo(maxQueueSize));
|
|
}
|
|
|
|
[Test]
|
|
public void ModifyMonitoredItemRevisesEventQueueSizeOne()
|
|
{
|
|
EventManager manager = CreateManager(10000, 10000, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
manager.ModifyMonitoredItem(
|
|
NewContext(),
|
|
item,
|
|
TimestampsToReturn.Both,
|
|
new MonitoredItemModifyRequest
|
|
{
|
|
RequestedParameters = new MonitoringParameters
|
|
{
|
|
ClientHandle = 42,
|
|
SamplingInterval = 1000.0,
|
|
QueueSize = 1,
|
|
DiscardOldest = true
|
|
}
|
|
},
|
|
new EventFilter());
|
|
|
|
Assert.That(
|
|
((MonitoredItem)item).QueueSize,
|
|
Is.EqualTo(EventManager.DefaultEventQueueSize));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Part 4 7.21: a NaN sampling interval on create is revised to the publishing interval
|
|
/// instead of being echoed back.
|
|
/// </summary>
|
|
[Test]
|
|
public void CreateMonitoredItemRevisesNaNSamplingIntervalToPublishingInterval()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, new MonitoredItemIdFactory(),
|
|
TimestampsToReturn.Both, 750.0, NewCreateRequest(double.NaN, 5),
|
|
new EventFilter(), false);
|
|
|
|
Assert.That(((MonitoredItem)item).SamplingInterval, Is.EqualTo(750.0));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Part 4 7.21: any negative sampling interval on modify selects the publishing interval
|
|
/// of the subscription; the negative value is never returned as the revised interval.
|
|
/// </summary>
|
|
[TestCase(-1.0)]
|
|
[TestCase(-5.0)]
|
|
[TestCase(double.NaN)]
|
|
public void ModifyMonitoredItemRevisesNegativeSamplingIntervalToPublishingInterval(
|
|
double requestedSamplingInterval)
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, new MonitoredItemIdFactory(),
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(500.0, 5),
|
|
new EventFilter(), false);
|
|
var subscription = new Mock<ISubscription>();
|
|
subscription.SetupGet(s => s.PublishingInterval).Returns(250.0);
|
|
item.SubscriptionCallback = subscription.Object;
|
|
|
|
manager.ModifyMonitoredItem(
|
|
NewContext(),
|
|
item,
|
|
TimestampsToReturn.Both,
|
|
new MonitoredItemModifyRequest
|
|
{
|
|
RequestedParameters = new MonitoringParameters
|
|
{
|
|
ClientHandle = 42,
|
|
SamplingInterval = requestedSamplingInterval,
|
|
QueueSize = 5,
|
|
DiscardOldest = true
|
|
}
|
|
},
|
|
new EventFilter());
|
|
|
|
Assert.That(((MonitoredItem)item).SamplingInterval, Is.EqualTo(250.0));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Regression for the CTT "Auditing Connections" failures: the CTT audit
|
|
/// subscription requests QueueSize 1 on Server.EventNotifier. Every event
|
|
/// raised between two publishes must still be delivered.
|
|
/// </summary>
|
|
[Test]
|
|
public void EventBurstIsNotCollapsedWhenQueueSizeOneRequested()
|
|
{
|
|
EventManager manager = CreateManager(10000, 10000, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 1),
|
|
new EventFilter(), false);
|
|
|
|
for (int ii = 0; ii < 3; ii++)
|
|
{
|
|
((MonitoredItem)item).QueueEvent(new EventFieldList
|
|
{
|
|
ClientHandle = 42,
|
|
EventFields = [new Variant("event" + ii)]
|
|
});
|
|
}
|
|
|
|
var notifications = new Queue<EventFieldList>();
|
|
((MonitoredItem)item).Publish(NewContext(), notifications, 100);
|
|
|
|
// an overflowing queue would drop events and append an
|
|
// EventQueueOverflowEvent, so compare the exact payloads.
|
|
Assert.That(
|
|
notifications.Select(n => n.EventFields[0].GetString()),
|
|
Is.EqualTo(s_eventBurst));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A durable event queue persisted with the literal size 1 must be resized
|
|
/// to the revised size when the monitored item is restored.
|
|
/// </summary>
|
|
[Test]
|
|
public void RestoreMonitoredItemResizesRestoredEventQueue()
|
|
{
|
|
Mock<IServerInternal> server = DeterministicServerMock.Create(
|
|
out MonitoredItemQueueFactory queueFactory);
|
|
using var manager = new EventManager(server.Object, 10000, 10000);
|
|
|
|
IEventMonitoredItemQueue persisted = queueFactory.CreateEventQueue(false, 7);
|
|
persisted.SetQueueSize(1, true);
|
|
persisted.Enqueue(new EventFieldList
|
|
{
|
|
ClientHandle = 42,
|
|
EventFields = [new Variant("event0")]
|
|
});
|
|
|
|
var stored = new StoredMonitoredItem
|
|
{
|
|
Id = 7,
|
|
SubscriptionId = 1,
|
|
TypeMask = MonitoredItemTypeMask.Events,
|
|
MonitoringMode = MonitoringMode.Reporting,
|
|
NodeId = ObjectIds.Server,
|
|
AttributeId = Attributes.EventNotifier,
|
|
ClientHandle = 42,
|
|
QueueSize = 1,
|
|
DiscardOldest = true,
|
|
SamplingInterval = 0,
|
|
TimestampsToReturn = TimestampsToReturn.Both,
|
|
DiagnosticsMasks = DiagnosticsMasks.None,
|
|
OriginalFilter = new EventFilter(),
|
|
FilterToUse = new EventFilter(),
|
|
IndexRange = string.Empty,
|
|
ParsedIndexRange = NumericRange.Null,
|
|
RestoredEventQueue = persisted
|
|
};
|
|
|
|
var item = (MonitoredItem)manager.RestoreMonitoredItem(
|
|
new Mock<IAsyncNodeManager>().Object,
|
|
null!,
|
|
stored);
|
|
|
|
Assert.That(item.QueueSize, Is.EqualTo(EventManager.DefaultEventQueueSize));
|
|
|
|
for (int ii = 1; ii < 3; ii++)
|
|
{
|
|
item.QueueEvent(new EventFieldList
|
|
{
|
|
ClientHandle = 42,
|
|
EventFields = [new Variant("event" + ii)]
|
|
});
|
|
}
|
|
|
|
var notifications = new Queue<EventFieldList>();
|
|
item.Publish(NewContext(), notifications, 100);
|
|
|
|
Assert.That(
|
|
notifications.Select(n => n.EventFields[0].GetString()),
|
|
Is.EqualTo(s_eventBurst));
|
|
}
|
|
|
|
[Test]
|
|
public void CreateMonitoredItemUsesPublishingIntervalWhenSamplingNegative()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(),
|
|
nm.Object,
|
|
null!,
|
|
1,
|
|
idFactory,
|
|
TimestampsToReturn.Both,
|
|
2500.0,
|
|
NewCreateRequest(-1.0, 5),
|
|
new EventFilter(),
|
|
false);
|
|
|
|
Assert.That(item.SamplingInterval, Is.EqualTo(2500.0));
|
|
}
|
|
|
|
[Test]
|
|
public void CreateMonitoredItemAssignsDistinctIds()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem first = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
IEventMonitoredItem second = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
Assert.That(first.Id, Is.Not.EqualTo(second.Id));
|
|
Assert.That(manager.GetMonitoredItems(), Has.Count.EqualTo(2));
|
|
}
|
|
|
|
[Test]
|
|
public void DeleteMonitoredItemRemovesItem()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
manager.DeleteMonitoredItem(item.Id);
|
|
|
|
Assert.That(manager.GetMonitoredItems(), Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void ModifyMonitoredItemIgnoresForeignItem()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out _);
|
|
var foreign = new Mock<IEventMonitoredItem>();
|
|
foreign.SetupGet(m => m.Id).Returns(9999);
|
|
foreign.SetupGet(m => m.IsDurable).Returns(false);
|
|
|
|
Assert.DoesNotThrow(() => manager.ModifyMonitoredItem(
|
|
NewContext(),
|
|
foreign.Object,
|
|
TimestampsToReturn.Both,
|
|
new MonitoredItemModifyRequest
|
|
{
|
|
RequestedParameters = new MonitoringParameters { QueueSize = 5 }
|
|
},
|
|
new EventFilter()));
|
|
|
|
foreign.Verify(
|
|
m => m.ModifyAttributes(
|
|
It.IsAny<DiagnosticsMasks>(),
|
|
It.IsAny<TimestampsToReturn>(),
|
|
It.IsAny<uint>(),
|
|
It.IsAny<MonitoringFilter>(),
|
|
It.IsAny<MonitoringFilter>(),
|
|
It.IsAny<Range>(),
|
|
It.IsAny<double>(),
|
|
It.IsAny<uint>(),
|
|
It.IsAny<bool>()),
|
|
Times.Never);
|
|
}
|
|
|
|
[Test]
|
|
public void ModifyMonitoredItemUpdatesOwnedItem()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
IEventMonitoredItem item = manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
Assert.DoesNotThrow(() => manager.ModifyMonitoredItem(
|
|
NewContext(),
|
|
item,
|
|
TimestampsToReturn.Both,
|
|
new MonitoredItemModifyRequest
|
|
{
|
|
RequestedParameters = new MonitoringParameters
|
|
{
|
|
ClientHandle = 7,
|
|
SamplingInterval = 2000.0,
|
|
QueueSize = 8,
|
|
DiscardOldest = false
|
|
}
|
|
},
|
|
new EventFilter()));
|
|
|
|
Assert.That(((MonitoredItem)item).QueueSize, Is.EqualTo(8));
|
|
}
|
|
|
|
[Test]
|
|
public void GetMonitoredItemsReturnsSnapshot()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
IList<IEventMonitoredItem> first = manager.GetMonitoredItems();
|
|
first.Clear();
|
|
|
|
Assert.That(manager.GetMonitoredItems(), Has.Count.EqualTo(1));
|
|
}
|
|
|
|
[Test]
|
|
public void DisposeClearsMonitoredItems()
|
|
{
|
|
EventManager manager = CreateManager(100, 100, out _, out Mock<IAsyncNodeManager> nm);
|
|
var idFactory = new MonitoredItemIdFactory();
|
|
|
|
manager.CreateMonitoredItem(
|
|
NewContext(), nm.Object, null!, 1, idFactory,
|
|
TimestampsToReturn.Both, 1000.0, NewCreateRequest(1000.0, 5),
|
|
new EventFilter(), false);
|
|
|
|
manager.Dispose();
|
|
|
|
Assert.That(manager.GetMonitoredItems(), Is.Empty);
|
|
}
|
|
|
|
[Test]
|
|
public void ReportEventWithNullEventThrows()
|
|
{
|
|
#pragma warning disable CS0618 // testing the obsolete overload deliberately
|
|
Assert.That(
|
|
() => EventManager.ReportEvent(null!, []),
|
|
Throws.TypeOf<ArgumentNullException>());
|
|
#pragma warning restore CS0618
|
|
}
|
|
|
|
[Test]
|
|
public void ReportEventQueuesEventToEachItem()
|
|
{
|
|
var filterTarget = new Mock<IFilterTarget>();
|
|
var item1 = new Mock<IEventMonitoredItem>();
|
|
var item2 = new Mock<IEventMonitoredItem>();
|
|
|
|
#pragma warning disable CS0618 // testing the obsolete overload deliberately
|
|
EventManager.ReportEvent(
|
|
filterTarget.Object,
|
|
[item1.Object, item2.Object]);
|
|
#pragma warning restore CS0618
|
|
|
|
item1.Verify(m => m.QueueEvent(filterTarget.Object), Times.Once);
|
|
item2.Verify(m => m.QueueEvent(filterTarget.Object), Times.Once);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Defines the ordered event payloads expected after publishing a three-event burst.
|
|
/// </summary>
|
|
private static readonly string[] s_eventBurst = ["event0", "event1", "event2"];
|
|
}
|
|
}
|