using Akka.Actor;
using Akka.Event;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Health;
///
/// Single-flight cached health probe against the ConfigDb. Reads cached state via
/// Ask<DbHealthStatus>; a single SELECT runs at most every RefreshInterval.
/// Consumed by both the host's /health/ready endpoint and
/// RedundancyStateActor's stale calc.
///
///
/// The probe runs OFF the mailbox (a thread-pool task that pipes its outcome back), with a bounded
/// command timeout. It used to run synchronously on the actor thread, relying on SqlClient's implicit
/// 15 s connect / 30 s command timeouts — so a hanging SQL Server pinned a dispatcher thread for up to
/// 30 s per tick, later ticks queued behind it, and the cached answer was
/// unreachable for exactly as long as the database was. Single-flight: a tick that lands while a probe
/// is still running is skipped rather than stacked.
///
public sealed class DbHealthProbeActor : ReceiveActor, IWithTimers
{
public static readonly TimeSpan RefreshInterval = TimeSpan.FromSeconds(5);
/// Bound on the probe's SQL command, relational providers only (the in-memory provider the
/// actor tests run against has no command timeout).
public static readonly TimeSpan CommandTimeout = TimeSpan.FromSeconds(2);
public sealed class GetStatus { public static readonly GetStatus Instance = new(); private GetStatus() { } }
public sealed record DbHealthStatus(bool Reachable, DateTime AsOfUtc, string? LastError);
public sealed class Tick { public static readonly Tick Instance = new(); private Tick() { } }
/// Piped back by the off-thread probe with its outcome.
private sealed record ProbeCompleted(DbHealthStatus Status);
private readonly IDbContextFactory _dbFactory;
private readonly ILoggingAdapter _log = Context.GetLogger();
private DbHealthStatus _last = new(false, DateTime.MinValue, "not probed yet");
private bool _probeInFlight;
/// Gets or sets the timer scheduler for periodic health probes.
public ITimerScheduler Timers { get; set; } = null!;
/// Creates a Props instance for the DbHealthProbeActor.
/// The factory for creating ConfigDb contexts.
/// The Akka for creating this actor.
public static Props Props(IDbContextFactory dbFactory) =>
Akka.Actor.Props.Create(() => new DbHealthProbeActor(dbFactory));
/// Initializes a new instance of the class.
/// The factory for creating ConfigDb contexts.
public DbHealthProbeActor(IDbContextFactory dbFactory)
{
_dbFactory = dbFactory;
Receive(_ => Sender.Tell(_last));
Receive(_ => StartProbe());
Receive(msg =>
{
_probeInFlight = false;
_last = msg.Status;
if (!msg.Status.Reachable)
_log.Warning("DbHealthProbe: probe failed: {Error}", msg.Status.LastError);
});
}
///
protected override void PreStart()
{
StartProbe();
Timers.StartPeriodicTimer("probe", Tick.Instance, RefreshInterval);
}
private void StartProbe()
{
if (_probeInFlight)
{
_log.Debug("DbHealthProbe: previous probe still running; skipping this tick");
return;
}
_probeInFlight = true;
var factory = _dbFactory;
// Never touches actor state; the outcome comes back as a message.
Task.Run(() => Probe(factory)).PipeTo(
Self,
success: status => new ProbeCompleted(status),
failure: ex => new ProbeCompleted(new DbHealthStatus(false, DateTime.UtcNow, ex.Message)));
}
private static DbHealthStatus Probe(IDbContextFactory factory)
{
try
{
using var db = factory.CreateDbContext();
// Local to this lease — the pool resets it on return (see DriverHostActor.LoadArtifactBlob).
if (db.Database.IsRelational())
db.Database.SetCommandTimeout(CommandTimeout);
_ = db.Deployments.AsNoTracking().Take(1).ToList();
return new DbHealthStatus(true, DateTime.UtcNow, null);
}
catch (Exception ex)
{
return new DbHealthStatus(false, DateTime.UtcNow, ex.Message);
}
}
}