< Summary

Line coverage
100%
Covered lines: 130
Uncovered lines: 0
Coverable lines: 130
Total lines: 342
Line coverage: 100%
Branch coverage
97%
Covered branches: 41
Total branches: 42
Branch coverage: 97.6%
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: RunAsync()100%44100%
File 2: RepairAsync()100%44100%
File 2: CheckAsync()83.33%66100%
File 2: CheckAsync()100%1010100%
File 2: GroupAsync()100%1212100%
File 2: SimilarNeighboursAsync()100%66100%
File 2: Thumbnail(...)100%11100%
File 2: ToResult()100%11100%

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/Bursts/BurstDetection.cs

#LineLine coverage
 1using Anichron.Core;
 2using Anichron.Core.Data;
 3using Anichron.Core.Data.Repository;
 4using Anichron.Core.Domain;
 5using Anichron.Core.Work;
 6using Anichron.Worker.Settings;
 7using Anichron.Worker.Work;
 8using Microsoft.Extensions.Options;
 9using NodaTime;
 10using System.IO.Abstractions;
 11
 12namespace Anichron.Worker.Bursts;
 13
 14public sealed record BurstDetectionResult
 15{
 16    public int Checked { get; init; }
 17    public int Created { get; init; }
 18    public int Merged { get; init; }
 19    public int Dissolved { get; init; }
 20    public int Matched { get; init; }
 21    public int NotMatched { get; init; }
 22}
 23
 6324internal sealed partial class BurstDetectionHandler(
 6325    ActiveStorageConfigs activeConfigs,
 6326    IBurstRepository bursts,
 6327    IUnitOfWork unitOfWork,
 6328    IOriginalPhotoReader reader,
 6329    IThumbnailMatcher matcher,
 6330    IFileSystem fileSystem,
 6331    IClock clock,
 6332    IGuidFactory guids,
 6333    IOptions<WorkerSettings> options,
 6334    ILogger<BurstDetectionHandler> logger) : IWorkHandler<BurstDetectionPayload>
 35{
 36    internal const int BatchSize = 100;
 37
 38    public async Task<object?> RunAsync(BurstDetectionPayload payload, WorkRun run, CancellationToken ct)
 6239    {
 6240        if (await activeConfigs.FindAsync(BurstDetectionPayload.Kind, payload.StorageConfigId, ct) is not { } config)
 241            return StorageConfigSkipped.MissingOrInactive;
 42
 6043        if (!fileSystem.Directory.Exists(config.RootPath))
 144            throw new DirectoryNotFoundException($"The storage config's root {config.RootPath} is missing.");
 45
 5946        var tally = new Tally();
 5947        await RepairAsync(config.Id, tally, ct);
 5948        await CheckAsync(config, tally, run.Progress, ct);
 49
 5850        Log.Finished(logger, config.Id, tally.Checked, tally.Created, tally.Merged, tally.Dissolved, tally.Matched, tall
 5851        return tally.ToResult();
 6052    }
 53
 54    private async Task RepairAsync(Guid configId, Tally tally, CancellationToken ct)
 5955    {
 21556        foreach (var burst in await bursts.GetInConfigWithMembersAsync(configId, ct))
 1957        {
 1958            if (burst.Assets.Count(a => !a.IsSoftDeleted) < 2)
 359            {
 360                bursts.Remove(burst);
 361                tally.Dissolved++;
 362            }
 63            else
 1664            {
 1665                burst.PrimaryAssetId = BurstGrouping.Cover(burst.Assets).Id;
 1666            }
 1967        }
 68
 5969        await unitOfWork.SaveChangesAsync(ct);
 5970        tally.Dissolved += await bursts.DeleteMemberlessAsync(ct);
 5971    }
 72
 73    private async Task CheckAsync(UserStorageConfig config, Tally tally, IWorkProgress progress, CancellationToken ct)
 5974    {
 5975        var total = await bursts.CountUncheckedPhotosAsync(config.Id, ct);
 5976        MediaAsset? last = null;
 11577        while (await bursts.GetUncheckedPhotosAsync(config.Id, last, BatchSize, ct) is { Count: > 0 } batch)
 5778        {
 77279            foreach (var photo in batch)
 30180            {
 30181                await CheckAsync(config, photo, tally, ct);
 30082                progress.Report(++tally.Checked, total, "Checking photos for bursts");
 30083            }
 84
 5685            last = batch[^1];
 5686            bursts.ForgetLoaded();
 5687            matcher.Forget();
 5688        }
 5889    }
 90
 91    private async Task CheckAsync(UserStorageConfig config, MediaAsset photo, Tally tally, CancellationToken ct)
 30192    {
 30193        var facts = reader.Read(fileSystem.Path.Combine(config.RootPath, photo.FilePath));
 30194        var check = new BurstCheck
 30195        {
 30196            AssetId = photo.Id,
 30197            CheckedAt = clock.GetCurrentInstant(),
 30198            IsCandidate = photo.Metadata is { Description: { CameraMake: not null, CameraModel: not null } }
 30199                && photo.ProxyFiles.Any(p => p.ProxyType == ProxyType.Thumbnail),
 301100            CameraBurstId = facts.CameraBurstId,
 301101        };
 301102        bursts.AddCheck(check);
 301103        if (check.IsCandidate)
 298104            await GroupAsync(config.Id, photo, check.CameraBurstId, tally, ct);
 105
 300106        await unitOfWork.SaveChangesAsync(ct);
 300107    }
 108
 109    private async Task GroupAsync(Guid configId, MediaAsset photo, string? label, Tally tally, CancellationToken ct)
 298110    {
 298111        var labelled = label is null ? [] : await bursts.GetCandidatesLabelledAsync(configId, label, ct);
 298112        var similar = await SimilarNeighboursAsync(configId, photo, labelled, tally, ct);
 297113        if (labelled.Count + similar.Count == 0)
 255114            return;
 115
 42116        var joined = await bursts.GetWithMembersAsync(
 42117            [.. labelled.Concat(similar).Select(a => a.BurstId).OfType<Guid>().Distinct()], ct);
 42118        if (BurstGrouping.Join(photo, labelled, similar, joined, options.Value.BurstSpanSeconds) is not { } join)
 2119            return;
 120
 40121        var target = join.Target;
 40122        if (target is null)
 25123        {
 25124            target = new Burst { Id = guids.NewGuid(), CreatedAt = clock.GetCurrentInstant() };
 25125            bursts.Add(target);
 25126            tally.Created++;
 25127        }
 128
 126129        foreach (var merged in join.Merged)
 3130        {
 3131            bursts.Remove(merged);
 3132            tally.Merged++;
 3133        }
 134
 328135        foreach (var member in join.Members)
 104136            member.BurstId = target.Id;
 40137        target.PrimaryAssetId = join.Cover.Id;
 297138    }
 139
 140    private async Task<IReadOnlyList<MediaAsset>> SimilarNeighboursAsync(
 141        Guid configId, MediaAsset photo, IReadOnlyCollection<MediaAsset> labelled, Tally tally, CancellationToken ct)
 298142    {
 298143        var labelledBursts = labelled.Select(a => a.BurstId).OfType<Guid>().ToHashSet();
 298144        var gap = options.Value.BurstGapSeconds;
 298145        var neighbours = await bursts.GetCandidatesNearAsync(
 298146            configId,
 298147            photo.Metadata!.Description.CameraMake!,
 298148            photo.Metadata.Description.CameraModel!,
 298149            photo.DateCaptured!.Value.PlusSeconds(-gap),
 298150            photo.DateCaptured.Value.PlusSeconds(gap),
 298151            ct);
 152
 297153        var similar = new List<MediaAsset>();
 1375154        foreach (var neighbour in neighbours.Where(n => !labelled.Contains(n) && !(n.BurstId is { } id && labelledBursts
 242155        {
 242156            var score = await matcher.ScoreAsync(Thumbnail(photo), Thumbnail(neighbour), ct);
 242157            Log.Compared(logger, photo.Id, neighbour.Id, score);
 242158            if (score >= options.Value.BurstSimilarityThreshold)
 25159            {
 25160                similar.Add(neighbour);
 25161                tally.Matched++;
 25162            }
 163            else
 217164            {
 217165                tally.NotMatched++;
 217166            }
 242167        }
 168
 297169        return similar;
 297170    }
 171
 172    private static string Thumbnail(MediaAsset asset)
 173        // Stryker disable once Linq
 484174        => asset.ProxyFiles.First(p => p.ProxyType == ProxyType.Thumbnail).ProxyPath;
 175
 176    private sealed class Tally
 177    {
 178        public int Checked { get; set; }
 179        public int Created { get; set; }
 180        public int Merged { get; set; }
 181        public int Dissolved { get; set; }
 182        public int Matched { get; set; }
 183        public int NotMatched { get; set; }
 184
 58185        public BurstDetectionResult ToResult() => new()
 58186        {
 58187            Checked = Checked,
 58188            Created = Created,
 58189            Merged = Merged,
 58190            Dissolved = Dissolved,
 58191            Matched = Matched,
 58192            NotMatched = NotMatched,
 58193        };
 194    }
 195
 196    private static partial class Log
 197    {
 198        [LoggerMessage(Level = LogLevel.Information, Message = "Burst detection for storage config {Id} checked {Checked
 199        public static partial void Finished(ILogger logger, Guid id, int @checked, int created, int merged, int dissolve
 200
 201        [LoggerMessage(Level = LogLevel.Debug, Message = "Burst detection compared photo {Photo} with {Neighbour}: score
 202        public static partial void Compared(ILogger logger, Guid photo, Guid neighbour, double score);
 203    }
 204}