9a87d7a328
Second slice of the 2026-09-09 whole-system review remediation
(docs/plans/2026-09-09-arch-review.md §10), on top of the High slice 146a1323.
Runtime/devices: SR-2 alarm on-trigger integration scope; SR-3 correlated NativeAlarmActor
subscribe retry; SR-4 immutable audited DB target; SR-5 ordered InstanceActor stop/flush;
SR-12 rehydration fence; SR-13 S&F gate recheck per delivery; DC-4 no OPC UA security
downgrade; DC-5 alarm snapshot for every new subscriber; ORCH-1 sync-dispose joins the pump.
Management/UI: MG-2 site scope on audit tree + Flow Debugger Replay; MG-3 stale-probe memo
removed; MG-4 server-owned bulk-deploy deadline; UI-5 sandbox runs in a killable child
process (new CentralUI.SandboxWorker project); UI-14 bounded sandbox output/IPC.
Edge/audit: EI-1 relay audit ownership; EI-2 SkipBodyCapture suppresses error text; EI-3/EI-11
error-field redaction + caps; EI-4 single relay deadline, pre-execution-only retry; EI-5
authenticated relay provenance; EI-10 body cap before audit read.
Persistence/contracts: DL-1 global Instance.UniqueName unique index + conflict translation;
DL-2 DataConnection protocol config encrypted at rest (migration
20260909203046_EnforceGlobalInstanceNamesAndProtectProtocolConfiguration — coordinated
central upgrade, old binaries cannot read protected rows); DL-3 bounded Replay paging;
DL-6 cross-site Overwrite of a deployed instance rejected; XC-4 proto descriptor contract test.
Config/hygiene: XC-1 central listener isolation by local port; XC-2/XC-3 inert SMTP + cron
keys removed from rig settings; CM-2 env2 bootstrap guard enabled; DC-6 deploy site exit code;
DC-7 notifier retries only explicit standby rejection; XC-5 ClusterClient purged from docs.
Gates recorded in the report: build 0/0, 9 397 passed / 0 failed, rig redeployed on all
eight nodes with the migration applied. 46 Low findings remain open.
117 lines
6.3 KiB
C#
117 lines
6.3 KiB
C#
using Moq;
|
|
using Akka.Actor;
|
|
using Akka.TestKit.Xunit2;
|
|
using Microsoft.CodeAnalysis.CSharp.Scripting;
|
|
using Microsoft.CodeAnalysis.Scripting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming;
|
|
using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors;
|
|
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors;
|
|
|
|
/// <summary>
|
|
/// Final review M6: an alarm on-trigger run's <c>ScriptRuntimeContext</c> was built without a
|
|
/// <c>sourceScript</c>, so the context's <c>_logTarget</c> — which names the script on every
|
|
/// <c>Log.*</c> line and on the run's trace rows — fell back to the INSTANCE name. The launcher now
|
|
/// passes the same <c>AlarmActor:{alarmName}</c> source key it already uses for this alarm's site
|
|
/// events, from which the context derives the alarm's own name.
|
|
/// </summary>
|
|
public class AlarmScriptLogTargetTests : TestKit, IDisposable
|
|
{
|
|
private sealed record Entry(LogLevel Level, string Message);
|
|
|
|
/// <summary>A minimal recording logger — the alarm path hands its own ILogger down to the script logger.</summary>
|
|
private sealed class RecordingLogger<T> : ILogger<T>
|
|
{
|
|
public List<Entry> Entries { get; } = [];
|
|
|
|
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
|
|
|
public bool IsEnabled(LogLevel logLevel) => true;
|
|
|
|
public void Log<TState>(LogLevel level, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
|
{
|
|
lock (Entries) Entries.Add(new Entry(level, formatter(state, exception)));
|
|
}
|
|
}
|
|
|
|
private readonly SharedScriptLibrary _sharedLibrary = new(
|
|
new ScriptCompilationService(NullLogger<ScriptCompilationService>.Instance),
|
|
NullLogger<SharedScriptLibrary>.Instance);
|
|
|
|
void IDisposable.Dispose() => Shutdown();
|
|
|
|
[Fact]
|
|
public void AlarmOnTriggerRun_AttributesItsLogLinesToTheALARM_NotJustTheInstance()
|
|
{
|
|
var options = new SiteRuntimeOptions
|
|
{
|
|
ScriptExecutionTimeoutSeconds = 10,
|
|
MaxScriptCallDepth = 10,
|
|
};
|
|
var scriptOptions = ScriptOptions.Default
|
|
.WithReferences(typeof(object).Assembly, typeof(Enumerable).Assembly, typeof(ScriptGlobals).Assembly)
|
|
.WithImports("System", "System.Threading.Tasks");
|
|
var compiled = CSharpScript.Create<object?>("Log.Info(\"alarm handler ran\"); return null;", scriptOptions, typeof(ScriptGlobals));
|
|
compiled.Compile();
|
|
|
|
var logger = new RecordingLogger<AlarmActor>();
|
|
using var scheduler = new ScriptExecutionScheduler(1);
|
|
var config = new ResolvedAlarm
|
|
{
|
|
CanonicalName = "HighTemp",
|
|
TriggerType = "ValueMatch",
|
|
TriggerConfiguration = "{\"attributeName\":\"Status\",\"matchValue\":\"Critical\"}",
|
|
PriorityLevel = 100,
|
|
};
|
|
var alarm = ActorOfAsTestActorRef<AlarmActor>(
|
|
Props.Create(() => new AlarmActor(
|
|
"HighTemp", "Inst1", CreateTestProbe().Ref, config, compiled, _sharedLibrary, options,
|
|
logger, null, null, null, null, null, scheduler, null)),
|
|
"alarm-logtarget-" + Guid.NewGuid().ToString("N"));
|
|
|
|
alarm.Tell(new AttributeValueChanged("Inst1", "Status", "Status", "Critical", "Good", DateTimeOffset.UtcNow));
|
|
|
|
AwaitAssert(
|
|
() =>
|
|
{
|
|
Entry[] snapshot;
|
|
lock (logger.Entries) snapshot = [.. logger.Entries];
|
|
// "[script] {Instance}/{Script} {ExecutionId}: {Message}" — the script half is the
|
|
// alarm's name because the launcher passed "AlarmActor:HighTemp" as the source.
|
|
Assert.Contains(snapshot, e => e.Message.StartsWith("[script] Inst1/HighTemp ", StringComparison.Ordinal)
|
|
&& e.Message.EndsWith(": alarm handler ran", StringComparison.Ordinal));
|
|
},
|
|
TimeSpan.FromSeconds(15));
|
|
}
|
|
[Fact]
|
|
public void SR2_AlarmRunResolvesAndDisposesScopedIntegrationServices()
|
|
{
|
|
var store = new Moq.Mock<ZB.MOM.WW.ScadaBridge.Commons.Interfaces.IOperationTrackingStore>();
|
|
store.Setup(s => s.GetStatusAsync(Moq.It.IsAny<ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId>(), Moq.It.IsAny<CancellationToken>()))
|
|
.ReturnsAsync((ZB.MOM.WW.ScadaBridge.Commons.Types.TrackingStatusSnapshot?)null);
|
|
store.As<IDisposable>().Setup(s => s.Dispose());
|
|
using var provider = Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(
|
|
Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddScoped<ZB.MOM.WW.ScadaBridge.Commons.Interfaces.IOperationTrackingStore>(
|
|
new Microsoft.Extensions.DependencyInjection.ServiceCollection(), _ => store.Object));
|
|
var options = ScriptOptions.Default.WithReferences(typeof(object).Assembly, typeof(ScriptGlobals).Assembly,
|
|
typeof(ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId).Assembly)
|
|
.WithImports("ZB.MOM.WW.ScadaBridge.Commons.Types");
|
|
var compiled = CSharpScript.Create<object?>("await Instance.Tracking.Status(TrackedOperationId.New()); return null;", options, typeof(ScriptGlobals));
|
|
Assert.DoesNotContain(compiled.Compile(), d => d.Severity == Microsoft.CodeAnalysis.DiagnosticSeverity.Error);
|
|
using var scheduler = new ScriptExecutionScheduler(1);
|
|
var done = CreateTestProbe();
|
|
var logger = new RecordingLogger<AlarmActor>();
|
|
ScriptRunLauncher.LaunchAlarmScript("alarm", "instance", ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.AlarmLevel.High,
|
|
1, "alarm", compiled, CreateTestProbe().Ref, _sharedLibrary, new SiteRuntimeOptions(), done.Ref,
|
|
logger, null, provider, 1, 10, null, scheduler);
|
|
Assert.True(done.ExpectMsg<AlarmActor.AlarmExecutionCompleted>(TimeSpan.FromSeconds(10)).Success, string.Join(";", logger.Entries.Select(e => e.Message)));
|
|
store.Verify(s => s.GetStatusAsync(Moq.It.IsAny<ZB.MOM.WW.ScadaBridge.Commons.Types.TrackedOperationId>(), Moq.It.IsAny<CancellationToken>()), Moq.Times.Once);
|
|
AwaitAssert(() => store.As<IDisposable>().Verify(s => s.Dispose(), Moq.Times.Once));
|
|
}
|
|
|
|
}
|