using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Sessions;
using ZB.MOM.WW.MxGateway.Server.Workers;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
///
/// Startup wiring of and its registration order
/// relative to the session subsystem (mxaccessgw#205, R21-O32).
///
public sealed class OrphanWorkerCleanupHostedServiceTests
{
private static readonly string WorkerPath = Path.GetFullPath(Path.Combine(
Path.GetTempPath(), "OrphanHostedTests", "ZB.MOM.WW.MxGateway.Worker.exe"));
private static OrphanWorkerCleanupHostedService Create(CountingInspector inspector) =>
new(
new OrphanWorkerTerminator(
Options.Create(new GatewayOptions { Worker = new WorkerOptions { ExecutablePath = WorkerPath } }),
inspector,
new GatewayMetrics()),
NullLogger.Instance);
/// StartAsync sweeps for orphans exactly once and kills what the terminator finds.
/// A task that represents the asynchronous operation.
[Fact]
public async Task StartAsync_TerminatesOrphansOnce()
{
CountingInspector inspector = new([new RunningProcessInfo(4242, WorkerPath)]);
OrphanWorkerCleanupHostedService service = Create(inspector);
await service.StartAsync(CancellationToken.None);
await service.StopAsync(CancellationToken.None);
Assert.Equal(1, inspector.EnumerateCalls);
Assert.Equal([4242], inspector.Killed);
}
/// A cleanup failure is swallowed so the gateway still starts.
/// A task that represents the asynchronous operation.
[Fact]
public async Task StartAsync_WhenCleanupThrows_DoesNotFailStartup()
{
CountingInspector inspector = new([]) { ThrowOnEnumerate = true };
OrphanWorkerCleanupHostedService service = Create(inspector);
await service.StartAsync(CancellationToken.None);
Assert.Equal(1, inspector.EnumerateCalls);
}
///
/// The worker launcher registration must put orphan cleanup ahead of the session
/// subsystem's hosted services, so leaked workers are gone before sessions are accepted.
///
[Fact]
public void Registration_OrdersOrphanCleanupBeforeSessionHostedServices()
{
ServiceCollection services = new();
services.AddWorkerProcessLauncher();
services.AddGatewaySessions();
List hosted = services
.Where(d => d.ServiceType == typeof(IHostedService))
.Select(d => d.ImplementationType)
.ToList();
int cleanup = hosted.IndexOf(typeof(OrphanWorkerCleanupHostedService));
int lease = hosted.IndexOf(typeof(SessionLeaseMonitorHostedService));
Assert.True(cleanup >= 0, "OrphanWorkerCleanupHostedService is not registered.");
Assert.True(lease >= 0, "SessionLeaseMonitorHostedService is not registered.");
Assert.True(cleanup < lease, "Orphan cleanup must start before the session lease monitor.");
Assert.Contains(typeof(SessionShutdownHostedService), hosted);
}
private sealed class CountingInspector(IReadOnlyList processes) : IRunningProcessInspector
{
public int EnumerateCalls { get; private set; }
public bool ThrowOnEnumerate { get; init; }
public List Killed { get; } = [];
public IReadOnlyList GetProcessesByName(string processName)
{
EnumerateCalls++;
if (ThrowOnEnumerate)
{
throw new InvalidOperationException("enumeration failed");
}
return processes;
}
public void Kill(int processId) => Killed.Add(processId);
}
}