namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// Node-wide admission limits for the source cache and retained work.
public sealed class DataResourceLimits
{
/// Maximum bounded partition fan-out for a hub and its producer fences.
public const int MaxPartitionCount = 256;
public int PartitionCount { get; init; } = 4;
public long MaxRetainedBytes { get; init; } = 64 * 1024 * 1024;
public int MaxTrackedSources { get; init; } = 100_000;
public int MaxIngressItemsPerPartition { get; init; } = 1024;
public int MaxDirtySourcesPerPartition { get; init; } = 1024;
public int MaxControlItemsPerPartition { get; init; } = 256;
public int MaxSnapshotItems { get; init; } = 10_000;
public long MaxSnapshotBytes { get; init; } = 16 * 1024 * 1024;
public int MaxSnapshotCatchUpItems { get; init; } = 1024;
public TimeSpan MaxSnapshotLifetime { get; init; } = TimeSpan.FromSeconds(30);
internal void Validate()
{
if (PartitionCount <= 0 || PartitionCount > MaxPartitionCount || MaxRetainedBytes <= 0 || MaxTrackedSources <= 0 ||
MaxIngressItemsPerPartition <= 0 || MaxDirtySourcesPerPartition <= 0 ||
MaxControlItemsPerPartition <= 0 || MaxSnapshotItems <= 0 || MaxSnapshotBytes <= 0 ||
MaxSnapshotCatchUpItems <= 0 || MaxSnapshotLifetime <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(DataResourceLimits));
}
}
/// Atomic accounting shared by partitions, reservations, snapshots and readers.
public sealed class DataResourceBudget
{
private long _retainedBytes;
internal DataResourceBudget(long maximum) => MaximumBytes = maximum;
public long MaximumBytes { get; }
public long RetainedBytes => Interlocked.Read(ref _retainedBytes);
internal bool TryReserve(long bytes)
{
if (bytes <= 0 || bytes > MaximumBytes) return false;
while (true)
{
var current = Interlocked.Read(ref _retainedBytes);
if (current > MaximumBytes - bytes) return false;
if (Interlocked.CompareExchange(ref _retainedBytes, current + bytes, current) == current) return true;
}
}
internal void Release(long bytes)
{
if (bytes > 0 && Interlocked.Add(ref _retainedBytes, -bytes) < 0)
throw new InvalidOperationException("Resource charge released more than once.");
}
}