|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | +using System.Threading.Tasks; |
| 4 | +using BaGet.Core.Entities; |
| 5 | +using BaGet.Tools.AzureSearchImporter.Entities; |
| 6 | +using Microsoft.EntityFrameworkCore; |
| 7 | +using Microsoft.Extensions.Logging; |
| 8 | +using MoreLinq; |
| 9 | + |
| 10 | +namespace BaGet.Tools.AzureSearchImporter |
| 11 | +{ |
| 12 | + public class Initializer |
| 13 | + { |
| 14 | + public const int InitializationBatchSize = 100; |
| 15 | + |
| 16 | + private readonly IContext _bagetContext; |
| 17 | + private readonly IndexerContext _indexerContext; |
| 18 | + private readonly ILogger<Initializer> _logger; |
| 19 | + |
| 20 | + public Initializer(IContext bagetContext, IndexerContext indexerContext, ILogger<Initializer> logger) |
| 21 | + { |
| 22 | + _bagetContext = bagetContext ?? throw new ArgumentNullException(nameof(bagetContext)); |
| 23 | + _indexerContext = indexerContext ?? throw new ArgumentNullException(nameof(indexerContext)); |
| 24 | + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); |
| 25 | + } |
| 26 | + |
| 27 | + public async Task InitializeAsync(bool force = false) |
| 28 | + { |
| 29 | + if (!force && await _indexerContext.PackageIds.AnyAsync()) |
| 30 | + { |
| 31 | + _logger.LogInformation("Skipping initialization"); |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + _logger.LogInformation("Finding packages to initialize..."); |
| 36 | + |
| 37 | + var packageIds = await _bagetContext.Packages |
| 38 | + .GroupBy(p => p.Id) |
| 39 | + .OrderByDescending(g => g.Sum(p => p.Downloads)) |
| 40 | + .Select(g => g.Key) |
| 41 | + .ToListAsync(); |
| 42 | + |
| 43 | + _logger.LogInformation("Found {PackageIdCount} package ids to initialize", packageIds.Count); |
| 44 | + |
| 45 | + var batchCount = 1; |
| 46 | + |
| 47 | + foreach (var batch in packageIds.Batch(InitializationBatchSize)) |
| 48 | + { |
| 49 | + foreach (var packageId in batch) |
| 50 | + { |
| 51 | + _indexerContext.PackageIds.Add(new PackageId |
| 52 | + { |
| 53 | + Value = packageId, |
| 54 | + Done = false, |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + _logger.LogInformation("Saving batch {BatchCount}", batchCount); |
| 59 | + |
| 60 | + await _indexerContext.SaveChangesAsync(); |
| 61 | + batchCount++; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments