using System.Security.Cryptography; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// /// 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 /// (realm, identifier) and the hash of the request details. /// /// The authenticated principal of the connection. /// The serving incarnation CURRENT when the cursor was issued (or, on a take, now). /// The history (address-space) epoch. /// The view's realm. /// The view's identifier. /// The view's binding tag (). /// The of the request. internal readonly record struct PeerHistoryContinuationKey( string Principal, string ServingIncarnation, long Epoch, AddressSpaceRealm Realm, string Identifier, string? BindingTag, string DetailsHash); /// /// 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 it when the connection closes); unlike the SDK session store () there is no /// session to own the points, so this store owns lifetime itself. /// /// Token: a fresh random 16-byte id (). Unguessable, so no MAC is needed; it /// carries nothing — the state stays here. /// Binding: each record binds the CALLER's principal and the serving incarnation current at save (both /// supplied by the caller — 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 differs in ANY of them is a miss /// (BadContinuationPointInvalid at the port). A save for a principal other than the owner is refused. /// Single-use: 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. /// Idle expiry: a record not taken within (default 60 s, matching v1 browse /// continuations) is gone — the backstop for a consumer that never resumes or releases. /// Capacity: at most live records (the export limit). Saving past it evicts the /// oldest-idle 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. /// /// Thread-safe; every operation is O(1) amortised under one short lock, and no I/O ever runs under it. /// internal sealed class PeerHistoryContinuationStore { /// The default idle expiry (60 s, as v1 browse continuations). public static readonly TimeSpan DefaultIdleExpiry = TimeSpan.FromSeconds(60); /// The token length in bytes. public const int TokenLength = 16; private readonly Lock _gate = new(); private readonly Dictionary> _entries = new(); private readonly LinkedList _byAge = new(); // oldest save first == oldest idle first private readonly TimeProvider _clock; /// Creates the store of one (principal, connection incarnation). /// The authenticated principal that owns the connection. /// The connection's own incarnation (identity only; never a binding). /// The export limit on concurrent continuations (≥ 1). /// Idle expiry; null = . Must be positive. /// Clock (tests inject a fake); null = system. 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; } /// The principal this instance serves. public string Principal { get; } /// /// 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 . /// public string ConnectionIncarnation { get; } /// The most live records. public int Capacity { get; } /// How long an untaken record lives. public TimeSpan IdleExpiry { get; } /// Live (unexpired) records — H3's "origin store count returns to 0" check reads it. public int Count { get { lock (_gate) { Sweep(_clock.GetTimestamp()); return _entries.Count; } } } /// /// Stores under a fresh token, bound to the calling , the /// current now, the state's own epoch and view /// ( / , set by /// the port) and . /// /// The bound resume state. /// The caller's authenticated principal; must be this store's owner. /// The serving incarnation current at save. /// The request's details hash. /// The 16-byte token. /// An unbound state. /// A principal other than the owner, or a blank incarnation. 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; } /// /// Takes (removes) the record behind and returns its state when it is live and every bound /// field equals ; otherwise null. The record is consumed either way. /// /// The token the peer handed back. /// What the resume must match. /// The state, or null (unknown, expired, evicted, malformed or mismatched). public HistoryContinuationState? TryTake(byte[]? token, PeerHistoryContinuationKey expected) => TryTake(token, () => expected); /// /// with the expectation computed only AFTER the record is /// consumed: if throws (the incarnation source is down), the token is already gone and the /// take is a miss — never a token left replayable. /// /// The token the peer handed back. /// Computes what the resume must match. /// The state, or null. public HistoryContinuationState? TryTake(byte[]? token, Func 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) } } /// Whether names a live (unexpired) record (diagnostics: de-duplicating open continuations). public bool Contains(byte[]? token) { if (token is not { Length: TokenLength }) return false; lock (_gate) { Sweep(_clock.GetTimestamp()); return _entries.ContainsKey(new Guid(token)); } } /// Drops a record without reading it (release_continuations). Idempotent. /// The token to release. /// Whether a live record was dropped. 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; } } /// Drops every record (the connection closed). 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 node) { _entries.Remove(node.Value.Id); _byAge.Remove(node); } private sealed record Entry(Guid Id, PeerHistoryContinuationKey Key, HistoryContinuationState State, long SavedAt); } /// /// 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 /// BadInternalError for the node (never BadHistoryOperationUnsupported), and H2 must surface it distinctly. /// internal sealed class PeerHistoryContinuationWiringException : InvalidOperationException { /// Creates the exception. /// What is miswired. /// The incarnation source's own failure, if any. public PeerHistoryContinuationWiringException(string message, Exception? inner = null) : base(message, inner) { } } /// /// The port's continuation scope for one remote peer's ONE request (create a new scope per ReadHistory call): /// saves and takes through that peer's , 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. /// /// The serving incarnation is read from 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 /// BadContinuationPointInvalid), 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 /// . Save never answers null (that would read as a /// complete read and truncate). /// /// /// The (principal, connection) store. /// The caller's authenticated principal. /// Reads this server's serving incarnation now. internal sealed class PeerHistoryContinuationScope( PeerHistoryContinuationStore store, string principal, Func currentServingIncarnation) : IHistoryContinuationScope { private readonly Lazy _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); /// public byte[]? Save(HistoryContinuationState state, HistoryContinuationBinding binding) => store.Save(state, principal, _incarnation.Value, binding.Details?.ComputeDetailsHash() ?? string.Empty); /// 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)); }