| | | 1 | | using Anichron.Core; |
| | | 2 | | using Anichron.Core.Domain; |
| | | 3 | | using Anichron.Worker.Ingestion; |
| | | 4 | | using Anichron.Worker.Ingestion.Pipeline; |
| | | 5 | | using Anichron.Worker.Settings; |
| | | 6 | | using Microsoft.Extensions.Options; |
| | | 7 | | using System.IO.Abstractions; |
| | | 8 | | using System.Threading.Channels; |
| | | 9 | | |
| | | 10 | | namespace Anichron.Worker.Crawling; |
| | | 11 | | |
| | | 12 | | internal interface IFileIngestionPipeline |
| | | 13 | | { |
| | | 14 | | Task RunAsync(UserStorageConfig config, CancellationToken ct); |
| | | 15 | | } |
| | | 16 | | |
| | 13 | 17 | | internal sealed partial class FileIngestionPipeline( |
| | 13 | 18 | | IServiceScopeFactory scopeFactory, |
| | 13 | 19 | | IFileSystem fileSystem, |
| | 13 | 20 | | ILivePhotoLinker livePhotoLinker, |
| | 13 | 21 | | IOptions<WorkerSettings> workerOptions, |
| | 13 | 22 | | IGuidFactory guidFactory, |
| | 13 | 23 | | ILogger<FileIngestionPipeline> logger) : IFileIngestionPipeline |
| | | 24 | | { |
| | 13 | 25 | | private readonly WorkerSettings settings = workerOptions.Value; |
| | | 26 | | |
| | | 27 | | public async Task RunAsync(UserStorageConfig config, CancellationToken ct) |
| | 13 | 28 | | { |
| | 13 | 29 | | var channel = Channel.CreateBounded<IngestionItem>( |
| | 13 | 30 | | new BoundedChannelOptions(settings.MaxConcurrentFiles * 2) |
| | 13 | 31 | | { |
| | 13 | 32 | | SingleWriter = true, |
| | 13 | 33 | | FullMode = BoundedChannelFullMode.Wait, |
| | 13 | 34 | | }); |
| | | 35 | | |
| | 13 | 36 | | var producer = ProduceAsync(config, channel.Writer, ct); |
| | 13 | 37 | | var consumers = Enumerable |
| | 13 | 38 | | .Range(0, settings.MaxConcurrentFiles) |
| | 13 | 39 | | .Select(workerIndex => ConsumeAsync(config, channel.Reader, workerIndex, ct)) |
| | 13 | 40 | | .ToArray(); |
| | | 41 | | |
| | 13 | 42 | | await Task.WhenAll([producer, .. consumers]); |
| | 11 | 43 | | } |
| | | 44 | | |
| | | 45 | | private async Task ProduceAsync( |
| | | 46 | | UserStorageConfig config, |
| | | 47 | | ChannelWriter<IngestionItem> writer, |
| | | 48 | | CancellationToken ct) |
| | 13 | 49 | | { |
| | | 50 | | try |
| | 13 | 51 | | { |
| | 13 | 52 | | var filesByDirectory = fileSystem.Directory |
| | 13 | 53 | | .EnumerateFiles(config.RootPath, "*", SearchOption.AllDirectories) |
| | 13 | 54 | | .GroupBy(path => fileSystem.Path.GetDirectoryName(path) ?? string.Empty); |
| | | 55 | | |
| | 60 | 56 | | foreach (var directoryGroup in filesByDirectory) |
| | 12 | 57 | | await EnqueueDirectoryItemsAsync([.. directoryGroup], config.RootPath, writer, ct); |
| | 12 | 58 | | } |
| | | 59 | | finally |
| | 13 | 60 | | { |
| | 13 | 61 | | writer.TryComplete(); |
| | 13 | 62 | | } |
| | 12 | 63 | | } |
| | | 64 | | |
| | | 65 | | private async Task EnqueueDirectoryItemsAsync( |
| | | 66 | | IList<string> filesInDirectory, |
| | | 67 | | string rootPath, |
| | | 68 | | ChannelWriter<IngestionItem> writer, |
| | | 69 | | CancellationToken ct) |
| | 12 | 70 | | { |
| | 12 | 71 | | var linkResult = livePhotoLinker.Link(filesInDirectory, rootPath); |
| | | 72 | | |
| | 46 | 73 | | foreach (var item in linkResult.Items) |
| | 5 | 74 | | await writer.WriteAsync(item, ct); |
| | | 75 | | |
| | 74 | 76 | | foreach (var filePath in filesInDirectory) |
| | 19 | 77 | | { |
| | 19 | 78 | | if (linkResult.ClaimedPaths.Contains(filePath)) |
| | 8 | 79 | | continue; |
| | | 80 | | |
| | 11 | 81 | | var mediaType = MediaTypeDetector.Detect(filePath); |
| | 11 | 82 | | if (mediaType is null) |
| | 2 | 83 | | { |
| | 2 | 84 | | Log.UnsupportedFile(logger, filePath); |
| | 2 | 85 | | continue; |
| | | 86 | | } |
| | | 87 | | |
| | 9 | 88 | | var relativePath = fileSystem.Path.GetRelativePath(rootPath, filePath); |
| | 9 | 89 | | await writer.WriteAsync(new SingleFileItem(filePath, relativePath, mediaType.Value), ct); |
| | 9 | 90 | | } |
| | 12 | 91 | | } |
| | | 92 | | |
| | | 93 | | private async Task ConsumeAsync( |
| | | 94 | | UserStorageConfig config, |
| | | 95 | | ChannelReader<IngestionItem> reader, |
| | | 96 | | int workerIndex, |
| | | 97 | | CancellationToken ct) |
| | 24 | 98 | | { |
| | 95 | 99 | | await foreach (var item in reader.ReadAllAsync(ct)) |
| | 12 | 100 | | { |
| | 12 | 101 | | var filename = fileSystem.Path.GetFileName(item.AbsolutePath); |
| | 12 | 102 | | using var logScope = logger.BeginScope( |
| | 12 | 103 | | "W{WorkerIndex} {IngestionFile}", workerIndex, filename); |
| | | 104 | | // Scoped services (e.g. DbContext) must not be shared across concurrent files. |
| | 12 | 105 | | using var diScope = scopeFactory.CreateScope(); |
| | 12 | 106 | | var runner = diScope.ServiceProvider.GetRequiredService<IIngestionPipelineRunner>(); |
| | | 107 | | try |
| | 12 | 108 | | { |
| | 12 | 109 | | var context = new IngestionContext { Item = item, Config = config, AssetId = guidFactory.NewGuid() }; |
| | 12 | 110 | | await runner.RunAsync(context, ct); |
| | 10 | 111 | | } |
| | 2 | 112 | | catch (Exception ex) when (IngestionShutdown.IsInProgress(ex, ct)) |
| | 1 | 113 | | { |
| | | 114 | | // A shutdown is not an item failure: stop promptly instead of draining the queue. |
| | 1 | 115 | | throw; |
| | | 116 | | } |
| | 1 | 117 | | catch (Exception ex) |
| | 1 | 118 | | { |
| | 1 | 119 | | Log.ItemFailed(logger, item.AbsolutePath, ex); |
| | 1 | 120 | | } |
| | 11 | 121 | | } |
| | 23 | 122 | | } |
| | | 123 | | |
| | | 124 | | private static partial class Log |
| | | 125 | | { |
| | | 126 | | [LoggerMessage(Level = LogLevel.Warning, Message = "Skipping unsupported file type: {Path}.")] |
| | | 127 | | public static partial void UnsupportedFile(ILogger logger, string path); |
| | | 128 | | |
| | | 129 | | [LoggerMessage(Level = LogLevel.Error, Message = "Failed to ingest {Path}.")] |
| | | 130 | | public static partial void ItemFailed(ILogger logger, string path, Exception ex); |
| | | 131 | | } |
| | | 132 | | } |