namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
/// Process-wide retained input budget shared across script owners and redeploys.
public static class ProjectedInputBudget
{
/// Current process-wide retained input limit in bytes.
public const long MaximumBytes = 16 * 1024 * 1024;
private const int MaximumSnapshots = 10_000;
private static long s_used;
/// Bytes currently reserved by projected input owners.
public static long RetainedBytes => Interlocked.Read(ref s_used);
/// Charges captured projected snapshots until the returned lease is disposed.
public static bool TryRetain(IEnumerable snapshots, out IDisposable? lease)
{
lease = null;
var values = new List();
long charge = 0;
try
{
foreach (var snapshot in snapshots)
{
if (values.Count == MaximumSnapshots || snapshot is null) return false;
charge = checked(charge + Estimate(snapshot.Value));
if (charge > MaximumBytes) return false;
values.Add(snapshot);
}
}
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
if (charge == 0) return true;
while (true)
{
var used = Interlocked.Read(ref s_used);
if (charge > MaximumBytes - used) return false;
if (Interlocked.CompareExchange(ref s_used, used + charge, used) == used) break;
}
lease = new Lease(values.ToArray(), charge);
return true;
}
private static long Estimate(object? value)
{
checked
{
long size = 512;
if (value is string text) size += 2L * text.Length;
else if (value is byte[] bytes) size += bytes.LongLength;
else if (value is Array array)
{
if (array.Rank > 4 || array.LongLength > 65536) throw new ArgumentException("Unsupported input array.");
var elementType = array.GetType().GetElementType();
if (elementType is null || !(elementType.IsPrimitive || elementType == typeof(string) ||
elementType == typeof(Guid) || elementType == typeof(DateTime) || elementType == typeof(DateTimeOffset)))
throw new ArgumentException("Unsupported input array.");
size += 128 + 48L * array.LongLength;
if (elementType == typeof(string)) foreach (var element in array) size += 2L * ((string?)element ?? "").Length;
}
else if (value is not null && !(value.GetType().IsPrimitive || value is Guid or DateTime or DateTimeOffset or decimal))
throw new ArgumentException("Unsupported input value.");
if (size > 4 * 1024 * 1024) throw new ArgumentException("Input is too large.");
return size;
}
}
private sealed class Lease(DataValueSnapshot[] snapshots, long charge) : IDisposable
{
private DataValueSnapshot[]? _snapshots = snapshots;
public void Dispose()
{
if (Interlocked.Exchange(ref _snapshots, null) is not null) Interlocked.Add(ref s_used, -charge);
}
}
}