feat(api): logs and troubleshooting-info endpoints for SPA parity (#145, #158)

Add GET /api/logs (thin wrapper over GetRecentLogEntries; paged, filtered,
clamped pageSize like LibraryBrowseController) and GET /api/troubleshoot/info
(wraps GetTroubleshootingInfo; General section serialized to the same JSON
shape the legacy Blazor Troubleshooting page renders, plus per-platform
capability dumps). Also adds [EndpointGroupName("general")] to the existing
troubleshoot playback endpoints so they surface in the OpenAPI spec (#158
item 3).
This commit is contained in:
2026-07-07 13:34:47 +02:00
parent 6e091c98ae
commit dfa561a97e
7 changed files with 296 additions and 0 deletions
@@ -0,0 +1,7 @@
#nullable enable
namespace ErsatzTV.Core.Api.Logs;
public record LogEntryResponseModel(
DateTimeOffset Timestamp,
string Level,
string Message);
@@ -0,0 +1,6 @@
#nullable enable
namespace ErsatzTV.Core.Api.Logs;
public record PagedLogEntriesResponseModel(
int TotalCount,
List<LogEntryResponseModel> Page);
@@ -0,0 +1,14 @@
#nullable enable
namespace ErsatzTV.Core.Api.Troubleshooting;
// GeneralJson mirrors the JSON blob rendered on the "General" tab of the legacy Blazor
// Troubleshooting page (version, environment, cpus, video controllers, health, ffmpeg settings,
// AviSynth flags, channels, ffmpeg profiles) - kept pre-serialized so the SPA can render/copy it
// verbatim without re-deriving the same shape. The remaining fields mirror the per-platform
// capability dump tabs (only the ones relevant to the current OS/GPU are non-empty).
public record TroubleshootingInfoResponseModel(
string GeneralJson,
string? NvidiaCapabilities,
string? QsvCapabilities,
string? VaapiCapabilities,
string? VideoToolboxCapabilities);
@@ -0,0 +1,89 @@
using System.Reflection;
using ErsatzTV.Application.Logs;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Core.Api.Logs;
using MediatR;
using Microsoft.AspNetCore.Mvc.Routing;
using NSubstitute;
using NUnit.Framework;
using Serilog.Events;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class LogsControllerTests
{
private LogsController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new LogsController(_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Route()
{
MethodInfo action = typeof(LogsController).GetMethod(nameof(LogsController.GetLogs))
?? throw new AssertionException("Missing action GetLogs");
HttpMethodAttribute attribute = action.GetCustomAttributes<HttpMethodAttribute>(inherit: true).Single();
attribute.HttpMethods.ShouldContain("GET");
attribute.Template.ShouldBe("/api/logs");
attribute.Name.ShouldBe("GetLogs");
}
[Test]
public async Task GetLogs_Should_Clamp_Paging_And_Send_Query()
{
_mediator.Send(Arg.Any<GetRecentLogEntries>(), Arg.Any<CancellationToken>())
.Returns(new PagedLogEntriesViewModel(0, []));
await _controller.GetLogs(-1, 500, "boom", CancellationToken.None);
await _mediator.Received(1).Send(
Arg.Is<GetRecentLogEntries>(q =>
q.PageNum == 0 &&
q.PageSize == 100 &&
q.Filter == "boom"),
Arg.Any<CancellationToken>());
}
[Test]
public async Task GetLogs_Should_Map_Entries_To_Response_Model()
{
var entries = new List<LogEntryViewModel>
{
new(DateTimeOffset.UnixEpoch, LogEventLevel.Warning, "uh oh"),
new(DateTimeOffset.UnixEpoch.AddMinutes(1), LogEventLevel.Information, "all good")
};
_mediator.Send(Arg.Any<GetRecentLogEntries>(), Arg.Any<CancellationToken>())
.Returns(new PagedLogEntriesViewModel(2, entries));
PagedLogEntriesResponseModel result = await _controller.GetLogs(
cancellationToken: CancellationToken.None);
result.TotalCount.ShouldBe(2);
result.Page.ShouldBe(
[
new LogEntryResponseModel(DateTimeOffset.UnixEpoch, "Warning", "uh oh"),
new LogEntryResponseModel(DateTimeOffset.UnixEpoch.AddMinutes(1), "Information", "all good")
]);
}
[Test]
public async Task GetLogs_Should_Return_Empty_Page_When_None_Exist()
{
_mediator.Send(Arg.Any<GetRecentLogEntries>(), Arg.Any<CancellationToken>())
.Returns(new PagedLogEntriesViewModel(0, []));
PagedLogEntriesResponseModel result = await _controller.GetLogs(
cancellationToken: CancellationToken.None);
result.TotalCount.ShouldBe(0);
result.Page.ShouldBeEmpty();
}
}
@@ -0,0 +1,84 @@
using System.IO.Abstractions;
using System.Reflection;
using System.Text.Json;
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.Troubleshooting;
using ErsatzTV.Application.Troubleshooting.Queries;
using ErsatzTV.Controllers.Api;
using ErsatzTV.Core.Api.Troubleshooting;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Interfaces.Troubleshooting;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace ErsatzTV.Tests.Controllers;
[TestFixture]
public class TroubleshootControllerTests
{
private TroubleshootController _controller = null!;
private IMediator _mediator = null!;
[SetUp]
public void SetUp()
{
_mediator = Substitute.For<IMediator>();
_controller = new TroubleshootController(
Channel.CreateUnbounded<IFFmpegWorkerRequest>().Writer,
Substitute.For<IFileSystem>(),
Substitute.For<IConfigElementRepository>(),
Substitute.For<ITroubleshootingNotifier>(),
_mediator);
}
[Test]
public void Controller_Should_Expose_Idiomatic_Rest_Route_For_Info()
{
MethodInfo action = typeof(TroubleshootController).GetMethod(nameof(TroubleshootController.GetInfo))
?? throw new AssertionException("Missing action GetInfo");
var attribute = action.GetCustomAttributes<HttpGetAttribute>().Single();
attribute.Template.ShouldBe("/api/troubleshoot/info");
attribute.Name.ShouldBe("GetTroubleshootingInfo");
}
[Test]
public async Task GetInfo_Should_Serialize_General_Section_And_Carry_Platform_Capabilities()
{
var info = new TroubleshootingInfo(
"1.2.3",
new Dictionary<string, string> { ["ETV_FOO"] = "bar" },
[],
[],
[],
new ErsatzTV.Application.FFmpegProfiles.FFmpegSettingsViewModel(),
[],
[],
[],
false,
false,
"nvidia output",
"qsv output",
"vaapi output",
"videotoolbox output");
_mediator.Send(Arg.Any<GetTroubleshootingInfo>(), Arg.Any<CancellationToken>())
.Returns(info);
TroubleshootingInfoResponseModel result = await _controller.GetInfo(CancellationToken.None);
result.NvidiaCapabilities.ShouldBe("nvidia output");
result.QsvCapabilities.ShouldBe("qsv output");
result.VaapiCapabilities.ShouldBe("vaapi output");
result.VideoToolboxCapabilities.ShouldBe("videotoolbox output");
using JsonDocument document = JsonDocument.Parse(result.GeneralJson);
document.RootElement.GetProperty("Version").GetString().ShouldBe("1.2.3");
document.RootElement.GetProperty("Environment").GetProperty("ETV_FOO").GetString().ShouldBe("bar");
document.RootElement.GetProperty("AviSynth").GetProperty("Demuxer").GetBoolean().ShouldBeFalse();
}
}
@@ -0,0 +1,39 @@
using ErsatzTV.Application.Logs;
using ErsatzTV.Core.Api.Logs;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace ErsatzTV.Controllers.Api;
[ApiController]
public class LogsController(IMediator mediator) : ControllerBase
{
private const int MaxPageSize = 100;
[HttpGet("/api/logs", Name = "GetLogs")]
[Tags("Logs")]
[EndpointSummary("Get recent log entries")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(PagedLogEntriesResponseModel), StatusCodes.Status200OK)]
public async Task<PagedLogEntriesResponseModel> GetLogs(
[FromQuery] int pageNum = 0,
[FromQuery] int pageSize = 100,
[FromQuery] string filter = "",
CancellationToken cancellationToken = default)
{
int clampedPageNum = Math.Max(0, pageNum);
int clampedPageSize = Math.Clamp(pageSize, 1, MaxPageSize);
PagedLogEntriesViewModel result = await mediator.Send(
new GetRecentLogEntries(clampedPageNum, clampedPageSize, filter ?? string.Empty),
cancellationToken);
return new PagedLogEntriesResponseModel(
result.TotalCount,
result.Page.Map(ProjectToResponseModel).ToList());
}
private static LogEntryResponseModel ProjectToResponseModel(LogEntryViewModel viewModel) =>
new(viewModel.Timestamp, viewModel.Level.ToString(), viewModel.Message);
}
@@ -1,15 +1,19 @@
using System.IO.Abstractions;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Channels;
using ErsatzTV.Application;
using ErsatzTV.Application.MediaItems;
using ErsatzTV.Application.Troubleshooting;
using ErsatzTV.Application.Troubleshooting.Queries;
using ErsatzTV.Core;
using ErsatzTV.Core.Api.Troubleshooting;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.FFmpeg;
using ErsatzTV.Core.Interfaces.Repositories;
using ErsatzTV.Core.Interfaces.Troubleshooting;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog.Context;
@@ -23,8 +27,55 @@ public class TroubleshootController(
ITroubleshootingNotifier notifier,
IMediator mediator) : ControllerBase
{
private static readonly JsonSerializerOptions GeneralJsonOptions = new()
{
Converters = { new JsonStringEnumConverter() },
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = true
};
[HttpGet("/api/troubleshoot/info", Name = "GetTroubleshootingInfo")]
[Tags("Troubleshooting")]
[EndpointSummary("Get troubleshooting diagnostic info")]
[EndpointGroupName("general")]
[ProducesResponseType(typeof(TroubleshootingInfoResponseModel), StatusCodes.Status200OK)]
public async Task<TroubleshootingInfoResponseModel> GetInfo(CancellationToken cancellationToken)
{
TroubleshootingInfo info = await mediator.Send(new GetTroubleshootingInfo(), cancellationToken);
// mirrors the "General" tab JSON blob built by Pages/Troubleshooting/Troubleshooting.razor
string generalJson = JsonSerializer.Serialize(
new
{
info.Version,
Environment = info.Environment.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value),
info.Cpus,
info.VideoControllers,
info.Health,
info.FFmpegSettings,
AviSynth = new
{
Demuxer = info.AviSynthDemuxer,
Installed = info.AviSynthInstalled
},
info.Channels,
info.FFmpegProfiles
},
GeneralJsonOptions);
return new TroubleshootingInfoResponseModel(
generalJson,
info.NvidiaCapabilities,
info.QsvCapabilities,
info.VaapiCapabilities,
info.VideoToolboxCapabilities);
}
[HttpHead("api/troubleshoot/playback.m3u8")]
[HttpGet("api/troubleshoot/playback.m3u8")]
[Tags("Troubleshooting")]
[EndpointSummary("Start a troubleshooting playback session")]
[EndpointGroupName("general")]
public async Task<IActionResult> TroubleshootPlayback(
[FromQuery]
int mediaItem,
@@ -159,6 +210,9 @@ public class TroubleshootController(
[HttpHead("api/troubleshoot/playback/archive")]
[HttpGet("api/troubleshoot/playback/archive")]
[Tags("Troubleshooting")]
[EndpointSummary("Download the last troubleshooting playback session archive")]
[EndpointGroupName("general")]
public async Task<IActionResult> TroubleshootPlaybackArchive(CancellationToken cancellationToken)
{
Option<string> maybeArchivePath = await mediator.Send(new ArchiveTroubleshootingResults(), cancellationToken);
@@ -182,6 +236,9 @@ public class TroubleshootController(
[HttpHead("api/troubleshoot/playback/sample/{mediaItemId:int}")]
[HttpGet("api/troubleshoot/playback/sample/{mediaItemId:int}")]
[Tags("Troubleshooting")]
[EndpointSummary("Download a media sample archive for troubleshooting")]
[EndpointGroupName("general")]
public async Task<IActionResult> TroubleshootPlaybackSample(int mediaItemId, CancellationToken cancellationToken)
{
Option<string> maybeArchivePath = await mediator.Send(new ArchiveMediaSample(mediaItemId), cancellationToken);