Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion src/Opc.Ua.Client/Subscription/MessageProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1930,7 +1930,40 @@ public static int Compare(IncomingMessage message, IncomingMessage other)
private uint m_lastServerId;
internal long m_missingCount;
internal long m_republishCount;
internal IReadOnlyList<uint> AvailableInRetransmissionQueue;

/// <summary>
/// The sequence numbers the server last listed as available. Reading returns
/// a copy. The numbers are kept in a reused array, so a long-lived subscription
/// does not reference a new array per response: each such write is a dirty card
/// every following gen0 collection has to walk.
/// </summary>
internal IReadOnlyList<uint> AvailableInRetransmissionQueue
{
get
{
lock (m_availableLock)
{
return m_available.AsSpan(0, m_availableCount).ToArray();
}
}
set
{
int count = value?.Count ?? 0;
lock (m_availableLock)
{
if (m_available.Length < count)
{
m_available = new uint[Math.Max(count * 2, 16)];
}
for (int i = 0; i < count; i++)
{
m_available[i] = value![i];
}
m_availableCount = count;
}
}
}

internal readonly ILogger Logger;
protected TimeProvider TimeProvider { get; }

Expand Down Expand Up @@ -1996,6 +2029,9 @@ protected bool IsDispatchingNotification
/// Sequence numbers advertised as available while a gap was open.
/// </summary>
private readonly HashSet<uint> m_gapAvailableSequenceNumbers = [];
private readonly Lock m_availableLock = new();
private uint[] m_available = [];
private int m_availableCount;
private long m_gapStartedTimestamp;

