feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user