diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 661528b3e..9d05abdef 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -67,7 +67,7 @@ The deploy gate compiles every script the deployment will run before the deploym | `Warn` | Logged and appended to the accepted deployment message; the deploy succeeds. | | `Off` | The gate does not run. | -Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the AdminUI waits 10 s for a deploy answer, so on a very large fleet the first deploy after a restart can report a timeout while it carries on — the next is cached. +Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the singleton warms the checker in the background as it starts (#1024) and the AdminUI waits 45 s for a deploy answer (10 s for ack/shelve), so only a very large fleet deployed within seconds of a restart can still report an `OutcomeUnknown` timeout while the deploy carries on — the next is cached. #### Known resource limits (accepted trade-offs) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs index f662b6b8c..84604d50a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs @@ -10,28 +10,47 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients; /// /// backed by the cluster singleton registered in /// AddOtOpcUaControlPlane. Resolves the singleton proxy from -/// at construction time; each call Asks the proxy with a 10s timeout. +/// at construction time; each call Asks the proxy with a 10s timeout (45s for the deploy trigger, #1024). /// public sealed class AdminOperationsClient : IAdminOperationsClient { - private static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10); + /// The general ask timeout (ack / shelve / probes). + internal static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10); + + /// + /// #1024: the deploy trigger's own ask timeout. The compose runs the Roslyn script compile gate, and on a + /// large fleet a COLD checker (first deploy after a central restart) can take well past 10 s; the singleton + /// warms the checker at start, but the first deploy may still race that. A timeout is still + /// , never a failure — this just makes it rarer. + /// + internal static readonly TimeSpan DefaultDeployAskTimeout = TimeSpan.FromSeconds(45); private readonly IActorRef _proxy; private readonly TimeSpan AskTimeout; + private readonly TimeSpan DeployAskTimeout; /// Initializes a new instance of the AdminOperationsClient. /// The actor registry to resolve the admin operations singleton proxy. - public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout) + public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout, DefaultDeployAskTimeout) { } - /// Test seam: the same client with a caller-chosen ask timeout. + /// Test seam: the same client with a caller-chosen ask timeout (also used for the deploy trigger). /// The actor registry to resolve the admin operations singleton proxy. /// How long to wait for the singleton's reply. - internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) + internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) : this(registry, askTimeout, askTimeout) + { + } + + /// Test seam: caller-chosen general and deploy-trigger ask timeouts. + /// The actor registry to resolve the admin operations singleton proxy. + /// How long to wait for the singleton's reply to ack/shelve. + /// How long to wait for the singleton's reply to StartDeployment. + internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout, TimeSpan deployAskTimeout) { _proxy = registry.Get(); AskTimeout = askTimeout; + DeployAskTimeout = deployAskTimeout; } /// @@ -48,10 +67,10 @@ public sealed class AdminOperationsClient : IAdminOperationsClient var correlationId = CorrelationId.NewId(); var msg = new StartDeployment(createdBy, correlationId, deploymentId); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); - linked.CancelAfter(AskTimeout); + linked.CancelAfter(DeployAskTimeout); try { - return await _proxy.Ask(msg, AskTimeout, linked.Token); + return await _proxy.Ask(msg, DeployAskTimeout, linked.Token); } catch (Exception ex) when (ex is AskTimeoutException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) @@ -60,7 +79,7 @@ public sealed class AdminOperationsClient : IAdminOperationsClient StartDeploymentOutcome.OutcomeUnknown, deploymentId, RevisionHash: null, - Message: $"No reply from the deployment service within {AskTimeout.TotalSeconds:0} s, so it is not known " + + Message: $"No reply from the deployment service within {DeployAskTimeout.TotalSeconds:0} s, so it is not known " + $"whether the deployment was created. If it was, it carries id {deploymentId.Value}; check the " + "deployment history (or GET /api/deployments/" + deploymentId.Value + ") before retrying.", correlationId); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 247fbe0a7..d5a8fffa8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -33,6 +33,8 @@ public sealed class AdminOperationsActor : ReceiveActor private readonly ScriptCompileGateMode _scriptCompileGateMode; + private readonly bool _warmScriptGateOnStart; + /// /// The coordinator's apply deadline. A Dispatching row with no expected-ack rows that is older /// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7). @@ -66,6 +68,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts; defaults to . /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1024: when true the checker's cache is warmed in the background as the actor starts (production wiring), so the first deploy after a restart is not a cold Roslyn compile. /// Props configured to create an AdminOperationsActor. public static Props Props( IDbContextFactory dbFactory, @@ -76,10 +79,11 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) => + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + bool warmScriptGateOnStart = false) => Akka.Actor.Props.Create(() => new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, - alarmVerdictWindow, scriptChecker, scriptCompileGateMode)); + alarmVerdictWindow, scriptChecker, scriptCompileGateMode, warmScriptGateOnStart)); /// Initializes a new instance of the AdminOperationsActor. /// Factory for creating config database contexts. @@ -91,6 +95,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: the /alerts verdict collection window. /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1024: warm the checker's cache in the background on start. public AdminOperationsActor( IDbContextFactory dbFactory, IActorRef coordinator, @@ -100,8 +105,10 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + bool warmScriptGateOnStart = false) { + _warmScriptGateOnStart = warmScriptGateOnStart; _scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker; _scriptCompileGateMode = scriptCompileGateMode; _alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow; @@ -127,6 +134,19 @@ public sealed class AdminOperationsActor : ReceiveActor Receive(HandleShelveAlarm); } + /// + /// #1024: warms the script compile gate's cache off the actor thread as the singleton starts (and on every + /// failover re-spawn), so the FIRST deploy after a central restart is not a cold Roslyn compile of the whole + /// fleet's scripts racing the AdminUI's ask timeout. Fire-and-forget; the warm-up is best-effort and a + /// concurrent deploy shares the in-flight compiles (the checker's per-key lazy). + /// + protected override void PreStart() + { + base.PreStart(); + if (_warmScriptGateOnStart && _scriptChecker is { } checker) + _ = Task.Run(() => WarmScriptCompileGateAsync(checker)); + } + /// /// The reply text for an unexpected server-side failure (R03:4.1): a fixed sentence plus the request's /// correlation id, never ex.Message — a SqlException or UriFormatException message carries diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs index 9849f0530..f4dc5c739 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs @@ -157,7 +157,8 @@ public static class ServiceCollectionExtensions // is past the coordinator's deadline, so the two must never drift. return AdminOperationsActor.Props(dbFactory, coordinator, probes, mode, meshRouter, applyDeadline: DeployTimings.ApplyDeadline, - scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode); + scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode, + warmScriptGateOnStart: true); }, singletonOptions); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs index a6df40c42..19705cbcb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs @@ -65,6 +65,38 @@ public sealed class AdminOperationsClientDeployTimeoutTests : TestKit .DeploymentId.ShouldBe(result.DeploymentId.Value.Value); } + /// + /// #1024: the deploy trigger has its own, longer ask timeout — a cold Roslyn compile on a large fleet can + /// outlast the 10 s used for ack/shelve. A compose slower than the short timeout but inside the deploy one + /// is a normal Accepted, not an OutcomeUnknown. + /// + [Fact] + public async Task Deploy_uses_its_own_longer_timeout_so_a_slow_compose_is_still_Accepted() + { + var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-longer-{Guid.NewGuid():N}")); + var coordinator = CreateTestProbe("coordinator"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty())); + var registry = new ActorRegistry(); + registry.Register(actor); + var client = new AdminOperationsClient(registry, TimeSpan.FromMilliseconds(300), TimeSpan.FromSeconds(30)); + + gated.Hold(); + var pending = client.StartDeploymentAsync("ci", CancellationToken.None); + await Task.Delay(800, TestContext.Current.CancellationToken); // past the short timeout + pending.IsCompleted.ShouldBeFalse(); + gated.Release(); + + (await pending).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + } + + /// The production default for the deploy trigger is longer than the general ask timeout. + [Fact] + public void Default_deploy_timeout_exceeds_the_general_ask_timeout() + { + AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThan(AdminOperationsClient.DefaultAskTimeout); + AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(30)); + } + /// A caller-initiated cancellation is still a cancellation, not an unknown outcome. [Fact] public async Task Caller_cancellation_still_throws() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs index f6f41bf2e..2688a0599 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs @@ -256,6 +256,48 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); } + /// #1024: with warm-on-start the checker is exercised the moment the singleton starts — before any deploy. + [Fact] + public void Warm_on_start_compiles_the_scripts_before_any_deploy_arrives() + { + var checker = new RecordingChecker(); + Sys.ActorOf(AdminOperationsActor.Props( + SeedDraft(new Seed()), CreateTestProbe().Ref, Enumerable.Empty(), + scriptChecker: checker, warmScriptGateOnStart: true)); + + AwaitAssert(() => checker.Calls.Count.ShouldBe(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); + checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate)); + } + + /// #1024: warm-on-start is off by default and never runs with the gate Off. + [Fact] + public void Warm_on_start_is_not_run_when_the_gate_is_off_or_not_requested() + { + var checker = new RecordingChecker(); + var db = SeedDraft(new Seed()); + Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty(), scriptChecker: checker)); + Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty(), + scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Off, warmScriptGateOnStart: true)); + Thread.Sleep(500); + checker.Calls.ShouldBeEmpty(); + } + + /// #1024: a throwing warm-up never takes the actor down — a deploy still works. + [Fact] + public void A_throwing_start_warm_up_does_not_break_the_next_deploy() + { + var dbFactory = SeedDraft(new Seed()); + var coordinator = CreateTestProbe(); + var checker = new RecordingChecker(@throw: true); + var actor = Sys.ActorOf(AdminOperationsActor.Props( + dbFactory, coordinator.Ref, Enumerable.Empty(), + scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Warn, warmScriptGateOnStart: true)); + AwaitAssert(() => checker.Calls.Count.ShouldBeGreaterThanOrEqualTo(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + [Fact] public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do() {