< Summary

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

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%

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
 517public sealed record ProxyOrphanDto(
 518    Guid Id,
 519    string ProxyPath,
 520    Guid? StorageConfigId,
 521    long SizeBytes,
 522    string LastWriteTime,
 523    string? Outcome,
 524    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)
 36    {
 37        var group = app.MapGroup(ApiPaths.ProxySweeps.Group).WithTags("Proxy sweeps")
 38                       .RequireAdmin();
 39        group.MapPost(string.Empty, RequestSweepAsync);
 40        group.MapGet(ApiPaths.ProxySweeps.Orphans, ListOrphansAsync);
 41        group.MapPost(ApiPaths.ProxySweeps.Deletions, RequestDeletionsAsync);
 42        return app;
 43    }
 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)
 54    {
 55        if (!Guid.TryParse(caller.FindFirstValue(ClaimTypes.NameIdentifier), out var callerId))
 56            return TypedResults.Unauthorized();
 57
 58        var id = await queue.EnqueueAsync(new ProxySweepPayload(), callerId, ct);
 59        return TypedResults.Accepted(ApiPaths.WorkItems.ItemLocation(id), new ProxySweepRequestedDto(id));
 60    }
 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)
 72    {
 73        var number = page ?? 1;
 74        var size = pageSize ?? DefaultPageSize;
 75        if (size is < 1 or > MaxPageSize)
 76            return ApiProblems.InvalidField(ErrorCodes.InvalidPageSize, nameof(pageSize), $"pageSize must be from 1 to {
 77        if (number < 1 || number > int.MaxValue / size)
 78            return ApiProblems.InvalidField(ErrorCodes.InvalidPage, nameof(page), "page is out of range.");
 79        if (pending is true && outcome is not null)
 80            return ApiProblems.InvalidField(ErrorCodes.PendingOrOutcome, nameof(pending), "Give either pending or outcom
 81
 82        var sweep = await StateOfAsync(sweepId, items, ct);
 83        if (sweep == SweepState.Unknown)
 84            return TypedResults.NotFound();
 85        if (sweep == SweepState.Unfinished)
 86            return TypedResults.Conflict();
 87
 88        var found = await orphans.ListAsync(new ProxyOrphanQuery(sweepId, outcome, pending is true, storageConfigId, (nu
 89        return TypedResults.Ok(new ProxyOrphanPageDto([.. found.Items.Select(ToDto)], number, size, found.Total));
 90    }
 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)
 112    {
 113        if (!Guid.TryParse(caller.FindFirstValue(ClaimTypes.NameIdentifier), out var callerId))
 114            return TypedResults.Unauthorized();
 115        if (request.All == (request.OrphanIds is not null))
 116            return ApiProblems.InvalidField(ErrorCodes.OrphanIdsOrAll, OrphanIdsField, "Give either orphanIds or all, no
 117        var selected = request.OrphanIds?.Distinct().ToList();
 118        if (selected is { Count: 0 or > MaxSelectedOrphans })
 119            return ApiProblems.InvalidField(ErrorCodes.InvalidOrphanCount, OrphanIdsField, $"orphanIds must hold from 1 
 120
 121        var sweep = await StateOfAsync(sweepId, items, ct);
 122        if (sweep == SweepState.Unknown)
 123            return TypedResults.NotFound();
 124        if (sweep == SweepState.Unfinished)
 125            return TypedResults.Conflict();
 126
 127        IReadOnlyList<ProxyDeletionPayload> deletions;
 128        if (selected is null)
 129        {
 130            deletions = ProxyDeletionPlan.ForAll(sweepId, await orphans.PendingConfigsAsync(sweepId, ct));
 131        }
 132        else
 133        {
 134            var found = await orphans.FindAsync(sweepId, selected, ct);
 135            if (found.Count < selected.Count)
 136                return ApiProblems.InvalidField(ErrorCodes.UnknownOrphans, OrphanIdsField, "Some ids are not orphans of 
 137            deletions = ProxyDeletionPlan.ForSelection(sweepId, found);
 138        }
 139
 140        var queued = new List<Guid>();
 141        foreach (var deletion in deletions)
 142            queued.Add(await queue.EnqueueAsync(deletion, callerId, ct));
 143
 144        return TypedResults.Accepted((string?)null, new ProxyDeletionsRequestedDto(queued));
 145    }
 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)
 155        => await items.FindAsync(sweepId, ct) switch
 156        {
 157            null or { Kind: not WorkKind.ProxySweep } => SweepState.Unknown,
 158            { Status: not WorkItemStatus.Succeeded } => SweepState.Unfinished,
 159            _ => SweepState.Succeeded,
 160        };
 161
 162    private static ProxyOrphanDto ToDto(ProxyOrphanView view)
 163        => new(
 164            view.Id,
 165            view.ProxyPath,
 166            view.StorageConfigId,
 167            view.SizeBytes,
 168            WorkItemDtoMapper.Format(view.LastWriteTime),
 169            view.DeletionOutcome?.ToString(),
 170            view.ProcessedAt is { } processed ? WorkItemDtoMapper.Format(processed) : null);
 171}