| | | 1 | | using Anichron.Core; |
| | | 2 | | using Anichron.Core.Domain; |
| | | 3 | | using Anichron.Core.Work; |
| | | 4 | | using Anichron.Worker.Ingestion; |
| | | 5 | | using Anichron.Worker.Ingestion.Pipeline; |
| | | 6 | | using Anichron.Worker.Settings; |
| | | 7 | | using Microsoft.Extensions.Options; |
| | | 8 | | using System.IO.Abstractions; |
| | | 9 | | using System.Threading.Channels; |
| | | 10 | | |
| | | 11 | | namespace Anichron.Worker.Crawling; |
| | | 12 | | |
| | | 13 | | internal interface IFileIngestionPipeline |
| | | 14 | | { |
| | | 15 | | Task<CrawlRun> RunAsync(UserStorageConfig config, IWorkProgress progress, CancellationToken ct); |
| | | 16 | | } |
| | | 17 | | |
| | 41 | 18 | | internal sealed partial class FileIngestionPipeline( |
| | 41 | 19 | | IServiceScopeFactory scopeFactory, |
| | 41 | 20 | | IFileSystem fileSystem, |
| | 41 | 21 | | ILivePhotoLinker livePhotoLinker, |
| | 41 | 22 | | CrawlExclusions exclusions, |
| | 41 | 23 | | IOptions<WorkerSettings> workerOptions, |
| | 41 | 24 | | IGuidFactory guidFactory, |
| | 41 | 25 | | ILogger<FileIngestionPipeline> logger) : IFileIngestionPipeline |
| | | 26 | | { |
| | 41 | 27 | | private readonly WorkerSettings settings = workerOptions.Value; |
| | | 28 | | |
| | | 29 | | public async Task<CrawlRun> RunAsync(UserStorageConfig config, IWorkProgress progress, CancellationToken ct) |
| | 42 | 30 | | { |
| | 42 | 31 | | var tally = new CrawlTally(progress); |
| | 42 | 32 | | var channel = Channel.CreateBounded<IngestionItem>( |
| | 42 | 33 | | // Stryker disable once Arithmetic,Initializer |
| | 42 | 34 | | new BoundedChannelOptions(settings.MaxConcurrentFiles * 2) |
| | 42 | 35 | | { |
| | 42 | 36 | | // Stryker disable once Boolean |
| | 42 | 37 | | SingleWriter = true, |
| | 42 | 38 | | FullMode = BoundedChannelFullMode.Wait, |
| | 42 | 39 | | }); |
| | | 40 | | |
| | 42 | 41 | | var producer = ProduceAsync(config, channel.Writer, tally, ct); |
| | 42 | 42 | | var consumers = Enumerable |
| | 42 | 43 | | .Range(0, settings.MaxConcurrentFiles) |
| | 42 | 44 | | .Select(workerIndex => ConsumeAsync(config, channel.Reader, workerIndex, tally, ct)) |
| | 42 | 45 | | .ToArray(); |
| | | 46 | | |
| | 42 | 47 | | await Task.WhenAll([producer, .. consumers]); |
| | 39 | 48 | | return tally.Run; |
| | 39 | 49 | | } |
| | | 50 | | |
| | | 51 | | private async Task ProduceAsync( |
| | | 52 | | UserStorageConfig config, |
| | | 53 | | ChannelWriter<IngestionItem> writer, |
| | | 54 | | CrawlTally tally, |
| | | 55 | | CancellationToken ct) |
| | 42 | 56 | | { |
| | | 57 | | try |
| | 42 | 58 | | { |
| | 42 | 59 | | var pending = new Stack<string>([config.RootPath]); |
| | 101 | 60 | | while (pending.TryPop(out var directory)) |
| | 60 | 61 | | { |
| | 60 | 62 | | var (files, subdirectories) = ListDirectory(directory, config.RootPath, tally); |
| | 59 | 63 | | await EnqueueDirectoryItemsAsync(files, config.RootPath, writer, tally, ct); |
| | 213 | 64 | | foreach (var subdirectory in subdirectories) |
| | 18 | 65 | | pending.Push(subdirectory); |
| | 59 | 66 | | } |
| | | 67 | | |
| | 41 | 68 | | tally.Walked(); |
| | 41 | 69 | | } |
| | | 70 | | finally |
| | 42 | 71 | | { |
| | 42 | 72 | | writer.TryComplete(); |
| | 42 | 73 | | } |
| | 41 | 74 | | } |
| | | 75 | | |
| | | 76 | | private (List<string> Files, List<string> Subdirectories) ListDirectory(string directory, string rootPath, CrawlTall |
| | 60 | 77 | | { |
| | | 78 | | try |
| | 60 | 79 | | { |
| | 60 | 80 | | return ( |
| | 60 | 81 | | [.. fileSystem.Directory.EnumerateFiles(directory) |
| | 60 | 82 | | .Where(file => !CrawlExclusions.IsExcludedFile(fileSystem.Path.GetFileName(file)) |
| | 60 | 83 | | && !SkipsAsLink(file, rootPath, tally))], |
| | 60 | 84 | | [.. fileSystem.Directory.EnumerateDirectories(directory) |
| | 60 | 85 | | .Where(subdirectory => !exclusions.IsExcludedDirectory(fileSystem.Path.GetFileName(subdirectory)) |
| | 60 | 86 | | && !SkipsAsLink(subdirectory, rootPath, tally))]); |
| | | 87 | | } |
| | 3 | 88 | | catch (Exception ex) when (directory != rootPath && ex is UnauthorizedAccessException or IOException) |
| | 2 | 89 | | { |
| | 2 | 90 | | Log.DirectoryUnreadable(logger, directory, ex); |
| | 2 | 91 | | tally.FolderSkipped(); |
| | 2 | 92 | | return ([], []); |
| | | 93 | | } |
| | 59 | 94 | | } |
| | | 95 | | |
| | | 96 | | private bool SkipsAsLink(string path, string rootPath, CrawlTally tally) |
| | 106 | 97 | | { |
| | 106 | 98 | | if (fileSystem.FileInfo.New(path).LinkTarget is null) |
| | 101 | 99 | | return false; |
| | | 100 | | |
| | 5 | 101 | | Log.LinkSkipped(logger, fileSystem.Path.GetRelativePath(rootPath, path)); |
| | 5 | 102 | | tally.LinkSkipped(); |
| | 5 | 103 | | return true; |
| | 106 | 104 | | } |
| | | 105 | | |
| | | 106 | | private async Task EnqueueDirectoryItemsAsync( |
| | | 107 | | IList<string> filesInDirectory, |
| | | 108 | | string rootPath, |
| | | 109 | | ChannelWriter<IngestionItem> writer, |
| | | 110 | | CrawlTally tally, |
| | | 111 | | CancellationToken ct) |
| | 59 | 112 | | { |
| | 59 | 113 | | var linkResult = livePhotoLinker.Link(filesInDirectory, rootPath); |
| | | 114 | | |
| | 195 | 115 | | foreach (var item in linkResult.Items) |
| | 9 | 116 | | { |
| | 9 | 117 | | tally.Found(item); |
| | 9 | 118 | | await writer.WriteAsync(item, ct); |
| | 9 | 119 | | } |
| | | 120 | | |
| | 343 | 121 | | foreach (var filePath in filesInDirectory) |
| | 83 | 122 | | { |
| | 83 | 123 | | if (linkResult.ClaimedPaths.Contains(filePath)) |
| | 16 | 124 | | continue; |
| | | 125 | | |
| | 67 | 126 | | var mediaType = MediaTypeDetector.Detect(filePath); |
| | 67 | 127 | | if (mediaType is null) |
| | 8 | 128 | | { |
| | 8 | 129 | | Log.UnsupportedFile(logger, filePath); |
| | 8 | 130 | | tally.UnsupportedSkipped(); |
| | 8 | 131 | | continue; |
| | | 132 | | } |
| | | 133 | | |
| | 59 | 134 | | var item = new SingleFileItem(filePath, fileSystem.Path.GetRelativePath(rootPath, filePath), mediaType.Value |
| | 59 | 135 | | tally.Found(item); |
| | 59 | 136 | | await writer.WriteAsync(item, ct); |
| | 59 | 137 | | } |
| | 59 | 138 | | } |
| | | 139 | | |
| | | 140 | | private async Task ConsumeAsync( |
| | | 141 | | UserStorageConfig config, |
| | | 142 | | ChannelReader<IngestionItem> reader, |
| | | 143 | | int workerIndex, |
| | | 144 | | CrawlTally tally, |
| | | 145 | | CancellationToken ct) |
| | 72 | 146 | | { |
| | 346 | 147 | | await foreach (var item in reader.ReadAllAsync(ct)) |
| | 66 | 148 | | { |
| | 66 | 149 | | var filename = fileSystem.Path.GetFileName(item.AbsolutePath); |
| | 66 | 150 | | using var logScope = logger.BeginScope( |
| | 66 | 151 | | "W{WorkerIndex} {IngestionFile}", workerIndex, filename); |
| | | 152 | | // Scoped services (e.g. DbContext) must not be shared across concurrent files. |
| | 66 | 153 | | using var diScope = scopeFactory.CreateScope(); |
| | 66 | 154 | | var runner = diScope.ServiceProvider.GetRequiredService<IIngestionPipelineRunner>(); |
| | | 155 | | try |
| | 66 | 156 | | { |
| | 66 | 157 | | var context = new IngestionContext { Item = item, Config = config, AttemptId = guidFactory.NewGuid() }; |
| | 66 | 158 | | await runner.RunAsync(context, ct); |
| | 52 | 159 | | tally.Processed(context); |
| | 52 | 160 | | } |
| | 14 | 161 | | catch (Exception ex) when (IngestionCancellation.IsRequested(ex, ct)) |
| | 2 | 162 | | { |
| | | 163 | | // A shutdown or a cancel is not an item failure: stop promptly instead of draining the queue. |
| | 2 | 164 | | throw; |
| | | 165 | | } |
| | 12 | 166 | | catch (Exception ex) when (BrokenFile.Rejected(ex)) |
| | 5 | 167 | | { |
| | 5 | 168 | | Log.ItemBroken(logger, item.AbsolutePath, ex.Message); |
| | 5 | 169 | | tally.Failed(); |
| | 5 | 170 | | } |
| | 7 | 171 | | catch (Exception ex) |
| | 7 | 172 | | { |
| | 7 | 173 | | Log.ItemFailed(logger, item.AbsolutePath, ex); |
| | 7 | 174 | | tally.Failed(); |
| | 7 | 175 | | } |
| | 64 | 176 | | } |
| | 70 | 177 | | } |
| | | 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 | | } |