< Summary

Line coverage
100%
Covered lines: 47
Uncovered lines: 0
Coverable lines: 47
Total lines: 1261
Line coverage: 100%
Branch coverage
100%
Covered branches: 6
Total branches: 6
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: TemporaryPathFor(...)100%11100%
File 2: TemporaryFilesOf(...)100%11100%
File 2: WriteAsync()100%11100%
File 2: PlaceAsync()100%11100%
File 2: MoveIntoPlaceAsync()100%44100%
File 2: DiscardTemporaryFile(...)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/Ingestion/Proxy/ProxyStagingWriter.cs

#LineLine coverage
 1using Anichron.Core;
 2using Anichron.Core.Domain;
 3using Anichron.Worker.Ingestion.Pipeline;
 4using NodaTime;
 5using System.IO.Abstractions;
 6
 7namespace Anichron.Worker.Ingestion.Proxy;
 8
 2599internal sealed partial class ProxyStagingWriter(
 25910    IFileSystem fileSystem,
 25911    IClock clock,
 25912    IGuidFactory guidFactory,
 25913    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)
 19024        => $"{proxyAbsolutePath}.{attemptId:N}{TemporaryFileSuffix}";
 25
 26    internal static string TemporaryFilesOf(Guid attemptId)
 2727        => $"*.{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)
 17939    {
 17940        var (proxy, replacedExistingFile) = await MoveIntoPlaceAsync(
 17941            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.
 17345        context.AddProxyFile(proxy, replacedExistingFile);
 17346        Log.ProxyWritten(logger, proxyType, proxy.SizeBytes, context.Item.RelativePath);
 17347    }
 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)
 1164    {
 1165        var (proxy, _) = await MoveIntoPlaceAsync(ownerAssetId, relativePath, proxyType, attemptId, produceAsync, ct);
 866        return proxy;
 867    }
 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)
 19076    {
 19077        var proxyAbsolutePath = StoragePath.ResolveProxy(relativePath)
 19078            ?? throw new InvalidOperationException($"Proxy path {relativePath} resolves outside the proxy root.");
 18979        var temporaryAbsolutePath = TemporaryPathFor(proxyAbsolutePath, attemptId);
 80        try
 18981        {
 18982            if (fileSystem.Path.GetDirectoryName(proxyAbsolutePath) is { } directory)
 18983                fileSystem.Directory.CreateDirectory(directory);
 84
 18985            await produceAsync(temporaryAbsolutePath, ct);
 18186            var sizeBytes = fileSystem.FileInfo.New(temporaryAbsolutePath).Length;
 18187            var replacedExistingFile = fileSystem.File.Exists(proxyAbsolutePath);
 18188            fileSystem.File.Move(temporaryAbsolutePath, proxyAbsolutePath, overwrite: true);
 18189            return (ProxyFileBuilder.Build(ownerAssetId, relativePath, proxyType, sizeBytes, guidFactory, clock), replac
 90        }
 91        finally
 18992        {
 18993            DiscardTemporaryFile(temporaryAbsolutePath);
 18994        }
 18195    }
 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)
 189101    {
 102        try
 189103        {
 189104            if (fileSystem.File.Exists(temporaryPath))
 4105                fileSystem.File.Delete(temporaryPath);
 188106        }
 1107        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
 1108        {
 1109            Log.DiscardFailed(logger, temporaryPath, ex);
 1110        }
 189111    }
 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}