fix(grpc-data): A2b security review — outcome-unknown after dispatch, per-principal registry cap, audit category + sanitising, monotonic activation sequence, bounded Lock wait, consumer cancel = OutcomeUnknown
This commit is contained in:
@@ -21,6 +21,10 @@ public sealed class DataConnectionOptions
|
||||
public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024;
|
||||
public long MaxPendingBytes { get; set; } = 1024 * 1024;
|
||||
public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1);
|
||||
/// <summary>A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals).</summary>
|
||||
public int MaxConditionMethodOperations { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalDataServices.DefaultConditionMethodMaxOperations;
|
||||
/// <summary>A2b security review: the same, per principal (≤ <see cref="MaxConditionMethodOperations"/>).</summary>
|
||||
public int MaxConditionMethodOperationsPerPrincipal { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal;
|
||||
public ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataResourceLimits Hub { get; set; } = new();
|
||||
public TimeSpan UnaryTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
public TimeSpan StreamCommandTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
@@ -36,6 +36,9 @@ public sealed class DataConnectionOptionsValidator(IHostEnvironment environment)
|
||||
|| options.Hub is null || options.BundleRefreshInterval < TimeSpan.FromMilliseconds(100)
|
||||
|| options.BundleRefreshInterval > TimeSpan.FromMinutes(1))
|
||||
errors.Add("Data-plane retained work and refresh limits are invalid.");
|
||||
if (options.MaxConditionMethodOperations is < 1 or > 65_536 || options.MaxConditionMethodOperationsPerPrincipal < 1
|
||||
|| options.MaxConditionMethodOperationsPerPrincipal > options.MaxConditionMethodOperations)
|
||||
errors.Add("Condition-method operation limits must be 1..65536, with the per-principal limit no larger than the total.");
|
||||
if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5)
|
||||
|| options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1))
|
||||
errors.Add("Unary and stream-command timeouts must be finite and within supported limits.");
|
||||
|
||||
@@ -39,6 +39,7 @@ public static class DataConnectionRegistration
|
||||
services.TryAddSingleton<TimeProvider>(TimeProvider.System);
|
||||
services.TryAddSingleton<DataWriteDispatchFence>();
|
||||
services.TryAddSingleton<DataConnectionWarmRoleView>();
|
||||
AddDataConnectionAuditLog(services);
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var role = sp.GetRequiredService<IClusterRoleInfo>();
|
||||
@@ -176,12 +177,15 @@ public static class DataConnectionRegistration
|
||||
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataWriteRuntime>(), host,
|
||||
sp.GetRequiredService<SubscriptionAcquisitionCapacity>(), new(4096, options.Hub.MaxTrackedSources,
|
||||
options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes,
|
||||
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)),
|
||||
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5),
|
||||
options.MaxConditionMethodOperations, options.MaxConditionMethodOperationsPerPrincipal),
|
||||
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
|
||||
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp),
|
||||
sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
|
||||
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
|
||||
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()));
|
||||
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()),
|
||||
// A2b security review: the audit trail on its OWN category from the host's logger factory.
|
||||
sp.GetRequiredService<IDataConnectionAuditLog>());
|
||||
});
|
||||
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
|
||||
services.AddSingleton<DataConnectionSecretChangeHandler>();
|
||||
@@ -276,6 +280,15 @@ public static class DataConnectionRegistration
|
||||
Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(logger, "{Reason}", keys.UnavailableReason);
|
||||
return keys;
|
||||
}
|
||||
/// <summary>
|
||||
/// A2b security review: registers the data-connection audit log — a logger of
|
||||
/// <see cref="LoggerDataConnectionAuditLog.Category"/> created from the host's REAL <c>ILoggerFactory</c> (no factory ⇒ no
|
||||
/// output), so operators can route the audit trail by category. A test or host may register its own first.
|
||||
/// </summary>
|
||||
internal static void AddDataConnectionAuditLog(IServiceCollection services) =>
|
||||
services.TryAddSingleton<IDataConnectionAuditLog>(sp =>
|
||||
LoggerDataConnectionAuditLog.Create(sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()));
|
||||
|
||||
private static Microsoft.Extensions.Logging.ILogger LoggerFor<T>(IServiceProvider sp) =>
|
||||
(Microsoft.Extensions.Logging.ILogger?)sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<T>()
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
@@ -36,5 +36,11 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer
|
||||
/// <inheritdoc />
|
||||
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) =>
|
||||
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call)
|
||||
: throw new InvalidOperationException("The OPC UA server is not running.");
|
||||
: throw new OriginConditionSourceUnavailableException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2b security review: the ONE exception a condition method port throws that proves nothing was dispatched — the OPC
|
||||
/// UA server (and so the node manager) is not running. Any other exception from the port means the outcome is unknown.
|
||||
/// </summary>
|
||||
public sealed class OriginConditionSourceUnavailableException() : InvalidOperationException("The OPC UA server is not running.");
|
||||
|
||||
@@ -52,47 +52,69 @@ public sealed partial class OtOpcUaNodeManager
|
||||
ArgumentNullException.ThrowIfNull(call);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.ConditionId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.Principal);
|
||||
lock (Lock)
|
||||
// Security review: a remote caller never waits on Lock without bound (a long rebuild or a stalled holder would
|
||||
// otherwise pin one gRPC worker per call). Not acquired ⇒ refused before ANY state change.
|
||||
var lockTaken = false;
|
||||
try
|
||||
{
|
||||
var key = MapKey(call.Realm, call.ConditionId);
|
||||
if (!_alarmConditions.TryGetValue(key, out var alarm))
|
||||
return Refused(false, StatusCodes.BadNodeIdUnknown, "The condition is not materialised.");
|
||||
var native = _nativeAlarmNodeIds.Contains(key);
|
||||
|
||||
if (_standby.RefusesMutations)
|
||||
return RefusedBy(native, WarmStandbyState.StandbyRefusal($"call {call.Method}"));
|
||||
if (NativeAlarmAckPrimaryGate is { } primary && !primary())
|
||||
return Refused(native, StatusCodes.BadInvalidState, "This server is not the redundancy Primary.");
|
||||
|
||||
MethodState? method = call.Method switch
|
||||
{
|
||||
"Acknowledge" => alarm.Acknowledge,
|
||||
"AddComment" => alarm.AddComment,
|
||||
"Confirm" when !native => alarm.Confirm,
|
||||
_ => null,
|
||||
};
|
||||
if (method is null) return Refused(native, StatusCodes.BadNotSupported, "The condition does not support this method.");
|
||||
|
||||
// T3: the marker moves only on a new occurrence; an unchanged re-projection keeps the caller's EventIds valid.
|
||||
var current = _activation.TryGetValue(key, out var entry) ? entry.Sequence : 0UL;
|
||||
if (!string.Equals(call.ExpectedActivation.Incarnation, ConditionIncarnation, StringComparison.Ordinal)
|
||||
|| call.ExpectedActivation.Sequence != current)
|
||||
return Refused(native, StatusCodes.BadEventIdUnknown, "The condition has a newer occurrence.");
|
||||
|
||||
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = call.Principal }, [],
|
||||
principal: call.Principal, apiKeyId: call.ApiKeyId);
|
||||
var context = new RemoteConditionMethodContext(Server, alarm, identity);
|
||||
var eventId = alarm.EventId?.Value ?? default;
|
||||
var comment = call.Comment is null ? default : new LocalizedText(call.Comment);
|
||||
var result = method switch
|
||||
{
|
||||
AddCommentMethodState { OnCall: { } onCall } m => onCall(context, m, alarm.NodeId, eventId, comment),
|
||||
_ => new ServiceResult(StatusCodes.BadNotSupported),
|
||||
};
|
||||
return ServiceResult.IsGood(result)
|
||||
? new OriginConditionMethodOutcome(true, native, StatusCodes.Good.Code, null)
|
||||
: RefusedBy(native, result);
|
||||
Monitor.TryEnter(Lock, ConditionMethodLockTimeout, ref lockTaken);
|
||||
if (!lockTaken)
|
||||
return Refused(false, StatusCodes.BadTimeout, "The node manager is busy; the condition method was not applied.");
|
||||
return TryExecuteConditionMethodLocked(call);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockTaken) Monitor.Exit(Lock);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How long a remote condition method waits for the node manager's <c>Lock</c> before it is refused
|
||||
/// (<c>BadTimeout</c>, nothing applied). Default 5 s — the consumer's default <c>ConditionMethodTimeoutMilliseconds</c>,
|
||||
/// after which the caller has given up anyway.
|
||||
/// </summary>
|
||||
internal TimeSpan ConditionMethodLockTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
private OriginConditionMethodOutcome TryExecuteConditionMethodLocked(OriginConditionMethodCall call)
|
||||
{
|
||||
var key = MapKey(call.Realm, call.ConditionId);
|
||||
if (!_alarmConditions.TryGetValue(key, out var alarm))
|
||||
return Refused(false, StatusCodes.BadNodeIdUnknown, "The condition is not materialised.");
|
||||
var native = _nativeAlarmNodeIds.Contains(key);
|
||||
|
||||
if (_standby.RefusesMutations)
|
||||
return RefusedBy(native, WarmStandbyState.StandbyRefusal($"call {call.Method}"));
|
||||
if (NativeAlarmAckPrimaryGate is { } primary && !primary())
|
||||
return Refused(native, StatusCodes.BadInvalidState, "This server is not the redundancy Primary.");
|
||||
|
||||
MethodState? method = call.Method switch
|
||||
{
|
||||
"Acknowledge" => alarm.Acknowledge,
|
||||
"AddComment" => alarm.AddComment,
|
||||
"Confirm" when !native => alarm.Confirm,
|
||||
_ => null,
|
||||
};
|
||||
if (method is null) return Refused(native, StatusCodes.BadNotSupported, "The condition does not support this method.");
|
||||
|
||||
// T3: the marker moves only on a new occurrence; an unchanged re-projection keeps the caller's EventIds valid.
|
||||
var current = _activation.TryGetValue(key, out var entry) ? entry.Sequence : 0UL;
|
||||
if (!string.Equals(call.ExpectedActivation.Incarnation, ConditionIncarnation, StringComparison.Ordinal)
|
||||
|| call.ExpectedActivation.Sequence != current)
|
||||
return Refused(native, StatusCodes.BadEventIdUnknown, "The condition has a newer occurrence.");
|
||||
|
||||
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = call.Principal }, [],
|
||||
principal: call.Principal, apiKeyId: call.ApiKeyId);
|
||||
var context = new RemoteConditionMethodContext(Server, alarm, identity);
|
||||
var eventId = alarm.EventId?.Value ?? default;
|
||||
var comment = call.Comment is null ? default : new LocalizedText(call.Comment);
|
||||
var result = method switch
|
||||
{
|
||||
AddCommentMethodState { OnCall: { } onCall } m => onCall(context, m, alarm.NodeId, eventId, comment),
|
||||
_ => new ServiceResult(StatusCodes.BadNotSupported),
|
||||
};
|
||||
return ServiceResult.IsGood(result)
|
||||
? new OriginConditionMethodOutcome(true, native, StatusCodes.Good.Code, null)
|
||||
: RefusedBy(native, result);
|
||||
}
|
||||
|
||||
private static OriginConditionMethodOutcome RefusedBy(bool native, ServiceResult result) =>
|
||||
|
||||
@@ -24,6 +24,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// last compared against. Mutable, only touched under <c>Lock</c>.</summary>
|
||||
private sealed class ActivationEntry
|
||||
{
|
||||
/// <summary>Drawn from the node manager's <see cref="_activationSequenceSource"/>, never per condition object.</summary>
|
||||
public ulong Sequence;
|
||||
public bool Active;
|
||||
public bool Acked = true;
|
||||
@@ -33,6 +34,11 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private IConditionStateSink? _conditionStateSink;
|
||||
private readonly HashSet<RealmKey> _conditionStateKnown = new();
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _activation = new();
|
||||
// A2b security review: ONE monotonic sequence for the node-manager lifetime (the lifetime of ConditionIncarnation).
|
||||
// Every fresh activation entry and every bump draws the next value, so a condition removed and re-created under the
|
||||
// same id never re-issues a marker its previous incarnation carried — a stale ack bound to the old condition can
|
||||
// never match the new one. Only touched under Lock.
|
||||
private ulong _activationSequenceSource;
|
||||
// Rebuild memory for SCRIPTED conditions (native ones ride NativeConditionCarryOver): their marker basis survives
|
||||
// the clear-and-re-materialise so the engine's re-assert of an unchanged active alarm is not a new occurrence.
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _rebuildScriptedActivation = new();
|
||||
@@ -222,7 +228,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_rebuildPendingRemoval.Remove(key);
|
||||
_activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : new ActivationEntry();
|
||||
_activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : NewActivationEntry();
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>, after registration and any carry-over restore: raise the condition's first record.</summary>
|
||||
@@ -329,15 +335,18 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>T3: bump on an Active false→true edge or ANY Acked true→false edge; never otherwise.</summary>
|
||||
private ActivationEntry AdvanceActivation(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = new ActivationEntry();
|
||||
if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = NewActivationEntry();
|
||||
var active = condition.ActiveState?.Id?.Value ?? false;
|
||||
var acked = condition.AckedState?.Id?.Value ?? true;
|
||||
if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence++;
|
||||
if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence = ++_activationSequenceSource;
|
||||
e.Active = active;
|
||||
e.Acked = acked;
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>: a fresh entry whose marker no earlier condition (incl. one under the same id) carried.</summary>
|
||||
private ActivationEntry NewActivationEntry() => new() { Sequence = ++_activationSequenceSource };
|
||||
|
||||
private ConditionStateRecord BuildConditionRecord(
|
||||
RealmKey key, AlarmConditionState c, long version, bool removed, ActivationEntry? entry = null)
|
||||
{
|
||||
|
||||
+5
-2
@@ -85,8 +85,11 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
|
||||
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
|
||||
or ArgumentException or IOException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested && ex is OperationCanceledException) throw;
|
||||
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, "OutcomeUnknown: the transport failed after the request was sent.");
|
||||
// Security review: a CALLER cancel after the request was handed to the transport is OutcomeUnknown too —
|
||||
// the origin may already have applied it, so it must never read as a clean failure (or be retried).
|
||||
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, cancellationToken.IsCancellationRequested
|
||||
? "OutcomeUnknown: the call was cancelled after the request was sent."
|
||||
: "OutcomeUnknown: the transport failed after the request was sent.");
|
||||
}
|
||||
}
|
||||
return new(DataWriteState.RejectedBeforeDispatch, unsupported ? BadNotSupportedMethod : BadNoCommunication,
|
||||
|
||||
+11
-2
@@ -5,9 +5,13 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Bounds shared physical demand and downstream subscription resources for one process.</summary>
|
||||
/// <param name="MaxConditionMethodOperations">A2b: condition-method operations the origin remembers at once (all principals).</param>
|
||||
/// <param name="MaxConditionMethodOperationsPerPrincipal">A2b security review: the same, per principal.</param>
|
||||
public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, int MaxOperations,
|
||||
int MaxOperationsPerPrincipal, long MaxTransportBytes, int MaxCommands, int MaxPendingFrames,
|
||||
long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout);
|
||||
long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout,
|
||||
int MaxConditionMethodOperations = LocalDataServices.DefaultConditionMethodMaxOperations,
|
||||
int MaxConditionMethodOperationsPerPrincipal = LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal);
|
||||
|
||||
/// <summary>Owns the local caller-bound services and the one shared physical-demand bridge.</summary>
|
||||
public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
@@ -20,7 +24,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits,
|
||||
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
|
||||
DataConnectionHistoryDiagnostics? historyDiagnostics = null,
|
||||
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null)
|
||||
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null,
|
||||
IDataConnectionAuditLog? audit = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
|
||||
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
|
||||
@@ -44,6 +49,10 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics,
|
||||
// A2: condition streams over the A1 hub and the node manager's snapshot port; keys from the coordinator.
|
||||
ConditionHub = conditionHub, ConditionSource = conditionSource, ConditionKeysSource = () => catalog.ConditionKeys,
|
||||
// A2b security review: the audit trail on its own logger category (the Host passes it), never the services' logger.
|
||||
Audit = audit ?? new LoggerDataConnectionAuditLog(logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance),
|
||||
ConditionMethodMaxOperations = limits.MaxConditionMethodOperations,
|
||||
ConditionMethodMaxOperationsPerPrincipal = limits.MaxConditionMethodOperationsPerPrincipal,
|
||||
};
|
||||
Services = services;
|
||||
}
|
||||
|
||||
+186
-55
@@ -24,19 +24,34 @@ public interface IDataConnectionAuditLog
|
||||
void RecordConditionMethod(DataConditionMethodAuditEntry entry);
|
||||
}
|
||||
|
||||
/// <summary>The default audit log: structured entries on a dedicated logger category.</summary>
|
||||
/// <summary>
|
||||
/// The default audit log: structured entries on the dedicated <see cref="Category"/> logger, so operators can route the
|
||||
/// audit trail to its own sink. Every caller-supplied string is passed through
|
||||
/// <see cref="LocalDataServices.SanitizeAuditText(string?, int)"/> again here (defence in depth: an
|
||||
/// <see cref="IDataConnectionAuditLog"/> entry built elsewhere cannot inject CR/LF or control characters into log text).
|
||||
/// </summary>
|
||||
public sealed class LoggerDataConnectionAuditLog(ILogger logger) : IDataConnectionAuditLog
|
||||
{
|
||||
/// <summary>The logger category operators route to the audit sink.</summary>
|
||||
public const string Category = "ZB.MOM.WW.OtOpcUa.DataConnections.Audit";
|
||||
|
||||
/// <summary>The audit log over a logger of <see cref="Category"/> from <paramref name="factory"/> (null ⇒ no output).</summary>
|
||||
/// <param name="factory">The host's logger factory.</param>
|
||||
/// <returns>The audit log.</returns>
|
||||
public static LoggerDataConnectionAuditLog Create(ILoggerFactory? factory) =>
|
||||
new((ILogger?)factory?.CreateLogger(Category) ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RecordConditionMethod(DataConditionMethodAuditEntry entry) =>
|
||||
public void RecordConditionMethod(DataConditionMethodAuditEntry entry)
|
||||
{
|
||||
static string Clean(string? text) => LocalDataServices.SanitizeAuditText(text, LocalDataServices.MaxAuditFieldLength) ?? "-";
|
||||
var address = entry.Placement.Address;
|
||||
logger.LogInformation(
|
||||
"Data-connection condition method {Method} by {Principal} (key {ApiKeyId}) on {PlacementRealm}:{PlacementNamespace}:{Placement} op {OperationId}: {State} 0x{StatusCode:X8}{Joined}; on behalf of {OnBehalfOf}",
|
||||
entry.Method, entry.Principal, entry.ApiKeyId ?? "-", entry.Placement.Realm, entry.Placement.Address.NamespaceUri,
|
||||
entry.Placement.Address.Identifier, entry.OperationId, entry.State, entry.StatusCode, entry.Joined ? " (joined)" : "",
|
||||
entry.OnBehalfOf ?? "-");
|
||||
entry.Method, Clean(entry.Principal), Clean(entry.ApiKeyId), entry.Placement.Realm, Clean(address.NamespaceUri),
|
||||
Clean(address.Identifier), Clean(entry.OperationId), entry.State, entry.StatusCode, entry.Joined ? " (joined)" : "",
|
||||
Clean(entry.OnBehalfOf));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A2b: the origin side of <c>CallConditionMethod</c> (plan §5.6 "Origin", §6).</summary>
|
||||
@@ -46,27 +61,50 @@ public sealed partial class LocalDataServices
|
||||
BadTimeout = 0x800A0000u, BadUserAccessDenied = 0x801F0000u, BadNodeIdUnknown = 0x80340000u,
|
||||
BadInvalidArgument = 0x80AB0000u;
|
||||
|
||||
/// <summary>The most characters of one caller-supplied audit field other than <c>on_behalf_of</c>.</summary>
|
||||
public const int MaxAuditFieldLength = 512;
|
||||
|
||||
/// <summary>Default <see cref="ConditionMethodMaxOperations"/>.</summary>
|
||||
public const int DefaultConditionMethodMaxOperations = 4096;
|
||||
|
||||
/// <summary>Default <see cref="ConditionMethodMaxOperationsPerPrincipal"/>.</summary>
|
||||
public const int DefaultConditionMethodMaxOperationsPerPrincipal = 256;
|
||||
|
||||
private readonly object _methodRegistryGate = new();
|
||||
private WriteOperationRegistry? _methodRegistry;
|
||||
private IDataConnectionAuditLog? _audit;
|
||||
|
||||
/// <summary>A2b: the data-connection audit log (default: <see cref="LoggerDataConnectionAuditLog"/> over <see cref="Logger"/>).</summary>
|
||||
/// <summary>
|
||||
/// A2b: the data-connection audit log. The Host passes <see cref="LoggerDataConnectionAuditLog.Create"/> over its
|
||||
/// logger factory (the dedicated audit category); the fallback writes to <see cref="Logger"/>.
|
||||
/// </summary>
|
||||
public IDataConnectionAuditLog Audit { get => _audit ??= new LoggerDataConnectionAuditLog(Logger); init => _audit = value; }
|
||||
|
||||
/// <summary>A2b: how long a completed operation id is remembered (a duplicate within it joins the stored outcome).</summary>
|
||||
public TimeSpan ConditionMethodRetention { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>A2b: the most condition-method operations the origin remembers at once (all principals).</summary>
|
||||
public int ConditionMethodMaxOperations { get; init; } = DefaultConditionMethodMaxOperations;
|
||||
|
||||
/// <summary>
|
||||
/// A2b security review: the most condition-method operations ONE principal may hold in the registry at once, so a
|
||||
/// single peer cannot exhaust <see cref="ConditionMethodMaxOperations"/> for every other peer. Refusals before
|
||||
/// dispatch hold no entry.
|
||||
/// </summary>
|
||||
public int ConditionMethodMaxOperationsPerPrincipal { get; init; } = DefaultConditionMethodMaxOperationsPerPrincipal;
|
||||
|
||||
/// <summary>Whether this origin serves remote condition methods: the condition port is up (same as streaming).</summary>
|
||||
internal bool ConditionMethodsServable => ConditionsServable;
|
||||
|
||||
/// <summary>The duplicate-protection registry of the current serving incarnation (a new incarnation starts empty).</summary>
|
||||
private WriteOperationRegistry MethodRegistry(string incarnation)
|
||||
internal WriteOperationRegistry MethodRegistry(string incarnation)
|
||||
{
|
||||
lock (_methodRegistryGate)
|
||||
{
|
||||
if (_methodRegistry is null || _methodRegistryIncarnation != incarnation)
|
||||
{
|
||||
_methodRegistry = new WriteOperationRegistry(incarnation, 4096, 8L * 1024 * 1024, ConditionMethodRetention, Clock);
|
||||
_methodRegistry = new WriteOperationRegistry(incarnation, ConditionMethodMaxOperations, 8L * 1024 * 1024,
|
||||
ConditionMethodRetention, Clock, ConditionMethodMaxOperationsPerPrincipal);
|
||||
_methodRegistryIncarnation = incarnation;
|
||||
}
|
||||
return _methodRegistry;
|
||||
@@ -81,8 +119,18 @@ public sealed partial class LocalDataServices
|
||||
/// (else <c>BadNodeIdUnknown</c> — existence is not disclosed); the origin ACL on the placement's subject
|
||||
/// (<c>BadUserAccessDenied</c>); native Confirm (<c>BadNotSupported</c>); the Galaxy service-ack opt-in
|
||||
/// (<c>BadUserAccessDenied</c>); then the operation registry (a duplicate id joins) and the node manager (Warm
|
||||
/// Standby, Primary, activation marker, native preflight). Never retried.
|
||||
/// Standby, Primary, activation marker, native preflight). Never retried. Every call is audited, whatever its end.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Time of check vs time of use (security review, documented).</b> Authorization (export grant, origin ACL,
|
||||
/// Galaxy opt-in, caller usability) is decided here against the catalog/authority captured at the start of the call,
|
||||
/// and the node manager applies the method afterwards under its own <c>Lock</c>. A deploy, key revocation or ACL change
|
||||
/// that lands between the two is not re-checked: the window is one synchronous hop (no I/O, no await between the ACL
|
||||
/// check and the dispatch other than the registry claim), the same bound a local OPC UA client's call has (its role
|
||||
/// is read before the SDK applies), and a revocation stops every later call. Serving-identity changes ARE caught at
|
||||
/// apply time — the node manager re-checks Primary and Warm Standby under <c>Lock</c>, and the activation marker
|
||||
/// refuses a condition re-created by a rebuild.
|
||||
/// </remarks>
|
||||
internal async Task<DataConditionMethodResult> CallConditionMethodAsync(DataAuthenticatedContext context, DataTarget target,
|
||||
DataConditionMethodRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -90,20 +138,36 @@ public sealed partial class LocalDataServices
|
||||
request.Validate();
|
||||
target.Validate();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var onBehalfOf = SanitizeAuditText(request.OnBehalfOf);
|
||||
var catalog = _catalog();
|
||||
var serving = catalog?.Serving;
|
||||
var (result, joined) = await DecideAsync().ConfigureAwait(false);
|
||||
result = result with { Serving = serving };
|
||||
Audit.RecordConditionMethod(new(Clock.GetUtcNow(), context.PrincipalId, context.ApiKeyId, request.Placement, request.OperationId,
|
||||
request.Method, result.State, result.StatusCode, joined, onBehalfOf));
|
||||
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", request.Method.ToString()),
|
||||
new KeyValuePair<string, object?>("outcome", result.State.ToString()));
|
||||
return result;
|
||||
DataConditionMethodResult? result = null;
|
||||
var joined = false;
|
||||
try
|
||||
{
|
||||
(result, joined) = await DecideAsync().ConfigureAwait(false);
|
||||
result = result with { Serving = serving };
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Security review: ALWAYS audited — a decided outcome, or (an exception escaped) OutcomeUnknown.
|
||||
var state = result?.State ?? DataWriteState.OutcomeUnknown;
|
||||
var status = result?.StatusCode ?? BadInternalError;
|
||||
try
|
||||
{
|
||||
Audit.RecordConditionMethod(AuditEntry(context, request, state, status, joined));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "The data-connection audit log failed to record a condition method call");
|
||||
}
|
||||
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", request.Method.ToString()),
|
||||
new KeyValuePair<string, object?>("outcome", state.ToString()));
|
||||
}
|
||||
|
||||
async Task<(DataConditionMethodResult, bool)> DecideAsync()
|
||||
{
|
||||
if (!ConditionMethodsServable) return (Reject(BadNotSupported, "Condition methods are not served."), false);
|
||||
if (!ConditionMethodsServable || ConditionSource is null) return (Reject(BadNotSupported, "Condition methods are not served."), false);
|
||||
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
|
||||
return (Reject(BadNoCommunication, "Condition methods unavailable."), false);
|
||||
// §5.6: remote condition methods are Primary-only for both kinds (the capability bits are stripped off-Primary too).
|
||||
@@ -121,13 +185,15 @@ public sealed partial class LocalDataServices
|
||||
var acl = operation == DataOperations.AlarmConfirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge;
|
||||
if (!_policy.AuthorizeLocal(Caller(context), acl, placement.Scope))
|
||||
return (Reject(BadUserAccessDenied, "Denied by the origin ACL."), false);
|
||||
if (placement.SourceKind == ConditionSourceKind.Native && (request.Method & DataConditionMethodSets.Native) == 0)
|
||||
var native = placement.SourceKind == ConditionSourceKind.Native;
|
||||
if (native && (request.Method & DataConditionMethodSets.Native) == 0)
|
||||
return (Reject(BadNotSupported, "A native condition supports Acknowledge and AddComment only."), false);
|
||||
if (placement.IsGalaxy && !catalog.AllowsGalaxyServiceAck(context.PrincipalId, placement))
|
||||
return (Reject(BadUserAccessDenied, "Galaxy service acknowledge is not enabled on this export."), false);
|
||||
|
||||
var claim = MethodRegistry(catalog.Serving.Incarnation).Claim(context.PrincipalId, request.OperationId,
|
||||
request.ExpectedServingIncarnation, SemanticHash(request));
|
||||
// Everything above refused without touching the registry, so a refusal holds no capacity.
|
||||
var registry = MethodRegistry(catalog.Serving.Incarnation);
|
||||
var claim = registry.Claim(context.PrincipalId, request.OperationId, request.ExpectedServingIncarnation, SemanticHash(request));
|
||||
switch (claim.Kind)
|
||||
{
|
||||
case WriteClaimKind.Stale: return (Reject(BadInvalidState, "Serving incarnation changed."), false);
|
||||
@@ -143,33 +209,91 @@ public sealed partial class LocalDataServices
|
||||
}
|
||||
|
||||
var owner = claim.Claim!;
|
||||
OriginConditionMethodOutcome verdict;
|
||||
DataWriteOutcome? outcome = null;
|
||||
try
|
||||
{
|
||||
verdict = ConditionSource!.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId,
|
||||
DataConditionMethodSets.Part9Name(request.Method), request.Comment,
|
||||
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
|
||||
context.PrincipalId, context.ApiKeyId));
|
||||
outcome = Dispatch();
|
||||
return (FromOutcome(outcome), false);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
finally
|
||||
{
|
||||
verdict = new(false, placement.SourceKind == ConditionSourceKind.Native, BadNoCommunication, ex.Message);
|
||||
// Security review: the claim is ALWAYS finished. An exception that escaped after the node manager may have
|
||||
// applied the call is OutcomeUnknown (joiners get the same); a refusal releases its entry at once.
|
||||
if (outcome is null)
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
outcome = new(DataWriteState.OutcomeUnknown, BadInternalError, "OutcomeUnknown: the origin failed while applying the call.");
|
||||
owner.Complete(outcome);
|
||||
}
|
||||
owner.PhysicalFinished();
|
||||
if (outcome.State == DataWriteState.RejectedBeforeDispatch)
|
||||
registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner);
|
||||
}
|
||||
DataWriteOutcome outcome;
|
||||
if (verdict.Applied)
|
||||
|
||||
DataWriteOutcome Dispatch()
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
outcome = verdict.Native
|
||||
? new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode, "AcceptedUnconfirmed: routed to the driver; its confirmation or revert arrives on the condition stream.")
|
||||
: new(DataWriteState.DriverConfirmedSuccess, verdict.StatusCode, null);
|
||||
OriginConditionMethodOutcome verdict;
|
||||
try
|
||||
{
|
||||
verdict = ConditionSource.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId,
|
||||
DataConditionMethodSets.Part9Name(request.Method), request.Comment,
|
||||
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
|
||||
context.PrincipalId, context.ApiKeyId));
|
||||
}
|
||||
catch (OriginConditionSourceUnavailableException ex)
|
||||
{
|
||||
// The ONE exception that proves nothing was dispatched: the node manager is not running.
|
||||
verdict = new(false, native, BadNoCommunication, ex.Message);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Anything else may have been thrown after the node manager applied the call: the outcome is unknown.
|
||||
Logger.LogWarning(ex, "A remote condition method failed inside the node manager; answering OutcomeUnknown");
|
||||
owner.TryMarkDispatched();
|
||||
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, BadInternalError,
|
||||
"OutcomeUnknown: the origin failed while applying the call.");
|
||||
owner.Complete(unknown);
|
||||
return unknown;
|
||||
}
|
||||
DataWriteOutcome decided;
|
||||
if (verdict.Applied)
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
decided = !verdict.Native
|
||||
? new(DataWriteState.DriverConfirmedSuccess, verdict.StatusCode, null)
|
||||
: request.Method == DataConditionMethods.Acknowledge
|
||||
? new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
|
||||
"AcceptedUnconfirmed: routed to the driver; its confirmation or revert arrives on the condition stream.")
|
||||
: new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
|
||||
"AcceptedUnconfirmed: the comment was applied at the origin (not sent to the driver); it arrives on the condition stream.");
|
||||
}
|
||||
else decided = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
|
||||
owner.Complete(decided);
|
||||
return decided;
|
||||
}
|
||||
else outcome = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
|
||||
owner.Complete(outcome);
|
||||
owner.PhysicalFinished();
|
||||
return (FromOutcome(outcome), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The audit entry with every caller-supplied string sanitised (security review: log injection).</summary>
|
||||
private DataConditionMethodAuditEntry AuditEntry(DataAuthenticatedContext context, DataConditionMethodRequest request,
|
||||
DataWriteState state, uint status, bool joined)
|
||||
{
|
||||
static string Field(string text) => SanitizeAuditText(text, MaxAuditFieldLength) ?? string.Empty;
|
||||
var p = request.Placement;
|
||||
var a = p.Address;
|
||||
var placement = p with
|
||||
{
|
||||
Address = a with
|
||||
{
|
||||
OriginClusterId = Field(a.OriginClusterId), NamespaceUri = Field(a.NamespaceUri),
|
||||
IdentifierKind = Field(a.IdentifierKind), Identifier = Field(a.Identifier),
|
||||
},
|
||||
MappingId = p.MappingId is null ? null : Field(p.MappingId), Subject = Field(p.Subject),
|
||||
};
|
||||
return new(Clock.GetUtcNow(), Field(context.PrincipalId), context.ApiKeyId is null ? null : Field(context.ApiKeyId), placement,
|
||||
Field(request.OperationId), request.Method, state, status, joined, SanitizeAuditText(request.OnBehalfOf));
|
||||
}
|
||||
|
||||
private static DataConditionMethodResult Reject(uint status, string diagnostic) =>
|
||||
new(DataWriteState.RejectedBeforeDispatch, status, diagnostic);
|
||||
|
||||
@@ -187,37 +311,44 @@ public sealed partial class LocalDataServices
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §6: the peer's <c>on_behalf_of</c> as the audit log may record it — control (Cc), format (Cf), line/paragraph
|
||||
/// separator and unpaired surrogate characters removed, then capped at
|
||||
/// <see cref="DataConditionMethodRequest.MaxOnBehalfOfLength"/> characters without splitting a surrogate pair.
|
||||
/// Null/empty-after-sanitising ⇒ null.
|
||||
/// §6: the peer's <c>on_behalf_of</c> as the audit log may record it — see <see cref="SanitizeAuditText(string?, int)"/>,
|
||||
/// capped at <see cref="DataConditionMethodRequest.MaxOnBehalfOfLength"/> characters.
|
||||
/// </summary>
|
||||
public static string? SanitizeAuditText(string? text)
|
||||
public static string? SanitizeAuditText(string? text) => SanitizeAuditText(text, DataConditionMethodRequest.MaxOnBehalfOfLength);
|
||||
|
||||
/// <summary>
|
||||
/// Caller-supplied text as the audit log may record it: control (Cc), format (Cf), private-use (Co), unassigned (Cn),
|
||||
/// line/paragraph separator and unpaired surrogate characters removed (in BMP and supplementary planes alike), then
|
||||
/// capped at <paramref name="maxLength"/> UTF-16 units without splitting a surrogate pair — the result is always
|
||||
/// well-formed UTF-16. Null/empty-after-sanitising ⇒ null.
|
||||
/// </summary>
|
||||
/// <param name="text">The untrusted text.</param>
|
||||
/// <param name="maxLength">The most UTF-16 units kept.</param>
|
||||
/// <returns>The sanitised text, or null.</returns>
|
||||
public static string? SanitizeAuditText(string? text, int maxLength)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return null;
|
||||
var builder = new StringBuilder(Math.Min(text.Length, DataConditionMethodRequest.MaxOnBehalfOfLength));
|
||||
for (var i = 0; i < text.Length && builder.Length < DataConditionMethodRequest.MaxOnBehalfOfLength; i++)
|
||||
if (string.IsNullOrEmpty(text) || maxLength <= 0) return null;
|
||||
var builder = new StringBuilder(Math.Min(text.Length, maxLength));
|
||||
for (var i = 0; i < text.Length && builder.Length < maxLength; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (char.IsHighSurrogate(c))
|
||||
{
|
||||
if (i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
|
||||
{
|
||||
var category = CharUnicodeInfo.GetUnicodeCategory(text, i);
|
||||
if (category != UnicodeCategory.Format && builder.Length + 2 <= DataConditionMethodRequest.MaxOnBehalfOfLength)
|
||||
if (!Dropped(CharUnicodeInfo.GetUnicodeCategory(text, i)) && builder.Length + 2 <= maxLength)
|
||||
builder.Append(c).Append(text[i + 1]);
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (char.IsLowSurrogate(c)) continue;
|
||||
switch (CharUnicodeInfo.GetUnicodeCategory(c))
|
||||
{
|
||||
case UnicodeCategory.Control or UnicodeCategory.Format or UnicodeCategory.LineSeparator
|
||||
or UnicodeCategory.ParagraphSeparator or UnicodeCategory.OtherNotAssigned: continue;
|
||||
default: builder.Append(c); break;
|
||||
}
|
||||
if (char.IsLowSurrogate(c) || Dropped(CharUnicodeInfo.GetUnicodeCategory(c))) continue;
|
||||
builder.Append(c);
|
||||
}
|
||||
return builder.Length == 0 ? null : builder.ToString();
|
||||
|
||||
static bool Dropped(UnicodeCategory category) => category is UnicodeCategory.Control or UnicodeCategory.Format
|
||||
or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator or UnicodeCategory.OtherNotAssigned
|
||||
or UnicodeCategory.PrivateUse or UnicodeCategory.Surrogate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,21 +11,31 @@ 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)
|
||||
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;
|
||||
@@ -47,23 +57,57 @@ public sealed class WriteOperationRegistry
|
||||
if (_entries.TryGetValue(key, out var existing))
|
||||
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
|
||||
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
|
||||
if (_entries.Count >= _maxEntries || bytes > _maxBytes - _retainedBytes)
|
||||
_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;
|
||||
_entries.Remove(pair.Key);
|
||||
_retainedBytes -= pair.Value.Bytes;
|
||||
Remove(pair.Key, pair.Value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +140,8 @@ public sealed class WriteClaim
|
||||
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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user