/// <summary>
Expand Down
4 changes: 1 addition & 3 deletions src/Opc.Ua.Client/Subscription/Subscription.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,7 @@ public SubscriptionStateSnapshot Snapshot()
items.Add(concrete.Snapshot());
}
}
uint[] available = AvailableInRetransmissionQueue == null
? []
: [.. AvailableInRetransmissionQueue];
uint[] available = [.. AvailableInRetransmissionQueue];
return SubscriptionStateSnapshot.AsOptions(
Options,
Id,
Expand Down
27 changes: 17 additions & 10 deletions src/Opc.Ua.Client/Subscription/SubscriptionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3266,7 +3266,7 @@ private readonly record struct SubscriptionClaim(
/// responses and guarded by the manager's registry lock, so recording a response does
/// not allocate.
/// </summary>
private sealed class AvailabilityWindow
internal sealed class AvailabilityWindow
{
/// <summary>
/// The owner's message generation when recorded.
Expand All @@ -3291,31 +3291,37 @@ public void Update(long messageGeneration, uint horizon, ArrayOf<uint> available
MessageGeneration = messageGeneration;
Horizon = horizon;
RetransmissionQueueUnsupported = unsupported;
m_available = available;
if (available.Count > kLinearSearchLimit)
// Copied, so a long-lived window does not reference a new array per response:
// each such write is a dirty card every following gen0 collection has to walk.
ReadOnlySpan<uint> source = available.Span;
m_count = source.Length;
if (m_count > kLinearSearchLimit)
{
m_lookup ??= [];
m_lookup.Clear();
foreach (uint sequenceNumber in available)
for (int i = 0; i < source.Length; i++)
{
m_lookup.Add(sequenceNumber);
m_lookup.Add(source[i]);
}
}
else
{
source.CopyTo(m_linear);
}
}

/// <summary>
/// Whether the server listed the sequence number as available.
/// </summary>
public bool Contains(uint sequenceNumber)
{
if (m_available.Count > kLinearSearchLimit)
if (m_count > kLinearSearchLimit)
{
return m_lookup!.Contains(sequenceNumber);
}
ReadOnlySpan<uint> available = m_available.Span;
for (int i = 0; i < available.Length; i++)
for (int i = 0; i < m_count; i++)
{
if (available[i] == sequenceNumber)
if (m_linear[i] == sequenceNumber)
{
return true;
}
Expand All @@ -3324,7 +3330,8 @@ public bool Contains(uint sequenceNumber)
}

private const int kLinearSearchLimit = 16;
private ArrayOf<uint> m_available;
private readonly uint[] m_linear = new uint[kLinearSearchLimit];
private int m_count;
private HashSet<uint>? m_lookup;
}

Expand Down
96 changes: 96 additions & 0 deletions tests/Opc.Ua.Client.Tests/Subscription/AvailabilityWindowTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/* ========================================================================
* 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.Linq;
using NUnit.Framework;

namespace Opc.Ua.Client.Subscriptions
{
[TestFixture]
public sealed class AvailabilityWindowTests
{
[TestCase(0)]
[TestCase(1)]
[TestCase(16)]
[TestCase(17)]
[TestCase(300)]
public void ContainsShouldFindExactlyTheListedNumbers(int count)
{
var window = new SubscriptionManager.AvailabilityWindow();

window.Update(1, 1000, Numbers(100, count), false);

for (int i = 0; i < count; i++)
{
Assert.That(window.Contains((uint)(100 + i)), Is.True);
}
Assert.That(window.Contains(99), Is.False);
Assert.That(window.Contains((uint)(100 + count)), Is.False);
}

[TestCase(300, 3)]
[TestCase(3, 300)]
[TestCase(5, 2)]
[TestCase(300, 20)]
public void UpdateShouldReplaceThePreviousView(int firstCount, int secondCount)
{
var window = new SubscriptionManager.AvailabilityWindow();

window.Update(1, 1000, Numbers(100, firstCount), false);
window.Update(2, 2000, Numbers(5000, secondCount), true);

Assert.That(window.MessageGeneration, Is.EqualTo(2));
Assert.That(window.Horizon, Is.EqualTo(2000));
Assert.That(window.RetransmissionQueueUnsupported, Is.True);
Assert.That(window.Contains(100), Is.False);
Assert.That(window.Contains((uint)(100 + firstCount - 1)), Is.False);
Assert.That(window.Contains(5000), Is.True);
Assert.That(window.Contains((uint)(5000 + secondCount - 1)), Is.True);
Assert.That(window.Contains((uint)(5000 + secondCount)), Is.False);
}

[Test]
public void UpdateShouldNotKeepTheCallersArray()
{
var window = new SubscriptionManager.AvailabilityWindow();
uint[] numbers = [7, 8];

window.Update(1, 1000, numbers.ToArrayOf(), false);
numbers[0] = 9;

Assert.That(window.Contains(7), Is.True);
Assert.That(window.Contains(9), Is.False);
}

private static ArrayOf<uint> Numbers(int start, int count)
{
return Enumerable.Range(start, count).Select(i => (uint)i).ToArray().ToArrayOf();
}
}
}
25 changes: 25 additions & 0 deletions tests/Opc.Ua.Client.Tests/Subscription/MessageProcessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,31 @@ public async Task WaitForQueuedAckAsyncShouldThrowWhenTheAckNeverArrives()
Assert.That(ex.Message, Does.Contain("only 0 arrived"));
}

[Test]
public async Task AvailableInRetransmissionQueueShouldReturnACopyOfTheLatestValuesAsync()
{
var sut = new TestMessageProcessor(m_mockServices.Object, m_completion, m_telemetry);
await using (sut.ConfigureAwait(false))
{
Assert.That(sut.AvailableInRetransmissionQueue, Is.Empty);

sut.AvailableInRetransmissionQueue = [1, 2, 3];
IReadOnlyList<uint> first = sut.AvailableInRetransmissionQueue;

// Shorter than the storage, then longer than it, then none.
sut.AvailableInRetransmissionQueue = [4];
Assert.That(first, Is.EqualTo(new uint[] { 1, 2, 3 }));
Assert.That(sut.AvailableInRetransmissionQueue, Is.EqualTo(new uint[] { 4 }));

uint[] many = [.. Enumerable.Range(10, 100).Select(i => (uint)i)];
sut.AvailableInRetransmissionQueue = many;
Assert.That(sut.AvailableInRetransmissionQueue, Is.EqualTo(many));

sut.AvailableInRetransmissionQueue = null!;
Assert.That(sut.AvailableInRetransmissionQueue, Is.Empty);
}
}

[Test]
public async Task OnPublishReceivedKeepAliveShouldDispatchKeepAliveAsync()
{
Expand Down
Loading