using Microsoft.Extensions.Diagnostics.HealthChecks; using ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess; using ZB.MOM.WW.OtOpcUa.Host.Configuration; namespace ZB.MOM.WW.OtOpcUa.Host.Health; /// /// Pure decision function for the script-runner probe (lmxopcua#780 design §10, owner decision §14 #12), factored /// out of so the matrix is table-testable without worker processes. /// public static class ScriptRunnerHealthDecision { /// /// Maps the runner's status to a health status. Never Unhealthy: a sick script runner does not stop the /// node serving driver data over OPC UA, so it must not fail readiness — on a redundant pair that would shift /// ServiceLevel to the peer over a script problem. Degraded is still ready (200) but visible. /// /// The out-of-process runner's status, or null when every seam runs in process. /// The status, a description and the per-shard data. public static (HealthStatus Status, string Description, IReadOnlyDictionary Data) Evaluate(ScriptRunnerStatus? status) { if (status is null) return (HealthStatus.Healthy, "Scripts run in process (Scripting:Runner=InProcess).", new Dictionary()); var data = new Dictionary(StringComparer.Ordinal) { ["state"] = status.State.ToString(), ["suspects"] = status.SuspectCount, ["quarantined"] = status.QuarantinedCount, ["peCache"] = status.PeCacheEnabled, }; foreach (var shard in status.Shards) { data[$"shard.{shard.Label}"] = shard.Up ? $"up pid {shard.Pid}, {shard.InFlight} in flight" : shard.DownFor is { } downFor ? $"down {downFor.TotalSeconds:F0} s ({shard.ConsecutiveFailures} failure(s))" : "not started"; } var down = status.Shards.Where(s => s.DownFor is not null).Select(s => s.Label).ToArray(); return status.State switch { ScriptRunnerState.Ready => (HealthStatus.Healthy, "Out-of-process script runner ready.", data), ScriptRunnerState.Degraded => (HealthStatus.Degraded, $"Out-of-process script runner degraded: ScriptWorker {string.Join(", ", down)} down; scripts placed there report BadResourceUnavailable until it restarts.", data), _ => (HealthStatus.Degraded, "Out-of-process script runner unavailable (circuit open): every ScriptWorker shard is down; every compiled script reports BadResourceUnavailable. OPC UA keeps serving driver data.", data), }; } } /// The script-runner readiness component: Healthy, or Degraded-but-ready (see ). /// The node's runner selection; null on nodes that never register one. public sealed class ScriptRunnerHealthCheck(ScriptRunnerSelection? selection) : IHealthCheck { /// The check's registration name. public const string Name = "script-runner"; /// public Task CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { var (status, description, data) = ScriptRunnerHealthDecision.Evaluate(selection?.Status()); return Task.FromResult(status == HealthStatus.Healthy ? HealthCheckResult.Healthy(description, data) : HealthCheckResult.Degraded(description, data: data)); } }