| | | 1 | | using Anichron.Core; |
| | | 2 | | using Anichron.Worker.Ingestion.Proxy; |
| | | 3 | | using System.IO.Abstractions; |
| | | 4 | | |
| | | 5 | | namespace Anichron.Worker.Ingestion.Pipeline; |
| | | 6 | | |
| | | 7 | | internal interface IIngestionPipelineRunner |
| | | 8 | | { |
| | | 9 | | Task RunAsync(IngestionContext context, CancellationToken ct); |
| | | 10 | | } |
| | | 11 | | |
| | 69 | 12 | | internal sealed partial class IngestionPipelineRunner( |
| | 69 | 13 | | IEnumerable<IIngestionMiddleware> middlewares, |
| | 69 | 14 | | IProxyDirectoryStrategy proxyDirectoryStrategy, |
| | 69 | 15 | | IFileSystem fileSystem, |
| | 69 | 16 | | ILogger<IngestionPipelineRunner> logger) : IIngestionPipelineRunner |
| | | 17 | | { |
| | 71 | 18 | | private readonly IngestionDelegate pipeline = BuildValidated([.. middlewares], logger); |
| | | 19 | | |
| | | 20 | | public async Task RunAsync(IngestionContext context, CancellationToken ct) |
| | 94 | 21 | | { |
| | | 22 | | try |
| | 94 | 23 | | { |
| | 94 | 24 | | await pipeline(context, ct); |
| | 54 | 25 | | } |
| | 40 | 26 | | catch (Exception ex) when (!IngestionCancellation.IsRequested(ex, ct)) |
| | 36 | 27 | | { |
| | | 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. |
| | 36 | 31 | | Compensate(context); |
| | 35 | 32 | | throw; |
| | | 33 | | } |
| | 54 | 34 | | } |
| | | 35 | | |
| | | 36 | | private void Compensate(IngestionContext context) |
| | 36 | 37 | | { |
| | | 38 | | const string proxyRoot = StoragePath.ProxiesRoot; |
| | 36 | 39 | | var proxies = context.CreatedProxyFiles; |
| | | 40 | | |
| | 142 | 41 | | foreach (var proxy in proxies) |
| | 17 | 42 | | 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. |
| | 36 | 47 | | if (context.ContentHash is { } contentHash) |
| | 24 | 48 | | CleanUpDirectory(proxyRoot, context, contentHash); |
| | 35 | 49 | | if (context.SecondaryHash is { } secondaryHash) |
| | 2 | 50 | | CleanUpDirectory(proxyRoot, context, secondaryHash); |
| | | 51 | | |
| | 35 | 52 | | Log.Compensated(logger, proxies.Count, context.Item.RelativePath); |
| | 35 | 53 | | } |
| | | 54 | | |
| | | 55 | | private void CleanUpDirectory(string proxyRoot, IngestionContext context, string contentHash) |
| | 26 | 56 | | { |
| | 26 | 57 | | var relativeDirectory = proxyDirectoryStrategy.GetDirectory(context.Config.Id, contentHash); |
| | 26 | 58 | | DiscardTemporaryFiles(fileSystem.Path.Combine(proxyRoot, relativeDirectory), context.AttemptId); |
| | | 59 | | |
| | 25 | 60 | | for (var directory = relativeDirectory; |
| | 75 | 61 | | directory.Length > 0; |
| | 50 | 62 | | directory = fileSystem.Path.GetDirectoryName(directory)!) |
| | 50 | 63 | | { |
| | 50 | 64 | | TryRemoveIfEmpty(fileSystem.Path.Combine(proxyRoot, directory)); |
| | 50 | 65 | | } |
| | 25 | 66 | | } |
| | | 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) |
| | 20 | 71 | | { |
| | | 72 | | try |
| | 20 | 73 | | { |
| | 20 | 74 | | if (fileSystem.File.Exists(absolutePath)) |
| | 20 | 75 | | fileSystem.File.Delete(absolutePath); |
| | 17 | 76 | | } |
| | 3 | 77 | | catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| | 3 | 78 | | { |
| | 3 | 79 | | Log.DeleteFailed(logger, absolutePath, ex); |
| | 3 | 80 | | } |
| | 20 | 81 | | } |
| | | 82 | | |
| | | 83 | | private void DiscardTemporaryFiles(string directory, Guid attemptId) |
| | 26 | 84 | | { |
| | | 85 | | try |
| | 26 | 86 | | { |
| | 26 | 87 | | var temporaryFiles = fileSystem.Directory.EnumerateFiles( |
| | 26 | 88 | | directory, ProxyStagingWriter.TemporaryFilesOf(attemptId)); |
| | 60 | 89 | | foreach (var temporaryPath in temporaryFiles) |
| | 3 | 90 | | TryDelete(temporaryPath); |
| | 18 | 91 | | } |
| | 4 | 92 | | catch (DirectoryNotFoundException) |
| | 4 | 93 | | { |
| | | 94 | | // Nothing was staged. |
| | 4 | 95 | | } |
| | 4 | 96 | | catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| | 3 | 97 | | { |
| | 3 | 98 | | Log.DeleteFailed(logger, directory, ex); |
| | 3 | 99 | | } |
| | 25 | 100 | | } |
| | | 101 | | |
| | | 102 | | private void TryRemoveIfEmpty(string directory) |
| | 50 | 103 | | { |
| | | 104 | | try |
| | 50 | 105 | | { |
| | 50 | 106 | | if (!fileSystem.Directory.EnumerateFileSystemEntries(directory).Any()) |
| | 24 | 107 | | fileSystem.Directory.Delete(directory); |
| | 37 | 108 | | } |
| | 7 | 109 | | catch (DirectoryNotFoundException) |
| | 7 | 110 | | { |
| | | 111 | | // Already gone. |
| | 7 | 112 | | } |
| | 6 | 113 | | catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| | 6 | 114 | | { |
| | 6 | 115 | | Log.DeleteFailed(logger, directory, ex); |
| | 6 | 116 | | } |
| | 50 | 117 | | } |
| | | 118 | | |
| | | 119 | | private static IngestionDelegate BuildValidated( |
| | | 120 | | IReadOnlyList<IIngestionMiddleware> middlewares, ILogger logger) |
| | 71 | 121 | | { |
| | 71 | 122 | | Validate(middlewares); |
| | 69 | 123 | | var ordered = middlewares.OrderBy(m => m.Order).ToArray(); |
| | 69 | 124 | | return IngestionPipelineBuilder.Build(ordered, logger); |
| | 69 | 125 | | } |
| | | 126 | | |
| | | 127 | | private static void Validate(IReadOnlyList<IIngestionMiddleware> middlewares) |
| | 71 | 128 | | { |
| | 71 | 129 | | var duplicates = middlewares |
| | 71 | 130 | | .GroupBy(m => m.Order) |
| | 71 | 131 | | .Where(g => g.Count() > 1) |
| | 71 | 132 | | .Select(g => g.Key) |
| | 71 | 133 | | .ToList(); |
| | 71 | 134 | | if (duplicates.Count > 0) |
| | 2 | 135 | | { |
| | 2 | 136 | | throw new InvalidOperationException( |
| | 2 | 137 | | $"Duplicate middleware orders: {string.Join(", ", duplicates)}"); |
| | | 138 | | } |
| | 69 | 139 | | } |
| | | 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 | | } |