using Opc.Ua;
using Opc.Ua.Server;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
///
/// A ring-buffer replacement for the SDK's (Gitea #870): the same observable
/// behaviour, but discarding the oldest event at a full queue is O(1) instead of a List.RemoveAt(0) shift of
/// the whole queue.
///
///
///
/// Why. Since #855 condition events are queued to folder event items by the reporter, under the node
/// manager's Lock. At a full queue with DiscardOldest the SDK's dequeues the
/// head and enqueues the new event; the SDK queue's dequeue is List.RemoveAt(0), ~1 µs per item at
/// QueueSize 1000 and ~10 µs at 10 000 — paid per stalled item per report while Lock is held.
///
///
/// What is reproduced (SDK 2.0.1, decompiled). The SDK queue is pure storage — DiscardOldest, the
/// EventQueueOverflowEventType positions and the discarded/overflow counters all live in
/// , which is unchanged and drives this queue exactly as it drives the SDK's.
/// Reproduced here: starts at 0; at QueueSize 0 throws
/// BadInternalError, and at Count == QueueSize drops the oldest
/// entry first; is FIFO and returns false (value null) when empty;
/// keeps the newest queueSize entries when discardOldest, else the
/// oldest; checks the newest ≤ 1000 entries with the SDK's own
/// (null entries skipped); is
/// false; does nothing observable (the SDK's does nothing at all). A durable queue is
/// never created here — hands that request to the SDK factory, which refuses it
/// exactly as before.
///
///
/// Not thread-safe, like the SDK's: is only used under its monitored item's lock.
/// Parity is pinned by RingEventMonitoredItemQueueParityTests.
///
///
public sealed class RingEventMonitoredItemQueue : IEventMonitoredItemQueue
{
/// The SDK's kMaxNoOfEntriesCheckedForDuplicateEvents.
internal const int MaxEntriesCheckedForDuplicates = 1000;
private const int MinimumCapacity = 4;
private EventFieldList?[] _buffer = [];
private int _head;
private int _count;
/// Creates an empty queue (QueueSize 0, as the SDK's).
/// The monitored item the queue belongs to.
public RingEventMonitoredItemQueue(uint monitoredItemId) => MonitoredItemId = monitoredItemId;
///
public uint MonitoredItemId { get; }
///
public bool IsDurable => false;
///
public uint QueueSize { get; private set; }
///
public int ItemsInQueue => _count;
/// Allocated slots (test observation: the buffer grows with use and shrinks with the queue size).
internal int Capacity => _buffer.Length;
///
public void SetQueueSize(uint queueSize, bool discardOldest)
{
QueueSize = queueSize;
if (_count > queueSize)
{
var excess = _count - (int)queueSize;
if (discardOldest)
{
for (var i = 0; i < excess; i++) DropHead();
}
else
{
for (var i = 0; i < excess; i++)
{
_buffer[Slot(_count - 1)] = null;
_count--;
}
}
}
// Not observable: release a buffer much larger than the new size (a List would keep it).
if (_buffer.Length > MinimumCapacity && _buffer.Length > 2 * Math.Max(queueSize, (uint)MinimumCapacity))
Resize(Math.Max(_count, MinimumCapacity));
}
///
public bool IsEventContainedInQueue(IFilterTarget instance)
{
var oldest = _count > MaxEntriesCheckedForDuplicates ? _count - MaxEntriesCheckedForDuplicates : 0;
for (var i = _count - 1; i >= oldest; i--)
{
var queued = _buffer[Slot(i)];
if (queued is not null && EventMonitoredItemQueue.IsEventRaisedFor(queued, instance)) return true;
}
return false;
}
///
public void Enqueue(EventFieldList value)
{
if (QueueSize == 0)
throw new ServiceResultException(StatusCodes.BadInternalError, "Error queueing Event. Queue size is set to 0");
if (_count == QueueSize) DropHead();
if (_count == _buffer.Length)
Resize((int)Math.Min(QueueSize, (ulong)Math.Max(MinimumCapacity, _buffer.Length * 2L)));
_buffer[Slot(_count)] = value;
_count++;
}
///
public bool Dequeue(out EventFieldList value)
{
value = null!;
if (_count == 0) return false;
value = _buffer[_head]!;
DropHead();
return true;
}
///
public void Dispose()
{
// The SDK's queue disposes nothing; the queue stays usable, as the SDK's does.
}
private int Slot(int index)
{
var slot = _head + index;
return slot >= _buffer.Length ? slot - _buffer.Length : slot;
}
private void DropHead()
{
_buffer[_head] = null;
_head = _head + 1 == _buffer.Length ? 0 : _head + 1;
_count--;
if (_count == 0) _head = 0;
}
private void Resize(int capacity)
{
var next = new EventFieldList?[Math.Max(capacity, _count)];
for (var i = 0; i < _count; i++) next[i] = _buffer[Slot(i)];
_buffer = next;
_head = 0;
}
}
///
/// The server's (Gitea #870): event queues are
/// ; data-change queues, durable requests and disposal go to the SDK's own
/// factory unchanged.
///
public sealed class RingEventQueueFactory(IMonitoredItemQueueFactory inner) : IMonitoredItemQueueFactory
{
private readonly IMonitoredItemQueueFactory _inner = inner ?? throw new ArgumentNullException(nameof(inner));
///
public bool SupportsDurableQueues => _inner.SupportsDurableQueues;
///
public IDataChangeMonitoredItemQueue CreateDataChangeQueue(bool isDurable, uint monitoredItemId) =>
_inner.CreateDataChangeQueue(isDurable, monitoredItemId);
///
public IEventMonitoredItemQueue CreateEventQueue(bool isDurable, uint monitoredItemId) =>
isDurable ? _inner.CreateEventQueue(isDurable, monitoredItemId) : new RingEventMonitoredItemQueue(monitoredItemId);
///
public void Dispose() => _inner.Dispose();
}