Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/PeerHistoryContinuationStore.cs
T

298 lines
16 KiB
C#

using System.Security.Cryptography;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
/// <summary>
/// Everything a peer continuation is bound to (plan §3.2): the authenticated principal, the serving incarnation
/// (an origin restart or failover changes it), the history epoch (a rebuild/removal bumps it), the view
/// <c>(realm, identifier)</c> and the hash of the request details.
/// </summary>
/// <param name="Principal">The authenticated principal of the connection.</param>
/// <param name="ServingIncarnation">The serving incarnation CURRENT when the cursor was issued (or, on a take, now).</param>
/// <param name="Epoch">The history (address-space) epoch.</param>
/// <param name="Realm">The view's realm.</param>
/// <param name="Identifier">The view's identifier.</param>
/// <param name="BindingTag">The view's binding tag (<see cref="HistoryReadPortItem.BindingTag"/>).</param>
/// <param name="DetailsHash">The <see cref="HistoryReadVariant.ComputeDetailsHash"/> of the request.</param>
internal readonly record struct PeerHistoryContinuationKey(
string Principal, string ServingIncarnation, long Epoch, AddressSpaceRealm Realm, string Identifier, string? BindingTag, string DetailsHash);
/// <summary>
/// The ORIGIN-side store for remote peers' HistoryRead continuation points (gRPC data history plan §3.2, phase H1;
/// wired to the RPC by H2). One instance per (authenticated principal, connection incarnation), so no peer can ever
/// reach another's cursors (H2 must <see cref="Clear"/> it when the connection closes); unlike the SDK session store (<see cref="SessionHistoryContinuationStore"/>) there is no
/// session to own the points, so this store owns lifetime itself.
/// <list type="bullet">
/// <item><b>Token:</b> a fresh random 16-byte id (<see cref="RandomNumberGenerator"/>). Unguessable, so no MAC is needed; it
/// carries nothing — the state stays here.</item>
/// <item><b>Binding:</b> each record binds the CALLER's principal and the serving incarnation current at save (both
/// supplied by the caller — <see cref="PeerHistoryContinuationScope"/> reads the incarnation live, so an in-process
/// failover or role change on a still-open connection invalidates its tokens), the history epoch, the view and the
/// details hash; a take whose expected <see cref="PeerHistoryContinuationKey"/> differs in ANY of them is a miss
/// (<c>BadContinuationPointInvalid</c> at the port). A save for a principal other than the owner is refused.</item>
/// <item><b>Single-use:</b> a take removes the record whether or not it matches, so a page lost in transit makes the
/// client's resume fail rather than silently skipping a page, and a token can never be replayed.</item>
/// <item><b>Idle expiry:</b> a record not taken within <see cref="IdleExpiry"/> (default 60 s, matching v1 browse
/// continuations) is gone — the backstop for a consumer that never resumes or releases.</item>
/// <item><b>Capacity:</b> at most <see cref="Capacity"/> live records (the export limit). Saving past it evicts the
/// <b>oldest-idle</b> record — the one saved longest ago, since a record is never touched between its save and its
/// (single-use) take — after expired ones are swept. Eviction is silent; the evicted token's resume is a miss.</item>
/// </list>
/// Thread-safe; every operation is O(1) amortised under one short lock, and no I/O ever runs under it.
/// </summary>
internal sealed class PeerHistoryContinuationStore
{
/// <summary>The default idle expiry (60 s, as v1 browse continuations).</summary>
public static readonly TimeSpan DefaultIdleExpiry = TimeSpan.FromSeconds(60);
/// <summary>The token length in bytes.</summary>
public const int TokenLength = 16;
private readonly Lock _gate = new();
private readonly Dictionary<Guid, LinkedListNode<Entry>> _entries = new();
private readonly LinkedList<Entry> _byAge = new(); // oldest save first == oldest idle first
private readonly TimeProvider _clock;
/// <summary>Creates the store of one (principal, connection incarnation).</summary>
/// <param name="principal">The authenticated principal that owns the connection.</param>
/// <param name="connectionIncarnation">The connection's own incarnation (identity only; never a binding).</param>
/// <param name="capacity">The export limit on concurrent continuations (≥ 1).</param>
/// <param name="idleExpiry">Idle expiry; null = <see cref="DefaultIdleExpiry"/>. Must be positive.</param>
/// <param name="clock">Clock (tests inject a fake); null = system.</param>
public PeerHistoryContinuationStore(
string principal, string connectionIncarnation, int capacity, TimeSpan? idleExpiry = null, TimeProvider? clock = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
ArgumentException.ThrowIfNullOrWhiteSpace(connectionIncarnation);
ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 1);
var idle = idleExpiry ?? DefaultIdleExpiry;
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(idle, TimeSpan.Zero, nameof(idleExpiry));
Principal = principal;
ConnectionIncarnation = connectionIncarnation;
Capacity = capacity;
IdleExpiry = idle;
_clock = clock ?? TimeProvider.System;
}
/// <summary>The principal this instance serves.</summary>
public string Principal { get; }
/// <summary>
/// The connection's incarnation — IDENTITY ONLY (which connection this store belongs to, for diagnostics and H2's
/// per-connection bookkeeping). It is never part of a binding: the serving incarnation a cursor binds is supplied per
/// request by <see cref="PeerHistoryContinuationScope"/>.
/// </summary>
public string ConnectionIncarnation { get; }
/// <summary>The most live records.</summary>
public int Capacity { get; }
/// <summary>How long an untaken record lives.</summary>
public TimeSpan IdleExpiry { get; }
/// <summary>Live (unexpired) records — H3's "origin store count returns to 0" check reads it.</summary>
public int Count
{
get
{
lock (_gate)
{
Sweep(_clock.GetTimestamp());
return _entries.Count;
}
}
}
/// <summary>
/// Stores <paramref name="state"/> under a fresh token, bound to the calling <paramref name="principal"/>, the
/// <paramref name="servingIncarnation"/> current now, the state's own epoch and view
/// (<see cref="HistoryContinuationState.BoundRealm"/> / <see cref="HistoryContinuationState.BoundIdentifier"/>, set by
/// the port) and <paramref name="detailsHash"/>.
/// </summary>
/// <param name="state">The bound resume state.</param>
/// <param name="principal">The caller's authenticated principal; must be this store's owner.</param>
/// <param name="servingIncarnation">The serving incarnation current at save.</param>
/// <param name="detailsHash">The request's details hash.</param>
/// <returns>The 16-byte token.</returns>
/// <exception cref="ArgumentException">An unbound state.</exception>
/// <exception cref="PeerHistoryContinuationWiringException">A principal other than the owner, or a blank incarnation.</exception>
public byte[] Save(HistoryContinuationState state, string principal, string servingIncarnation, string detailsHash)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(detailsHash);
if (state.BoundIdentifier is null)
throw new ArgumentException("A peer continuation must be bound to its view.", nameof(state));
if (string.IsNullOrWhiteSpace(servingIncarnation))
throw new PeerHistoryContinuationWiringException("A peer continuation needs the serving incarnation it is issued under.");
if (!string.Equals(principal, Principal, StringComparison.Ordinal))
throw new PeerHistoryContinuationWiringException("A peer continuation store holds only its owning principal's cursors.");
var token = RandomNumberGenerator.GetBytes(TokenLength);
var key = new PeerHistoryContinuationKey(
principal, servingIncarnation, state.AddressSpaceEpoch, state.BoundRealm, state.BoundIdentifier, state.BoundTag, detailsHash);
lock (_gate)
{
var now = _clock.GetTimestamp();
Sweep(now);
while (_entries.Count >= Capacity && _byAge.First is { } oldest) Remove(oldest);
var id = new Guid(token);
_entries[id] = _byAge.AddLast(new Entry(id, key, state, now));
}
return token;
}
/// <summary>
/// Takes (removes) the record behind <paramref name="token"/> and returns its state when it is live and every bound
/// field equals <paramref name="expected"/>; otherwise null. The record is consumed either way.
/// </summary>
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">What the resume must match.</param>
/// <returns>The state, or null (unknown, expired, evicted, malformed or mismatched).</returns>
public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) =>
TryTake(token, () => expected);
/// <summary>
/// <see cref="TryTake(byte[], PeerHistoryContinuationKey)"/> with the expectation computed only AFTER the record is
/// consumed: if <paramref name="expected"/> throws (the incarnation source is down), the token is already gone and the
/// take is a miss — never a token left replayable.
/// </summary>
/// <param name="token">The token the peer handed back.</param>
/// <param name="expected">Computes what the resume must match.</param>
/// <returns>The state, or null.</returns>
public HistoryContinuationState? TryTake(byte[]? token, Func<PeerHistoryContinuationKey> expected)
{
ArgumentNullException.ThrowIfNull(expected);
if (token is not { Length: TokenLength }) return null;
Entry taken;
lock (_gate)
{
var now = _clock.GetTimestamp();
Sweep(now);
if (!_entries.TryGetValue(new Guid(token), out var node)) return null;
Remove(node);
taken = node.Value;
}
try
{
return taken.Key == expected() ? taken.State : null;
}
catch (Exception)
{
return null; // consumed, unverifiable ⇒ a miss (BadContinuationPointInvalid at the port)
}
}
/// <summary>Whether <paramref name="token"/> names a live (unexpired) record (diagnostics: de-duplicating open continuations).</summary>
public bool Contains(byte[]? token)
{
if (token is not { Length: TokenLength }) return false;
lock (_gate)
{
Sweep(_clock.GetTimestamp());
return _entries.ContainsKey(new Guid(token));
}
}
/// <summary>Drops a record without reading it (<c>release_continuations</c>). Idempotent.</summary>
/// <param name="token">The token to release.</param>
/// <returns>Whether a live record was dropped.</returns>
public bool Release(byte[]? token)
{
if (token is not { Length: TokenLength }) return false;
lock (_gate)
{
if (!_entries.TryGetValue(new Guid(token), out var node)) return false;
Remove(node);
return true;
}
}
/// <summary>Drops every record (the connection closed).</summary>
public void Clear()
{
lock (_gate)
{
_entries.Clear();
_byAge.Clear();
}
}
private void Sweep(long now)
{
while (_byAge.First is { } oldest && _clock.GetElapsedTime(oldest.Value.SavedAt, now) >= IdleExpiry) Remove(oldest);
}
private void Remove(LinkedListNode<Entry> node)
{
_entries.Remove(node.Value.Id);
_byAge.Remove(node);
}
private sealed record Entry(Guid Id, PeerHistoryContinuationKey Key, HistoryContinuationState State, long SavedAt);
}
/// <summary>
/// A peer continuation store or scope was wired wrongly — a scope for a principal the store does not belong to, or a
/// serving-incarnation source that is blank or throws. A server fault, not a property of the request: the port answers
/// <c>BadInternalError</c> for the node (never <c>BadHistoryOperationUnsupported</c>), and H2 must surface it distinctly.
/// </summary>
internal sealed class PeerHistoryContinuationWiringException : InvalidOperationException
{
/// <summary>Creates the exception.</summary>
/// <param name="message">What is miswired.</param>
/// <param name="inner">The incarnation source's own failure, if any.</param>
public PeerHistoryContinuationWiringException(string message, Exception? inner = null) : base(message, inner) { }
}
/// <summary>
/// The port's continuation scope for one remote peer's ONE request (create a new scope per <c>ReadHistory</c> call):
/// saves and takes through that peer's <see cref="PeerHistoryContinuationStore"/>, binding the caller's principal, the
/// request's details hash and the serving incarnation, on top of the view and epoch the port itself re-checks.
/// <para>
/// The serving incarnation is read from <paramref name="currentServingIncarnation"/> ONCE, at the scope's first use,
/// and that snapshot is used for every take and save of the request: a request resumed under incarnation A binds its
/// next token to A even when a failover lands mid-request (the resume under B then fails
/// <c>BadContinuationPointInvalid</c>), and a later request reads the then-current incarnation, so an in-process
/// failover or role change on a still-open connection invalidates the connection's tokens. A take whose snapshot
/// cannot be read (blank / throwing source) is a miss with the token consumed; a save is a
/// <see cref="PeerHistoryContinuationWiringException"/>. Save never answers <c>null</c> (that would read as a
/// complete read and truncate).
/// </para>
/// </summary>
/// <param name="store">The (principal, connection) store.</param>
/// <param name="principal">The caller's authenticated principal.</param>
/// <param name="currentServingIncarnation">Reads this server's serving incarnation now.</param>
internal sealed class PeerHistoryContinuationScope(
PeerHistoryContinuationStore store, string principal, Func<string> currentServingIncarnation) : IHistoryContinuationScope
{
private readonly Lazy<string> _incarnation = new(() =>
{
string value;
try
{
value = currentServingIncarnation();
}
catch (Exception ex)
{
throw new PeerHistoryContinuationWiringException("The serving-incarnation source failed.", ex);
}
return string.IsNullOrWhiteSpace(value)
? throw new PeerHistoryContinuationWiringException("The serving-incarnation source answered a blank incarnation.")
: value;
}, LazyThreadSafetyMode.ExecutionAndPublication);
/// <inheritdoc />
public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) =>
store.Save(state, principal, _incarnation.Value, binding.Details?.ComputeDetailsHash() ?? string.Empty);
/// <inheritdoc />
public HistoryContinuationState? TryTake(byte[] continuationPoint, HistoryContinuationBinding binding) =>
store.TryTake(continuationPoint, () => new PeerHistoryContinuationKey(
principal, _incarnation.Value, binding.Epoch, binding.Realm, binding.Identifier, binding.Tag,
binding.Details?.ComputeDetailsHash() ?? string.Empty));
}