< Summary

Information
Class: Anichron.Worker.ProxySweeps.ProxyDeletionResult
Assembly: Anichron.Worker
File(s): /home/runner/work/anichron/anichron/src/Anichron.Worker/ProxySweeps/ProxyDeletion.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 9
Uncovered lines: 0
Coverable lines: 9
Total lines: 131
Line coverage: 100%
Branch coverage
100%
Covered branches: 6
Total branches: 6
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Counting(...)100%66100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.Worker/ProxySweeps/ProxyDeletion.cs

#LineLine coverage
 1using Anichron.Core;
 2using Anichron.Core.Data;
 3using Anichron.Core.Domain;
 4using Anichron.Core.Work;
 5using Anichron.Worker.Ingestion.Proxy;
 6using NodaTime;
 7using System.IO.Abstractions;
 8
 9namespace Anichron.Worker.ProxySweeps;
 10
 11public sealed record ProxyDeletionResult(int Deleted, int SkippedReferenced, int SkippedChanged, int Missing, int Failed
 12{
 13    public static ProxyDeletionResult None { get; } = new(0, 0, 0, 0, 0);
 14
 2715    public ProxyDeletionResult Counting(ProxyDeletionOutcome outcome) => outcome switch
 2716    {
 1417        ProxyDeletionOutcome.Deleted => this with { Deleted = Deleted + 1 },
 118        ProxyDeletionOutcome.SkippedReferenced => this with { SkippedReferenced = SkippedReferenced + 1 },
 219        ProxyDeletionOutcome.SkippedChanged => this with { SkippedChanged = SkippedChanged + 1 },
 720        ProxyDeletionOutcome.Missing => this with { Missing = Missing + 1 },
 221        ProxyDeletionOutcome.Failed => this with { Failed = Failed + 1 },
 122        _ => throw new ArgumentOutOfRangeException(nameof(outcome), outcome, "Not a deletion outcome."),
 2723    };
 24}
 25
 26internal sealed partial class ProxyDeletionHandler(
 27    IProxyOrphanStore store,
 28    IUnitOfWork unitOfWork,
 29    IProxyDirectoryStrategy directories,
 30    IFileSystem fileSystem,
 31    IClock clock,
 32    ILogger<ProxyDeletionHandler> logger) : IWorkHandler<ProxyDeletionPayload>
 33{
 34    internal const int BatchSize = 500;
 35
 36    public async Task<object?> RunAsync(ProxyDeletionPayload payload, WorkRun run, CancellationToken ct)
 37    {
 38        var result = ProxyDeletionResult.None;
 39        var done = 0;
 40        while (await store.GetPendingAsync(payload, BatchSize, ct) is { Count: > 0 } batch)
 41        {
 42            foreach (var orphan in batch)
 43            {
 44                var outcome = await DeleteAsync(orphan, ct);
 45                orphan.DeletionOutcome = outcome;
 46                orphan.ProcessedAt = clock.GetCurrentInstant();
 47                await unitOfWork.SaveChangesAsync(ct);
 48                result = result.Counting(outcome);
 49                run.Progress.Report(++done, note: "Deleting orphaned proxy files");
 50            }
 51
 52            store.ForgetLoaded();
 53        }
 54
 55        Log.Finished(logger, payload.SweepId, result.Deleted, result.SkippedReferenced, result.SkippedChanged, result.Mi
 56        return result;
 57    }
 58
 59    private async Task<ProxyDeletionOutcome> DeleteAsync(ProxyOrphan orphan, CancellationToken ct)
 60    {
 61        if (await store.IsReferencedAsync(orphan.ProxyPath, ct))
 62            return ProxyDeletionOutcome.SkippedReferenced;
 63
 64        if (StoragePath.ResolveProxy(orphan.ProxyPath) is not { } file)
 65        {
 66            Log.OutsideRoot(logger, orphan.ProxyPath);
 67            return ProxyDeletionOutcome.Failed;
 68        }
 69
 70        if (!fileSystem.File.Exists(file))
 71            return ProxyDeletionOutcome.Missing;
 72        if (ProxyFileStamp.Of(fileSystem.FileInfo.New(file)) != new ProxyFileStamp(orphan.SizeBytes, orphan.LastWriteTim
 73            return ProxyDeletionOutcome.SkippedChanged;
 74
 75        try
 76        {
 77            fileSystem.File.Delete(file);
 78        }
 79        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 80        {
 81            Log.DeleteFailed(logger, orphan.ProxyPath, ex);
 82            return ProxyDeletionOutcome.Failed;
 83        }
 84
 85        RemoveContentDirectoryIfEmpty(orphan.ProxyPath);
 86        return ProxyDeletionOutcome.Deleted;
 87    }
 88
 89    private void RemoveContentDirectoryIfEmpty(string proxyPath)
 90    {
 91        if (directories.ContentDirectoryOf(proxyPath) is not { } content)
 92            return;
 93        if (StoragePath.ResolveProxy(content) is not { } directory)
 94        {
 95            Log.DirectoryOutsideRoot(logger, content);
 96            return;
 97        }
 98
 99        try
 100        {
 101            if (!fileSystem.Directory.EnumerateFileSystemEntries(directory).Any())
 102                fileSystem.Directory.Delete(directory);
 103        }
 104        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 105        {
 106            Log.DirectoryKept(logger, directory, ex);
 107        }
 108    }
 109
 110    private static partial class Log
 111    {
 112        [LoggerMessage(
 113            Level = LogLevel.Information,
 114            Message = "Deleted orphaned proxy files of sweep {SweepId}: {Deleted} deleted, {SkippedReferenced} reference
 115                + "{SkippedChanged} changed, {Missing} missing, {Failed} failed.")]
 116        public static partial void Finished(
 117            ILogger logger, Guid sweepId, int deleted, int skippedReferenced, int skippedChanged, int missing, int faile
 118
 119        [LoggerMessage(Level = LogLevel.Warning, Message = "Could not delete orphaned proxy file {ProxyPath}.")]
 120        public static partial void DeleteFailed(ILogger logger, string proxyPath, Exception ex);
 121
 122        [LoggerMessage(Level = LogLevel.Warning, Message = "Did not delete orphaned proxy file {ProxyPath}: it resolves 
 123        public static partial void OutsideRoot(ILogger logger, string proxyPath);
 124
 125        [LoggerMessage(Level = LogLevel.Warning, Message = "Kept proxy directory {Directory}: it resolves outside the pr
 126        public static partial void DirectoryOutsideRoot(ILogger logger, string directory);
 127
 128        [LoggerMessage(Level = LogLevel.Debug, Message = "Kept proxy directory {Directory}: it could not be removed.")]
 129        public static partial void DirectoryKept(ILogger logger, string directory, Exception ex);
 130    }
 131}