< Summary

Line coverage
100%
Covered lines: 93
Uncovered lines: 0
Coverable lines: 93
Total lines: 1170
Line coverage: 100%
Branch coverage
100%
Covered branches: 16
Total branches: 16
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
File 1: .cctor()100%11100%
File 2: .ctor(...)100%11100%
File 2: RunAsync()100%11100%
File 2: Compensate(...)100%66100%
File 2: CleanUpDirectory(...)100%22100%
File 2: TryDelete(...)100%22100%
File 2: DiscardTemporaryFiles(...)100%22100%
File 2: TryRemoveIfEmpty(...)100%22100%
File 2: BuildValidated(...)100%11100%
File 2: Validate(...)100%22100%

File(s)

/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs

File '/home/runner/work/anichron/anichron/src/.artifacts/obj/Anichron.Worker/debug/Microsoft.Extensions.Logging.Generators/Microsoft.Extensions.Logging.Generators.LoggerMessageGenerator/LoggerMessage.g.cs' does not exist (any more).

/home/runner/work/anichron/anichron/src/Anichron.Worker/Ingestion/Pipeline/IngestionPipelineRunner.cs

#LineLine coverage
 1using Anichron.Core;
 2using Anichron.Worker.Ingestion.Proxy;
 3using System.IO.Abstractions;
 4
 5namespace Anichron.Worker.Ingestion.Pipeline;
 6
 7internal interface IIngestionPipelineRunner
 8{
 9    Task RunAsync(IngestionContext context, CancellationToken ct);
 10}
 11
 6912internal sealed partial class IngestionPipelineRunner(
 6913    IEnumerable<IIngestionMiddleware> middlewares,
 6914    IProxyDirectoryStrategy proxyDirectoryStrategy,
 6915    IFileSystem fileSystem,
 6916    ILogger<IngestionPipelineRunner> logger) : IIngestionPipelineRunner
 17{
 7118    private readonly IngestionDelegate pipeline = BuildValidated([.. middlewares], logger);
 19
 20    public async Task RunAsync(IngestionContext context, CancellationToken ct)
 9421    {
 22        try
 9423        {
 9424            await pipeline(context, ct);
 5425        }
 4026        catch (Exception ex) when (!IngestionCancellation.IsRequested(ex, ct))
 3627        {
 28            // The pipeline generates proxies before it writes the asset row, so a failure part-way
 29            // through leaves files on disk that no row will ever reference. This is the one place
 30            // that sees every file written across every step, so cleanup belongs here.
 3631            Compensate(context);
 3532            throw;
 33        }
 5434    }
 35
 36    private void Compensate(IngestionContext context)
 3637    {
 38        const string proxyRoot = StoragePath.ProxiesRoot;
 3639        var proxies = context.CreatedProxyFiles;
 40
 14241        foreach (var proxy in proxies)
 1742            TryDelete(fileSystem.Path.Combine(proxyRoot, proxy.ProxyPath));
 43
 44        // Asking the strategy rather than deriving the directory from the proxy paths keeps the
 45        // path rule in one place, and covers the attempt that failed in its first generator: it
 46        // registered no proxy at all, but the step had already created the directory.
 3647        if (context.ContentHash is { } contentHash)
 2448            CleanUpDirectory(proxyRoot, context, contentHash);
 3549        if (context.SecondaryHash is { } secondaryHash)
 250            CleanUpDirectory(proxyRoot, context, secondaryHash);
 51
 3552        Log.Compensated(logger, proxies.Count, context.Item.RelativePath);
 3553    }
 54
 55    private void CleanUpDirectory(string proxyRoot, IngestionContext context, string contentHash)
 2656    {
 2657        var relativeDirectory = proxyDirectoryStrategy.GetDirectory(context.Config.Id, contentHash);
 2658        DiscardTemporaryFiles(fileSystem.Path.Combine(proxyRoot, relativeDirectory), context.AttemptId);
 59
 2560        for (var directory = relativeDirectory;
 7561             directory.Length > 0;
 5062             directory = fileSystem.Path.GetDirectoryName(directory)!)
 5063        {
 5064            TryRemoveIfEmpty(fileSystem.Path.Combine(proxyRoot, directory));
 5065        }
 2566    }
 67
 68    // Deletion runs while the original exception is in flight, so a file that cannot be deleted is
 69    // reported and skipped: one locked file must not strand the others or replace the real error.
 70    private void TryDelete(string absolutePath)
 2071    {
 72        try
 2073        {
 2074            if (fileSystem.File.Exists(absolutePath))
 2075                fileSystem.File.Delete(absolutePath);
 1776        }
 377        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 378        {
 379            Log.DeleteFailed(logger, absolutePath, ex);
 380        }
 2081    }
 82
 83    private void DiscardTemporaryFiles(string directory, Guid attemptId)
 2684    {
 85        try
 2686        {
 2687            var temporaryFiles = fileSystem.Directory.EnumerateFiles(
 2688                directory, ProxyStagingWriter.TemporaryFilesOf(attemptId));
 6089            foreach (var temporaryPath in temporaryFiles)
 390                TryDelete(temporaryPath);
 1891        }
 492        catch (DirectoryNotFoundException)
 493        {
 94            // Nothing was staged.
 495        }
 496        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 397        {
 398            Log.DeleteFailed(logger, directory, ex);
 399        }
 25100    }
 101
 102    private void TryRemoveIfEmpty(string directory)
 50103    {
 104        try
 50105        {
 50106            if (!fileSystem.Directory.EnumerateFileSystemEntries(directory).Any())
 24107                fileSystem.Directory.Delete(directory);
 37108        }
 7109        catch (DirectoryNotFoundException)
 7110        {
 111            // Already gone.
 7112        }
 6113        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 6114        {
 6115            Log.DeleteFailed(logger, directory, ex);
 6116        }
 50117    }
 118
 119    private static IngestionDelegate BuildValidated(
 120        IReadOnlyList<IIngestionMiddleware> middlewares, ILogger logger)
 71121    {
 71122        Validate(middlewares);
 69123        var ordered = middlewares.OrderBy(m => m.Order).ToArray();
 69124        return IngestionPipelineBuilder.Build(ordered, logger);
 69125    }
 126
 127    private static void Validate(IReadOnlyList<IIngestionMiddleware> middlewares)
 71128    {
 71129        var duplicates = middlewares
 71130            .GroupBy(m => m.Order)
 71131            .Where(g => g.Count() > 1)
 71132            .Select(g => g.Key)
 71133            .ToList();
 71134        if (duplicates.Count > 0)
 2135        {
 2136            throw new InvalidOperationException(
 2137                $"Duplicate middleware orders: {string.Join(", ", duplicates)}");
 138        }
 69139    }
 140
 141    private static partial class Log
 142    {
 143        [LoggerMessage(Level = LogLevel.Information,
 144            Message = "Cleaned up {Count} proxy file(s) after a failed ingestion of {RelativePath}.")]
 145        public static partial void Compensated(ILogger logger, int count, string relativePath);
 146
 147        [LoggerMessage(Level = LogLevel.Warning, Message = "Could not delete {Path} during cleanup.")]
 148        public static partial void DeleteFailed(ILogger logger, string path, Exception ex);
 149    }
 150}