feat: expose mapped raw and uns data through grpc adapters
This commit is contained in:
+211
@@ -0,0 +1,211 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Serilog;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
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.Tests;
|
||||
|
||||
public sealed class GrpcDataCalculationOwnershipTests
|
||||
{
|
||||
private sealed class Proof : IProjectedSamplePublicationProof
|
||||
{
|
||||
public volatile bool Valid = true;
|
||||
public bool IsValid => Valid;
|
||||
public TimeProvider Clock => TimeProvider.System;
|
||||
public void Invalidate() => Valid = false;
|
||||
}
|
||||
|
||||
private sealed class HeldRunner : IPhysicalScriptRunner
|
||||
{
|
||||
private readonly TaskCompletionSource _release = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
public ConcurrentQueue<ScriptInvocation> Invocations { get; } = new();
|
||||
public void Release() => _release.TrySetResult();
|
||||
public async Task<ScriptRunOutcome> RunAsync(ScriptInvocation invocation, CancellationToken ct = default)
|
||||
{
|
||||
Invocations.Enqueue(invocation);
|
||||
try { await _release.Task; return ScriptRunOutcome.Ok(invocation.Inputs["src/a"].Value); }
|
||||
finally { invocation.PhysicalLease?.Dispose(); }
|
||||
}
|
||||
public void Reset(ScriptContextKind kind) { }
|
||||
public IReadOnlyCollection<string> QuarantinedKeys(ScriptContextKind kind) => [];
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||||
public async Task Large_projected_fanout_replaces_pending_entries_with_linear_queue_work()
|
||||
{
|
||||
const int tagCount = 200;
|
||||
const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;";
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
var runner = new HeldRunner();
|
||||
using var driver = new CalculationDriver(new CalculationDriverOptions
|
||||
{
|
||||
RawTags = Enumerable.Range(0, tagCount).Select(i => new RawTagEntry($"calc/{i}", json, WriteIdempotent: false)).ToArray(),
|
||||
ScriptRunner = runner
|
||||
}, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
try
|
||||
{
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var consumer = (IProjectedDependencyConsumer)(object)driver;
|
||||
var proof = new Proof();
|
||||
consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, proof);
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
runner.Invocations.ShouldNotBeEmpty();
|
||||
var before = driver.ProjectedQueueVisitsForTest;
|
||||
consumer.OnProjectedDependencyValue("src/a", 2, 0, DateTime.UtcNow, proof);
|
||||
var visits = driver.ProjectedQueueVisitsForTest - before;
|
||||
visits.ShouldBeLessThanOrEqualTo(tagCount * 4L,
|
||||
"replacing one projected entry per dependent should not scan the other queued tags");
|
||||
}
|
||||
finally { runner.Release(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||||
public async Task Pending_input_remains_charged_after_the_runner_finishes_while_output_is_blocked()
|
||||
{
|
||||
const string source = "return ctx.GetTag(\"src/a\").Value ?? 0;";
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
var runner = new HeldRunner();
|
||||
using var driver = new CalculationDriver(new CalculationDriverOptions
|
||||
{
|
||||
RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner
|
||||
}, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
var callbackEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var unblock = new ManualResetEventSlim();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != 0) return;
|
||||
callbackEntered.TrySetResult();
|
||||
unblock.Wait(TimeSpan.FromSeconds(10));
|
||||
};
|
||||
try
|
||||
{
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var bytes = new byte[1024 * 1024];
|
||||
((IProjectedDependencyConsumer)(object)driver).OnProjectedDependencyValue("src/a", bytes, 0, DateTime.UtcNow, new Proof());
|
||||
runner.Release();
|
||||
await callbackEntered.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
// The cache and the pending output each still retain the input; the runner has already released its lease.
|
||||
ProjectedInputBudget.RetainedBytes.ShouldBeGreaterThanOrEqualTo(2 * bytes.Length);
|
||||
}
|
||||
finally { unblock.Set(); runner.Release(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||||
public async Task Revocation_during_an_output_callback_is_checked_before_the_next_acceptance()
|
||||
{
|
||||
const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;";
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
var runner = new HeldRunner();
|
||||
using var driver = new CalculationDriver(new CalculationDriverOptions
|
||||
{
|
||||
RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner
|
||||
}, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
var firstCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
using var unblock = new ManualResetEventSlim();
|
||||
var downstream = new ConcurrentQueue<DataChangeEventArgs>();
|
||||
driver.OnDataChange += (_, e) =>
|
||||
{
|
||||
if (e.Snapshot.StatusCode != 0) return;
|
||||
firstCallback.TrySetResult();
|
||||
unblock.Wait(TimeSpan.FromSeconds(10));
|
||||
};
|
||||
driver.OnDataChange += (_, e) => downstream.Enqueue(e);
|
||||
var proof = new Proof();
|
||||
try
|
||||
{
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
((IProjectedDependencyConsumer)(object)driver).OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, proof);
|
||||
runner.Release();
|
||||
await firstCallback.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
proof.Valid = false;
|
||||
unblock.Set();
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (!driver.IsEvaluationIdle && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
driver.IsEvaluationIdle.ShouldBeTrue();
|
||||
downstream.ShouldNotContain(e => e.Snapshot.StatusCode == 0);
|
||||
}
|
||||
finally { unblock.Set(); runner.Release(); }
|
||||
}
|
||||
|
||||
[Fact(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||||
public async Task Rejected_projected_values_coalesce_while_the_pump_is_blocked()
|
||||
{
|
||||
const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;";
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
var runner = new HeldRunner();
|
||||
using var driver = new CalculationDriver(new CalculationDriverOptions
|
||||
{
|
||||
RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner
|
||||
}, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
var budgetLeases = new List<IDisposable>();
|
||||
try
|
||||
{
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var consumer = (IProjectedDependencyConsumer)(object)driver;
|
||||
consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, new Proof());
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
runner.Invocations.ShouldHaveSingleItem();
|
||||
var now = DateTime.UtcNow;
|
||||
var charged = new DataValueSnapshot(new byte[3 * 1024 * 1024], 0, now, now);
|
||||
for (var i = 0; i < 5; i++)
|
||||
{
|
||||
ProjectedInputBudget.TryRetain([charged], out var lease).ShouldBeTrue();
|
||||
budgetLeases.Add(lease.ShouldNotBeNull());
|
||||
}
|
||||
var payload = new byte[2 * 1024 * 1024];
|
||||
var proof = new Proof();
|
||||
for (var i = 0; i < 100; i++) consumer.OnProjectedDependencyValue("src/a", payload, 0, now, proof);
|
||||
var field = typeof(CalculationDriver).GetField("_pending", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
||||
var pending = (System.Collections.ICollection)field!.GetValue(driver)!;
|
||||
pending.Count.ShouldBeLessThanOrEqualTo(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var lease in budgetLeases) lease.Dispose();
|
||||
runner.Release();
|
||||
}
|
||||
}
|
||||
|
||||
[Theory(Timeout = 30000), Trait("Feature", "GrpcData"), Trait("Phase", "P08")]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Blocked_pump_coalesces_projected_triggers_and_rechecks_captured_source(bool revokeOldProof)
|
||||
{
|
||||
const string source = "return (int)ctx.GetTag(\"src/a\").Value + 1;";
|
||||
var json = $"{{\"scriptId\":\"s\",\"changeTriggered\":true,\"scriptSource\":{System.Text.Json.JsonSerializer.Serialize(source)}}}";
|
||||
var runner = new HeldRunner();
|
||||
using var driver = new CalculationDriver(new CalculationDriverOptions
|
||||
{
|
||||
RawTags = [new RawTagEntry("calc/x", json, WriteIdempotent: false)], ScriptRunner = runner
|
||||
}, "calc", new ScriptRootLogger(new LoggerConfiguration().CreateLogger()));
|
||||
var output = new ConcurrentQueue<DataChangeEventArgs>();
|
||||
driver.OnDataChange += (_, e) => output.Enqueue(e);
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var consumer = (IProjectedDependencyConsumer)(object)driver;
|
||||
var oldProof = new Proof();
|
||||
try
|
||||
{
|
||||
consumer.OnProjectedDependencyValue("src/a", 1, 0, DateTime.UtcNow, oldProof);
|
||||
var deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (runner.Invocations.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
runner.Invocations.ShouldHaveSingleItem().PhysicalLease.ShouldNotBeNull();
|
||||
if (revokeOldProof) oldProof.Valid = false;
|
||||
var latest = new Proof();
|
||||
for (var i = 2; i <= 100; i++)
|
||||
consumer.OnProjectedDependencyValue("src/a", i, 0, DateTime.UtcNow, latest);
|
||||
runner.Release();
|
||||
deadline = DateTime.UtcNow.AddSeconds(10);
|
||||
while (!driver.IsEvaluationIdle && DateTime.UtcNow < deadline) await Task.Delay(5, TestContext.Current.CancellationToken);
|
||||
driver.IsEvaluationIdle.ShouldBeTrue();
|
||||
runner.Invocations.Count.ShouldBeLessThanOrEqualTo(2);
|
||||
output.ShouldNotContain(e => e.Snapshot.StatusCode == 0 && Equals(e.Snapshot.Value, 1));
|
||||
output.ShouldContain(e => e.Snapshot.StatusCode == 0 && Equals(e.Snapshot.Value, 100));
|
||||
}
|
||||
finally { runner.Release(); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user