229 lines
13 KiB
C#
229 lines
13 KiB
C#
using System.Collections.Immutable;
|
|
using System.Security.Cryptography;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
internal sealed class WriteValueBudget(long limit)
|
|
{
|
|
private long _used;
|
|
public IDisposable? TryReserve(long bytes)
|
|
{
|
|
if (bytes <= 0 || limit <= 0) return null;
|
|
while (true)
|
|
{
|
|
var used = Volatile.Read(ref _used);
|
|
if (bytes > limit - used) return null;
|
|
if (Interlocked.CompareExchange(ref _used, used + bytes, used) == used) return new Lease(this, bytes);
|
|
}
|
|
}
|
|
private sealed class Lease(WriteValueBudget owner, long bytes) : IDisposable
|
|
{
|
|
private int _released;
|
|
public void Dispose() { if (Interlocked.Exchange(ref _released, 1) == 0) Interlocked.Add(ref owner._used, -bytes); }
|
|
}
|
|
}
|
|
|
|
/// <summary>Caller-bound origin-local mutation admission; routes only catalog-resolved views.</summary>
|
|
internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func<LocalExportCatalog?> catalog,
|
|
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, IDataWriteRoute route,
|
|
WriteOperationRegistry registry, WriteValueBudget values, TimeProvider clock, DriverWriteBounds bounds) : IDataWriteService
|
|
{
|
|
private static DataWriteOutcome Rejected(string reason) => new(DataWriteState.RejectedBeforeDispatch, 0x80310000u, reason);
|
|
private static readonly DataWriteOutcome Unknown = new(DataWriteState.OutcomeUnknown, 0x800A0000u, "Write outcome unknown.");
|
|
|
|
public async Task<IReadOnlyList<WriteItemResult>> WriteAsync(WriteBatch request, CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(request);
|
|
// The caller's budget covers validation and all batch preflight work.
|
|
var started = clock.GetTimestamp();
|
|
ArgumentNullException.ThrowIfNull(request.Items);
|
|
request.Budget.Validate();
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
if (request.Items.Count > Math.Min(request.Budget.MaxItems, capabilities.Limits.MaxBatchItems))
|
|
throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds the item limit.");
|
|
var totalBytes = 0L;
|
|
foreach (var item in request.Items)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(item);
|
|
ArgumentNullException.ThrowIfNull(item.Value);
|
|
totalBytes = checked(totalBytes + RetainedBytes(item));
|
|
}
|
|
if (totalBytes > request.Budget.MaxBytes) throw new ArgumentOutOfRangeException(nameof(request), "Write batch exceeds its byte limit.");
|
|
var pending = request.Items.Select(item => ExecuteItem(item, request.Budget, started, cancellationToken)).ToArray();
|
|
return await Task.WhenAll(pending).ConfigureAwait(false);
|
|
}
|
|
|
|
private async Task<WriteItemResult> ExecuteItem(WriteItem item, DataBudget budget, long start, CancellationToken cancellationToken)
|
|
{
|
|
WriteItemResult Reject(string reason) => new(item.CorrelationId, Rejected(reason));
|
|
if (item.View is null || item.View.Address is null) return Reject("Write unavailable or denied before dispatch.");
|
|
var current = catalog();
|
|
var caller = new DataCallerIdentity(context.PrincipalId, context.ApiKeyId, context.CredentialVersion, context.CredentialExpiresUtc);
|
|
if (current is null || !current.IsActive || !capabilities.IsReady || current.AuthorityEpoch != policy.AuthorityEpoch
|
|
|| current.Serving != capabilities.Serving || !policy.IsCallerUsable(caller)
|
|
|| !current.TryResolve(item.View, out var node) || !current.AllowsExport(context.PrincipalId, node, DataOperations.Write)
|
|
|| (node.Metadata.AllowedOperations & DataOperations.Write) == 0
|
|
|| !policy.AuthorizeLocal(caller, OpcUaOperation.WriteOperate, node.Scope))
|
|
return Reject("Write unavailable or denied before dispatch.");
|
|
// Role and structure are intentionally checked after authorization.
|
|
if (!string.Equals(current.Serving.Role, "Primary", StringComparison.OrdinalIgnoreCase)
|
|
|| !node.SourceEnabled || !node.Supported || !node.Metadata.Writable
|
|
|| !ValueMatches(node.Metadata, item.Value) || item.ExpectedCatalogRevision != current.Serving.CatalogEpoch
|
|
|| item.ExpectedServingIncarnation != current.Serving.Incarnation
|
|
|| item.ExpectedServingGeneration is { } generation && (generation <= 0 || generation != current.Serving.ServingGeneration))
|
|
return Reject("Write unavailable before dispatch.");
|
|
if (string.IsNullOrWhiteSpace(item.OperationId) || string.IsNullOrWhiteSpace(item.CorrelationId))
|
|
return Reject("Invalid write identity.");
|
|
|
|
byte[] hash;
|
|
try { hash = SemanticHash(node.Metadata.View, item); }
|
|
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
|
{ return Reject("Invalid write value."); }
|
|
var result = registry.Claim(context.PrincipalId, item.OperationId, item.ExpectedServingIncarnation, hash);
|
|
if (result.Kind is WriteClaimKind.Conflict or WriteClaimKind.Stale)
|
|
return new(item.CorrelationId, Unknown);
|
|
if (result.Kind == WriteClaimKind.Capacity || result.Claim is null)
|
|
return Reject("Write operation capacity exhausted.");
|
|
var claim = result.Claim;
|
|
if (result.Kind == WriteClaimKind.Existing)
|
|
{
|
|
var existing = claim.CurrentOutcome ?? await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
return new(item.CorrelationId, existing);
|
|
}
|
|
|
|
// Preserve one absolute request deadline, including the per-item bound; do not
|
|
// restart it after route lookup, byte admission, or retained-value preparation.
|
|
var allowance = item.RemainingBudget < budget.Timeout ? item.RemainingBudget : budget.Timeout;
|
|
long expiration;
|
|
try
|
|
{
|
|
if (allowance <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(item));
|
|
var timestampTicks = checked((long)((decimal)allowance.Ticks * clock.TimestampFrequency / TimeSpan.TicksPerSecond));
|
|
expiration = checked(start + timestampTicks);
|
|
}
|
|
catch (Exception ex) when (ex is OverflowException or ArgumentException)
|
|
{
|
|
var rejected = Rejected("Invalid write deadline or value.");
|
|
claim.Complete(rejected);
|
|
return new(item.CorrelationId, rejected);
|
|
}
|
|
bool HasDispatchBudget(long now)
|
|
{
|
|
try
|
|
{
|
|
var elapsed = clock.GetElapsedTime(start, now);
|
|
return elapsed >= TimeSpan.Zero && elapsed < allowance && now < expiration &&
|
|
allowance - elapsed >= bounds.GatewayAsk;
|
|
}
|
|
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
|
|
}
|
|
WriteRouteTarget? target;
|
|
try { target = !cancellationToken.IsCancellationRequested && HasDispatchBudget(clock.GetTimestamp()) &&
|
|
route.TryResolve(node.Metadata.View, out var resolved) ? resolved : null; }
|
|
catch { target = null; }
|
|
if (target is null || cancellationToken.IsCancellationRequested || !HasDispatchBudget(clock.GetTimestamp()))
|
|
{
|
|
var rejected = Rejected("Insufficient budget or no active driver route.");
|
|
claim.Complete(rejected);
|
|
return new(item.CorrelationId, rejected);
|
|
}
|
|
var lease = values.TryReserve(RetainedBytes(item));
|
|
if (lease is null)
|
|
{
|
|
var rejected = Rejected("Retained write byte budget exhausted.");
|
|
claim.Complete(rejected);
|
|
return new(item.CorrelationId, rejected);
|
|
}
|
|
WriteAdmissionTicket ticket;
|
|
try
|
|
{
|
|
var issued = clock.GetTimestamp();
|
|
var admission = new DataWriteAdmission(context.PrincipalId, node.Metadata.View, current.AuthorityEpoch,
|
|
current.Serving.CatalogEpoch, current.Serving.Incarnation, target.DriverIncarnation, item.OperationId,
|
|
expiration, context.ApiKeyId, context.CredentialExpiresUtc, context.CredentialVersion);
|
|
var scope = new FrozenWriteScope(node.Scope.ClusterId, node.Scope.Kind, node.Scope.Segments.ToImmutableArray());
|
|
var proof = new WriteRouteProof(admission, scope, node.EntityKind, node.EntityId, node.Source,
|
|
target.DriverInstanceId, target.DriverReference, target.RouteGeneration, target.PrimaryGeneration, current.Serving);
|
|
ticket = new WriteAdmissionTicket(proof, item.Value.Retain(), issued, lease);
|
|
}
|
|
catch
|
|
{
|
|
lease.Dispose();
|
|
var rejected = Rejected("Invalid write deadline or value.");
|
|
claim.Complete(rejected);
|
|
return new(item.CorrelationId, rejected);
|
|
}
|
|
if (cancellationToken.IsCancellationRequested || !HasDispatchBudget(clock.GetTimestamp()))
|
|
{
|
|
ticket.Dispose();
|
|
var rejected = Rejected("Insufficient budget or no active driver route.");
|
|
claim.Complete(rejected);
|
|
return new(item.CorrelationId, rejected);
|
|
}
|
|
_ = DispatchAsync(route, ticket, claim);
|
|
return new(item.CorrelationId, await claim.Completion.WaitAsync(cancellationToken).ConfigureAwait(false));
|
|
}
|
|
|
|
private static async Task DispatchAsync(IDataWriteRoute route, WriteAdmissionTicket ticket, WriteClaim claim)
|
|
{
|
|
try
|
|
{
|
|
var outcome = await route.DispatchAsync(ticket, claim, CancellationToken.None).ConfigureAwait(false);
|
|
// The physical observer is the sole publisher of definitive dispatched outcomes. A route
|
|
// reply can establish only a proven no-call rejection or an ambiguous post-dispatch outcome;
|
|
// otherwise it could refine an Unknown after late-result retention has already expired.
|
|
if (outcome.State == DataWriteState.RejectedBeforeDispatch)
|
|
{
|
|
if (claim.Complete(outcome)) ticket.Dispose();
|
|
}
|
|
else if (outcome.State == DataWriteState.OutcomeUnknown)
|
|
claim.Complete(outcome);
|
|
}
|
|
catch
|
|
{
|
|
var rejection = Rejected("Write route failed before dispatch.");
|
|
if (claim.Complete(rejection)) ticket.Dispose();
|
|
else claim.Complete(Unknown);
|
|
}
|
|
}
|
|
|
|
private static bool ValueMatches(DataMetadata metadata, DataValue value) =>
|
|
value.Kind == DataValueKind.Null || metadata.ValueKind == value.Kind &&
|
|
(value.Kind != DataValueKind.Array || metadata.ArrayElementKind == value.ArrayElementKind &&
|
|
metadata.Dimensions.Count == value.Dimensions!.Count &&
|
|
metadata.Dimensions.Zip(value.Dimensions).All(x => x.First == 0 || x.First == x.Second));
|
|
|
|
private static long RetainedBytes(WriteItem item) => checked(3 * item.Value.EstimatedRetainedBytes + 512L + 2L *
|
|
((item.CorrelationId?.Length ?? 0) + (item.OperationId?.Length ?? 0) + (item.View?.Subject?.Length ?? 0)
|
|
+ (item.View?.MappingId?.Length ?? 0) + (item.View?.Address?.OriginClusterId?.Length ?? 0)
|
|
+ (item.View?.Address?.NamespaceUri?.Length ?? 0) + (item.View?.Address?.IdentifierKind?.Length ?? 0)
|
|
+ (item.View?.Address?.Identifier?.Length ?? 0) + (item.ExpectedServingIncarnation?.Length ?? 0)));
|
|
|
|
private static byte[] SemanticHash(DataView canonicalView, WriteItem item)
|
|
{
|
|
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
|
|
// Hash the catalog's actual resolved identity, not a caller's equivalent spelling or subject claim.
|
|
// UTF-16 code units are framed directly, so distinct ordinal strings never collapse via replacement.
|
|
DataFingerprintEncoding.AppendInt32(hash, 1);
|
|
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.OriginClusterId);
|
|
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.NamespaceUri);
|
|
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.IdentifierKind);
|
|
DataFingerprintEncoding.AppendString(hash, canonicalView.Address.Identifier);
|
|
DataFingerprintEncoding.AppendInt32(hash, (int)canonicalView.Realm);
|
|
DataFingerprintEncoding.AppendByte(hash, canonicalView.MappingId is null ? (byte)0 : (byte)1);
|
|
if (canonicalView.MappingId is not null) DataFingerprintEncoding.AppendString(hash, canonicalView.MappingId);
|
|
DataFingerprintEncoding.AppendInt64(hash, canonicalView.MappingRevision);
|
|
DataFingerprintEncoding.AppendString(hash, canonicalView.Subject);
|
|
DataFingerprintEncoding.AppendInt64(hash, item.ExpectedCatalogRevision);
|
|
DataFingerprintEncoding.AppendString(hash, item.ExpectedServingIncarnation);
|
|
DataFingerprintEncoding.AppendByte(hash, item.ExpectedServingGeneration.HasValue ? (byte)1 : (byte)0);
|
|
if (item.ExpectedServingGeneration is { } generation) DataFingerprintEncoding.AppendInt64(hash, generation);
|
|
item.Value.AppendSemanticFingerprint(hash);
|
|
return hash.GetHashAndReset();
|
|
}
|
|
}
|