Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/WriteOperationRegistry.cs
T

192 lines
9.0 KiB
C#

using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
public enum WriteClaimKind { Owner, Existing, Conflict, Stale, Capacity }
public sealed record WriteClaimResult(WriteClaimKind Kind, WriteClaim? Claim = null);
/// <summary>Bounded, incarnation-local duplicate protection. Payload storage is owned by the executor.</summary>
public sealed class WriteOperationRegistry
{
private readonly object _gate = new();
private readonly Dictionary<(string Principal, string Operation), Entry> _entries = new(new KeyComparer());
// Retained entries per principal (case-insensitive like the key), so one principal cannot exhaust the global table.
private readonly Dictionary<string, int> _perPrincipal = new(StringComparer.OrdinalIgnoreCase);
private readonly string _incarnation;
private readonly int _maxEntries;
private readonly int _maxEntriesPerPrincipal;
private readonly long _maxBytes;
private readonly TimeSpan _retention;
private readonly TimeProvider _clock;
private long _retainedBytes;
/// <param name="maxEntriesPerPrincipal">
/// A2b security review: the most entries one principal may hold at once (null ⇒ <paramref name="maxEntries"/>, i.e.
/// only the global cap). Past it that principal's claims answer <see cref="WriteClaimKind.Capacity"/> while other
/// principals are still admitted.
/// </param>
public WriteOperationRegistry(string servingIncarnation, int maxEntries, long maxRetainedBytes,
TimeSpan retention, TimeProvider? clock = null, int? maxEntriesPerPrincipal = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation);
if (maxEntries <= 0 || maxRetainedBytes <= 0 || retention <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(maxEntries));
if (maxEntriesPerPrincipal is <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntriesPerPrincipal));
_incarnation = servingIncarnation;
_maxEntries = maxEntries;
_maxEntriesPerPrincipal = Math.Min(maxEntriesPerPrincipal ?? maxEntries, maxEntries);
_maxBytes = maxRetainedBytes;
_retention = retention;
_clock = clock ?? TimeProvider.System;
}
public WriteClaimResult Claim(string principal, string operationId, string expectedServingIncarnation,
ReadOnlyMemory<byte> semanticHash)
{
ArgumentException.ThrowIfNullOrWhiteSpace(principal);
ArgumentException.ThrowIfNullOrWhiteSpace(operationId);
ArgumentException.ThrowIfNullOrWhiteSpace(expectedServingIncarnation);
if (semanticHash.Length != 32) throw new ArgumentException("A SHA-256 hash is required.", nameof(semanticHash));
if (!StringComparer.Ordinal.Equals(_incarnation, expectedServingIncarnation)) return new(WriteClaimKind.Stale);
var bytes = 256L + 2L * principal.Length + 2L * operationId.Length + semanticHash.Length;
lock (_gate)
{
Prune();
var key = (principal, operationId);
if (_entries.TryGetValue(key, out var existing))
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
_perPrincipal.TryGetValue(principal, out var held);
if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
return new(WriteClaimKind.Capacity);
var claim = new WriteClaim(_clock);
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
_perPrincipal[principal] = held + 1;
_retainedBytes += bytes;
return new(WriteClaimKind.Owner, claim);
}
}
/// <summary>
/// A2b security review: forgets an entry whose operation was refused BEFORE dispatch (nothing applied), so a refusal
/// retains no capacity. Only removes <paramref name="claim"/> itself, and only once it has completed undispatched;
/// a joiner already waiting on it still receives its outcome. A later call with the same id is a fresh owner.
/// </summary>
/// <returns>True when the entry was removed.</returns>
public bool ReleaseUndispatched(string principal, string operationId, WriteClaim claim)
{
ArgumentNullException.ThrowIfNull(claim);
if (!claim.IsCompletedUndispatched) return false;
lock (_gate)
{
var key = (principal, operationId);
if (!_entries.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Claim, claim)) return false;
Remove(key, entry);
return true;
}
}
/// <summary>Test seam: the entries currently retained (all principals).</summary>
internal int CountForTests { get { lock (_gate) return _entries.Count; } }
private void Remove((string Principal, string Operation) key, Entry entry)
{
_entries.Remove(key);
_retainedBytes -= entry.Bytes;
if (_perPrincipal.TryGetValue(key.Principal, out var held))
{
if (held <= 1) _perPrincipal.Remove(key.Principal);
else _perPrincipal[key.Principal] = held - 1;
}
}
private void Prune()
{
var now = _clock.GetTimestamp();
foreach (var pair in _entries.ToArray())
{
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
Remove(pair.Key, pair.Value);
}
}
private sealed record Entry(byte[] Hash, WriteClaim Claim, long Bytes);
private sealed class KeyComparer : IEqualityComparer<(string Principal, string Operation)>
{
public bool Equals((string Principal, string Operation) x, (string Principal, string Operation) y) =>
StringComparer.OrdinalIgnoreCase.Equals(x.Principal, y.Principal) &&
StringComparer.Ordinal.Equals(x.Operation, y.Operation);
public int GetHashCode((string Principal, string Operation) key) =>
HashCode.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(key.Principal),
StringComparer.Ordinal.GetHashCode(key.Operation));
}
}
/// <summary>One shared operation. Dispatch and rejection compete through a lock-free transition.</summary>
public sealed class WriteClaim
{
// 0 pending, 1 dispatched, 2/3 completing before/after dispatch, 4/5 completed before/after dispatch.
private int _state;
private int _physicalFinished;
private long _completedTimestamp;
private readonly TimeProvider _clock;
private readonly object _outcomeGate = new();
private DataWriteOutcome? _outcome;
private readonly TaskCompletionSource<DataWriteOutcome> _completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal WriteClaim(TimeProvider clock) => _clock = clock;
public Task<DataWriteOutcome> Completion => _completion.Task;
public bool IsDispatched => Volatile.Read(ref _state) is 1 or 3 or 5;
public DataWriteOutcome? CurrentOutcome => Volatile.Read(ref _outcome);
/// <summary>Completed as rejected before dispatch (state 4): nothing was applied.</summary>
public bool IsCompletedUndispatched => Volatile.Read(ref _state) == 4;
public bool TryMarkDispatched() => Interlocked.CompareExchange(ref _state, 1, 0) == 0;
public bool Complete(DataWriteOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
outcome.Validate();
while (true)
{
var state = Volatile.Read(ref _state);
if (state is not (0 or 1)) return false;
if ((state == 0) != (outcome.State == DataWriteState.RejectedBeforeDispatch)) return false;
if (Interlocked.CompareExchange(ref _state, state + 2, state) != state) continue;
lock (_outcomeGate)
{
Volatile.Write(ref _outcome, outcome);
_completedTimestamp = _clock.GetTimestamp();
Volatile.Write(ref _state, state + 4);
_completion.TrySetResult(outcome);
}
return true;
}
}
public bool LateRefine(DataWriteOutcome outcome)
{
ArgumentNullException.ThrowIfNull(outcome);
outcome.Validate();
if (outcome.State is not (DataWriteState.DriverConfirmedSuccess or DataWriteState.DriverConfirmedFailure)) return false;
lock (_outcomeGate)
{
if (_outcome?.State is not (DataWriteState.OutcomeUnknown or DataWriteState.AcceptedUnconfirmed)) return false;
Volatile.Write(ref _completedTimestamp, _clock.GetTimestamp());
Volatile.Write(ref _outcome, outcome);
return true;
}
}
internal void PhysicalFinished() => Volatile.Write(ref _physicalFinished, 1);
internal bool CanRetire(long now, TimeSpan retention)
{
var state = Volatile.Read(ref _state);
return state is 4 or 5 && (state == 4 || Volatile.Read(ref _physicalFinished) != 0)
&& _clock.GetElapsedTime(Volatile.Read(ref _completedTimestamp), now) >= retention;
}
}