using System.Text.Json; using Akka.Actor; using Akka.TestKit.Xunit2; using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.ScadaBridge.Commons.Messages.DataConnection; using ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView; using ZB.MOM.WW.ScadaBridge.Commons.Messages.Instance; using ZB.MOM.WW.ScadaBridge.Commons.Types.Alarms; using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums; using ZB.MOM.WW.ScadaBridge.Commons.Types.Flattening; using ZB.MOM.WW.ScadaBridge.SiteRuntime.Actors; using ZB.MOM.WW.ScadaBridge.SiteRuntime.Persistence; using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts; using ZB.MOM.WW.ScadaBridge.TestSupport; namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Actors; /// /// SRT-12 (2026-12-02 review, WP3 task 3.10): the redeploy reset gate (clear static overrides, /// then clear native alarms) must cover the successor's whole start, not just its override load — /// the native-alarm rehydration read and the first static-override flush are ordered behind it too. /// public class InstanceActorRedeployGateTests : TestKit, IDisposable { private readonly SiteStorageService _storage; private readonly ScriptCompilationService _compilationService; private readonly SharedScriptLibrary _sharedScriptLibrary; private readonly SiteRuntimeOptions _options = new(); private readonly TestLocalDb _localDb; /// Creates a temporary LocalDb-backed site storage and the script services the actor needs. public InstanceActorRedeployGateTests() { _localDb = TestLocalDb.CreateTemp("instance-redeploy-gate"); _storage = new SiteStorageService(_localDb.Db, NullLogger.Instance); _storage.InitializeAsync().GetAwaiter().GetResult(); _compilationService = new ScriptCompilationService(NullLogger.Instance); _sharedScriptLibrary = new SharedScriptLibrary(_compilationService, NullLogger.Instance); } /// void IDisposable.Dispose() { Shutdown(); var path = _localDb.Path; _localDb.Dispose(); TestLocalDb.DeleteFiles(path); } private IActorRef CreateGated(string name, FlattenedConfiguration config, IActorRef? dcl, Task gate) => ActorOf(Props.Create(() => new InstanceActor( name, JsonSerializer.Serialize(config), _storage, _compilationService, _sharedScriptLibrary, null, _options, NullLogger.Instance, dcl, null, null, null, gate))); /// Holds true for the whole window (polling, not a blind sleep). private static async Task AssertHoldsFor(Func> holds, TimeSpan window, string because) { var deadline = DateTime.UtcNow + window; while (DateTime.UtcNow < deadline) { Assert.True(await holds(), because); await Task.Delay(50); } } /// /// The successor's first static-override flush lands only after the reset: a write made while /// the (slow) clear is still pending must survive it. Pre-fix the flush committed within /// ~100 ms, the delayed clear then deleted it, and the next restart silently reverted it. /// /// A task that represents the asynchronous operation. [Fact] public async Task FirstStaticFlush_IsOrderedAfterTheResetGate() { var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var config = new FlattenedConfiguration { InstanceUniqueName = "GateFlush", Attributes = [new ResolvedAttribute { CanonicalName = "Mode", Value = "Auto", DataType = "String" }], }; var actor = CreateGated("GateFlush", config, null, gate.Task); actor.Tell(new SetStaticAttributeCommand("w1", "GateFlush", "Mode", "Manual", DateTimeOffset.UtcNow)); Assert.True(ExpectMsg().Success); // While the reset is pending, nothing may reach the table (pre-fix: committed at ~100 ms). await AssertHoldsFor( async () => (await _storage.GetStaticOverridesAsync("GateFlush")).Count == 0, TimeSpan.FromMilliseconds(500), "a static flush committed ahead of the redeploy reset"); // The reset runs, then the gate opens: the write lands after it and survives. await _storage.ClearStaticOverridesAsync("GateFlush"); gate.SetResult(); await AwaitAssertAsync(async () => { var stored = await _storage.GetStaticOverridesAsync("GateFlush"); Assert.Equal("Manual", stored.GetValueOrDefault("Mode")); }, TimeSpan.FromSeconds(5), TimeSpan.FromMilliseconds(50)); } /// /// The native-alarm rehydration read is chained behind the gate, so the successor can only see /// the CLEARED table. Pre-fix NativeAlarmActor read native_alarm_state directly in PreStart and /// re-emitted the predecessor's conditions (stale alarms from an old binding). /// /// A task that represents the asynchronous operation. [Fact] public async Task NativeAlarmRehydration_IsOrderedAfterTheResetGate() { // The predecessor left an active condition behind. await _storage.UpsertNativeAlarmAsync("GateNative", "Pressure", "T01.Hi", JsonSerializer.Serialize(new AlarmConditionState(true, false, null, AlarmShelveState.Unshelved, false, 800)), DateTimeOffset.UtcNow); var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var config = new FlattenedConfiguration { InstanceUniqueName = "GateNative", NativeAlarmSources = [ new ResolvedNativeAlarmSource { CanonicalName = "Pressure", ConnectionName = "Opc", SourceReference = "ns=2;s=T01" } ], }; var dcl = CreateTestProbe(); var actor = CreateGated("GateNative", config, dcl.Ref, gate.Task); dcl.ExpectMsg(TimeSpan.FromSeconds(5)); // The reset clears the table, THEN the gate opens. await Task.Delay(200); // give a pre-fix (ungated) PreStart read every chance to win the race await _storage.ClearNativeAlarmsForInstanceAsync("GateNative"); gate.SetResult(); await AssertHoldsFor(async () => { var snap = await actor.Ask(new SubscribeDebugViewRequest("GateNative", "c"), TimeSpan.FromSeconds(3)); return !snap.AlarmStates.Any(a => a.SourceReference == "T01.Hi" && !a.IsConfiguredPlaceholder); }, TimeSpan.FromSeconds(1), "the predecessor's native alarm was rehydrated"); } }