Files
ersatztv/ErsatzTV.Application/Libraries/Commands/CreateLocalLibraryHandler.cs
T
timothy f916695e15 fix(489): address adversarial review — enforce the local-Mixed invariant, handle blank CollectionType
Review verdict was MERGEABLE; these are the findings worth fixing before merge.

M1 (the one gating finding): LibraryMediaKind.Mixed was accepted by
POST /api/v1/libraries/local. That created a library with no scanner, which
then failed every scan forever and logged at ERROR on each scheduler tick.
The invariant was asserted in prose twice and enforced nowhere -- and hiding
it from the SPA dropdown is not enforcement, since machine clients are a
stated audience for /api/v1. Now validated in CreateLocalLibraryHandler.

M3: an empty or whitespace CollectionType did not match the `null` pattern
and fell through to None, so on Jellyfin versions that serialize it that way
the whole feature silently no-opped -- no library, no log line. Normalized
via IsNullOrWhiteSpace, covered by a TestCase for "" and "   ".

L4: the cancellation test asserted IsLeft but not that ScanCanceled reaches
the caller's info-log branch. That is the fragile bit -- folding it into an
aggregate BaseError would silently demote a user cancellation to an ERROR
log (#410). Now pinned in both directions.

Nit: reverted the show-guard message to match the byte-identical Plex/Emby
guards; the original wording is still accurate since the guard only fires
when the kind is neither Shows nor Mixed.

Also documented three accepted limitations in decisions.md (progress bar
resets per kind, one failing kind forces the others to rescan, and the fact
that the music-video scanner does no reconciliation at all -- which is why it
cannot cross-delete, but also means removals never propagate).

Negative controls: reverting the M1 validation fails its test; reverting the
projection/dispatch fails theirs.

Refs #489
2026-07-20 17:35:47 +02:00

106 lines
4.3 KiB
C#

using System.IO.Abstractions;
using System.Threading.Channels;
using ErsatzTV.Application.MediaSources;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain;
using ErsatzTV.Core.Interfaces.Locking;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
using static ErsatzTV.Application.Libraries.Mapper;
namespace ErsatzTV.Application.Libraries;
public class CreateLocalLibraryHandler : LocalLibraryHandlerBase,
IRequestHandler<CreateLocalLibrary, Either<BaseError, LocalLibraryViewModel>>
{
private readonly IDbContextFactory<TvContext> _dbContextFactory;
private readonly IEntityLocker _entityLocker;
private readonly IFileSystem _fileSystem;
private readonly ChannelWriter<IScannerBackgroundServiceRequest> _scannerWorkerChannel;
public CreateLocalLibraryHandler(
ChannelWriter<IScannerBackgroundServiceRequest> scannerWorkerChannel,
IEntityLocker entityLocker,
IFileSystem fileSystem,
IDbContextFactory<TvContext> dbContextFactory)
{
_scannerWorkerChannel = scannerWorkerChannel;
_entityLocker = entityLocker;
_fileSystem = fileSystem;
_dbContextFactory = dbContextFactory;
}
public async Task<Either<BaseError, LocalLibraryViewModel>> Handle(
CreateLocalLibrary request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, LocalLibrary> validation = await Validate(_fileSystem, dbContext, request);
return await validation.Apply(localLibrary => PersistLocalLibrary(dbContext, localLibrary));
}
private async Task<LocalLibraryViewModel> PersistLocalLibrary(
TvContext dbContext,
LocalLibrary localLibrary)
{
await dbContext.LocalLibraries.AddAsync(localLibrary);
await dbContext.SaveChangesAsync();
if (_entityLocker.LockLibrary(localLibrary.Id))
{
try
{
await _scannerWorkerChannel.WriteAsync(new ForceScanLocalLibrary(localLibrary.Id));
}
catch
{
// the scanner only unlocks when it receives the message; if the enqueue fails
// after we acquired the lock, release it here or it is held forever.
_entityLocker.UnlockLibrary(localLibrary.Id);
throw;
}
}
return ProjectToViewModel(localLibrary);
}
private static Task<Validation<BaseError, LocalLibrary>> Validate(
IFileSystem fileSystem,
TvContext dbContext,
CreateLocalLibrary request) =>
MediaSourceMustExist(dbContext, request)
.BindT(localLibrary => NameMustBeValid(request, localLibrary))
.BindT(MediaKindMustBeSupportedLocally)
.BindT(localLibrary => PathsMustBeValid(dbContext, localLibrary))
.BindT(localLibrary => NewPathsMustExist(fileSystem, localLibrary));
/// <summary>
/// Mixed is only ever produced for remote (Jellyfin) libraries, where the media server classifies
/// each item for us. No local folder scanner handles it, so a local Mixed library would fail every
/// scan forever. The API takes a raw LibraryMediaKind, so this must be enforced here rather than
/// left to the SPA's media-kind options.
/// </summary>
private static Validation<BaseError, LocalLibrary> MediaKindMustBeSupportedLocally(
LocalLibrary localLibrary) =>
localLibrary.MediaKind is LibraryMediaKind.Mixed
? BaseError.New(
"Local libraries cannot use the Mixed media kind; it is only valid for Jellyfin libraries.")
: localLibrary;
private static Task<Validation<BaseError, LocalLibrary>> MediaSourceMustExist(
TvContext dbContext,
CreateLocalLibrary request) =>
dbContext.LocalMediaSources
.OrderBy(lms => lms.Id)
.FirstOrDefaultAsync()
.Map(Optional)
.MapT(lms => new LocalLibrary
{
Name = request.Name,
Paths = request.Paths.Map(p => new LibraryPath { Path = p }).ToList(),
MediaKind = request.MediaKind,
MediaSourceId = lms.Id
})
.Map(o => o.ToValidation<BaseError>("LocalMediaSource does not exist."));
}