< Summary

Line coverage
100%
Covered lines: 125
Uncovered lines: 0
Coverable lines: 125
Total lines: 493
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: ProduceAsync()100%44100%
File 2: ListDirectory(...)100%11100%
File 2: SkipsAsLink(...)100%22100%
File 2: EnqueueDirectoryItemsAsync()100%88100%
File 2: ConsumeAsync()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/Crawling/FileIngestionPipeline.cs

#LineLine coverage
 1using Anichron.Core;
 2using Anichron.Core.Domain;
 3using Anichron.Core.Work;
 4using Anichron.Worker.Ingestion;
 5using Anichron.Worker.Ingestion.Pipeline;
 6using Anichron.Worker.Settings;
 7using Microsoft.Extensions.Options;
 8using System.IO.Abstractions;
 9using System.Threading.Channels;
 10
 11namespace Anichron.Worker.Crawling;
 12
 13internal interface IFileIngestionPipeline
 14{
 15    Task<CrawlRun> RunAsync(UserStorageConfig config, IWorkProgress progress, CancellationToken ct);
 16}
 17
 4118internal sealed partial class FileIngestionPipeline(
 4119    IServiceScopeFactory scopeFactory,
 4120    IFileSystem fileSystem,
 4121    ILivePhotoLinker livePhotoLinker,
 4122    CrawlExclusions exclusions,
 4123    IOptions<WorkerSettings> workerOptions,
 4124    IGuidFactory guidFactory,
 4125    ILogger<FileIngestionPipeline> logger) : IFileIngestionPipeline
 26{
 4127    private readonly WorkerSettings settings = workerOptions.Value;
 28
 29    public async Task<CrawlRun> RunAsync(UserStorageConfig config, IWorkProgress progress, CancellationToken ct)
 4230    {
 4231        var tally = new CrawlTally(progress);
 4232        var channel = Channel.CreateBounded<IngestionItem>(
 4233            // Stryker disable once Arithmetic,Initializer
 4234            new BoundedChannelOptions(settings.MaxConcurrentFiles * 2)
 4235            {
 4236                // Stryker disable once Boolean
 4237                SingleWriter = true,
 4238                FullMode = BoundedChannelFullMode.Wait,
 4239            });
 40
 4241        var producer = ProduceAsync(config, channel.Writer, tally, ct);
 4242        var consumers = Enumerable
 4243            .Range(0, settings.MaxConcurrentFiles)
 4244            .Select(workerIndex => ConsumeAsync(config, channel.Reader, workerIndex, tally, ct))
 4245            .ToArray();
 46
 4247        await Task.WhenAll([producer, .. consumers]);
 3948        return tally.Run;
 3949    }
 50
 51    private async Task ProduceAsync(
 52        UserStorageConfig config,
 53        ChannelWriter<IngestionItem> writer,
 54        CrawlTally tally,
 55        CancellationToken ct)
 4256    {
 57        try
 4258        {
 4259            var pending = new Stack<string>([config.RootPath]);
 10160            while (pending.TryPop(out var directory))
 6061            {
 6062                var (files, subdirectories) = ListDirectory(directory, config.RootPath, tally);
 5963                await EnqueueDirectoryItemsAsync(files, config.RootPath, writer, tally, ct);
 21364                foreach (var subdirectory in subdirectories)
 1865                    pending.Push(subdirectory);
 5966            }
 67
 4168            tally.Walked();
 4169        }
 70        finally
 4271        {
 4272            writer.TryComplete();
 4273        }
 4174    }
 75
 76    private (List<string> Files, List<string> Subdirectories) ListDirectory(string directory, string rootPath, CrawlTall
 6077    {
 78        try
 6079        {
 6080            return (
 6081                [.. fileSystem.Directory.EnumerateFiles(directory)
 6082                    .Where(file => !CrawlExclusions.IsExcludedFile(fileSystem.Path.GetFileName(file))
 6083                        && !SkipsAsLink(file, rootPath, tally))],
 6084                [.. fileSystem.Directory.EnumerateDirectories(directory)
 6085                    .Where(subdirectory => !exclusions.IsExcludedDirectory(fileSystem.Path.GetFileName(subdirectory))
 6086                        && !SkipsAsLink(subdirectory, rootPath, tally))]);
 87        }
 388        catch (Exception ex) when (directory != rootPath && ex is UnauthorizedAccessException or IOException)
 289        {
 290            Log.DirectoryUnreadable(logger, directory, ex);
 291            tally.FolderSkipped();
 292            return ([], []);
 93        }
 5994    }
 95
 96    private bool SkipsAsLink(string path, string rootPath, CrawlTally tally)
 10697    {
 10698        if (fileSystem.FileInfo.New(path).LinkTarget is null)
 10199            return false;
 100
 5101        Log.LinkSkipped(logger, fileSystem.Path.GetRelativePath(rootPath, path));
 5102        tally.LinkSkipped();
 5103        return true;
 106104    }
 105
 106    private async Task EnqueueDirectoryItemsAsync(
 107        IList<string> filesInDirectory,
 108        string rootPath,
 109        ChannelWriter<IngestionItem> writer,
 110        CrawlTally tally,
 111        CancellationToken ct)
 59112    {
 59113        var linkResult = livePhotoLinker.Link(filesInDirectory, rootPath);
 114
 195115        foreach (var item in linkResult.Items)
 9116        {
 9117            tally.Found(item);
 9118            await writer.WriteAsync(item, ct);
 9119        }
 120
 343121        foreach (var filePath in filesInDirectory)
 83122        {
 83123            if (linkResult.ClaimedPaths.Contains(filePath))
 16124                continue;
 125
 67126            var mediaType = MediaTypeDetector.Detect(filePath);
 67127            if (mediaType is null)
 8128            {
 8129                Log.UnsupportedFile(logger, filePath);
 8130                tally.UnsupportedSkipped();
 8131                continue;
 132            }
 133
 59134            var item = new SingleFileItem(filePath, fileSystem.Path.GetRelativePath(rootPath, filePath), mediaType.Value
 59135            tally.Found(item);
 59136            await writer.WriteAsync(item, ct);
 59137        }
 59138    }
 139
 140    private async Task ConsumeAsync(
 141        UserStorageConfig config,
 142        ChannelReader<IngestionItem> reader,
 143        int workerIndex,
 144        CrawlTally tally,
 145        CancellationToken ct)
 72146    {
 346147        await foreach (var item in reader.ReadAllAsync(ct))
 66148        {
 66149            var filename = fileSystem.Path.GetFileName(item.AbsolutePath);
 66150            using var logScope = logger.BeginScope(
 66151                "W{WorkerIndex} {IngestionFile}", workerIndex, filename);
 152            // Scoped services (e.g. DbContext) must not be shared across concurrent files.
 66153            using var diScope = scopeFactory.CreateScope();
 66154            var runner = diScope.ServiceProvider.GetRequiredService<IIngestionPipelineRunner>();
 155            try
 66156            {
 66157                var context = new IngestionContext { Item = item, Config = config, AttemptId = guidFactory.NewGuid() };
 66158                await runner.RunAsync(context, ct);
 52159                tally.Processed(context);
 52160            }
 14161            catch (Exception ex) when (IngestionCancellation.IsRequested(ex, ct))
 2162            {
 163                // A shutdown or a cancel is not an item failure: stop promptly instead of draining the queue.
 2164                throw;
 165            }
 12166            catch (Exception ex) when (BrokenFile.Rejected(ex))
 5167            {
 5168                Log.ItemBroken(logger, item.AbsolutePath, ex.Message);
 5169                tally.Failed();
 5170            }
 7171            catch (Exception ex)
 7172            {
 7173                Log.ItemFailed(logger, item.AbsolutePath, ex);
 7174                tally.Failed();
 7175            }
 64176        }
 70177    }
 178
 179    private static partial class Log
 180    {
 181        [LoggerMessage(Level = LogLevel.Debug, Message = "Skipping unsupported file type: {Path}.")]
 182        public static partial void UnsupportedFile(ILogger logger, string path);
 183
 184        [LoggerMessage(Level = LogLevel.Error, Message = "Failed to ingest {Path}.")]
 185        public static partial void ItemFailed(ILogger logger, string path, Exception ex);
 186
 187        [LoggerMessage(Level = LogLevel.Warning, Message = "Failed to ingest {Path}: {Reason}")]
 188        public static partial void ItemBroken(ILogger logger, string path, string reason);
 189
 190        [LoggerMessage(Level = LogLevel.Warning, Message = "Skipping link {Path}: a crawl never follows links.")]
 191        public static partial void LinkSkipped(ILogger logger, string path);
 192
 193        [LoggerMessage(Level = LogLevel.Warning, Message = "Skipping unreadable folder {Path}.")]
 194        public static partial void DirectoryUnreadable(ILogger logger, string path, Exception ex);
 195    }
 196}