Adds normalized audio playback pipeline

This commit is contained in:
BinaryAlley committed 2026-10-17 20:52:08 +03:00
1 parent 6991640710
commit 4e13b23f16
35 files changed
+3817 -41

No files matched your search

@@ -0,0 +1,275 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
#endregion
namespace Lumina.Infrastructure.Common.Caching;
/// <summary>
/// Provides the location, the ownership marker and the permissions of the temporary directory into which the audio normalization pipeline writes the normalized audio.
/// </summary>
internal static class TranscodingCachePaths
{
/// <summary>
/// The name of the temporary directory that is used when no cache directory is configured.
/// </summary>
public const string DEFAULT_DIRECTORY_NAME = "lumina-transcoding-cache";
/// <summary>
/// The name of the file that marks a directory as a normalized audio cache created and owned by this application.
/// </summary>
public const string CACHE_MARKER_FILE_NAME = ".lumina-transcoding-cache";
/// <summary>
/// The prefix of the temporary directories of the normalization jobs that have not been published to the cache yet.
/// </summary>
public const string TEMPORARY_DIRECTORY_PREFIX = "tmp-";
/// <summary>
/// The prefix of the tombstone directories that were detached from the cache and are waiting to be deleted.
/// </summary>
public const string DELETION_DIRECTORY_PREFIX = "del-";
private const int CACHE_ID_HEX_LENGTH = 64;
private const UnixFileMode PRIVATE_DIRECTORY_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute;
private const UnixFileMode PRIVATE_FILE_MODE = UnixFileMode.UserRead | UnixFileMode.UserWrite;
private const int USER_SUFFIX_LENGTH = 16;
/// <summary>
/// Gets the absolute path of the directory into which the audio normalization pipeline writes the normalized audio of the tracks.
/// </summary>
/// <param name="configuredDirectory">
/// The configured cache directory, relative to the application base directory when not rooted, or <see langword="null"/> to use a private directory
/// under the system temporary directory. The default directory is scoped to the operating system account that runs the process.
/// </param>
/// <returns>The absolute path of the transcoding cache directory.</returns>
public static string GetRootDirectory(string? configuredDirectory)
{
if (!string.IsNullOrWhiteSpace(configuredDirectory))
{
string trimmedDirectory = configuredDirectory.Trim();
string absoluteDirectory = Path.IsPathRooted(trimmedDirectory)
? trimmedDirectory
: Path.Combine(AppContext.BaseDirectory, trimmedDirectory);
return Path.GetFullPath(absoluteDirectory);
}
return Path.Combine(Path.GetTempPath(), DEFAULT_DIRECTORY_NAME + "-" + GetUserSuffix());
}
/// <summary>
/// Checks whether a directory carries the marker of a normalized audio cache created by this application.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to check.</param>
/// <returns><see langword="true"/> when the directory carries the cache marker, otherwise <see langword="false"/>.</returns>
public static bool HasCacheMarker(string directoryPath)
{
return File.Exists(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME));
}
/// <summary>
/// Writes the marker that records the directory as a normalized audio cache created and owned by this application.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to mark.</param>
/// <remarks>
/// The marker is an ownership signal, not a lock: it is written once, and its presence is what allows a later startup to clean the directory. A directory
/// without the marker is never cleaned, so a cache directory that was configured by mistake can never lose data that does not belong to this application.
/// </remarks>
public static void WriteCacheMarker(string directoryPath)
{
if (HasCacheMarker(directoryPath))
return;
File.WriteAllText(Path.Combine(directoryPath, CACHE_MARKER_FILE_NAME), "Lumina normalized audio cache." + Environment.NewLine);
}
/// <summary>
/// Checks whether an entry name belongs to the namespace of the normalized audio cache.
/// </summary>
/// <param name="entryName">The name of the entry, without its directory.</param>
/// <returns><see langword="true"/> when the name is a cache identifier, a temporary directory name or a deletion tombstone name, otherwise <see langword="false"/>.</returns>
public static bool IsCacheEntryName(string entryName)
{
if (string.IsNullOrEmpty(entryName))
return false;
return IsValidCacheId(entryName) ||
entryName.StartsWith(TEMPORARY_DIRECTORY_PREFIX, StringComparison.Ordinal) ||
entryName.StartsWith(DELETION_DIRECTORY_PREFIX, StringComparison.Ordinal);
}
/// <summary>
/// Checks whether a value is a well formed opaque cache identifier.
/// </summary>
/// <param name="cacheId">The value to check.</param>
/// <returns><see langword="true"/> when the value is a well formed cache identifier, otherwise <see langword="false"/>.</returns>
public static bool IsValidCacheId(string cacheId)
{
if (string.IsNullOrEmpty(cacheId) || cacheId.Length != CACHE_ID_HEX_LENGTH)
return false;
foreach (char character in cacheId)
if (!char.IsAsciiHexDigitLower(character))
return false;
return true;
}
/// <summary>
/// Removes the entries of a directory that belong to the namespace of the normalized audio cache, and leaves every other entry untouched.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <remarks>
/// The cache directory itself is never deleted, and entries that do not carry a cache identifier, a temporary directory name or a deletion tombstone
/// name are never inspected. This makes the startup cleanup safe even when the configured directory is not one this application created.
/// </remarks>
/// <exception cref="OperationCanceledException">The cleanup was canceled.</exception>
/// <exception cref="IOException">An entry could not be deleted.</exception>
/// <exception cref="UnauthorizedAccessException">An entry could not be deleted because access was denied.</exception>
public static void ClearCacheEntries(string directoryPath, CancellationToken cancellationToken)
{
foreach (string entryPath in Directory.GetDirectories(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
if (!IsCacheEntryName(Path.GetFileName(entryPath)))
continue;
DirectoryInfo entryDirectory = new(entryPath);
// A cache entry is never a link. A link left under a cache like name is deleted as a link, so the deletion can never be redirected outside the cache.
if (entryDirectory.LinkTarget is not null)
entryDirectory.Delete();
else
DeleteDirectoryRecursive(entryPath, cancellationToken);
}
}
/// <summary>
/// Deletes a directory and everything it contains.
/// </summary>
/// <param name="directoryPath">The directory to delete.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <exception cref="OperationCanceledException">The deletion was canceled.</exception>
/// <exception cref="IOException">A file or directory could not be deleted.</exception>
/// <exception cref="UnauthorizedAccessException">A file or directory could not be deleted because access was denied.</exception>
private static void DeleteDirectoryRecursive(string directoryPath, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
foreach (string filePath in Directory.EnumerateFiles(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
File.Delete(filePath);
}
foreach (string childDirectoryPath in Directory.EnumerateDirectories(directoryPath))
{
cancellationToken.ThrowIfCancellationRequested();
DirectoryInfo childDirectory = new(childDirectoryPath);
// A link is deleted as a link, so a tampered entry can never make the cleanup follow it outside the cache.
if (childDirectory.LinkTarget is not null)
childDirectory.Delete();
else
DeleteDirectoryRecursive(childDirectoryPath, cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
Directory.Delete(directoryPath);
}
/// <summary>
/// Verifies that an existing cache directory is not a symbolic link and tightens its permissions to the private mode on Unix.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <exception cref="IOException">The path is a symbolic link or cannot be inspected.</exception>
/// <exception cref="UnauthorizedAccessException">The directory is owned by another user or cannot be changed.</exception>
public static void RestrictPermissions(string directoryPath)
{
DirectoryInfo directoryInformation = new(directoryPath);
// A symbolic link is rejected even when its target does not exist, so CreateDirectory can never be redirected outside the intended path.
if (directoryInformation.LinkTarget is not null)
throw new IOException("The normalized audio cache directory is a symbolic link.");
// On Unix a directory that already exists is not changed by CreateDirectory, and a directory planted by another user under a predictable name in
// the shared temporary directory would otherwise be reused with its own mode. Tightening it fails when the directory is not owned by this
// account, which makes the caller treat the cache as unavailable instead of using a directory it does not control.
if (!OperatingSystem.IsWindows() && directoryInformation.Exists)
File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE);
}
/// <summary>
/// Tightens the permissions of a file the cache created to owner read and write on Unix.
/// </summary>
/// <param name="filePath">The absolute path of the file.</param>
/// <exception cref="IOException">The file permissions could not be changed.</exception>
/// <exception cref="UnauthorizedAccessException">The file is owned by another user or cannot be changed.</exception>
public static void RestrictFilePermissions(string filePath)
{
// Windows inherits the ACL of the private cache directory, so only the Unix mode bits need to be tightened here.
if (!OperatingSystem.IsWindows())
File.SetUnixFileMode(filePath, PRIVATE_FILE_MODE);
}
/// <summary>
/// Creates a directory with private permissions on the platforms that support them.
/// </summary>
/// <param name="directoryPath">The absolute path of the directory to create.</param>
/// <exception cref="IOException">The directory could not be created.</exception>
/// <exception cref="UnauthorizedAccessException">The directory could not be created because access was denied.</exception>
public static void CreatePrivateDirectory(string directoryPath)
{
if (OperatingSystem.IsWindows())
{
Directory.CreateDirectory(directoryPath);
return;
}
Directory.CreateDirectory(directoryPath, PRIVATE_DIRECTORY_MODE);
// CreateDirectory does not change an existing directory, so the mode is applied again after the directory is known to exist.
File.SetUnixFileMode(directoryPath, PRIVATE_DIRECTORY_MODE);
}
/// <summary>
/// Creates the cache directory when it does not exist, or tightens an existing one, with private permissions on the platforms that support them.
/// </summary>
/// <param name="directoryPath">The absolute path of the cache directory.</param>
/// <remarks>
/// A directory created by this method is marked as owned by this application. An existing directory is never marked, so an operator supplied directory
/// is adopted only by the startup component, and only when it is empty.
/// </remarks>
/// <exception cref="IOException">The directory could not be created, or the path is a symbolic link.</exception>
/// <exception cref="UnauthorizedAccessException">The directory could not be created or changed because access was denied.</exception>
public static void EnsureDirectoryExists(string directoryPath)
{
RestrictPermissions(directoryPath);
bool isCreated = !Directory.Exists(directoryPath);
CreatePrivateDirectory(directoryPath);
if (isCreated)
WriteCacheMarker(directoryPath);
}
/// <summary>
/// Deletes a directory, and reports whether it was deleted.
/// </summary>
/// <param name="directoryPath">The directory to delete.</param>
/// <returns><see langword="true"/> when the directory no longer exists, otherwise <see langword="false"/>.</returns>
public static bool TryDeleteDirectory(string directoryPath)
{
try
{
if (Directory.Exists(directoryPath))
Directory.Delete(directoryPath, recursive: true);
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
}
/// <summary>
/// Gets a short, file name safe suffix of the operating system account that runs the process, so the default directory is not shared between users.
/// </summary>
/// <returns>The account suffix used in the default cache directory name.</returns>
private static string GetUserSuffix()
{
string userIdentity = Environment.UserName;
if (string.IsNullOrWhiteSpace(userIdentity))
userIdentity = "default";
byte[] identityHash = SHA256.HashData(Encoding.UTF8.GetBytes(userIdentity));
return Convert.ToHexString(identityHash).ToLowerInvariant()[..USER_SUFFIX_LENGTH];
}
}
@@ -152,6 +152,18 @@ public static class InfrastructureLayerServices
// repackaged into another container, or re-encoded into another codec.
services.AddSingleton<IPlaybackFormatService, PlaybackFormatService>();
// Music playback: records the outcome of the ffmpeg probe, so a missing binary or encoder is reported as unavailable for the affected formats.
services.AddSingleton<TranscodingToolchainStatus>();
// Music playback: produces the normalized (remuxed or transcoded) audio of a track with ffmpeg, caches it as fixed duration
// segments and serves it from the cache, bounded in concurrency, cancellable and capped in disk usage. The playback stream surface
// is its intended consumer; no API request path calls it yet.
services.AddSingleton<ITrackNormalizationService, TrackNormalizationService>();
// Music playback: owns the normalized audio cache lifecycle and verifies the ffmpeg encoders at startup, so a missing or changed toolchain
// is recorded and reported as unavailable for the affected formats instead of surfacing as a per track playback failure.
services.AddHostedService<TranscodingStartupInitializer>();
// Book reading: resolves the book reader plugins, extracts the books into a temporary directory, and serves their contents.
// The enablement cache lets the reading service skip the per-request database read of the reader configurations.
services.AddSingleton<IBookReaderEnablementCache, BookReaderEnablementCache>();
@@ -70,6 +70,11 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<TranscodingSettingsDto>()
.Bind(configuration.GetRequiredSection(TranscodingSettingsDto.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return services;
}
}
@@ -33,5 +33,18 @@ public static partial class Errors
public static Error ThemeMaxExpandedBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxExpandedBytesMustBePositive));
public static Error ThemeMaxSingleFileBytesMustBePositive => Error.Validation(description: nameof(ThemeMaxSingleFileBytesMustBePositive));
public static Error ThemeMaxEntriesMustBePositive => Error.Validation(description: nameof(ThemeMaxEntriesMustBePositive));
public static Error TranscodingFfmpegPathCannotBeEmpty => Error.Validation(description: nameof(TranscodingFfmpegPathCannotBeEmpty));
public static Error TranscodingMaxConcurrentJobsMustBePositive => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsMustBePositive));
public static Error TranscodingMaxConcurrentJobsIsTooLarge => Error.Validation(description: nameof(TranscodingMaxConcurrentJobsIsTooLarge));
public static Error TranscodingMaxCacheBytesMustBePositive => Error.Validation(description: nameof(TranscodingMaxCacheBytesMustBePositive));
public static Error TranscodingJobTimeoutMustBePositive => Error.Validation(description: nameof(TranscodingJobTimeoutMustBePositive));
public static Error TranscodingJobTimeoutIsTooLong => Error.Validation(description: nameof(TranscodingJobTimeoutIsTooLong));
public static Error TranscodingEvictionGraceSecondsMustBePositive => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsMustBePositive));
public static Error TranscodingEvictionGraceSecondsIsTooLong => Error.Validation(description: nameof(TranscodingEvictionGraceSecondsIsTooLong));
public static Error TranscodingCacheDirectoryIsInvalid => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInvalid));
public static Error TranscodingCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryIsInsideMediaRoot));
public static Error TranscodingCacheDirectoryContainsMediaRoot => Error.Validation(description: nameof(TranscodingCacheDirectoryContainsMediaRoot));
public static Error TranscodingCacheDirectoryIsUnsafeLocation => Error.Validation(description: nameof(TranscodingCacheDirectoryIsUnsafeLocation));
public static Error TranscodingDefaultCacheDirectoryIsInsideMediaRoot => Error.Validation(description: nameof(TranscodingDefaultCacheDirectoryIsInsideMediaRoot));
}
}
@@ -0,0 +1,45 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.Configuration;
/// <summary>
/// Data transfer object for deserializing the settings of the audio normalization pipeline.
/// </summary>
[DebuggerDisplay("Section name: {SECTION_NAME}")]
public sealed class TranscodingSettingsDto
{
public const string SECTION_NAME = "TranscodingSettings";
/// <summary>
/// Gets or sets the file name or path of the ffmpeg binary, relative to the process search path when not rooted.
/// </summary>
public string FfmpegPath { get; set; } = "ffmpeg";
/// <summary>
/// Gets or sets the maximum number of normalization jobs that may run at the same time.
/// </summary>
public int MaxConcurrentJobs { get; set; } = 2;
/// <summary>
/// Gets or sets the maximum total size of the normalized audio cache, in bytes.
/// </summary>
public long MaxCacheBytes { get; set; } = 2L * 1024 * 1024 * 1024;
/// <summary>
/// Gets or sets the maximum duration of a single normalization job, in seconds, after which the job is stopped.
/// </summary>
public int JobTimeoutSeconds { get; set; } = 900;
/// <summary>
/// Gets or sets the period, in seconds, during which a cache entry that was just produced or served is protected from eviction.
/// </summary>
public int EvictionGraceSeconds { get; set; } = 120;
/// <summary>
/// Gets or sets the directory where normalized audio is cached, relative to the API base directory when not rooted. When absent or empty, a
/// private directory under the system temporary directory is used.
/// </summary>
public string? CacheDirectory { get; set; }
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Describes how a single container and codec combination of the audio normalization pipeline is muxed and, when it has to be re-encoded, encoded.
/// </summary>
/// <param name="Container">The canonical container of the delivered audio.</param>
/// <param name="Codec">The canonical codec of the delivered audio.</param>
/// <param name="MuxerName">The name of the ffmpeg muxer that writes the container.</param>
/// <param name="FileExtension">The file extension of a single segment, including the leading dot.</param>
/// <param name="EncoderName">The name of the ffmpeg encoder used when the audio is transcoded.</param>
/// <param name="IsLossless">Whether the codec is lossless, in which case an encoder bitrate cap does not apply.</param>
[DebuggerDisplay("Container: {Container} Codec: {Codec} Muxer: {MuxerName}")]
internal sealed record NormalizedAudioFormatDto(
string Container,
string Codec,
string MuxerName,
string FileExtension,
string EncoderName,
bool IsLossless
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents the persisted description of a cached normalized track, which lets the cache be read without parsing the ffmpeg output again.
/// </summary>
/// <param name="Version">The version of the index layout, so an index written by an older version is treated as a cache miss.</param>
/// <param name="TrackId">The Id of the track the cached audio belongs to, so a cache handle can be authorized against the track of the route.</param>
/// <param name="Mode">The way the audio is delivered, which is a remux or a transcode.</param>
/// <param name="Container">The container of the delivered audio.</param>
/// <param name="Codec">The codec of the delivered audio.</param>
/// <param name="SegmentDurationSeconds">The duration of each segment of the delivered audio, in seconds.</param>
/// <param name="DurationInSeconds">
/// The duration of the produced and cached audio, in seconds, rounded up to the next second. It is the produced end rather than the probed duration, so
/// it always covers every produced segment.
/// </param>
/// <param name="Segments">The segments that make up the delivered audio, in playback order.</param>
[DebuggerDisplay("TrackId: {TrackId} Container: {Container} Codec: {Codec} Segments: {Segments.Count}")]
// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway.
[method: JsonConstructor]
internal sealed record NormalizedTrackIndexDto(
int Version,
Guid TrackId,
PlaybackDeliveryMode Mode,
string Container,
string Codec,
int SegmentDurationSeconds,
int DurationInSeconds,
IReadOnlyList<NormalizedTrackSegmentIndexDto> Segments
);
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents the persisted description of a single segment of a cached normalized track.
/// </summary>
/// <param name="Index">The zero based position of the segment in the delivered audio.</param>
/// <param name="StartSeconds">The time, in seconds from the start of the track, at which the segment starts.</param>
/// <param name="DurationSeconds">The duration of the segment, in seconds.</param>
/// <param name="FileName">The file name of the segment inside the cache entry.</param>
/// <param name="Length">The length of the segment, in bytes.</param>
[DebuggerDisplay("Index: {Index} StartSeconds: {StartSeconds} FileName: {FileName}")]
// The record is internal, so its primary constructor is not public. Marking it tells System.Text.Json to use it for the on disk index anyway.
[method: JsonConstructor]
internal sealed record NormalizedTrackSegmentIndexDto(
int Index,
decimal StartSeconds,
decimal DurationSeconds,
string FileName,
long Length
);
@@ -0,0 +1,21 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Playback;
/// <summary>
/// Represents a single entry of the normalized audio cache, used to enforce the cache size limit.
/// </summary>
/// <param name="Path">The absolute path of the directory that holds the entry.</param>
/// <param name="Size">The total size of the entry, in bytes.</param>
/// <param name="LastUsedUtc">The date and time, in UTC, when the entry was last produced or served.</param>
/// <param name="ProducedAtUtc">The date and time, in UTC, when the entry was produced or, for an entry found on disk, the earliest representable time.</param>
[DebuggerDisplay("Path: {Path} Size: {Size}")]
internal sealed record TranscodingCacheEntryDto(
string Path,
long Size,
DateTime LastUsedUtc,
DateTime ProducedAtUtc
);
@@ -0,0 +1,291 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Infrastructure.Common.Caching;
using Lumina.Infrastructure.Common.Models.DTO.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the TranscodingSettings application configuration settings section.
/// </summary>
public class TranscodingSettingsDtoValidator : AbstractValidator<TranscodingSettingsDto>
{
private const int MAX_CONCURRENT_JOBS = 64;
private const int MAX_JOB_TIMEOUT_SECONDS = 86400;
private const int MAX_EVICTION_GRACE_SECONDS = 86400;
private static readonly StringComparison s_pathComparison = OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
private readonly IPathService _pathService;
private readonly string _mediaRootDirectory;
private readonly string[] _conflictingDirectories;
/// <summary>
/// Initializes a new instance of the <see cref="TranscodingSettingsDtoValidator"/> class.
/// </summary>
/// <param name="mediaSettings">The media settings, used to reject a cache directory that would be served by the media route.</param>
/// <param name="pluginsSettings">The plugin settings, used to reject a cache directory that would overlap the plugins directory.</param>
/// <param name="pathService">The service used to check whether two directories overlap.</param>
public TranscodingSettingsDtoValidator(IOptions<MediaSettingsDto> mediaSettings, IOptions<PluginsSettingsDto> pluginsSettings, IPathService pathService)
{
_pathService = pathService;
_mediaRootDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, mediaSettings.Value.RootDirectory));
_conflictingDirectories = BuildConflictingDirectories(pluginsSettings.Value);
RuleFor(settings => settings.FfmpegPath)
.NotEmpty()
.WithError(Errors.Errors.Configuration.TranscodingFfmpegPathCannotBeEmpty);
RuleFor(settings => settings.MaxConcurrentJobs)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsMustBePositive);
RuleFor(settings => settings.MaxConcurrentJobs)
.Must(maxConcurrentJobs => maxConcurrentJobs <= MAX_CONCURRENT_JOBS)
.WithError(Errors.Errors.Configuration.TranscodingMaxConcurrentJobsIsTooLarge);
RuleFor(settings => settings.MaxCacheBytes)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingMaxCacheBytesMustBePositive);
RuleFor(settings => settings.JobTimeoutSeconds)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingJobTimeoutMustBePositive);
// CancellationTokenSource(TimeSpan) cannot represent an arbitrarily large delay, and a job that may run for days is a configuration error.
RuleFor(settings => settings.JobTimeoutSeconds)
.Must(jobTimeoutSeconds => jobTimeoutSeconds <= MAX_JOB_TIMEOUT_SECONDS)
.WithError(Errors.Errors.Configuration.TranscodingJobTimeoutIsTooLong);
RuleFor(settings => settings.EvictionGraceSeconds)
.GreaterThan(0)
.WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsMustBePositive);
RuleFor(settings => settings.EvictionGraceSeconds)
.Must(evictionGraceSeconds => evictionGraceSeconds <= MAX_EVICTION_GRACE_SECONDS)
.WithError(Errors.Errors.Configuration.TranscodingEvictionGraceSecondsIsTooLong);
RuleFor(settings => settings.CacheDirectory)
.Must(BeAValidDirectoryPath)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInvalid)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory));
// A malformed path is reported by the rule above, so the rules below must not try to resolve it: Path.GetFullPath would throw and abort
// startup with a raw exception instead of a configuration error.
RuleFor(settings => settings.CacheDirectory)
.Must(BeConfiguredDirectoryOutsideMediaRoot)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsInsideMediaRoot)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// The reverse containment is just as destructive: a cache directory that contains the media root would delete the media when it is cleaned.
RuleFor(settings => settings.CacheDirectory)
.Must(BeConfiguredDirectoryNotContainingMediaRoot)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryContainsMediaRoot)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// The cache directory is cleaned at startup, so it must never resolve to a location whose cleanup would damage the application or the host.
RuleFor(settings => settings.CacheDirectory)
.Must(BeInSafeLocation)
.WithError(Errors.Errors.Configuration.TranscodingCacheDirectoryIsUnsafeLocation)
.When(settings => !string.IsNullOrWhiteSpace(settings.CacheDirectory) && BeAValidDirectoryPath(settings.CacheDirectory));
// When no directory is configured the service uses a per-user directory under the system temporary directory. A failure of that default is a
// different configuration problem from a CacheDirectory the operator chose, so it is reported with its own error and never names CacheDirectory.
RuleFor(settings => settings.CacheDirectory)
.Must(_ => BeDefaultDirectoryOutsideMediaRoot())
.WithError(Errors.Errors.Configuration.TranscodingDefaultCacheDirectoryIsInsideMediaRoot)
.When(settings => string.IsNullOrWhiteSpace(settings.CacheDirectory));
}
/// <summary>
/// Checks whether the provided cache directory is a path the file system accepts.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory, or <see langword="null"/> when the default is used.</param>
/// <returns><see langword="true"/> when the path is valid, otherwise <see langword="false"/>.</returns>
private static bool BeAValidDirectoryPath(string? cacheDirectory)
{
if (string.IsNullOrWhiteSpace(cacheDirectory))
return true;
try
{
Path.GetFullPath(cacheDirectory);
return true;
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// <summary>
/// Checks whether the configured cache directory is outside the media root, which is served without authentication at the media route.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the cache is outside the media root, otherwise <see langword="false"/>.</returns>
private bool BeConfiguredDirectoryOutsideMediaRoot(string? cacheDirectory)
{
try
{
return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(cacheDirectory), _mediaRootDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the configured cache directory does not contain the media root.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the cache does not contain the media root, otherwise <see langword="false"/>.</returns>
private bool BeConfiguredDirectoryNotContainingMediaRoot(string? cacheDirectory)
{
try
{
return !IsSameOrWithin(_mediaRootDirectory, TranscodingCachePaths.GetRootDirectory(cacheDirectory));
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the configured cache directory is a location whose cleanup cannot damage the application or the host.
/// </summary>
/// <param name="cacheDirectory">The configured cache directory. It is already known to be a valid path.</param>
/// <returns><see langword="true"/> when the location is safe, otherwise <see langword="false"/>.</returns>
private bool BeInSafeLocation(string? cacheDirectory)
{
try
{
string resolvedCacheDirectory = TranscodingCachePaths.GetRootDirectory(cacheDirectory);
if (IsFileSystemRoot(resolvedCacheDirectory))
return false;
// The cache must never be the application base directory or one of its ancestors, because cleaning it would remove the application itself.
if (IsSameOrWithin(AppContext.BaseDirectory, resolvedCacheDirectory))
return false;
// The logs and plugins directories are managed by the application, so the cache must not overlap them in either direction.
foreach (string conflictingDirectory in _conflictingDirectories)
if (IsSameOrWithin(resolvedCacheDirectory, conflictingDirectory) || IsSameOrWithin(conflictingDirectory, resolvedCacheDirectory))
return false;
return true;
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// The validity rule owns the malformed path error; this rule never turns it into an unhandled startup exception.
return true;
}
}
/// <summary>
/// Checks whether the default cache directory, used when none is configured, is outside the media root.
/// </summary>
/// <returns><see langword="true"/> when the default cache is outside the media root, otherwise <see langword="false"/>.</returns>
private bool BeDefaultDirectoryOutsideMediaRoot()
{
try
{
return !IsSameOrWithin(TranscodingCachePaths.GetRootDirectory(configuredDirectory: null), _mediaRootDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// A temporary directory that cannot be resolved is reported by the startup initializer; it is not a media root containment error.
return true;
}
}
/// <summary>
/// Checks whether a path is equal to, or is located inside, another path.
/// </summary>
/// <param name="path">The path to check.</param>
/// <param name="parentPath">The path that must contain, or be equal to, the checked path.</param>
/// <returns><see langword="true"/> when the path is equal to or inside the parent path, otherwise <see langword="false"/>.</returns>
private bool IsSameOrWithin(string path, string parentPath)
{
string normalizedPath = NormalizePath(path);
string normalizedParentPath = NormalizePath(parentPath);
if (string.Equals(normalizedPath, normalizedParentPath, s_pathComparison))
return true;
return _pathService.IsPathWithin(normalizedPath, normalizedParentPath);
}
/// <summary>
/// Checks whether a path is the root of a file system, or of a volume, instead of a directory inside it.
/// </summary>
/// <param name="path">The absolute path to check.</param>
/// <returns><see langword="true"/> when the path is a file system root, otherwise <see langword="false"/>.</returns>
private static bool IsFileSystemRoot(string path)
{
string normalizedPath = NormalizePath(path);
string? rootPath = Path.GetPathRoot(normalizedPath);
return rootPath is not null && string.Equals(normalizedPath, rootPath, s_pathComparison);
}
/// <summary>
/// Gets the full form of a path, without a trailing separator unless the path itself is the root of a file system or volume.
/// </summary>
/// <param name="path">The path to normalize.</param>
/// <returns>The normalized absolute path.</returns>
private static string NormalizePath(string path)
{
string fullPath = Path.GetFullPath(path);
string? rootPath = Path.GetPathRoot(fullPath);
// The root must keep its trailing separator, otherwise a drive root such as "C:\" degenerates into the drive relative path "C:".
if (rootPath is null || fullPath.Length <= rootPath.Length)
return fullPath;
return fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
/// <summary>
/// Gets the directories that the cache directory must never overlap: the logs directory and the plugins directory.
/// </summary>
/// <param name="pluginsSettings">The plugin settings, whose directory is resolved against the application base directory.</param>
/// <returns>The absolute paths of the directories the cache must not overlap.</returns>
private static string[] BuildConflictingDirectories(PluginsSettingsDto pluginsSettings)
{
List<string> conflictingDirectories = [];
if (!string.IsNullOrWhiteSpace(pluginsSettings.Directory))
AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, pluginsSettings.Directory));
// The local log path is always the logs directory of the application base directory; the environment variable and the container path cover
// the other two ways the log path is selected at startup.
AddConflictingDirectory(conflictingDirectories, Path.Combine(AppContext.BaseDirectory, "logs"));
AddConflictingDirectory(conflictingDirectories, Environment.GetEnvironmentVariable("LOG_PATH"));
if (string.Equals(Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER"), "true", StringComparison.OrdinalIgnoreCase))
AddConflictingDirectory(conflictingDirectories, "/logs");
return [.. conflictingDirectories];
}
/// <summary>
/// Adds the full form of a directory to the list of conflicting directories, when it can be resolved and is not already listed.
/// </summary>
/// <param name="conflictingDirectories">The list of conflicting directories to add to.</param>
/// <param name="directory">The directory to add, or <see langword="null"/> when it is not configured.</param>
private static void AddConflictingDirectory(List<string> conflictingDirectories, string? directory)
{
if (string.IsNullOrWhiteSpace(directory))
return;
try
{
string resolvedDirectory = NormalizePath(directory);
if (!conflictingDirectories.Contains(resolvedDirectory, StringComparer.FromComparison(s_pathComparison)))
conflictingDirectories.Add(resolvedDirectory);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException)
{
// A malformed log path is reported by the logging configuration, not by the cache validation.
}
}
}