fix(grpc-data): H2 review 1/5/9 - bound origin history memory per request and per principal

Nodes are read in sub-batches sized to the response budget and no sub-batch starts once it is spent: the rest are
DEFERRED chunk tokens (transport; read on resume from their original continuation) or BadTooManyOperations (direct
consumer). Processed intervals and AtTime times above MaxHistoryValuesPerPage are refused unsent. Remainder bytes are
charged to a per-principal budget across sessions (concurrent reads x max(response budget, one page)); sizes come
from the encoded CalculateSize; a single value above the response budget is a per-item BadTooManyOperations.
Sessions are capped per principal (own LRU evicted first) and globally (the heaviest principal pays); a release never
creates a session; channel-close registrations are unregistered on clear.
This commit is contained in:
Joseph Doherty
2026-11-23 21:59:59 -05:00
parent 82d34b84a8
commit 53e3970f27
5 changed files with 429 additions and 83 deletions
@@ -43,6 +43,9 @@ public sealed partial class LocalDataServices
/// <summary>Live history sessions (diagnostics/tests).</summary>
internal int HistorySessionCount => _historySessions.Count;
/// <summary>Remainder bytes retained for a principal across its sessions (diagnostics/tests).</summary>
internal long HistoryRetainedBytes(string principal) => _historySessions.RetainedBytes(principal);
private bool IsHistorized(LocalDataNode node) =>
_history is not null && node.Source is not null && node.Metadata.View.Address.IdentifierKind == "string"
&& _history.IsHistorized(Realm(node), node.Metadata.View.Address.Identifier);
@@ -78,65 +81,92 @@ public sealed partial class LocalDataServices
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request.Items);
ArgumentNullException.ThrowIfNull(request.Details); ArgumentNullException.ThrowIfNull(channel);
var catalog = _catalog();
CheckBudget(request.Budget, request.Items.Count, catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems,
cancellationToken);
var batchLimit = catalog is null ? _capabilities.Limits.MaxBatchItems : Limits(catalog, context).MaxBatchItems;
CheckBudget(request.Budget, request.Items.Count, batchLimit, cancellationToken);
foreach (var item in request.Items) { ArgumentNullException.ThrowIfNull(item); item.View.Validate(); }
ValidateDetails(request);
DataHistoryReadResult[] All(uint status) =>
request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null)).ToArray();
DataHistoryReadResult[] All(uint status, string? diagnostic = null) =>
request.Items.Select(x => new DataHistoryReadResult(x.CorrelationId, status, [], null, diagnostic)).ToArray();
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
throw new InvalidOperationException("History is unavailable for this target.");
if (!_policy.IsCallerUsable(Caller(context))) throw new UnauthorizedAccessException();
if (_history is null || HistoryServing is null || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits)
return Record(request, All(Refused));
// AtTime: every requested time is one value of every node; above the per-page ceiling the request is refused unsent.
if (request.Details is DataHistoryAtTimeDetails atTime && atTime.RequestedTimesUtc.Count > limits.ValuesPerPage)
return Record(request, All(BadTooManyOperations, "More requested times than the origin's history values per page."));
if (!_historySessions.TryAdmit(context.PrincipalId, limits.ConcurrentReads)) return Record(request, All(BadTooManyOperations));
try
{
var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems)));
var session = _historySessions.Get(context, channel, SessionCapacity(limits.ConcurrentReads, batchLimit));
var details = Clamp(request.Details, limits.ValuesPerPage);
var detailsKey = DetailsKey(details);
var incarnation = ServingIncarnation();
// Per-request memory bound: the response budget (transport: the export's response cap; direct: the caller's
// MaxBytes). Nodes are read in sub-batches sized so a sub-batch at the per-page ceiling fits it, and no further
// sub-batch starts once the budget is spent — those nodes are deferred (transport) or BadTooManyOperations (direct).
var budget = ResponseBudget(chunked, limits.ResponseBytes, request.Budget.MaxBytes);
var subBatch = (int)Math.Clamp(budget / Math.Max(1L, (long)limits.ValuesPerPage * 64L), 1L, Math.Max(1, request.Items.Count));
var results = new DataHistoryReadResult?[request.Items.Count];
var nodes = new LocalDataNode?[request.Items.Count];
var portIndexes = new List<int>();
var portItems = new List<OriginHistoryItem>();
var deferred = new bool[request.Items.Count];
var pending = new List<(int Index, OriginHistoryItem Item)>();
for (var i = 0; i < request.Items.Count; i++)
{
var item = request.Items[i];
if (!Gate(catalog, context, item.View, out var node)) { results[i] = new(item.CorrelationId, Refused, [], null); continue; }
nodes[i] = node;
var continuation = item.Continuation;
if (session.TakeChunk(item.Continuation) is { } chunk)
{
// A chunk token resumes the transport's remainder; it is bound to the view, details and serving identity.
results[i] = chunk.View == node.Metadata.View && chunk.DetailsKey == detailsKey && chunk.Incarnation == incarnation
? new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic)
: Invalid(item, chunk);
if (chunk.View != node.Metadata.View || chunk.DetailsKey != detailsKey || chunk.Incarnation != incarnation)
{ results[i] = Invalid(item, chunk); continue; }
if (!chunk.Deferred)
{ results[i] = new(item.CorrelationId, chunk.StatusCode, chunk.Remaining, chunk.Continuation, chunk.Diagnostic); continue; }
continuation = chunk.Continuation; // a deferred node is read now, from where it was
}
if (Buckets(details) > limits.ValuesPerPage)
{
results[i] = new(item.CorrelationId, BadTooManyOperations, [], null, "More processing intervals than the origin's history values per page.");
continue;
}
portIndexes.Add(i);
portItems.Add(new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View),
item.AggregateId, item.Continuation));
pending.Add((i, new OriginHistoryItem(Realm(node), node.Metadata.View.Address.Identifier, BindingTag(node.Metadata.View),
item.AggregateId, continuation)));
}
if (portItems.Count > 0)
long used = 0;
for (var start = 0; start < pending.Count; start += subBatch)
{
var slice = pending.Skip(start).Take(subBatch).ToArray();
if (used >= budget)
{
foreach (var (index, portItem) in slice)
{
deferred[index] = true;
results[index] = new(request.Items[index].CorrelationId, 0, [], portItem.Continuation);
}
continue;
}
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
deadline.CancelAfter(request.Budget.Timeout);
IReadOnlyList<OriginHistoryOutcome> outcomes;
try
{
outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, details, portItems, deadline.Token)
.ConfigureAwait(false);
outcomes = await _history.ReadAsync(session.Cursors, context.PrincipalId, ServingIncarnation, details,
slice.Select(x => x.Item).ToArray(), deadline.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
// The budget expired before the port answered: every in-flight node is BadTimeout, as the port itself answers.
outcomes = portItems.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
outcomes = slice.Select(_ => new OriginHistoryOutcome(0x800A0000u, [], null, false)).ToArray();
}
cancellationToken.ThrowIfCancellationRequested(); // a caller cancel is never a backend outcome
for (var k = 0; k < portIndexes.Count; k++)
for (var k = 0; k < slice.Length; k++)
{
var index = portIndexes[k];
results[index] = ToResult(request.Items[index], nodes[index]!, outcomes[k], details);
var index = slice[k].Index;
var result = ToResult(request.Items[index], nodes[index]!, outcomes[k], details);
results[index] = result;
foreach (var sample in result.Samples) used += SampleBytes(sample, nodes[index]!.Metadata);
}
}
// Authority may have moved while the backend answered: re-check every served item before handing anything back.
@@ -146,9 +176,12 @@ public sealed partial class LocalDataServices
{
results[i]!.Dispose();
results[i] = new(request.Items[i].CorrelationId, Refused, [], null);
deferred[i] = false;
}
var final = results.Select(x => x!).ToArray();
if (chunked) final = Chunk(final, nodes, session, detailsKey, incarnation, Math.Min(limits.ResponseBytes, _capabilities.Limits.MaxMessageBytes));
final = chunked
? Chunk(final, nodes, deferred, session, detailsKey, incarnation, budget, RemainderBudget(limits, budget))
: Direct(final, deferred);
return Record(request, final);
}
finally { _historySessions.Leave(context.PrincipalId); }
@@ -159,12 +192,34 @@ public sealed partial class LocalDataServices
{
ArgumentNullException.ThrowIfNull(continuations); ArgumentNullException.ThrowIfNull(channel);
cancellationToken.ThrowIfCancellationRequested();
if (_catalog() is not { } catalog || catalog.HistoryLimitsFor(context.PrincipalId) is not { } limits) return Task.CompletedTask;
var session = _historySessions.Get(context, channel, Math.Max(1, limits.ConcurrentReads * Math.Max(1, Limits(catalog, context).MaxBatchItems)));
// A release never creates a session: an unknown channel holds nothing to release.
if (_historySessions.TryGet(context, channel) is not { } session) return Task.CompletedTask;
foreach (var token in continuations) session.Release(token);
return Task.CompletedTask;
}
/// <summary>Records per session: the principal's concurrent reads × its batch, overflow-safe (both are bounded by the validator).</summary>
private static int SessionCapacity(int concurrentReads, int batch) =>
(int)Math.Clamp((long)Math.Max(1, concurrentReads) * Math.Max(1, batch), 1L, 1_000_000L);
/// <summary>The per-request response budget in encoded bytes.</summary>
private long ResponseBudget(bool chunked, int responseBytes, long callerBytes) => chunked
? Math.Max(16 * 1024, Math.Min(responseBytes, _capabilities.Limits.MaxMessageBytes) - ResponseMarginBytes)
: Math.Max(16 * 1024, callerBytes);
/// <summary>
/// The principal's retained-remainder budget across ALL its sessions: concurrent reads × max(response budget, one
/// page at 64 B a value). A remainder past it is BadTooManyOperations for that node (explicit, nothing dropped).
/// </summary>
private static long RemainderBudget((int ConcurrentReads, int ValuesPerPage, int ResponseBytes) limits, long budget) =>
Math.Max(1, limits.ConcurrentReads) * Math.Max(budget, (long)limits.ValuesPerPage * 64L);
/// <summary>Processed: intervals per node (each one value); 1 for other variants.</summary>
private static long Buckets(DataHistoryDetails details) => details is DataHistoryProcessedDetails p
&& p.StartUtc is { } s && p.EndUtc is { } e && p.ProcessingInterval > TimeSpan.Zero
? (long)Math.Ceiling(Math.Abs((e - s).Ticks) / (double)p.ProcessingInterval.Ticks)
: 1;
/// <summary>The per-item ingress gate (order: catalog/view, export grant + origin ACL, historized). One answer for every refusal.</summary>
private bool Gate(LocalExportCatalog catalog, DataAuthenticatedContext context, DataView view, out LocalDataNode node)
{
@@ -241,44 +296,74 @@ public sealed partial class LocalDataServices
}
/// <summary>
/// Splits the response under the byte cap: a result that does not fit keeps what fits, stores the rest as a single-use
/// chunk remainder, and answers <c>ChunkContinues</c> with the chunk token; the final chunk carries the real status and
/// page continuation. A remainder the session cannot hold is BadTooManyOperations (never a silent truncation).
/// Transport split under the response budget, sized from the real encoded size. A result that does not fit keeps
/// what fits and stores the rest as a single-use chunk (its bytes charged to the principal's remainder budget); a node
/// not read because the budget was spent is stored as a DEFERRED chunk (no bytes) and read on resume. Either way the
/// answer is <c>ChunkContinues</c> + the chunk token, and the final chunk carries the real status and page
/// continuation. A single value larger than the whole budget, or a chunk the session / budget cannot hold, is
/// BadTooManyOperations for that node — explicit, never a silent truncation.
/// </summary>
private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, OriginHistorySession session,
string detailsKey, string incarnation, int capBytes)
private static DataHistoryReadResult[] Chunk(DataHistoryReadResult[] results, LocalDataNode?[] nodes, bool[] deferred,
OriginHistorySession session, string detailsKey, string incarnation, long budget, long remainderBudget)
{
long budget = Math.Max(16 * 1024, capBytes - ResponseMarginBytes);
long used = 0;
var anySample = false;
for (var i = 0; i < results.Length; i++)
{
var result = results[i];
used += 128 + 2L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0));
var fit = 0;
foreach (var sample in result.Samples)
used += 32 + 3L * (result.CorrelationId.Length + (result.Diagnostic?.Length ?? 0));
if (deferred[i])
{
var size = SampleBytes(sample);
if (used + size > budget && (anySample || fit > 0)) break;
used += size; fit++; anySample = true;
}
if (fit == result.Samples.Count) continue;
var node = nodes[i]!;
var remaining = result.Samples.Skip(fit).ToArray();
var token = session.SaveChunk(new OriginHistorySession.Chunk(node.Metadata.View, detailsKey, incarnation, remaining,
result.StatusCode, result.Continuation, result.Diagnostic, 0));
if (token is null)
{
result.Dispose();
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full.");
var token = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, [],
0, result.Continuation, null, 0, 0, Deferred: true), remainderBudget);
results[i] = token is null
? new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history session is full.")
: new(result.CorrelationId, 0, [], token, null, ChunkContinues: true);
continue;
}
results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), token, null, ChunkContinues: true);
var fit = 0;
var oversized = false;
foreach (var sample in result.Samples)
{
var size = SampleBytes(sample, nodes[i]?.Metadata);
if (size > budget) { oversized = true; break; }
if (used + size > budget) break;
used += size; fit++;
}
if (oversized)
{
result.Dispose();
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "A history value exceeds the origin's response limit.");
continue;
}
if (fit == result.Samples.Count) continue;
var remaining = result.Samples.Skip(fit).ToArray();
var bytes = remaining.Sum(x => SampleBytes(x, nodes[i]?.Metadata));
var saved = session.SaveChunk(new OriginHistorySession.Chunk(nodes[i]!.Metadata.View, detailsKey, incarnation, remaining,
result.StatusCode, result.Continuation, result.Diagnostic, 0, bytes), remainderBudget);
if (saved is null)
{
result.Dispose();
results[i] = new(result.CorrelationId, BadTooManyOperations, [], null, "Origin history remainder budget is full.");
continue;
}
results[i] = new(result.CorrelationId, result.StatusCode, result.Samples.Take(fit).ToArray(), saved, null, ChunkContinues: true);
}
return results;
}
private static long SampleBytes(DataHistorySample sample) => Math.Max(48, sample.Value.EstimatedRetainedBytes - 192);
/// <summary>A direct consumer is never handed chunks: a node deferred by the request budget is BadTooManyOperations.</summary>
private static DataHistoryReadResult[] Direct(DataHistoryReadResult[] results, bool[] deferred)
{
for (var i = 0; i < results.Length; i++)
if (deferred[i])
results[i] = new(results[i].CorrelationId, BadTooManyOperations, [], null,
"Request byte budget spent before this node was read; read it in a later request.");
return results;
}
/// <summary>The encoded wire size of one sample (what the response actually carries), plus its repeated-field framing.</summary>
private static long SampleBytes(DataHistorySample sample, DataMetadata? catalog) =>
DataHistoryProtoMapper.EncodeSample(sample, catalog).CalculateSize() + 6L;
private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results)
{
@@ -7,59 +7,84 @@ namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
/// <summary>
/// The ORIGIN's remote-history session of one (authenticated principal, credential, transport channel): the H1 page
/// cursor store plus the transport's chunk remainders (plan §3.2). A peer never reaches another session's tokens; the
/// session is cleared when its channel closes, and idle expiry is the backstop.
/// session is cleared when its channel closes, and idle expiry is the backstop. Remainder BYTES are charged to the
/// principal's budget in <see cref="OriginHistorySessions"/>, so retained memory is bounded across all its sessions.
/// </summary>
internal sealed class OriginHistorySession
{
private readonly Lock _gate = new();
private readonly Dictionary<Guid, Chunk> _chunks = new();
private readonly TimeProvider _clock;
private readonly OriginHistorySessions _owner;
private CancellationTokenRegistration _closed;
internal OriginHistorySession(string principal, string channelId, int capacity, TimeProvider clock)
internal OriginHistorySession(OriginHistorySessions owner, string principal, string channelId, int capacity, TimeProvider clock)
{
_owner = owner;
_clock = clock;
Principal = principal;
Capacity = capacity;
Cursors = new OriginHistoryCursors(principal, channelId, capacity, null, clock);
}
/// <summary>The owning principal.</summary>
public string Principal { get; }
/// <summary>The H1 page-continuation store of this session.</summary>
public OriginHistoryCursors Cursors { get; }
/// <summary>The most live records of each kind.</summary>
public int Capacity { get; }
/// <summary>Live chunk remainders.</summary>
internal void Bind(CancellationTokenRegistration closed) => _closed = closed;
/// <summary>Live chunk records.</summary>
public int ChunkCount
{
get { lock (_gate) { Sweep(_clock.GetTimestamp()); return _chunks.Count; } }
}
/// <summary>A stored remainder of one node's answer: what is left, and the final status/continuation it ends with.</summary>
/// <summary>
/// A stored part of one node's answer. <see cref="Deferred"/> = the node was not read yet because the response budget
/// was spent: resuming reads it then, from <see cref="Continuation"/> (its original page token, or null = fresh).
/// Otherwise <see cref="Remaining"/> is what is left and the final status/continuation it ends with.
/// </summary>
internal sealed record Chunk(DataView View, string DetailsKey, string Incarnation, IReadOnlyList<DataHistorySample> Remaining,
uint StatusCode, byte[]? Continuation, string? Diagnostic, long SavedAt);
uint StatusCode, byte[]? Continuation, string? Diagnostic, long SavedAt, long Bytes = 0, bool Deferred = false);
/// <summary>Stores a remainder; null when the session is full (the caller answers BadTooManyOperations, never truncates).</summary>
public byte[]? SaveChunk(Chunk chunk)
/// <summary>
/// Stores a chunk; null when the session is full or the principal's remainder byte budget is spent (the caller answers
/// BadTooManyOperations, never a silent truncation).
/// </summary>
public byte[]? SaveChunk(Chunk chunk, long budgetBytes)
{
if (!_owner.TryReserve(Principal, chunk.Bytes, budgetBytes)) return null;
var token = RandomNumberGenerator.GetBytes(16);
lock (_gate)
{
Sweep(_clock.GetTimestamp());
if (_chunks.Count >= Capacity) return null;
if (_chunks.Count >= Capacity)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
return null;
}
_chunks[new Guid(token)] = chunk with { SavedAt = _clock.GetTimestamp() };
}
return token;
}
/// <summary>Takes (single-use) a remainder; null when the token is not a live chunk token.</summary>
/// <summary>Takes (single-use) a chunk; null when the token is not a live chunk token. Its bytes are released.</summary>
public Chunk? TakeChunk(byte[]? token)
{
if (token is not { Length: 16 }) return null;
Chunk? chunk;
lock (_gate)
{
Sweep(_clock.GetTimestamp());
return _chunks.Remove(new Guid(token), out var chunk) ? chunk : null;
if (!_chunks.Remove(new Guid(token), out chunk)) return null;
}
_owner.ReleaseBytes(Principal, chunk.Bytes);
return chunk;
}
/// <summary>Releases a chunk or a page token (idempotent).</summary>
@@ -72,10 +97,11 @@ internal sealed class OriginHistorySession
/// <summary>Drops everything (the channel closed or the session was evicted).</summary>
public void Clear()
{
_closed.Unregister();
Cursors.Clear();
Chunk[] dropped;
lock (_gate) { dropped = _chunks.Values.ToArray(); _chunks.Clear(); }
foreach (var chunk in dropped) foreach (var sample in chunk.Remaining) sample.Dispose();
foreach (var chunk in dropped) Drop(chunk);
}
private void Sweep(long now)
@@ -84,28 +110,49 @@ internal sealed class OriginHistorySession
if (_clock.GetElapsedTime(chunk.SavedAt, now) >= Cursors.IdleExpiry)
{
_chunks.Remove(id);
foreach (var sample in chunk.Remaining) sample.Dispose();
Drop(chunk);
}
}
private void Drop(Chunk chunk)
{
_owner.ReleaseBytes(Principal, chunk.Bytes);
foreach (var sample in chunk.Remaining) sample.Dispose();
}
}
/// <summary>
/// Every live <see cref="OriginHistorySession"/> of this origin, keyed by (principal, credential, channel), bounded,
/// plus the per-principal history admission counter (<c>MaxConcurrentHistoryReads</c>).
/// Every live <see cref="OriginHistorySession"/> of this origin, keyed by (principal, credential, channel), plus the
/// per-principal history admission counter (<c>MaxConcurrentHistoryReads</c>) and retained-remainder byte budget.
/// Bounded per principal (<see cref="MaxSessionsPerPrincipal"/>; past it the principal's own least-recently-used
/// session is evicted) and globally (<see cref="MaxSessions"/>; past it the oldest session of the principal holding the
/// most is evicted), so one principal cannot evict another's sessions while it stays within its own cap.
/// </summary>
internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions = 4096)
internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions = 4096, int maxSessionsPerPrincipal = 64)
{
private readonly Lock _gate = new();
private readonly Dictionary<string, (OriginHistorySession Session, long Used)> _sessions = new(StringComparer.Ordinal);
private readonly Dictionary<string, int> _inFlight = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, long> _retained = new(StringComparer.OrdinalIgnoreCase);
public int MaxSessions { get; } = maxSessions;
public int MaxSessionsPerPrincipal { get; } = maxSessionsPerPrincipal;
private static string Key(DataAuthenticatedContext caller, DataHistoryChannel channel) =>
string.Join('\0', caller.PrincipalId.ToUpperInvariant(), caller.ApiKeyId, caller.CredentialVersion, channel.ChannelId);
/// <summary>The existing session of a channel, or null (a release never creates one).</summary>
public OriginHistorySession? TryGet(DataAuthenticatedContext caller, DataHistoryChannel channel)
{
lock (_gate) return _sessions.TryGetValue(Key(caller, channel), out var existing) ? existing.Session : null;
}
/// <summary>The session of one channel, created on first use and cleared when <see cref="DataHistoryChannel.Closed"/> fires.</summary>
public OriginHistorySession Get(DataAuthenticatedContext caller, DataHistoryChannel channel, int capacity)
{
var key = string.Join('\0', caller.PrincipalId.ToUpperInvariant(), caller.ApiKeyId, caller.CredentialVersion, channel.ChannelId);
OriginHistorySession? evicted = null;
var key = Key(caller, channel);
var evicted = new List<OriginHistorySession>();
OriginHistorySession session;
var created = false;
lock (_gate)
{
if (_sessions.TryGetValue(key, out var existing) && existing.Session.Capacity == capacity)
@@ -113,26 +160,62 @@ internal sealed class OriginHistorySessions(TimeProvider clock, int maxSessions
_sessions[key] = (existing.Session, clock.GetTimestamp());
return existing.Session;
}
if (_sessions.Remove(key, out var resized)) evicted = resized.Session;
else if (_sessions.Count >= maxSessions)
if (_sessions.Remove(key, out var resized)) evicted.Add(resized.Session);
var own = _sessions.Where(x => string.Equals(x.Value.Session.Principal, caller.PrincipalId, StringComparison.OrdinalIgnoreCase)).ToList();
while (own.Count >= MaxSessionsPerPrincipal)
{
var oldest = _sessions.MinBy(x => x.Value.Used);
var oldest = own.MinBy(x => x.Value.Used);
own.Remove(oldest);
_sessions.Remove(oldest.Key);
evicted = oldest.Value.Session;
evicted.Add(oldest.Value.Session);
}
session = new OriginHistorySession(caller.PrincipalId, channel.ChannelId, capacity, clock);
if (_sessions.Count >= MaxSessions)
{
// The principal holding the most sessions pays (never one within its cap while another exceeds the average).
var heaviest = _sessions.GroupBy(x => x.Value.Session.Principal, StringComparer.OrdinalIgnoreCase)
.MaxBy(g => g.Count())!.MinBy(x => x.Value.Used);
_sessions.Remove(heaviest.Key);
evicted.Add(heaviest.Value.Session);
}
session = new OriginHistorySession(this, caller.PrincipalId, channel.ChannelId, capacity, clock);
_sessions[key] = (session, clock.GetTimestamp());
created = true;
}
evicted?.Clear();
if (created && channel.Closed.CanBeCanceled)
channel.Closed.Register(() => Close(key, session));
foreach (var old in evicted) old.Clear();
if (channel.Closed.CanBeCanceled) session.Bind(channel.Closed.Register(() => Close(key, session)));
return session;
}
/// <summary>Live sessions (diagnostics/tests).</summary>
public int Count { get { lock (_gate) return _sessions.Count; } }
/// <summary>Remainder bytes retained for <paramref name="principal"/> across its sessions.</summary>
public long RetainedBytes(string principal) { lock (_gate) return _retained.GetValueOrDefault(principal); }
/// <summary>Reserves remainder bytes against the principal's budget; false when it would be exceeded.</summary>
public bool TryReserve(string principal, long bytes, long budget)
{
if (bytes <= 0) return true;
lock (_gate)
{
var current = _retained.GetValueOrDefault(principal);
if (current + bytes > budget) return false;
_retained[principal] = current + bytes;
return true;
}
}
/// <summary>Returns reserved remainder bytes.</summary>
public void ReleaseBytes(string principal, long bytes)
{
if (bytes <= 0) return;
lock (_gate)
{
var left = _retained.GetValueOrDefault(principal) - bytes;
if (left > 0) _retained[principal] = left;
else _retained.Remove(principal);
}
}
/// <summary>Admits one history request of <paramref name="principal"/>; false past <paramref name="limit"/>.</summary>
public bool TryAdmit(string principal, int limit)
{