< Summary

Information
Class: Anichron.API.Endpoints.ProxySweepEndpoints
Assembly: Anichron.API
File(s): /home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/ProxySweepEndpoints.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 73
Uncovered lines: 0
Coverable lines: 73
Total lines: 171
Line coverage: 100%
Branch coverage
100%
Covered branches: 56
Total branches: 56
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
MapProxySweepEndpoints(...)100%11100%
RequestSweepAsync()100%22100%
ListOrphansAsync()100%2020100%
RequestDeletionsAsync()100%2424100%
StateOfAsync()100%66100%
ToDto(...)100%44100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.API/Endpoints/ProxySweepEndpoints.cs

#LineLine coverage
 1using Anichron.API.Infrastructure;
 2using Anichron.Core.Data.Repository;
 3using Anichron.Core.Domain;
 4using Anichron.Core.Work;
 5using Microsoft.AspNetCore.Http.HttpResults;
 6using Microsoft.AspNetCore.Mvc;
 7using System.Security.Claims;
 8
 9namespace Anichron.API.Endpoints;
 10
 11public sealed record ProxySweepRequestedDto(Guid WorkItemId);
 12
 13public sealed record ProxyDeletionRequest(IReadOnlyList<Guid>? OrphanIds, bool All);
 14
 15public sealed record ProxyDeletionsRequestedDto(IReadOnlyList<Guid> WorkItemIds);
 16
 17public sealed record ProxyOrphanDto(
 18    Guid Id,
 19    string ProxyPath,
 20    Guid? StorageConfigId,
 21    long SizeBytes,
 22    string LastWriteTime,
 23    string? Outcome,
 24    string? ProcessedAt);
 25
 26public sealed record ProxyOrphanPageDto(IReadOnlyList<ProxyOrphanDto> Items, int Page, int PageSize, int Total);
 27
 28public static class ProxySweepEndpoints
 29{
 30    internal const int DefaultPageSize = 100;
 31    internal const int MaxPageSize = 1000;
 32    internal const int MaxSelectedOrphans = 1000;
 33    internal const string OrphanIdsField = "orphanIds";
 34
 35    public static IEndpointRouteBuilder MapProxySweepEndpoints(this IEndpointRouteBuilder app)
 4336    {
 4337        var group = app.MapGroup(ApiPaths.ProxySweeps.Group).WithTags("Proxy sweeps")
 4338                       .RequireAdmin();
 4339        group.MapPost(string.Empty, RequestSweepAsync);
 4340        group.MapGet(ApiPaths.ProxySweeps.Orphans, ListOrphansAsync);
 4341        group.MapPost(ApiPaths.ProxySweeps.Deletions, RequestDeletionsAsync);
 4342        return app;
 4343    }
 44
 45    /// <summary>Queues a sweep, or returns the one already queued.</summary>
 46    /// <param name="caller">The requesting admin.</param>
 47    /// <param name="queue">Takes the request.</param>
 48    /// <param name="ct">Cancels the request.</param>
 49    /// <returns>202 with the sweep's work item, whose status and progress the work-item endpoints show.</returns>
 50    internal static async Task<Results<Accepted<ProxySweepRequestedDto>, UnauthorizedHttpResult>> RequestSweepAsync(
 51        ClaimsPrincipal caller,
 52        [FromServices] IWorkQueue queue,
 53        CancellationToken ct)
 354    {
 355        if (!Guid.TryParse(caller.FindFirstValue(ClaimTypes.NameIdentifier), out var callerId))
 156            return TypedResults.Unauthorized();
 57
 258        var id = await queue.EnqueueAsync(new ProxySweepPayload(), callerId, ct);
 259        return TypedResults.Accepted(ApiPaths.WorkItems.ItemLocation(id), new ProxySweepRequestedDto(id));
 360    }
 61
 62    internal static async Task<Results<Ok<ProxyOrphanPageDto>, ValidationProblem, NotFound, Conflict>> ListOrphansAsync(
 63        Guid sweepId,
 64        ProxyDeletionOutcome? outcome,
 65        bool? pending,
 66        Guid? storageConfigId,
 67        int? page,
 68        int? pageSize,
 69        [FromServices] IWorkItemReader items,
 70        [FromServices] IProxyOrphanReader orphans,
 71        CancellationToken ct)
 2172    {
 2173        var number = page ?? 1;
 2174        var size = pageSize ?? DefaultPageSize;
 2175        if (size is < 1 or > MaxPageSize)
 276            return ApiProblems.InvalidField(ErrorCodes.InvalidPageSize, nameof(pageSize), $"pageSize must be from 1 to {
 1977        if (number < 1 || number > int.MaxValue / size)
 278            return ApiProblems.InvalidField(ErrorCodes.InvalidPage, nameof(page), "page is out of range.");
 1779        if (pending is true && outcome is not null)
 180            return ApiProblems.InvalidField(ErrorCodes.PendingOrOutcome, nameof(pending), "Give either pending or outcom
 81
 1682        var sweep = await StateOfAsync(sweepId, items, ct);
 1683        if (sweep == SweepState.Unknown)
 284            return TypedResults.NotFound();
 1485        if (sweep == SweepState.Unfinished)
 486            return TypedResults.Conflict();
 87
 1088        var found = await orphans.ListAsync(new ProxyOrphanQuery(sweepId, outcome, pending is true, storageConfigId, (nu
 1089        return TypedResults.Ok(new ProxyOrphanPageDto([.. found.Items.Select(ToDto)], number, size, found.Total));
 2190    }
 91
 92    /// <summary>
 93    /// Queues one deletion per storage config the selected orphans name; orphans of configs that no
 94    /// longer exist, or of none, share one unscoped deletion.
 95    /// </summary>
 96    /// <param name="sweepId">The sweep whose orphans to delete.</param>
 97    /// <param name="request">Either the orphans' ids, or every orphan of the sweep.</param>
 98    /// <param name="caller">The requesting admin.</param>
 99    /// <param name="items">Reads the sweep's work item.</param>
 100    /// <param name="orphans">Reads the sweep's orphans.</param>
 101    /// <param name="queue">Takes the deletions.</param>
 102    /// <param name="ct">Cancels the request.</param>
 103    /// <returns>202 with the deletions' work items.</returns>
 104    internal static async Task<Results<Accepted<ProxyDeletionsRequestedDto>, ValidationProblem, NotFound, Conflict, Unau
 105        Guid sweepId,
 106        ProxyDeletionRequest request,
 107        ClaimsPrincipal caller,
 108        [FromServices] IWorkItemReader items,
 109        [FromServices] IProxyOrphanReader orphans,
 110        [FromServices] IWorkQueue queue,
 111        CancellationToken ct)
 16112    {
 16113        if (!Guid.TryParse(caller.FindFirstValue(ClaimTypes.NameIdentifier), out var callerId))
 1114            return TypedResults.Unauthorized();
 15115        if (request.All == (request.OrphanIds is not null))
 2116            return ApiProblems.InvalidField(ErrorCodes.OrphanIdsOrAll, OrphanIdsField, "Give either orphanIds or all, no
 13117        var selected = request.OrphanIds?.Distinct().ToList();
 13118        if (selected is { Count: 0 or > MaxSelectedOrphans })
 2119            return ApiProblems.InvalidField(ErrorCodes.InvalidOrphanCount, OrphanIdsField, $"orphanIds must hold from 1 
 120
 11121        var sweep = await StateOfAsync(sweepId, items, ct);
 11122        if (sweep == SweepState.Unknown)
 2123            return TypedResults.NotFound();
 9124        if (sweep == SweepState.Unfinished)
 1125            return TypedResults.Conflict();
 126
 127        IReadOnlyList<ProxyDeletionPayload> deletions;
 8128        if (selected is null)
 3129        {
 3130            deletions = ProxyDeletionPlan.ForAll(sweepId, await orphans.PendingConfigsAsync(sweepId, ct));
 3131        }
 132        else
 5133        {
 5134            var found = await orphans.FindAsync(sweepId, selected, ct);
 5135            if (found.Count < selected.Count)
 1136                return ApiProblems.InvalidField(ErrorCodes.UnknownOrphans, OrphanIdsField, "Some ids are not orphans of 
 4137            deletions = ProxyDeletionPlan.ForSelection(sweepId, found);
 4138        }
 139
 7140        var queued = new List<Guid>();
 39141        foreach (var deletion in deletions)
 9142            queued.Add(await queue.EnqueueAsync(deletion, callerId, ct));
 143
 7144        return TypedResults.Accepted((string?)null, new ProxyDeletionsRequestedDto(queued));
 16145    }
 146
 147    private enum SweepState
 148    {
 149        Unknown = 1,
 150        Unfinished = 2,
 151        Succeeded = 3,
 152    }
 153
 154    private static async Task<SweepState> StateOfAsync(Guid sweepId, IWorkItemReader items, CancellationToken ct)
 27155        => await items.FindAsync(sweepId, ct) switch
 27156        {
 4157            null or { Kind: not WorkKind.ProxySweep } => SweepState.Unknown,
 5158            { Status: not WorkItemStatus.Succeeded } => SweepState.Unfinished,
 18159            _ => SweepState.Succeeded,
 27160        };
 161
 162    private static ProxyOrphanDto ToDto(ProxyOrphanView view)
 3163        => new(
 3164            view.Id,
 3165            view.ProxyPath,
 3166            view.StorageConfigId,
 3167            view.SizeBytes,
 3168            WorkItemDtoMapper.Format(view.LastWriteTime),
 3169            view.DeletionOutcome?.ToString(),
 3170            view.ProcessedAt is { } processed ? WorkItemDtoMapper.Format(processed) : null);
 171}