feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -729,8 +729,11 @@ public static class DataProtoMapper
|
||||
ExpectedCatalogRevision = i.ExpectedCatalogRevision,
|
||||
ExpectedServingIncarnation = i.ExpectedServingIncarnation,
|
||||
RemainingBudgetTicks = i.RemainingBudget.Ticks,
|
||||
ExpectedServingGeneration = i.ExpectedServingGeneration ?? 0,
|
||||
}
|
||||
);
|
||||
for (var index = 0; index < x.Items.Count; index++)
|
||||
if (x.Items[index].ExpectedServingGeneration is null) v.Items[index].ClearExpectedServingGeneration();
|
||||
return v;
|
||||
}
|
||||
|
||||
@@ -751,7 +754,8 @@ public static class DataProtoMapper
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(item.OperationId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(item.ExpectedServingIncarnation);
|
||||
if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0)
|
||||
if (item.ExpectedCatalogRevision <= 0 || item.RemainingBudgetTicks <= 0 ||
|
||||
item.HasExpectedServingGeneration && item.ExpectedServingGeneration <= 0)
|
||||
throw new ArgumentException("Invalid write preconditions.");
|
||||
}
|
||||
var items = new List<WriteItem>();
|
||||
@@ -766,7 +770,8 @@ public static class DataProtoMapper
|
||||
TypedValueCodec.Decode(i.Value, maxElements, maxBytes),
|
||||
i.ExpectedCatalogRevision,
|
||||
i.ExpectedServingIncarnation,
|
||||
TimeSpan.FromTicks(i.RemainingBudgetTicks)
|
||||
TimeSpan.FromTicks(i.RemainingBudgetTicks),
|
||||
i.HasExpectedServingGeneration ? i.ExpectedServingGeneration : null
|
||||
)
|
||||
);
|
||||
return new(items, DecodeBudget(x.Budget));
|
||||
@@ -962,6 +967,7 @@ public static class DataProtoMapper
|
||||
ExpectedCatalogRevision = item.ExpectedCatalogRevision,
|
||||
ExpectedServingIncarnation = item.ExpectedServingIncarnation,
|
||||
};
|
||||
if (item.ExpectedServingGeneration is { } generation) wire.ExpectedServingGeneration = generation;
|
||||
return System.Security.Cryptography.SHA256.HashData(wire.ToByteArray());
|
||||
}
|
||||
|
||||
@@ -988,6 +994,7 @@ public static class DataProtoMapper
|
||||
CompactCodecVersion = x.CompactCodecVersion,
|
||||
SubscriptionAgeReadiness = x.SubscriptionAgeReadiness,
|
||||
ResponseServingIdentity = x.ResponseServingIdentity,
|
||||
WriteServingGenerationEnforced = x.WriteServingGenerationEnforced,
|
||||
Limits = new W.Limits
|
||||
{
|
||||
MaxPageItems = l.MaxPageItems,
|
||||
@@ -1053,7 +1060,8 @@ public static class DataProtoMapper
|
||||
x.CompactCodecVersion,
|
||||
x.ClusterId,
|
||||
x.SubscriptionAgeReadiness,
|
||||
x.ResponseServingIdentity
|
||||
x.ResponseServingIdentity,
|
||||
x.WriteServingGenerationEnforced
|
||||
);
|
||||
result.Validate();
|
||||
return result;
|
||||
|
||||
@@ -149,3 +149,16 @@ public sealed class NullVirtualTagEvaluator : IVirtualTagEvaluator
|
||||
public VirtualTagEvalResult Evaluate(string virtualTagId, string expression, IReadOnlyDictionary<string, object?> dependencies)
|
||||
=> VirtualTagEvalResult.NoChange;
|
||||
}
|
||||
|
||||
/// <summary>An evaluator that owns projected input memory through physical script completion.</summary>
|
||||
public interface IProjectedVirtualTagEvaluator : IVirtualTagEvaluator
|
||||
{
|
||||
/// <summary>Evaluates an imported snapshot, taking ownership of its physical lease on entry.</summary>
|
||||
/// <param name="virtualTagId">The virtual-tag identity.</param>
|
||||
/// <param name="expression">The expression to run.</param>
|
||||
/// <param name="dependencies">The captured inputs.</param>
|
||||
/// <param name="physicalLease">Ownership of the imported input memory.</param>
|
||||
/// <returns>The evaluation result.</returns>
|
||||
Task<VirtualTagEvalResult> EvaluateProjectedAsync(string virtualTagId, string expression,
|
||||
IReadOnlyDictionary<string, DataValueSnapshot> dependencies, IDisposable physicalLease);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
/// <summary>
|
||||
@@ -12,7 +14,7 @@ namespace ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
/// no-op against <see cref="NullOpcUaAddressSpaceSink"/>, so the actor stays safe to
|
||||
/// receive messages from the moment it boots.
|
||||
/// </summary>
|
||||
public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink
|
||||
public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddressSpaceSink, IProjectedValueSink
|
||||
{
|
||||
private volatile IOpcUaAddressSpaceSink _inner = NullOpcUaAddressSpaceSink.Instance;
|
||||
|
||||
@@ -22,6 +24,13 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical
|
||||
public void SetSink(IOpcUaAddressSpaceSink? sink) =>
|
||||
_inner = sink ?? NullOpcUaAddressSpaceSink.Instance;
|
||||
|
||||
/// <summary>Resolves an optional capability against the currently bound SDK sink.</summary>
|
||||
public T? GetCapability<T>() where T : class => _inner as T;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryPublish(IReadOnlyList<ProjectedValueWrite> values) =>
|
||||
_inner is IProjectedValueSink projected && projected.TryPublish(values);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void WriteValue(string nodeId, object? value, uint statusCode, DateTime sourceTimestampUtc, AddressSpaceRealm realm)
|
||||
=> _inner.WriteValue(nodeId, value, statusCode, sourceTimestampUtc, realm);
|
||||
|
||||
@@ -113,6 +113,7 @@ message CapabilitiesResponse {
|
||||
string cluster_id = 10;
|
||||
bool subscription_age_readiness = 11;
|
||||
bool response_serving_identity = 12;
|
||||
bool write_serving_generation_enforced = 13;
|
||||
}
|
||||
message Metadata {
|
||||
View view = 1;
|
||||
@@ -186,6 +187,7 @@ message WriteItem {
|
||||
int64 expected_catalog_revision = 5;
|
||||
string expected_serving_incarnation = 6;
|
||||
int64 remaining_budget_ticks = 7;
|
||||
optional int64 expected_serving_generation = 8;
|
||||
}
|
||||
message WriteRequest {
|
||||
repeated WriteItem items = 1;
|
||||
|
||||
@@ -246,7 +246,8 @@ public sealed record DataLimits(int MaxPageItems, int MaxBatchItems, int MaxMess
|
||||
}
|
||||
public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, ServingIdentity Serving, DataReadiness Readiness,
|
||||
DataOperations Operations, IReadOnlySet<DataValueKind> ValueKinds, DataLimits Limits, bool CompactBatches,
|
||||
int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false)
|
||||
int CompactCodecVersion, string ClusterId, bool SubscriptionAgeReadiness = false, bool ResponseServingIdentity = false,
|
||||
bool WriteServingGenerationEnforced = false)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
@@ -276,7 +277,7 @@ public sealed record DataCapabilities(int ProtocolMajor, int ProtocolMinor, Serv
|
||||
}
|
||||
public sealed record DataMetadata(DataView View, string BrowseName, string NodeKind, DataValueKind ValueKind, int ValueRank,
|
||||
IReadOnlyList<int> Dimensions, bool Writable, DataOperations AllowedOperations, long CatalogRevision,
|
||||
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null)
|
||||
string? StableSourceId, string? EngineeringUnits, bool IsStale, DataValueKind? ArrayElementKind = null, ServingIdentity? Serving = null)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
@@ -311,4 +312,4 @@ public sealed record DataMetadata(DataView View, string BrowseName, string NodeK
|
||||
}
|
||||
public sealed record DataItemResult<T>(string CorrelationId, DataItemStatus Status, T? Value, string? Diagnostic);
|
||||
public sealed record DataBrowseBranch(DataView Parent, DataItemStatus Status, IReadOnlyList<DataMetadata> Items,
|
||||
bool Complete, string? Continuation, MetadataLease? Lease);
|
||||
bool Complete, string? Continuation, MetadataLease? Lease, ServingIdentity? Serving = null);
|
||||
|
||||
@@ -22,7 +22,7 @@ public sealed record ReadResult(string CorrelationId, DataItemStatus Status, Dat
|
||||
}
|
||||
}
|
||||
public sealed record WriteItem(string CorrelationId, string OperationId, DataView View, DataValue Value,
|
||||
long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget);
|
||||
long ExpectedCatalogRevision, string ExpectedServingIncarnation, TimeSpan RemainingBudget, long? ExpectedServingGeneration = null);
|
||||
/// <summary>
|
||||
/// Admission binds the stable principal and original credential separately. Before dispatch,
|
||||
/// recheck the original key's current principal and credential version against authority and its
|
||||
@@ -131,6 +131,12 @@ public interface IDataSubscription : IAsyncDisposable
|
||||
Task SendAsync(DataSubscriptionCommand command, CancellationToken cancellationToken);
|
||||
IAsyncEnumerable<DataSubscriptionFrame> ReadAllAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
/// <summary>Immutable serving identity captured when the subscription was established.</summary>
|
||||
public interface IDataSubscriptionProvenance
|
||||
{
|
||||
ServingIdentity Serving { get; }
|
||||
}
|
||||
|
||||
/// <summary>One lifetime-scoped delivery mode, separate from direct enumeration.</summary>
|
||||
public interface IDataSubscriptionTransport : IDataSubscription
|
||||
{
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Disjoint local identifiers for mapped nodes. Decoding never establishes authorization.</summary>
|
||||
public static class ProjectedDataIds
|
||||
{
|
||||
public const string RawNamespaceUri = "https://zb.com/otopcua/mapped/raw";
|
||||
public const string UnsNamespaceUri = "https://zb.com/otopcua/mapped/uns";
|
||||
private const string Prefix = "p1.";
|
||||
private const int MaximumIdentifierLength = 16_384;
|
||||
private sealed record Identity(string MappingId, DataAddress Origin);
|
||||
|
||||
public static string NamespaceUri(DataRealm realm) => realm switch
|
||||
{
|
||||
DataRealm.Raw => RawNamespaceUri,
|
||||
DataRealm.Uns => UnsNamespaceUri,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(realm))
|
||||
};
|
||||
|
||||
public static bool IsMappedNamespace(string namespaceUri) =>
|
||||
namespaceUri is RawNamespaceUri or UnsNamespaceUri;
|
||||
|
||||
/// <summary>A portable dependency key, distinct from ordinary unqualified local paths.</summary>
|
||||
public static string DependencyReference(DataRealm realm, string localIdentifier)
|
||||
{
|
||||
if (!TryDecodeIdentifier(localIdentifier, out _, out _)) throw new ArgumentException("Invalid projected identifier.", nameof(localIdentifier));
|
||||
return "nsu=" + NamespaceUri(realm) + ";s=" + localIdentifier;
|
||||
}
|
||||
|
||||
public static bool TryParseDependencyReference(string reference, out DataRealm realm, out string localIdentifier)
|
||||
{
|
||||
realm = DataRealm.Unspecified; localIdentifier = string.Empty;
|
||||
if (reference is null) return false;
|
||||
foreach (var candidate in new[] { DataRealm.Raw, DataRealm.Uns })
|
||||
{
|
||||
var prefix = "nsu=" + NamespaceUri(candidate) + ";s=";
|
||||
if (!reference.StartsWith(prefix, StringComparison.Ordinal)) continue;
|
||||
var identifier = reference[prefix.Length..];
|
||||
if (!TryDecodeIdentifier(identifier, out _, out _)) return false;
|
||||
realm = candidate; localIdentifier = identifier; return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static string Identifier(string mappingId, DataAddress origin)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(mappingId);
|
||||
if (mappingId.Length > 256) throw new ArgumentOutOfRangeException(nameof(mappingId));
|
||||
ArgumentNullException.ThrowIfNull(origin);
|
||||
origin.Validate();
|
||||
var payload = JsonSerializer.SerializeToUtf8Bytes(new Identity(mappingId, origin));
|
||||
if (payload.Length > (MaximumIdentifierLength - Prefix.Length) * 3 / 4)
|
||||
throw new ArgumentOutOfRangeException(nameof(origin));
|
||||
return Prefix + Convert.ToBase64String(payload).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
}
|
||||
|
||||
public static bool TryDecodeIdentifier(string identifier, out string mappingId, out DataAddress? origin)
|
||||
{
|
||||
mappingId = string.Empty; origin = null;
|
||||
if (identifier is null || identifier.Length > MaximumIdentifierLength || !identifier.StartsWith(Prefix, StringComparison.Ordinal))
|
||||
return false;
|
||||
var encoded = identifier[Prefix.Length..];
|
||||
if (encoded.Length == 0 || encoded.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '-' and not '_')) return false;
|
||||
try
|
||||
{
|
||||
var padded = encoded.Replace('-', '+').Replace('_', '/');
|
||||
padded = padded.PadRight((padded.Length + 3) / 4 * 4, '=');
|
||||
var parsed = JsonSerializer.Deserialize<Identity>(Convert.FromBase64String(padded));
|
||||
if (parsed?.Origin is null || !string.Equals(Identifier(parsed.MappingId, parsed.Origin), identifier, StringComparison.Ordinal))
|
||||
return false;
|
||||
mappingId = parsed.MappingId; origin = parsed.Origin;
|
||||
return true;
|
||||
}
|
||||
catch (Exception error) when (error is JsonException or FormatException or ArgumentException)
|
||||
{ return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Process-wide retained input budget shared across script owners and redeploys.</summary>
|
||||
public static class ProjectedInputBudget
|
||||
{
|
||||
/// <summary>Current process-wide retained input limit in bytes.</summary>
|
||||
public const long MaximumBytes = 16 * 1024 * 1024;
|
||||
private const int MaximumSnapshots = 10_000;
|
||||
private static long s_used;
|
||||
|
||||
/// <summary>Bytes currently reserved by projected input owners.</summary>
|
||||
public static long RetainedBytes => Interlocked.Read(ref s_used);
|
||||
|
||||
/// <summary>Charges captured projected snapshots until the returned lease is disposed.</summary>
|
||||
public static bool TryRetain(IEnumerable<DataValueSnapshot> snapshots, out IDisposable? lease)
|
||||
{
|
||||
lease = null;
|
||||
var values = new List<DataValueSnapshot>();
|
||||
long charge = 0;
|
||||
try
|
||||
{
|
||||
foreach (var snapshot in snapshots)
|
||||
{
|
||||
if (values.Count == MaximumSnapshots || snapshot is null) return false;
|
||||
charge = checked(charge + Estimate(snapshot.Value));
|
||||
if (charge > MaximumBytes) return false;
|
||||
values.Add(snapshot);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or OverflowException) { return false; }
|
||||
if (charge == 0) return true;
|
||||
while (true)
|
||||
{
|
||||
var used = Interlocked.Read(ref s_used);
|
||||
if (charge > MaximumBytes - used) return false;
|
||||
if (Interlocked.CompareExchange(ref s_used, used + charge, used) == used) break;
|
||||
}
|
||||
lease = new Lease(values.ToArray(), charge);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static long Estimate(object? value)
|
||||
{
|
||||
checked
|
||||
{
|
||||
long size = 512;
|
||||
if (value is string text) size += 2L * text.Length;
|
||||
else if (value is byte[] bytes) size += bytes.LongLength;
|
||||
else if (value is Array array)
|
||||
{
|
||||
if (array.Rank > 4 || array.LongLength > 65536) throw new ArgumentException("Unsupported input array.");
|
||||
var elementType = array.GetType().GetElementType();
|
||||
if (elementType is null || !(elementType.IsPrimitive || elementType == typeof(string) ||
|
||||
elementType == typeof(Guid) || elementType == typeof(DateTime) || elementType == typeof(DateTimeOffset)))
|
||||
throw new ArgumentException("Unsupported input array.");
|
||||
size += 128 + 48L * array.LongLength;
|
||||
if (elementType == typeof(string)) foreach (var element in array) size += 2L * ((string?)element ?? "").Length;
|
||||
}
|
||||
else if (value is not null && !(value.GetType().IsPrimitive || value is Guid or DateTime or DateTimeOffset or decimal))
|
||||
throw new ArgumentException("Unsupported input value.");
|
||||
if (size > 4 * 1024 * 1024) throw new ArgumentException("Input is too large.");
|
||||
return size;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Lease(DataValueSnapshot[] snapshots, long charge) : IDisposable
|
||||
{
|
||||
private DataValueSnapshot[]? _snapshots = snapshots;
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _snapshots, null) is not null) Interlocked.Add(ref s_used, -charge);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
|
||||
/// <summary>Captured sample/route authority, independent of each local monitored item's caller.</summary>
|
||||
public interface IProjectedSamplePublicationProof
|
||||
{
|
||||
/// <summary>Checks the original live source, route, role and lease without network work.</summary>
|
||||
bool IsValid { get; }
|
||||
/// <summary>Stable source ownership; distinct sample witnesses may share this identity.</summary>
|
||||
object SourceIdentity => this;
|
||||
/// <summary>Source and route lifetime, independent of one sample's age.</summary>
|
||||
bool IsSourceValid => IsValid;
|
||||
TimeProvider Clock { get; }
|
||||
/// <summary>Synchronously invalidates value readiness after failed or lost ingress; metadata may remain browsable.</summary>
|
||||
void Invalidate();
|
||||
}
|
||||
|
||||
/// <summary>An imported sample retaining original ingress age through local actor and SDK queues.</summary>
|
||||
public sealed record ProjectedValueWrite(DataRealm Realm, string LocalIdentifier, long ProjectionGeneration,
|
||||
ServingIdentity Serving, DataValueSnapshot Snapshot, DataAgeBounds OriginAgeBounds, long ReceivedTimestamp,
|
||||
IProjectedSamplePublicationProof Proof, bool IsCompleteSnapshot = false);
|
||||
|
||||
/// <summary>Applies imported values only after checking their captured proof at the actual SDK boundary.</summary>
|
||||
public interface IProjectedValueSink
|
||||
{
|
||||
bool TryPublish(IReadOnlyList<ProjectedValueWrite> values);
|
||||
}
|
||||
@@ -42,3 +42,16 @@ public interface IDependencyConsumer
|
||||
/// <param name="timestampUtc">The source timestamp of the change.</param>
|
||||
void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc);
|
||||
}
|
||||
|
||||
/// <summary>A dependency consumer that retains and checks the authority of imported samples.</summary>
|
||||
public interface IProjectedDependencyConsumer
|
||||
{
|
||||
/// <summary>Receives an imported dependency together with its exact sample authority.</summary>
|
||||
/// <param name="rawPath">The dependency reference.</param>
|
||||
/// <param name="value">The imported value.</param>
|
||||
/// <param name="statusCode">The imported status code.</param>
|
||||
/// <param name="timestampUtc">The source timestamp.</param>
|
||||
/// <param name="proof">The captured sample and source authority.</param>
|
||||
void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc,
|
||||
DataConnections.IProjectedSamplePublicationProof proof);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||||
|
||||
/// <summary>Original input authority captured independently of later input replacement.</summary>
|
||||
public interface IAlarmInputEvidence
|
||||
{
|
||||
bool IsValid { get; }
|
||||
}
|
||||
|
||||
/// <summary>Provides evidence for the exact immutable snapshot read by an evaluation.</summary>
|
||||
public interface IAlarmInputEvidenceSource
|
||||
{
|
||||
IAlarmInputEvidence? CaptureEvidence(DataValueSnapshot exactSnapshot);
|
||||
}
|
||||
|
||||
/// <summary>Reserves the retained input bytes through physical script completion.</summary>
|
||||
public interface IAlarmInputPhysicalEvidence : IAlarmInputEvidence
|
||||
{
|
||||
bool TryRetainPhysical(DataValueSnapshot exactSnapshot, out IDisposable? lease);
|
||||
}
|
||||
@@ -547,12 +547,15 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
var projections = new List<ScriptedAlarmProjection>(_alarms.Count);
|
||||
foreach (var (alarmId, state) in _alarms)
|
||||
{
|
||||
var inputs = new Dictionary<string, DataValueSnapshot>(StringComparer.Ordinal);
|
||||
RefillReadCache(inputs, state.Inputs);
|
||||
var captured = CaptureInputs(state, inputs);
|
||||
projections.Add(new ScriptedAlarmProjection(
|
||||
AlarmId: alarmId,
|
||||
Severity: state.Definition.Severity,
|
||||
Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup),
|
||||
Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, LookupControlValue),
|
||||
Condition: state.Condition,
|
||||
WorstInputStatusCode: LastWorstStatus(alarmId)));
|
||||
WorstInputStatusCode: captured.Evidence is { IsValid: false } ? 0x80310000u : LastWorstStatus(alarmId)));
|
||||
}
|
||||
|
||||
return projections;
|
||||
@@ -890,6 +893,9 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
state.Definition.AlarmId,
|
||||
_ => new AlarmScratch(state.Inputs, state.Logger, _clock));
|
||||
RefillReadCache(scratch.ReadCache, state.Inputs);
|
||||
var captured = CaptureInputs(state, scratch.ReadCache);
|
||||
scratch.HasProjectedInputs = captured.Evidence is not null;
|
||||
if (captured.Evidence is { IsValid: false }) return seed;
|
||||
|
||||
// Worst OPC UA quality across the alarm's inputs, computed BEFORE the readiness
|
||||
// short-circuit so an outright-Bad input is still observed. A bucket change with no state
|
||||
@@ -908,18 +914,20 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
// bucket — annotate it out of band so a comms-lost / Bad-input scripted condition reports
|
||||
// Bad, mirroring the native OT path.
|
||||
if (TrackQualityBucket(state.Definition.AlarmId, worstStatus))
|
||||
pendingEmissions.Add(BuildQualityEmission(state, seed, worstStatus));
|
||||
pendingEmissions.Add(BuildQualityEmission(state, seed, worstStatus, captured));
|
||||
return seed;
|
||||
}
|
||||
|
||||
var context = scratch.Context;
|
||||
var context = captured.Evidence is null ? scratch.Context
|
||||
: new AlarmPredicateContext(captured.Values, state.Logger, _clock);
|
||||
|
||||
if (!TryRetainInputs(captured, out var physicalLease)) return seed;
|
||||
bool predicateTrue;
|
||||
try
|
||||
{
|
||||
predicateTrue = await _guard.RunAsync(
|
||||
state.Definition.AlarmId, state.Definition.PredicateScriptSource, state.Evaluator!, context,
|
||||
_scriptTimeout, ct)
|
||||
_scriptTimeout, ct, physicalLease)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
@@ -950,6 +958,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
state.Logger.Error(ex, "Alarm predicate threw — state unchanged");
|
||||
return seed;
|
||||
}
|
||||
if (captured.Evidence is { IsValid: false }) return seed;
|
||||
MirrorPredicate(state, scratch, ScriptRunOutcome.Ok(predicateTrue));
|
||||
scratch.LastNonCompletion = null;
|
||||
|
||||
@@ -961,7 +970,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
|
||||
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
|
||||
var transition = result.Emission != EmissionKind.None
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus)
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
|
||||
: null;
|
||||
if (transition is not null)
|
||||
{
|
||||
@@ -972,7 +981,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
else if (qualityBucketChanged)
|
||||
{
|
||||
// No transition (or a Suppressed one) but the quality bucket moved — annotate out of band.
|
||||
pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus));
|
||||
pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus, captured));
|
||||
}
|
||||
return result.State;
|
||||
}
|
||||
@@ -984,7 +993,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// </summary>
|
||||
private void MirrorPredicate(AlarmState state, AlarmScratch scratch, ScriptRunOutcome published)
|
||||
{
|
||||
if (_shadow is null) return;
|
||||
if (_shadow is null || scratch.HasProjectedInputs) return;
|
||||
_shadow.Mirror(new ScriptInvocation(
|
||||
state.Definition.AlarmId, ScriptContextKind.AlarmPredicate, state.Definition.PredicateScriptSource,
|
||||
scratch.ReadCache, _scriptTimeout), published);
|
||||
@@ -1030,6 +1039,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
var runner = _runner!;
|
||||
var after = new AlarmConditionState[items.Count];
|
||||
var scratches = new AlarmScratch[items.Count];
|
||||
var capturedInputs = new CapturedInputs[items.Count];
|
||||
var worst = new uint[items.Count];
|
||||
var slot = new int[items.Count];
|
||||
var invocations = new List<ScriptInvocation>(items.Count);
|
||||
@@ -1041,21 +1051,39 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
var scratch = scratches[i] = _scratchByAlarmId.GetOrAdd(
|
||||
state.Definition.AlarmId, _ => new AlarmScratch(state.Inputs, state.Logger, _clock));
|
||||
RefillReadCache(scratch.ReadCache, state.Inputs);
|
||||
var captured = capturedInputs[i] = CaptureInputs(state, scratch.ReadCache);
|
||||
worst[i] = WorstInputStatus(scratch.ReadCache);
|
||||
if (!AreInputsReady(scratch.ReadCache))
|
||||
if (!AreInputsReady(scratch.ReadCache) || captured.Evidence is { IsValid: false })
|
||||
{
|
||||
slot[i] = -1;
|
||||
continue;
|
||||
}
|
||||
if (!TryRetainInputs(captured, out var physicalLease))
|
||||
{
|
||||
slot[i] = -1;
|
||||
continue;
|
||||
}
|
||||
if (physicalLease is not null && runner is not IPhysicalScriptRunner)
|
||||
{
|
||||
physicalLease.Dispose();
|
||||
slot[i] = -1;
|
||||
continue;
|
||||
}
|
||||
slot[i] = invocations.Count;
|
||||
// A copy: the runner may still read the inputs after the caller has its answer (a soft timeout), and the
|
||||
// scratch is refilled by the next pass.
|
||||
invocations.Add(new ScriptInvocation(state.Definition.AlarmId, ScriptContextKind.AlarmPredicate,
|
||||
state.Definition.PredicateScriptSource,
|
||||
new Dictionary<string, DataValueSnapshot>(scratch.ReadCache, StringComparer.Ordinal), _scriptTimeout, state.Logger));
|
||||
captured.Values, _scriptTimeout, state.Logger, physicalLease));
|
||||
}
|
||||
|
||||
var outcomes = invocations.Count == 0 ? [] : runner.RunBatch(invocations, ct);
|
||||
IReadOnlyList<Task<ScriptRunOutcome>> outcomes;
|
||||
try { outcomes = invocations.Count == 0 ? [] : runner.RunBatch(invocations, ct); }
|
||||
catch
|
||||
{
|
||||
foreach (var invocation in invocations) invocation.PhysicalLease?.Dispose();
|
||||
throw;
|
||||
}
|
||||
PredicateBatchSubmittedForTest?.Invoke(invocations.Count);
|
||||
|
||||
// Pass 2, in order: exactly what the serial path does with each alarm.
|
||||
@@ -1066,20 +1094,21 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
if (slot[i] < 0)
|
||||
{
|
||||
if (TrackQualityBucket(state.Definition.AlarmId, worst[i]))
|
||||
pendingEmissions.Add(BuildQualityEmission(state, seed, worst[i]));
|
||||
pendingEmissions.Add(BuildQualityEmission(state, seed, worst[i], capturedInputs[i]));
|
||||
after[i] = seed;
|
||||
continue;
|
||||
}
|
||||
|
||||
var outcome = await outcomes[slot[i]].ConfigureAwait(false);
|
||||
after[i] = ApplyPredicateOutcome(state, seed, scratch, worst[i], outcome, nowUtc, ct, pendingEmissions);
|
||||
after[i] = capturedInputs[i].Evidence is { IsValid: false } ? seed
|
||||
: ApplyPredicateOutcome(state, seed, scratch, worst[i], outcome, nowUtc, ct, pendingEmissions, capturedInputs[i]);
|
||||
}
|
||||
return after;
|
||||
}
|
||||
|
||||
/// <summary>One runner outcome onto one alarm (the second half of <see cref="EvaluatePredicateToStateAsync"/>).</summary>
|
||||
private AlarmConditionState ApplyPredicateOutcome(AlarmState state, AlarmConditionState seed, AlarmScratch scratch,
|
||||
uint worstStatus, ScriptRunOutcome outcome, DateTime nowUtc, CancellationToken ct, List<ScriptedAlarmEvent> pendingEmissions)
|
||||
uint worstStatus, ScriptRunOutcome outcome, DateTime nowUtc, CancellationToken ct, List<ScriptedAlarmEvent> pendingEmissions, CapturedInputs captured)
|
||||
{
|
||||
switch (outcome.Status)
|
||||
{
|
||||
@@ -1115,10 +1144,10 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
var qualityBucketChanged = TrackQualityBucket(state.Definition.AlarmId, worstStatus);
|
||||
var result = Part9StateMachine.ApplyPredicate(seed, predicateTrue, nowUtc);
|
||||
var transition = result.Emission != EmissionKind.None
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus)
|
||||
? BuildEmission(state, result.State, result.Emission, worstStatus, captured)
|
||||
: null;
|
||||
if (transition is not null) pendingEmissions.Add(transition);
|
||||
else if (qualityBucketChanged) pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus));
|
||||
else if (qualityBucketChanged) pendingEmissions.Add(BuildQualityEmission(state, result.State, worstStatus, captured));
|
||||
return result.State;
|
||||
}
|
||||
|
||||
@@ -1216,13 +1245,14 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// released.
|
||||
/// </summary>
|
||||
private ScriptedAlarmEvent? BuildEmission(
|
||||
AlarmState state, AlarmConditionState condition, EmissionKind kind, uint worstInputStatus)
|
||||
AlarmState state, AlarmConditionState condition, EmissionKind kind, uint worstInputStatus, CapturedInputs? captured = null)
|
||||
{
|
||||
// Suppressed kind means shelving ate the emission — we don't fire for subscribers
|
||||
// but the state record still advanced so startup recovery reflects reality.
|
||||
if (kind == EmissionKind.Suppressed || kind == EmissionKind.None) return null;
|
||||
|
||||
var message = MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup);
|
||||
var message = MessageTemplate.Resolve(state.Definition.MessageTemplate,
|
||||
captured?.Evidence is null ? LookupControlValue : path => captured.Values.GetValueOrDefault(path));
|
||||
return new ScriptedAlarmEvent(
|
||||
AlarmId: state.Definition.AlarmId,
|
||||
EquipmentPath: state.Definition.EquipmentPath,
|
||||
@@ -1249,7 +1279,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
HistorizeToAveva: state.Definition.HistorizeToAveva,
|
||||
// The worst input quality at evaluation time rides the transition so the projected
|
||||
// full snapshot keeps quality consistent (no clobber-to-Good).
|
||||
WorstInputStatusCode: worstInputStatus);
|
||||
WorstInputStatusCode: worstInputStatus) { InputEvidence = captured?.Evidence };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1260,19 +1290,20 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// no <c>/alerts</c> row, no historian write); the <see cref="IAlarmSource"/> fan-out skips it.
|
||||
/// </summary>
|
||||
private ScriptedAlarmEvent BuildQualityEmission(
|
||||
AlarmState state, AlarmConditionState condition, uint worstInputStatus)
|
||||
AlarmState state, AlarmConditionState condition, uint worstInputStatus, CapturedInputs? captured = null)
|
||||
=> new(
|
||||
AlarmId: state.Definition.AlarmId,
|
||||
EquipmentPath: state.Definition.EquipmentPath,
|
||||
AlarmName: state.Definition.AlarmName,
|
||||
Kind: state.Definition.Kind,
|
||||
Severity: state.Definition.Severity,
|
||||
Message: MessageTemplate.Resolve(state.Definition.MessageTemplate, TryLookup),
|
||||
Message: MessageTemplate.Resolve(state.Definition.MessageTemplate,
|
||||
captured?.Evidence is null ? LookupControlValue : path => captured.Values.GetValueOrDefault(path)),
|
||||
Condition: condition,
|
||||
Emission: EmissionKind.QualityChanged,
|
||||
TimestampUtc: _clock(),
|
||||
HistorizeToAveva: state.Definition.HistorizeToAveva,
|
||||
WorstInputStatusCode: worstInputStatus);
|
||||
WorstInputStatusCode: worstInputStatus) { InputEvidence = captured?.Evidence };
|
||||
|
||||
/// <summary>Worst OPC UA StatusCode across a refilled read cache — the entry with the highest severity
|
||||
/// bits (top 2). An input that has never been pushed is NOT a quality signal: it means "no data", which
|
||||
@@ -1338,6 +1369,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// </summary>
|
||||
private void FireEvent(ScriptedAlarmEvent evt)
|
||||
{
|
||||
if (evt.InputEvidence is { IsValid: false }) return;
|
||||
try { OnEvent?.Invoke(this, evt); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -1345,6 +1377,69 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record CapturedInputs(Dictionary<string, DataValueSnapshot> Values, IAlarmInputEvidence? Evidence);
|
||||
|
||||
private sealed class PhysicalInputLease(IDisposable[] leases) : IDisposable
|
||||
{
|
||||
private IDisposable[]? _leases = leases;
|
||||
public void Dispose()
|
||||
{
|
||||
var owned = Interlocked.Exchange(ref _leases, null);
|
||||
if (owned is null) return;
|
||||
foreach (var lease in owned) lease.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private bool TryRetainInputs(CapturedInputs captured, out IDisposable? lease)
|
||||
{
|
||||
lease = null;
|
||||
if (captured.Evidence is null) return true;
|
||||
if (!captured.Evidence.IsValid) return false;
|
||||
var retained = new List<IDisposable>();
|
||||
try
|
||||
{
|
||||
if (_upstream is IAlarmInputEvidenceSource source)
|
||||
foreach (var snapshot in captured.Values.Values.Distinct<DataValueSnapshot>(ReferenceEqualityComparer.Instance))
|
||||
if (source.CaptureEvidence(snapshot) is IAlarmInputPhysicalEvidence physical)
|
||||
{
|
||||
if (!physical.TryRetainPhysical(snapshot, out var owned) || owned is null) return false;
|
||||
retained.Add(owned);
|
||||
}
|
||||
if (!captured.Evidence.IsValid) return false;
|
||||
if (retained.Count != 0) lease = new PhysicalInputLease(retained.ToArray());
|
||||
retained.Clear();
|
||||
return true;
|
||||
}
|
||||
finally { foreach (var owned in retained) owned.Dispose(); }
|
||||
}
|
||||
|
||||
private sealed class InputEvidence(IAlarmInputEvidence[] inputs) : IAlarmInputEvidence
|
||||
{
|
||||
public bool IsValid => inputs.All(input => input.IsValid);
|
||||
}
|
||||
|
||||
private CapturedInputs CaptureInputs(AlarmState state, Dictionary<string, DataValueSnapshot> inputs)
|
||||
{
|
||||
if (_upstream is not IAlarmInputEvidenceSource source ||
|
||||
!inputs.Values.Any(snapshot => source.CaptureEvidence(snapshot) is not null) &&
|
||||
!state.TemplateTokens.Any(path => TryLookup(path) is { } snapshot && source.CaptureEvidence(snapshot) is not null))
|
||||
return new CapturedInputs(inputs, null);
|
||||
var values = new Dictionary<string, DataValueSnapshot>(inputs, StringComparer.Ordinal);
|
||||
foreach (var path in state.TemplateTokens)
|
||||
if (!values.ContainsKey(path) && TryLookup(path) is { } snapshot) values[path] = snapshot;
|
||||
var evidence = values.Values.Select(source.CaptureEvidence).OfType<IAlarmInputEvidence>().ToArray();
|
||||
return new CapturedInputs(values, evidence.Length == 0 ? null : new InputEvidence(evidence));
|
||||
}
|
||||
|
||||
// Control/recovery events have durable semantics independent of current inputs. They must not
|
||||
// embed transient remote values without the original evaluation's authority and physical lease.
|
||||
private DataValueSnapshot? LookupControlValue(string path)
|
||||
{
|
||||
var value = TryLookup(path);
|
||||
return value is not null && _upstream is IAlarmInputEvidenceSource source && source.CaptureEvidence(value) is not null
|
||||
? null : value;
|
||||
}
|
||||
|
||||
private DataValueSnapshot? TryLookup(string path)
|
||||
=> _valueCache.TryGetValue(path, out var v) ? v : null;
|
||||
|
||||
@@ -1624,6 +1719,7 @@ public sealed class ScriptedAlarmEngine : IDisposable
|
||||
/// <summary>The reason the last evaluation did not complete (timeout / refused / quarantined), or null
|
||||
/// after a completed run — the once-per-change log gate for <c>PredicateDidNotComplete</c>.</summary>
|
||||
public string? LastNonCompletion { get; set; }
|
||||
public bool HasProjectedInputs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new AlarmScratch with the specified inputs, logger, and clock.
|
||||
@@ -1666,7 +1762,12 @@ public sealed record ScriptedAlarmEvent(
|
||||
// since Core.ScriptedAlarms does not reference Commons. The host carries it to the condition
|
||||
// node UNCHANGED — it used to be collapsed to a 3-state bucket and re-expanded, losing the sub-code.
|
||||
// Default 0u == Good keeps every existing constructor call unchanged.
|
||||
uint WorstInputStatusCode = 0u);
|
||||
uint WorstInputStatusCode = 0u)
|
||||
{
|
||||
/// <summary>Transient exact-input authority for the local final emission boundary.</summary>
|
||||
[System.Text.Json.Serialization.JsonIgnore]
|
||||
public IAlarmInputEvidence? InputEvidence { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A loaded alarm's current condition, ready to be projected onto its OPC UA node.
|
||||
|
||||
@@ -67,7 +67,7 @@ public sealed record ScriptRunnerStatus(
|
||||
/// HMAC-verified compiled images instead of re-entering Roslyn after a restart.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable, IDisposable
|
||||
public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisposable, IDisposable
|
||||
{
|
||||
/// <summary>The worker entry assembly's file name.</summary>
|
||||
public const string WorkerAssemblyFileName = "ZB.MOM.WW.OtOpcUa.ScriptWorker.dll";
|
||||
@@ -366,6 +366,13 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable,
|
||||
public async Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(invocation);
|
||||
var ownership = new PhysicalLeaseOwnership(invocation.PhysicalLease);
|
||||
try { return await RunOwnedAsync(invocation, ownership, ct).ConfigureAwait(false); }
|
||||
finally { ownership.DisposeIfUntransferred(); }
|
||||
}
|
||||
|
||||
private async Task<ScriptRunOutcome> RunOwnedAsync(ScriptInvocation invocation, PhysicalLeaseOwnership ownership, CancellationToken ct)
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0) return ScriptRunOutcome.Unavailable(ScriptRunOutcome.RunnerUnavailableReason);
|
||||
|
||||
var key = InProcessScriptRunner.ScopedKey(invocation.Kind, invocation.Key);
|
||||
@@ -435,7 +442,8 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable,
|
||||
// run by then.
|
||||
var submitted = Stopwatch.GetTimestamp();
|
||||
var pending = connection.Submit(key, BuildRequest(key, entry, invocation), invocation.Timeout,
|
||||
_worker.EffectiveHardGrace(invocation.Timeout), SlotRelease(key, state, gate));
|
||||
_worker.EffectiveHardGrace(invocation.Timeout), SlotRelease(key, state, gate, ownership));
|
||||
ownership.Transfer();
|
||||
handedOff = true;
|
||||
return await AwaitSubmittedAsync(key, state, invocation, shard, connection, pending, submitted, ct).ConfigureAwait(false);
|
||||
}
|
||||
@@ -478,6 +486,7 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable,
|
||||
{
|
||||
var invocation = invocations[i];
|
||||
ArgumentNullException.ThrowIfNull(invocation);
|
||||
if (invocation.PhysicalLease is not null) { outcomes[i] = RunAsync(invocation, ct); continue; }
|
||||
switch (TryPrepareBatchItem(invocation, out var item, out var answered))
|
||||
{
|
||||
case BatchPreparation.Submit:
|
||||
@@ -555,16 +564,20 @@ public sealed class OutOfProcessScriptRunner : IScriptRunner, IAsyncDisposable,
|
||||
/// 32 of 200 refused when the release was an unordered continuation). On a worker death, attribution (strike,
|
||||
/// quarantine, suspect) has already run by then.
|
||||
/// </summary>
|
||||
private Action SlotRelease(string key, KeyState state, SemaphoreSlim? heldGate)
|
||||
private Action SlotRelease(string key, KeyState state, SemaphoreSlim? heldGate, IDisposable? physicalLease = null)
|
||||
{
|
||||
var released = 0;
|
||||
return () =>
|
||||
{
|
||||
if (Interlocked.Exchange(ref released, 1) != 0) return;
|
||||
SlotReleasingForTest?.Invoke(key);
|
||||
Volatile.Write(ref state.StalledRun, null);
|
||||
Interlocked.Exchange(ref state.InFlight, 0);
|
||||
heldGate?.Release();
|
||||
try
|
||||
{
|
||||
SlotReleasingForTest?.Invoke(key);
|
||||
Volatile.Write(ref state.StalledRun, null);
|
||||
Interlocked.Exchange(ref state.InFlight, 0);
|
||||
heldGate?.Release();
|
||||
}
|
||||
finally { physicalLease?.Dispose(); }
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,9 @@ public interface IScriptRunner
|
||||
IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind);
|
||||
}
|
||||
|
||||
/// <summary>A runner that owns invocation physical leases until underlying execution actually completes.</summary>
|
||||
public interface IPhysicalScriptRunner : IScriptRunner { }
|
||||
|
||||
/// <summary>Which script context (and result type) a script compiles against.</summary>
|
||||
public enum ScriptContextKind
|
||||
{
|
||||
@@ -86,13 +89,15 @@ public enum ScriptContextKind
|
||||
/// <param name="Inputs">The read cache: dependency snapshots by path. Not mutated until the run completes.</param>
|
||||
/// <param name="Timeout">The soft budget <c>T</c>.</param>
|
||||
/// <param name="ScriptLogger">The per-evaluation script logger <c>ctx.Logger</c> writes through; null ⇒ a silent logger.</param>
|
||||
/// <param name="PhysicalLease">Retained input ownership transferred to a physical-lifetime-aware runner.</param>
|
||||
public sealed record ScriptInvocation(
|
||||
string Key,
|
||||
ScriptContextKind Kind,
|
||||
string Source,
|
||||
IReadOnlyDictionary<string, DataValueSnapshot> Inputs,
|
||||
TimeSpan Timeout,
|
||||
Serilog.ILogger? ScriptLogger = null);
|
||||
Serilog.ILogger? ScriptLogger = null,
|
||||
IDisposable? PhysicalLease = null);
|
||||
|
||||
/// <summary>How an evaluation ended.</summary>
|
||||
public enum ScriptRunStatus
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
/// existing guard code, so the default mode is unchanged byte for byte. Unlike those paths, this runner remembers
|
||||
/// compile failures by source for every kind (Calculation already did, R07:P4).
|
||||
/// </remarks>
|
||||
public sealed class InProcessScriptRunner : IScriptRunner, IDisposable
|
||||
public sealed class InProcessScriptRunner : IPhysicalScriptRunner, IDisposable
|
||||
{
|
||||
private readonly CompiledScriptCache<VirtualTagContext, object?> _valueCache = new();
|
||||
private readonly CompiledScriptCache<AlarmPredicateContext, bool> _predicateCache = new();
|
||||
@@ -40,6 +40,13 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable
|
||||
public async Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(invocation);
|
||||
var ownership = new PhysicalLeaseOwnership(invocation.PhysicalLease);
|
||||
try { return await RunOwnedAsync(invocation, ownership, ct).ConfigureAwait(false); }
|
||||
finally { ownership.DisposeIfUntransferred(); }
|
||||
}
|
||||
|
||||
private async Task<ScriptRunOutcome> RunOwnedAsync(ScriptInvocation invocation, PhysicalLeaseOwnership ownership, CancellationToken ct)
|
||||
{
|
||||
var key = ScopedKey(invocation.Kind, invocation.Key);
|
||||
var failureKey = ScopedKey(invocation.Kind, invocation.Source);
|
||||
if (_compileFailures.TryGetValue(failureKey, out var known)) return ScriptRunOutcome.Failed(known);
|
||||
@@ -54,7 +61,7 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable
|
||||
{
|
||||
var evaluator = await Task.Run(() => _valueCache.GetOrCompile(invocation.Source), ct).ConfigureAwait(false);
|
||||
var context = new VirtualTagContext(invocation.Inputs, static (_, _) => { }, logger);
|
||||
var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct)
|
||||
var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct, ownership.Transfer())
|
||||
.ConfigureAwait(false);
|
||||
return ScriptRunOutcome.Ok(value);
|
||||
}
|
||||
@@ -62,7 +69,7 @@ public sealed class InProcessScriptRunner : IScriptRunner, IDisposable
|
||||
{
|
||||
var evaluator = await Task.Run(() => _predicateCache.GetOrCompile(invocation.Source), ct).ConfigureAwait(false);
|
||||
var context = new AlarmPredicateContext(invocation.Inputs, logger);
|
||||
var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct)
|
||||
var value = await _guard.RunAsync(key, invocation.Source, evaluator, context, invocation.Timeout, ct, ownership.Transfer())
|
||||
.ConfigureAwait(false);
|
||||
return ScriptRunOutcome.Ok(value);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>Idempotent transfer of a retained physical payload to a runner completion callback.</summary>
|
||||
public sealed class PhysicalLeaseOwnership(IDisposable? lease) : IDisposable
|
||||
{
|
||||
private IDisposable? _lease = lease;
|
||||
private int _transferred;
|
||||
public IDisposable? Transfer() { Interlocked.Exchange(ref _transferred, 1); return this; }
|
||||
public void DisposeIfUntransferred() { if (Volatile.Read(ref _transferred) == 0) Dispose(); }
|
||||
public void Dispose() => Interlocked.Exchange(ref _lease, null)?.Dispose();
|
||||
}
|
||||
@@ -174,15 +174,20 @@ public sealed class ScriptRunGuard
|
||||
/// <exception cref="ScriptRunRefusedException">The key's previous run is still executing.</exception>
|
||||
/// <exception cref="ScriptTimeoutException">The run exceeded <paramref name="timeout"/>.</exception>
|
||||
/// <exception cref="OperationCanceledException"><paramref name="ct"/> was cancelled.</exception>
|
||||
/// <param name="physicalLease">Input ownership released on nonadmission or actual evaluator completion.</param>
|
||||
public async Task<TResult> RunAsync<TContext, TResult>(
|
||||
string key,
|
||||
string? sourceIdentity,
|
||||
ScriptEvaluator<TContext, TResult> evaluator,
|
||||
TContext context,
|
||||
TimeSpan timeout,
|
||||
CancellationToken ct = default)
|
||||
CancellationToken ct = default,
|
||||
IDisposable? physicalLease = null)
|
||||
where TContext : ScriptContext
|
||||
{
|
||||
var transferred = false;
|
||||
try
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
ArgumentNullException.ThrowIfNull(evaluator);
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
@@ -267,14 +272,19 @@ public sealed class ScriptRunGuard
|
||||
// evaluation still running" — a Bad publish for a script that had finished. Seen under load:
|
||||
// 24 of 4,800 sequential same-key evaluations. A late-finishing orphan that breached the
|
||||
// allocation budget quarantines its key first, so no re-trigger slips in between.
|
||||
if (succeeded && BreachedBudget(slot.AllocatedBytes))
|
||||
Quarantine(key, state, AllocationReason(slot.AllocatedBytes), "allocation");
|
||||
SlotReleasingForTest?.Invoke(key);
|
||||
Volatile.Write(ref state.RunStartedTimestamp, 0);
|
||||
Interlocked.Exchange(ref state.InFlight, 0);
|
||||
Interlocked.Decrement(ref _inFlight);
|
||||
try
|
||||
{
|
||||
if (succeeded && BreachedBudget(slot.AllocatedBytes))
|
||||
Quarantine(key, state, AllocationReason(slot.AllocatedBytes), "allocation");
|
||||
SlotReleasingForTest?.Invoke(key);
|
||||
Volatile.Write(ref state.RunStartedTimestamp, 0);
|
||||
Interlocked.Exchange(ref state.InFlight, 0);
|
||||
Interlocked.Decrement(ref _inFlight);
|
||||
}
|
||||
finally { physicalLease?.Dispose(); }
|
||||
}
|
||||
});
|
||||
transferred = true;
|
||||
|
||||
_ = runTask.ContinueWith(t =>
|
||||
{
|
||||
@@ -320,6 +330,8 @@ public sealed class ScriptRunGuard
|
||||
throw new ScriptQuarantinedException(key, state.QuarantineReason!);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
finally { if (!transferred) physicalLease?.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>Resolve the key's state, rolling it over when the source identity changed, and refuse a quarantined key.</summary>
|
||||
|
||||
Reference in New Issue
Block a user