feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
@@ -5,6 +5,7 @@ using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Serilog;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation;
|
||||
@@ -45,7 +46,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Calculation;
|
||||
/// A historized Bad records <c>BadInternalError</c>.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscribable, IReadable, ISkippedTagReporter, IDisposable
|
||||
public sealed class CalculationDriver : IDriver, IDependencyConsumer, IProjectedDependencyConsumer, ISubscribable, IReadable, ISkippedTagReporter, IDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not build into its calc table. A raw tag with
|
||||
/// no <c>scriptId</c> is not a calc tag and computes nothing.</summary>
|
||||
@@ -85,6 +86,8 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
// comms-lost input apart from a genuine Good null, and storing values only is what let this driver
|
||||
// compute a Good output from a dead source.
|
||||
private readonly Dictionary<string, DataValueSnapshot> _depValues = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, IProjectedSamplePublicationProof> _projectedProofs = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, IDisposable> _projectedCacheLeases = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _arrivedDeps = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, TagState> _stateByRawPath = new(StringComparer.Ordinal);
|
||||
|
||||
@@ -105,8 +108,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
// Change-triggered evaluations queued by OnDependencyValue and drained, in arrival order, by a single
|
||||
// pump task. Both fields are guarded by _lock; _pumpScheduled stays true until the pump observes an
|
||||
// empty queue under the lock, so an enqueue can never be lost against a pump that is exiting.
|
||||
private readonly Queue<PendingEvaluation> _pending = new();
|
||||
private readonly LinkedList<PendingEvaluation> _pending = new();
|
||||
private readonly Dictionary<string, LinkedListNode<PendingEvaluation>> _pendingProjected = new(StringComparer.Ordinal);
|
||||
private bool _pumpScheduled;
|
||||
private long _projectedQueueVisits;
|
||||
internal long ProjectedQueueVisitsForTest => Interlocked.Read(ref _projectedQueueVisits);
|
||||
|
||||
private CalculationTimerScheduler? _timers;
|
||||
private volatile bool _running;
|
||||
@@ -204,6 +210,13 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
.SelectMany(t => t.DependencyRefs)
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
foreach (var path in _projectedProofs.Keys.Except(_dependencyRefs, StringComparer.Ordinal).ToArray())
|
||||
{
|
||||
if (_projectedCacheLeases.Remove(path, out var lease)) lease.Dispose();
|
||||
_projectedProofs.Remove(path);
|
||||
_depValues.Remove(path);
|
||||
_arrivedDeps.Remove(path);
|
||||
}
|
||||
}
|
||||
|
||||
// Reinit config-bind options — mirrors the factory's bind (case-insensitive, enum-string, trailing-comma
|
||||
@@ -261,7 +274,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
// Queued evaluations were prepared against the OUTGOING tag table (old script source, old
|
||||
// dependency set), so they are stale the moment the rebuild lands — drop them rather than
|
||||
// publish one last pre-edit value after the delta was applied.
|
||||
_pending.Clear();
|
||||
ClearPending();
|
||||
RebuildTagTable(newOptions);
|
||||
}
|
||||
// Drop compiled scripts (IScriptCacheOwner contract — stops collectible ALCs accreting AND forces a
|
||||
@@ -337,7 +350,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
_running = false;
|
||||
StopTimers();
|
||||
// The pump exits at its next iteration; an evaluation already in flight is bounded by RunTimeout.
|
||||
lock (_lock) _pending.Clear();
|
||||
lock (_lock) ClearPending();
|
||||
// R07:L2 — nothing in the runtime disposes a driver, and every config change is a respawn, so
|
||||
// the compiled scripts' collectible ALCs survived each generation until GC got round to the whole
|
||||
// driver graph. Drop them here (idempotent; a later InitializeAsync recompiles on first use). An
|
||||
@@ -367,14 +380,38 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
|
||||
/// <inheritdoc />
|
||||
public void OnDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc)
|
||||
=> OnDependencyValueCore(rawPath, value, statusCode, timestampUtc, null);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void OnProjectedDependencyValue(string rawPath, object? value, uint statusCode, DateTime timestampUtc,
|
||||
IProjectedSamplePublicationProof proof)
|
||||
=> OnDependencyValueCore(rawPath, value, statusCode, timestampUtc, proof);
|
||||
|
||||
private void OnDependencyValueCore(string rawPath, object? value, uint statusCode, DateTime timestampUtc,
|
||||
IProjectedSamplePublicationProof? proof)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_disposed || proof is not null && !_dependencyRefs.Contains(rawPath, StringComparer.Ordinal)) return;
|
||||
var snapshot = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc);
|
||||
IDisposable? cacheLease = null;
|
||||
if (proof is not null && (!ProofValid(proof) ||
|
||||
!ProjectedInputBudget.TryRetain([snapshot], out cacheLease) || cacheLease is null))
|
||||
{
|
||||
snapshot = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc);
|
||||
}
|
||||
if (_projectedCacheLeases.Remove(rawPath, out var oldLease)) oldLease.Dispose();
|
||||
_projectedProofs.Remove(rawPath);
|
||||
if (proof is not null)
|
||||
{
|
||||
_projectedProofs[rawPath] = proof;
|
||||
if (cacheLease is not null) _projectedCacheLeases[rawPath] = cacheLease;
|
||||
}
|
||||
// Recorded REGARDLESS of _running (R07:H6): the mux adapter registers interest at construction,
|
||||
// so inputs — the mux's retained-value replay in particular — can land before InitializeAsync.
|
||||
// Dropping them left every calc tag waiting for each input to change again; keeping them means
|
||||
// the first trigger after init evaluates from current inputs. Only the EVALUATION is gated.
|
||||
_depValues[rawPath] = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc);
|
||||
_depValues[rawPath] = snapshot;
|
||||
_arrivedDeps.Add(rawPath);
|
||||
if (!_running) return;
|
||||
if (!_changeDependents.TryGetValue(rawPath, out var dependents) || dependents.Count == 0) return;
|
||||
@@ -387,7 +424,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
foreach (var calcRawPath in dependents)
|
||||
{
|
||||
if (PrepareEvaluation(calcRawPath, timestampUtc) is not { } prepared) continue;
|
||||
_pending.Enqueue(prepared);
|
||||
EnqueueEvaluation(prepared);
|
||||
queued = true;
|
||||
}
|
||||
if (queued) SchedulePump();
|
||||
@@ -459,11 +496,18 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
/// <param name="WorstInputStatus">The worst status among <paramref name="Dependencies"/>
|
||||
/// (<see cref="InputQuality.WorstOf"/>). Bad ⇒ the script is HELD and this status is published;
|
||||
/// Good or Uncertain ⇒ the script runs and its result is stamped with it.</param>
|
||||
/// <param name="Proofs">Captured authority for each projected dependency.</param>
|
||||
/// <param name="Ownership">Retained ownership of the projected inputs.</param>
|
||||
private sealed record PendingEvaluation(
|
||||
CalculationTagDefinition Definition,
|
||||
IReadOnlyDictionary<string, DataValueSnapshot> Dependencies,
|
||||
DateTime TimestampUtc,
|
||||
uint WorstInputStatus);
|
||||
uint WorstInputStatus,
|
||||
IReadOnlyDictionary<string, IProjectedSamplePublicationProof> Proofs,
|
||||
PhysicalLeaseOwnership? Ownership) : IDisposable
|
||||
{
|
||||
public void Dispose() => Ownership?.DisposeIfUntransferred();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepare one calc tag's evaluation: resolve the definition, apply the change-gate, and snapshot
|
||||
@@ -502,7 +546,71 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
// Worst-of-input, computed from the SAME snapshot the evaluation will use, so the status
|
||||
// published can never disagree with the values it was derived from.
|
||||
var worst = InputQuality.WorstOf(def.DependencyRefs.Select(r => deps.GetValueOrDefault(r)));
|
||||
return new PendingEvaluation(def, deps, timestampUtc, worst);
|
||||
var proofs = new Dictionary<string, IProjectedSamplePublicationProof>(StringComparer.Ordinal);
|
||||
foreach (var dep in def.DependencyRefs)
|
||||
if (_projectedProofs.TryGetValue(dep, out var proof)) proofs[dep] = proof;
|
||||
PhysicalLeaseOwnership? ownership = null;
|
||||
if (proofs.Count > 0)
|
||||
{
|
||||
if (proofs.Values.Any(p => !ProofValid(p)) ||
|
||||
!ProjectedInputBudget.TryRetain(proofs.Keys.Select(key => deps[key]), out var lease) || lease is null)
|
||||
{
|
||||
// Do not retain uncharged projected payloads in queued work.
|
||||
foreach (var key in proofs.Keys) deps[key] = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc);
|
||||
worst = 0x80310000u;
|
||||
}
|
||||
else ownership = new PhysicalLeaseOwnership(lease);
|
||||
}
|
||||
return new PendingEvaluation(def, deps, timestampUtc, worst, proofs, ownership);
|
||||
}
|
||||
|
||||
private static bool ProofValid(IProjectedSamplePublicationProof proof)
|
||||
{
|
||||
try { return proof.IsValid; } catch (Exception) { return false; }
|
||||
}
|
||||
|
||||
private bool EvidenceValid(PendingEvaluation pending)
|
||||
{
|
||||
foreach (var (path, captured) in pending.Proofs)
|
||||
{
|
||||
if (!ProofValid(captured) || !_projectedProofs.TryGetValue(path, out var current)) return false;
|
||||
try { if (!ReferenceEquals(captured.SourceIdentity, current.SourceIdentity) || !current.IsSourceValid) return false; }
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ClearPending()
|
||||
{
|
||||
while (_pending.Count != 0) DequeuePending().Dispose();
|
||||
}
|
||||
|
||||
private PendingEvaluation DequeuePending()
|
||||
{
|
||||
var first = _pending.First!;
|
||||
_pending.RemoveFirst();
|
||||
if (first.Value.Proofs.Count > 0) _pendingProjected.Remove(first.Value.Definition.RawPath);
|
||||
return first.Value;
|
||||
}
|
||||
|
||||
private void EnqueueEvaluation(PendingEvaluation pending)
|
||||
{
|
||||
// Projected work is latest-wins per tag. Remove its indexed node and append the
|
||||
// replacement in arrival order, without traversing unrelated projected or local work.
|
||||
if (pending.Proofs.Count > 0)
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
if (_pendingProjected.Remove(pending.Definition.RawPath, out var prior))
|
||||
{
|
||||
_projectedQueueVisits++;
|
||||
_pending.Remove(prior);
|
||||
prior.Value.Dispose();
|
||||
}
|
||||
var node = _pending.AddLast(pending);
|
||||
_pendingProjected.Add(pending.Definition.RawPath, node);
|
||||
_projectedQueueVisits++;
|
||||
}
|
||||
else _pending.AddLast(pending);
|
||||
}
|
||||
|
||||
/// <summary>Start the evaluation pump if it is not already running. MUST be called under
|
||||
@@ -535,18 +643,18 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
PendingEvaluation next;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) _pending.Clear();
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
return;
|
||||
}
|
||||
next = _pending.Dequeue();
|
||||
next = DequeuePending();
|
||||
}
|
||||
|
||||
// _evalGate (never _lock) is held across the run, so the pump and the timer ticks still
|
||||
// evaluate one at a time while no host thread can block behind a script.
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { next.Dispose(); return; } // disposed
|
||||
try
|
||||
{
|
||||
await RunEvaluationAsync(next).ConfigureAwait(false);
|
||||
@@ -578,7 +686,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
List<PendingEvaluation> batch;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_running) _pending.Clear();
|
||||
if (!_running) ClearPending();
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
_pumpScheduled = false;
|
||||
@@ -586,10 +694,10 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
}
|
||||
batch = [];
|
||||
var inBatch = new HashSet<string>(StringComparer.Ordinal);
|
||||
while (_pending.Count > 0 && inBatch.Add(_pending.Peek().Definition.RawPath)) batch.Add(_pending.Dequeue());
|
||||
while (_pending.Count > 0 && inBatch.Add(_pending.First!.Value.Definition.RawPath)) batch.Add(DequeuePending());
|
||||
}
|
||||
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { foreach (var item in batch) item.Dispose(); return; } // disposed
|
||||
try
|
||||
{
|
||||
await RunEvaluationBatchAsync(batch).ConfigureAwait(false);
|
||||
@@ -610,6 +718,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
/// <param name="batch">The prepared evaluations; no calc tag twice.</param>
|
||||
private async Task RunEvaluationBatchAsync(IReadOnlyList<PendingEvaluation> batch)
|
||||
{
|
||||
if (batch.Any(item => item.Proofs.Count > 0 || item.Ownership is not null))
|
||||
{
|
||||
try { foreach (var item in batch) await RunEvaluationAsync(item).ConfigureAwait(false); }
|
||||
finally { foreach (var item in batch) item.Dispose(); }
|
||||
return;
|
||||
}
|
||||
// Hold-on-Bad entries never reach the runner; the rest are submitted together.
|
||||
var requests = new List<(string, string, IReadOnlyDictionary<string, DataValueSnapshot>)>(batch.Count);
|
||||
var slot = new int[batch.Count];
|
||||
@@ -641,7 +755,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
PendingEvaluation? prepared;
|
||||
lock (_lock) prepared = PrepareEvaluation(rawPath, DateTime.UtcNow);
|
||||
if (prepared is null) return;
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) return; // disposed
|
||||
if (!await TryEnterEvalGateAsync().ConfigureAwait(false)) { prepared.Dispose(); return; } // disposed
|
||||
try
|
||||
{
|
||||
await RunEvaluationAsync(prepared).ConfigureAwait(false);
|
||||
@@ -677,7 +791,16 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
/// <param name="pending">The prepared evaluation.</param>
|
||||
private async Task RunEvaluationAsync(PendingEvaluation pending)
|
||||
{
|
||||
try
|
||||
{
|
||||
var def = pending.Definition;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!EvidenceValid(pending))
|
||||
{
|
||||
pending = pending with { WorstInputStatus = 0x80310000u };
|
||||
}
|
||||
}
|
||||
|
||||
// HOLD ON BAD (matching ScriptedAlarmEngine's AreInputsReady): a Bad input is not
|
||||
// usable, so the script does NOT run — which removes the "(double)ctx.GetTag(x).Value threw"
|
||||
@@ -691,9 +814,22 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
|
||||
// Snapshots, not bare values: the script's ctx.GetTag(path).StatusCode / .SourceTimestampUtc are
|
||||
// then the input's real ones rather than a fabricated Good stamped at evaluation time.
|
||||
var result = await _evaluator.EvaluateAsync(def.RawPath, def.ScriptSource, pending.Dependencies, _evalCts.Token)
|
||||
// Pending work remains charged through output acceptance, independently of the
|
||||
// physical run: either one may outlive the other (a blocked callback or a timeout).
|
||||
IDisposable? physicalLease = null;
|
||||
if (pending.Proofs.Count > 0 &&
|
||||
(!ProjectedInputBudget.TryRetain(pending.Proofs.Keys.Select(key => pending.Dependencies[key]), out physicalLease) ||
|
||||
physicalLease is null))
|
||||
{
|
||||
HoldOnBadInput(pending with { WorstInputStatus = 0x80310000u });
|
||||
return;
|
||||
}
|
||||
var result = await _evaluator.EvaluateAsync(def.RawPath, def.ScriptSource, pending.Dependencies, _evalCts.Token,
|
||||
physicalLease)
|
||||
.ConfigureAwait(false);
|
||||
ApplyEvaluationResult(pending, result);
|
||||
}
|
||||
finally { pending.Dispose(); }
|
||||
}
|
||||
|
||||
/// <summary>A Bad input holds the script: publish the input's own status (once per transition), no script log.</summary>
|
||||
@@ -726,8 +862,11 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
// A ReinitializeAsync can drop the tag while its script is running; its result is then stale
|
||||
// by definition and there is no state left to record it against.
|
||||
if (!_stateByRawPath.TryGetValue(def.RawPath, out var st)) return;
|
||||
|
||||
if (!result.Success)
|
||||
if (!EvidenceValid(pending))
|
||||
{
|
||||
toPublish = MarkInputsBad(st, 0x80310000u, pending.TimestampUtc);
|
||||
}
|
||||
else if (!result.Success)
|
||||
{
|
||||
var reason = result.Reason ?? "evaluator failure";
|
||||
toPublish = MarkEvaluationFailed(st, pending.TimestampUtc, result.StatusCode ?? StatusBadInternalError);
|
||||
@@ -754,7 +893,12 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
}
|
||||
|
||||
if (failureToLog is not null) PublishScriptLog(def, failureToLog);
|
||||
if (toPublish is { } p) Publish(def.RawPath, p.Value, p.StatusCode, pending.TimestampUtc);
|
||||
lock (_lock)
|
||||
{
|
||||
if (!EvidenceValid(pending) && _stateByRawPath.TryGetValue(def.RawPath, out var current))
|
||||
toPublish = MarkInputsBad(current, 0x80310000u, pending.TimestampUtc);
|
||||
}
|
||||
if (toPublish is { } p) Publish(def.RawPath, p.Value, p.StatusCode, pending.TimestampUtc, pending);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -770,7 +914,7 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
if (_stateByRawPath.TryGetValue(rawPath, out var st)) st.RecoveryArmed = false;
|
||||
if (!_running || _disposed) return;
|
||||
if (PrepareEvaluation(rawPath, DateTime.UtcNow) is not { } prepared) return;
|
||||
_pending.Enqueue(prepared);
|
||||
EnqueueEvaluation(prepared);
|
||||
SchedulePump();
|
||||
}
|
||||
}
|
||||
@@ -856,13 +1000,31 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
return (st.HasValue ? st.LastValue : null, badStatus);
|
||||
}
|
||||
|
||||
private void Publish(string rawPath, object? value, uint statusCode, DateTime timestampUtc)
|
||||
private void Publish(string rawPath, object? value, uint statusCode, DateTime timestampUtc,
|
||||
PendingEvaluation? pending = null)
|
||||
{
|
||||
var snapshot = new DataValueSnapshot(value, statusCode, timestampUtc, timestampUtc);
|
||||
// Fired outside both locks, from the single evaluation worker — so publish order still follows
|
||||
// evaluation order, and a subscriber can neither deadlock against the state lock nor re-enter the
|
||||
// driver behind it (DriverInstanceActor marshals the event onto its own thread regardless).
|
||||
OnDataChange?.Invoke(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot));
|
||||
var handlers = OnDataChange;
|
||||
if (handlers is null) return;
|
||||
// Every handler is a distinct acceptance boundary: an earlier callback may block while
|
||||
// the source is revoked. Local-only publication retains its existing multicast behavior.
|
||||
if (pending is null || pending.Proofs.Count == 0)
|
||||
{
|
||||
handlers.Invoke(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot));
|
||||
return;
|
||||
}
|
||||
foreach (EventHandler<DataChangeEventArgs> handler in handlers.GetInvocationList())
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!EvidenceValid(pending))
|
||||
{
|
||||
snapshot = new DataValueSnapshot(null, 0x80310000u, timestampUtc, timestampUtc);
|
||||
if (_stateByRawPath.TryGetValue(rawPath, out var state)) MarkInputsBad(state, 0x80310000u, timestampUtc);
|
||||
}
|
||||
}
|
||||
handler(this, new DataChangeEventArgs(SharedHandle, rawPath, snapshot));
|
||||
}
|
||||
}
|
||||
|
||||
private void PublishScriptLog(CalculationTagDefinition def, string reason)
|
||||
@@ -920,7 +1082,14 @@ public sealed class CalculationDriver : IDriver, IDependencyConsumer, ISubscriba
|
||||
_disposed = true;
|
||||
_running = false;
|
||||
StopTimers();
|
||||
lock (_lock) _pending.Clear();
|
||||
lock (_lock)
|
||||
{
|
||||
ClearPending();
|
||||
foreach (var lease in _projectedCacheLeases.Values) lease.Dispose();
|
||||
foreach (var path in _projectedProofs.Keys) _depValues.Remove(path);
|
||||
_projectedCacheLeases.Clear();
|
||||
_projectedProofs.Clear();
|
||||
}
|
||||
// Cancel an awaited run first (the guard lets the caller's cancel win over the timeout), then drop
|
||||
// the compiled scripts.
|
||||
try { _evalCts.Cancel(); } catch (ObjectDisposedException) { }
|
||||
|
||||
@@ -161,11 +161,17 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO
|
||||
/// <param name="scriptSource">The C# script source producing the tag's value.</param>
|
||||
/// <param name="dependencies">Read-only snapshot of dependency values keyed by RawPath.</param>
|
||||
/// <param name="ct">Caller cancellation (driver shutdown); wins over the run timeout.</param>
|
||||
/// <param name="physicalLease">Optional projected input ownership transferred to physical execution.</param>
|
||||
/// <returns>The evaluation outcome.</returns>
|
||||
public async Task<VirtualTagEvalResult> EvaluateAsync(
|
||||
string calcTagId, string scriptSource, IReadOnlyDictionary<string, DataValueSnapshot> dependencies,
|
||||
CancellationToken ct = default)
|
||||
CancellationToken ct = default, IDisposable? physicalLease = null)
|
||||
{
|
||||
var ownership = new PhysicalLeaseOwnership(physicalLease);
|
||||
try
|
||||
{
|
||||
if (physicalLease is not null && _runner is not null && _runner is not IPhysicalScriptRunner)
|
||||
return VirtualTagEvalResult.Failure("runner does not support projected input ownership");
|
||||
if (_disposed) return VirtualTagEvalResult.Failure("evaluator disposed");
|
||||
if (string.IsNullOrWhiteSpace(scriptSource)) return VirtualTagEvalResult.Failure("empty expression");
|
||||
|
||||
@@ -201,21 +207,26 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO
|
||||
// quarantine and the negative compile cache for this seam. Unavailable publishes BadResourceUnavailable.
|
||||
if (_runner is not null)
|
||||
{
|
||||
var outcome = await _runner.RunAsync(new ScriptInvocation(
|
||||
calcTagId, ScriptContextKind.Calculation, scriptSource, readCache, _runTimeout, scriptLog), ct).ConfigureAwait(false);
|
||||
var invocation = new ScriptInvocation(calcTagId, ScriptContextKind.Calculation, scriptSource, readCache,
|
||||
_runTimeout, scriptLog, physicalLease is null ? null : ownership.Transfer());
|
||||
ScriptRunOutcome outcome;
|
||||
try { outcome = await _runner.RunAsync(invocation, ct).ConfigureAwait(false); }
|
||||
catch { ownership.Dispose(); throw; }
|
||||
return outcome.ToVirtualTagEvalResult();
|
||||
}
|
||||
|
||||
var result = await RunInProcessAsync(calcTagId, scriptSource, context, ct).ConfigureAwait(false);
|
||||
var result = await RunInProcessAsync(calcTagId, scriptSource, context, ct, physicalLease is null ? null : ownership).ConfigureAwait(false);
|
||||
// lmxopcua#780 P2 — Shadow: `result` is what gets published; the same evaluation is mirrored to the worker pool
|
||||
// and only compared. Mirror never blocks and nothing it does reaches this result.
|
||||
if (_shadow is not null && result.ToMirroredOutcome() is { } mirrored)
|
||||
if (physicalLease is null && _shadow is not null && result.ToMirroredOutcome() is { } mirrored)
|
||||
_shadow.Mirror(new ScriptInvocation(calcTagId, ScriptContextKind.Calculation, scriptSource, readCache, _runTimeout), mirrored);
|
||||
return result;
|
||||
}
|
||||
finally { ownership.DisposeIfUntransferred(); }
|
||||
}
|
||||
|
||||
private async Task<VirtualTagEvalResult> RunInProcessAsync(
|
||||
string calcTagId, string scriptSource, VirtualTagContext context, CancellationToken ct)
|
||||
string calcTagId, string scriptSource, VirtualTagContext context, CancellationToken ct, PhysicalLeaseOwnership? ownership)
|
||||
{
|
||||
// A source that already failed to compile fails the same way without touching Roslyn (R07:P4).
|
||||
var sourceKey = HashSource(scriptSource);
|
||||
@@ -258,7 +269,7 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO
|
||||
// CancellationToken can't interrupt a CPU-bound/infinite-loop Roslyn script, so the wall-clock
|
||||
// budget is what bounds a runaway script — and the guard is what keeps the next trigger from
|
||||
// stacking another orphan behind it (one per tag, then quarantine).
|
||||
var raw = await _guard.RunAsync(calcTagId, scriptSource, evaluator, context, _runTimeout, ct)
|
||||
var raw = await _guard.RunAsync(calcTagId, scriptSource, evaluator, context, _runTimeout, ct, ownership?.Transfer())
|
||||
.ConfigureAwait(false);
|
||||
return VirtualTagEvalResult.Ok(raw);
|
||||
}
|
||||
@@ -279,7 +290,7 @@ public sealed class CalculationEvaluator : IScriptCacheOwner, IScriptQuarantineO
|
||||
{
|
||||
return VirtualTagEvalResult.Failure("evaluation cancelled (driver shutting down)");
|
||||
}
|
||||
catch (ObjectDisposedException) when (!_disposed && attempt == 0)
|
||||
catch (ObjectDisposedException) when (!_disposed && attempt == 0 && ownership is null)
|
||||
{
|
||||
// A concurrent ClearCompiledScripts disposed the evaluator between our GetOrCompile and the
|
||||
// run's disposed-guard. Re-fetch (recompiling the same source into the CURRENT generation)
|
||||
|
||||
Reference in New Issue
Block a user