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; /// /// Final review M6: an alarm on-trigger run's ScriptRuntimeContext was built without a /// sourceScript, so the context's _logTarget — which names the script on every /// Log.* line and on the run's trace rows — fell back to the INSTANCE name. The launcher now /// passes the same AlarmActor:{alarmName} source key it already uses for this alarm's site /// events, from which the context derives the alarm's own name. /// public class AlarmScriptLogTargetTests : TestKit, IDisposable { private sealed record Entry(LogLevel Level, string Message); /// A minimal recording logger — the alarm path hands its own ILogger down to the script logger. private sealed class RecordingLogger : ILogger { public List Entries { get; } = []; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel level, EventId eventId, TState state, Exception? exception, Func formatter) { lock (Entries) Entries.Add(new Entry(level, formatter(state, exception))); } } private readonly SharedScriptLibrary _sharedLibrary = new( new ScriptCompilationService(NullLogger.Instance), NullLogger.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("Log.Info(\"alarm handler ran\"); return null;", scriptOptions, typeof(ScriptGlobals)); compiled.Compile(); var logger = new RecordingLogger(); using var scheduler = new ScriptExecutionScheduler(1); var config = new ResolvedAlarm { CanonicalName = "HighTemp", TriggerType = "ValueMatch", TriggerConfiguration = "{\"attributeName\":\"Status\",\"matchValue\":\"Critical\"}", PriorityLevel = 100, }; var alarm = ActorOfAsTestActorRef( 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(); store.Setup(s => s.GetStatusAsync(Moq.It.IsAny(), Moq.It.IsAny())) .ReturnsAsync((ZB.MOM.WW.ScadaBridge.Commons.Types.TrackingStatusSnapshot?)null); store.As().Setup(s => s.Dispose()); using var provider = Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider( Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddScoped( 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("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(); 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(TimeSpan.FromSeconds(10)).Success, string.Join(";", logger.Entries.Select(e => e.Message))); store.Verify(s => s.GetStatusAsync(Moq.It.IsAny(), Moq.It.IsAny()), Moq.Times.Once); AwaitAssert(() => store.As().Verify(s => s.Dispose(), Moq.Times.Once)); } }