|
| 1 | +// --------------------------------------------------------------------------------------------------------------------- |
| 2 | +// Imports |
| 3 | +// --------------------------------------------------------------------------------------------------------------------- |
| 4 | +using Microsoft.Extensions.DependencyInjection; |
| 5 | +using Microsoft.Extensions.Logging; |
| 6 | +using System.Collections.Concurrent; |
| 7 | +using System.Reflection; |
| 8 | + |
| 9 | +namespace CodeOfChaos.Types; |
| 10 | +// --------------------------------------------------------------------------------------------------------------------- |
| 11 | +// Code |
| 12 | +// --------------------------------------------------------------------------------------------------------------------- |
| 13 | +public abstract class OneTimeDataSeederService(IServiceProvider serviceProvider, ILogger<OneTimeDataSeederService> logger) : IDataSeederService { |
| 14 | + private readonly ConcurrentQueue<SeederGroup> _seeders = []; |
| 15 | + private readonly ConcurrentBag<Type> _seederTypes = []; |
| 16 | + private bool _collectedRemainders;// If set to true, the remainder seeders have been collected and thus should throw an exception if any are added |
| 17 | + |
| 18 | + // ----------------------------------------------------------------------------------------------------------------- |
| 19 | + // Methods |
| 20 | + // ----------------------------------------------------------------------------------------------------------------- |
| 21 | + public async Task StartAsync(CancellationToken ct = default) { |
| 22 | + logger.LogInformation("DataSeederService starting..."); |
| 23 | + |
| 24 | + // User has to collect the seeders |
| 25 | + await CollectAsync(ct); |
| 26 | + ct.ThrowIfCancellationRequested();// Don't throw during collection, but throw afterward |
| 27 | + |
| 28 | + // Validation has to succeed before we continue |
| 29 | + // Technically this library doesn't need to validate much, |
| 30 | + // but to make sure we've enabled overloading of the method |
| 31 | + if (!ValidateSeeders()) return; |
| 32 | + |
| 33 | + int i = 0; |
| 34 | + foreach (SeederGroup seederGroup in _seeders) { |
| 35 | + if (ct.IsCancellationRequested) { |
| 36 | + logger.LogWarning("Seeding process canceled during execution."); |
| 37 | + break; |
| 38 | + } |
| 39 | + |
| 40 | + if (seederGroup.IsEmpty) { |
| 41 | + logger.LogDebug("ExecutionStep {step} : Skipping empty seeder array", i++); |
| 42 | + continue; |
| 43 | + } |
| 44 | + |
| 45 | + logger.LogDebug("ExecutionStep {step} : {count} Seeder(s) found, executing...", i++, seederGroup.Count); |
| 46 | + await Task.WhenAll(seederGroup.Select(seeder => seeder.StartAsync(logger, ct))); |
| 47 | + } |
| 48 | + |
| 49 | + logger.LogInformation("All seeders completed in {i} steps", i); |
| 50 | + // Cleanup |
| 51 | + _seeders.Clear(); |
| 52 | + _seederTypes.Clear(); |
| 53 | + _collectedRemainders = false; |
| 54 | + } |
| 55 | + |
| 56 | + public Task StopAsync(CancellationToken ct = default) { |
| 57 | + logger.LogInformation("Stopping DataSeederService..."); |
| 58 | + return Task.CompletedTask; |
| 59 | + } |
| 60 | + |
| 61 | + protected virtual Task CollectAsync(CancellationToken ct = default) => Task.CompletedTask; |
| 62 | + |
| 63 | + // ----------------------------------------------------------------------------------------------------------------- |
| 64 | + // Seeder manipulation Methods |
| 65 | + // ----------------------------------------------------------------------------------------------------------------- |
| 66 | + public IDataSeederService AddSeeder<TSeeder>() where TSeeder : ISeeder |
| 67 | + => AddSeederGroup(group => group.AddSeeder<TSeeder>()); |
| 68 | + |
| 69 | + public IDataSeederService AddSeederGroup(params ISeeder[] seeders) |
| 70 | + => AddSeederGroup(new SeederGroup(seeders, serviceProvider)); |
| 71 | + |
| 72 | + public IDataSeederService AddSeederGroup(Action<SeederGroup> group) { |
| 73 | + var seeders = new SeederGroup(serviceProvider); |
| 74 | + group(seeders); |
| 75 | + return AddSeederGroup(seeders); |
| 76 | + } |
| 77 | + |
| 78 | + public IDataSeederService AddSeederGroup(SeederGroup group) { |
| 79 | + ThrowIfRemainderSeeders(); |
| 80 | + |
| 81 | + _seeders.Enqueue(group); |
| 82 | + foreach (ISeeder seeder in group) { |
| 83 | + _seederTypes.Add(seeder.GetType()); |
| 84 | + } |
| 85 | + |
| 86 | + return this; |
| 87 | + } |
| 88 | + |
| 89 | + public void AddRemainderSeeders(Assembly assembly) { |
| 90 | + Type[] types = CollectTypes(assembly); |
| 91 | + var errors = new List<Exception>(); |
| 92 | + |
| 93 | + foreach (Type type in types) { |
| 94 | + if (_seederTypes.Contains(type)) { |
| 95 | + logger.LogDebug("Skipping {t} as it was already assigned", type); |
| 96 | + continue; |
| 97 | + } |
| 98 | + |
| 99 | + try { |
| 100 | + AddSeederGroup(group => group.AddSeeder(type)); |
| 101 | + } |
| 102 | + catch (Exception ex) { |
| 103 | + logger.LogError(ex, "Failed to instantiate {t}. Skipping...", type); |
| 104 | + errors.Add(ex); |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + if (errors.Count != 0) throw new AggregateException(errors); |
| 109 | + |
| 110 | + _collectedRemainders = true; |
| 111 | + } |
| 112 | + |
| 113 | + public void AddRemainderSeedersAsOneGroup(Assembly assembly) { |
| 114 | + Type[] types = CollectTypes(assembly); |
| 115 | + var group = new SeederGroup(serviceProvider); |
| 116 | + var errors = new List<Exception>(); |
| 117 | + |
| 118 | + foreach (Type type in types) { |
| 119 | + if (_seederTypes.Contains(type)) { |
| 120 | + logger.LogDebug("Skipping {t} as it was already assigned", type); |
| 121 | + continue; |
| 122 | + } |
| 123 | + |
| 124 | + try { |
| 125 | + group.AddSeeder(type); |
| 126 | + _seederTypes.Add(type); |
| 127 | + } |
| 128 | + catch (Exception ex) { |
| 129 | + logger.LogError(ex, "Failed to instantiate {t}. Skipping...", type); |
| 130 | + errors.Add(ex); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + if (errors.Count != 0) throw new AggregateException(errors); |
| 135 | + |
| 136 | + // Collect as one Concurrent step |
| 137 | + AddSeederGroup(group); |
| 138 | + _collectedRemainders = true; |
| 139 | + } |
| 140 | + |
| 141 | + private static Type[] CollectTypes(Assembly assembly) |
| 142 | + => assembly.GetTypes() |
| 143 | + // order is deterministic |
| 144 | + .OrderBy(t => t.FullName) |
| 145 | + .Where(type => type.IsAssignableTo(typeof(ISeeder)) |
| 146 | + && type is { IsAbstract: false, IsInterface: false, IsGenericTypeDefinition: false }) |
| 147 | + .ToArray(); |
| 148 | + |
| 149 | + private void ThrowIfRemainderSeeders() { |
| 150 | + if (!_collectedRemainders) return; |
| 151 | + |
| 152 | + logger.LogError("Remainder seeders have already been collected"); |
| 153 | + throw new InvalidOperationException("Remainder seeders have already been collected"); |
| 154 | + } |
| 155 | + |
| 156 | + protected virtual bool ValidateSeeders() { |
| 157 | + if (!_seeders.IsEmpty) return true; |
| 158 | + |
| 159 | + logger.LogWarning("No seeders were added prior to execution."); |
| 160 | + return false; |
| 161 | + |
| 162 | + } |
| 163 | +} |
0 commit comments