| | | 1 | | using Anichron.Core; |
| | | 2 | | using Anichron.Core.Domain; |
| | | 3 | | using Anichron.Worker.Ingestion.Pipeline; |
| | | 4 | | using NodaTime; |
| | | 5 | | using System.IO.Abstractions; |
| | | 6 | | |
| | | 7 | | namespace Anichron.Worker.Ingestion.Proxy; |
| | | 8 | | |
| | 259 | 9 | | internal sealed partial class ProxyStagingWriter( |
| | 259 | 10 | | IFileSystem fileSystem, |
| | 259 | 11 | | IClock clock, |
| | 259 | 12 | | IGuidFactory guidFactory, |
| | 259 | 13 | | ILogger<ProxyStagingWriter> logger) |
| | | 14 | | { |
| | | 15 | | // A proxy is written under this suffix and renamed into place once complete, so a crash or a |
| | | 16 | | // killed transcode can never leave a truncated file wearing a valid proxy's name. Leftovers |
| | | 17 | | // are recognisable by this suffix, both to an operator and to the orphan sweeper (#174). |
| | | 18 | | internal const string TemporaryFileSuffix = ".tmp"; |
| | | 19 | | |
| | | 20 | | // Naming a leftover and finding one are the same rule, so they live together: a consumer that |
| | | 21 | | // hunts for staging artifacts — compensation here, the orphan sweeper in #174 — must never |
| | | 22 | | // re-express how this writer names them. |
| | | 23 | | internal static string TemporaryPathFor(string proxyAbsolutePath, Guid attemptId) |
| | 190 | 24 | | => $"{proxyAbsolutePath}.{attemptId:N}{TemporaryFileSuffix}"; |
| | | 25 | | |
| | | 26 | | internal static string TemporaryFilesOf(Guid attemptId) |
| | 27 | 27 | | => $"*.{attemptId:N}{TemporaryFileSuffix}"; |
| | | 28 | | |
| | | 29 | | // The one place a proxy reaches its final name: produceAsync writes the bytes to the temporary |
| | | 30 | | // path it is handed, and only a complete file is renamed into place and registered on the |
| | | 31 | | // context. The rename stays within one directory, so it is atomic. |
| | | 32 | | internal async Task WriteAsync( |
| | | 33 | | IngestionContext context, |
| | | 34 | | Guid ownerAssetId, |
| | | 35 | | string relativePath, |
| | | 36 | | ProxyType proxyType, |
| | | 37 | | Func<string, CancellationToken, Task> produceAsync, |
| | | 38 | | CancellationToken ct) |
| | 179 | 39 | | { |
| | 179 | 40 | | var (proxy, replacedExistingFile) = await MoveIntoPlaceAsync( |
| | 179 | 41 | | ownerAssetId, relativePath, proxyType, context.AttemptId, produceAsync, ct); |
| | | 42 | | |
| | | 43 | | // Registered at the moment it lands, so the context always reflects what is on disk |
| | | 44 | | // and compensation can delete precisely the files this attempt wrote. |
| | 173 | 45 | | context.AddProxyFile(proxy, replacedExistingFile); |
| | 173 | 46 | | Log.ProxyWritten(logger, proxyType, proxy.SizeBytes, context.Item.RelativePath); |
| | 173 | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <summary>Writes a proxy outside ingestion, by the same rule as <see cref="WriteAsync"/>.</summary> |
| | | 50 | | /// <param name="ownerAssetId">The asset the proxy belongs to.</param> |
| | | 51 | | /// <param name="relativePath">The proxy's path relative to the proxy root.</param> |
| | | 52 | | /// <param name="proxyType">The proxy's type.</param> |
| | | 53 | | /// <param name="attemptId">Names this attempt's temporary file.</param> |
| | | 54 | | /// <param name="produceAsync">Writes the bytes to the temporary path it is handed.</param> |
| | | 55 | | /// <param name="ct">Cancels the write.</param> |
| | | 56 | | /// <returns>The row describing the file now at its final name, for the caller to add.</returns> |
| | | 57 | | internal async Task<ProxyFile> PlaceAsync( |
| | | 58 | | Guid ownerAssetId, |
| | | 59 | | string relativePath, |
| | | 60 | | ProxyType proxyType, |
| | | 61 | | Guid attemptId, |
| | | 62 | | Func<string, CancellationToken, Task> produceAsync, |
| | | 63 | | CancellationToken ct) |
| | 11 | 64 | | { |
| | 11 | 65 | | var (proxy, _) = await MoveIntoPlaceAsync(ownerAssetId, relativePath, proxyType, attemptId, produceAsync, ct); |
| | 8 | 66 | | return proxy; |
| | 8 | 67 | | } |
| | | 68 | | |
| | | 69 | | private async Task<(ProxyFile Proxy, bool ReplacedExistingFile)> MoveIntoPlaceAsync( |
| | | 70 | | Guid ownerAssetId, |
| | | 71 | | string relativePath, |
| | | 72 | | ProxyType proxyType, |
| | | 73 | | Guid attemptId, |
| | | 74 | | Func<string, CancellationToken, Task> produceAsync, |
| | | 75 | | CancellationToken ct) |
| | 190 | 76 | | { |
| | 190 | 77 | | var proxyAbsolutePath = StoragePath.ResolveProxy(relativePath) |
| | 190 | 78 | | ?? throw new InvalidOperationException($"Proxy path {relativePath} resolves outside the proxy root."); |
| | 189 | 79 | | var temporaryAbsolutePath = TemporaryPathFor(proxyAbsolutePath, attemptId); |
| | | 80 | | try |
| | 189 | 81 | | { |
| | 189 | 82 | | if (fileSystem.Path.GetDirectoryName(proxyAbsolutePath) is { } directory) |
| | 189 | 83 | | fileSystem.Directory.CreateDirectory(directory); |
| | | 84 | | |
| | 189 | 85 | | await produceAsync(temporaryAbsolutePath, ct); |
| | 181 | 86 | | var sizeBytes = fileSystem.FileInfo.New(temporaryAbsolutePath).Length; |
| | 181 | 87 | | var replacedExistingFile = fileSystem.File.Exists(proxyAbsolutePath); |
| | 181 | 88 | | fileSystem.File.Move(temporaryAbsolutePath, proxyAbsolutePath, overwrite: true); |
| | 181 | 89 | | return (ProxyFileBuilder.Build(ownerAssetId, relativePath, proxyType, sizeBytes, guidFactory, clock), replac |
| | | 90 | | } |
| | | 91 | | finally |
| | 189 | 92 | | { |
| | 189 | 93 | | DiscardTemporaryFile(temporaryAbsolutePath); |
| | 189 | 94 | | } |
| | 181 | 95 | | } |
| | | 96 | | |
| | | 97 | | // Runs while an exception may already be in flight — including a shutdown cancellation, where |
| | | 98 | | // the half-written file is dropped but completed proxies are kept. A failure to delete must |
| | | 99 | | // never replace the error that caused the cleanup. |
| | | 100 | | private void DiscardTemporaryFile(string temporaryPath) |
| | 189 | 101 | | { |
| | | 102 | | try |
| | 189 | 103 | | { |
| | 189 | 104 | | if (fileSystem.File.Exists(temporaryPath)) |
| | 4 | 105 | | fileSystem.File.Delete(temporaryPath); |
| | 188 | 106 | | } |
| | 1 | 107 | | catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| | 1 | 108 | | { |
| | 1 | 109 | | Log.DiscardFailed(logger, temporaryPath, ex); |
| | 1 | 110 | | } |
| | 189 | 111 | | } |
| | | 112 | | |
| | | 113 | | private static partial class Log |
| | | 114 | | { |
| | | 115 | | [LoggerMessage(Level = LogLevel.Debug, Message = "Wrote {ProxyType} proxy ({SizeBytes} B) for {RelativePath}.")] |
| | | 116 | | public static partial void ProxyWritten(ILogger logger, ProxyType proxyType, long sizeBytes, string relativePath |
| | | 117 | | |
| | | 118 | | [LoggerMessage(Level = LogLevel.Warning, Message = "Could not delete temporary proxy file {Path}.")] |
| | | 119 | | public static partial void DiscardFailed(ILogger logger, string path, Exception ex); |
| | | 120 | | } |
| | | 121 | | } |