Files
ersatztv/ErsatzTV.Tests/Infrastructure/Health/HealthCheckServiceTests.cs
T
timothyandClaude Opus 4.8 be25df670e
Build ErsatzTV Image / CI image pin matches docker/ci (pull_request) Successful in 6s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 16s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 13m16s
Build ErsatzTV Image / decisions.md append-only (pull_request) Failing after 12m23s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Failing after 14m6s
Build ErsatzTV Image / Functional E2E (curl contracts) (pull_request) Successful in 14m44s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 19m19s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 19m28s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
feat(431): TTL-cache health-check results; ?refresh=true forces a fresh run
GET /api/v1/health re-ran all 14 health checks on every request, 4 of
which shell out to ffmpeg/ffprobe via CliWrap — so each poll spawned ~4
subprocesses. The existing HealthCheckSummary cache was write-only.

Cache the full result list for 30s inside HealthCheckService keyed on a
new "healthcheck.results" entry; a non-forced call returns it on a hit,
skipping the checks and the (subscriber-less) summary publish. Add a
`bool forceRefresh` first parameter to IHealthCheckService.PerformHealthChecks:
the API poll path reads the cache, while startup (RunHealthChecksService)
and the troubleshooting support bundle force a fresh run.

Refresh surface: GET /api/v1/health gains an optional `[FromQuery] bool
refresh` (additive, follows the ?deep= exemplar); the SPA "Refresh health"
button calls /api/v1/health?refresh=true, the initial/poll load does not.

Tests: HealthCheckService cache-hit vs force-bypass (mutually opposing,
non-vacuous), handler+controller refresh-flag threading, SPA refresh URL.
Docs: decisions.md 2026-07-19 (#431), api-conventions §2; regenerated v1.json.

fixes #431

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 14:41:12 +02:00

108 lines
4.1 KiB
C#

using ErsatzTV.Core.Health;
using ErsatzTV.Core.Health.Checks;
using ErsatzTV.Infrastructure.Health;
using LanguageExt;
using MediatR;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Infrastructure.Health;
[TestFixture]
public class HealthCheckServiceTests
{
private IFFmpegVersionHealthCheck _representativeCheck = null!;
private IMemoryCache _memoryCache = null!;
private IMediator _mediator = null!;
private HealthCheckService _service = null!;
[SetUp]
public void SetUp()
{
_memoryCache = new MemoryCache(new MemoryCacheOptions());
_mediator = Substitute.For<IMediator>();
_representativeCheck = PassCheck<IFFmpegVersionHealthCheck>();
// All 14 checks run together on a single PerformHealthChecks call, so the representative
// check's invocation count equals the number of actual (non-cached) runs.
_service = new HealthCheckService(
PassCheck<IMacOsConfigFolderHealthCheck>(),
_representativeCheck,
PassCheck<IFFmpegCapabilitiesHealthCheck>(),
PassCheck<IFFmpegReportsHealthCheck>(),
PassCheck<IHardwareAccelerationHealthCheck>(),
PassCheck<IMovieMetadataHealthCheck>(),
PassCheck<IEpisodeMetadataHealthCheck>(),
PassCheck<IZeroDurationHealthCheck>(),
PassCheck<IFileNotFoundHealthCheck>(),
PassCheck<IUnavailableHealthCheck>(),
PassCheck<IVaapiDriverHealthCheck>(),
PassCheck<IUnifiedDockerHealthCheck>(),
PassCheck<IDowngradeHealthCheck>(),
PassCheck<IEmptyScheduleHealthCheck>(),
_memoryCache,
_mediator,
NullLogger<HealthCheckService>.Instance);
}
[TearDown]
public void TearDown() => (_memoryCache as MemoryCache)?.Dispose();
[Test]
public async Task PerformHealthChecks_Should_Serve_Cache_Within_Window()
{
await _service.PerformHealthChecks(false, CancellationToken.None);
await _service.PerformHealthChecks(false, CancellationToken.None);
// Second call is served from cache: checks are not re-run, summary is not re-published.
await _representativeCheck.Received(1).Check(Arg.Any<CancellationToken>());
await _mediator.Received(1).Publish(Arg.Any<HealthCheckSummary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task PerformHealthChecks_Should_Return_Cached_Instance_Within_Window()
{
List<HealthCheckResult> first = await _service.PerformHealthChecks(false, CancellationToken.None);
List<HealthCheckResult> second = await _service.PerformHealthChecks(false, CancellationToken.None);
second.ShouldBeSameAs(first);
}
[Test]
public async Task PerformHealthChecks_Should_Bypass_Cache_On_Force_Refresh()
{
await _service.PerformHealthChecks(false, CancellationToken.None);
await _service.PerformHealthChecks(true, CancellationToken.None);
// Force refresh re-runs the checks and re-publishes, regardless of the warm cache.
await _representativeCheck.Received(2).Check(Arg.Any<CancellationToken>());
await _mediator.Received(2).Publish(Arg.Any<HealthCheckSummary>(), Arg.Any<CancellationToken>());
}
[Test]
public async Task Force_Refresh_Should_Repopulate_Cache_For_Later_Reads()
{
// A forced run should warm the cache so a following non-forced read is a hit.
await _service.PerformHealthChecks(true, CancellationToken.None);
await _service.PerformHealthChecks(false, CancellationToken.None);
await _representativeCheck.Received(1).Check(Arg.Any<CancellationToken>());
}
private static T PassCheck<T>() where T : class, IHealthCheck
{
var check = Substitute.For<T>();
check.Check(Arg.Any<CancellationToken>())
.Returns(_ => new HealthCheckResult(
typeof(T).Name,
HealthCheckStatus.Pass,
"ok",
"ok",
Option<HealthCheckLink>.None));
return check;
}
}