using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MongoDB.Driver; using StellaOps.Feedser.Core.Jobs; using StellaOps.Feedser.Storage.Mongo.Advisories; using StellaOps.Feedser.Storage.Mongo.ChangeHistory; using StellaOps.Feedser.Storage.Mongo.Documents; using StellaOps.Feedser.Storage.Mongo.Dtos; using StellaOps.Feedser.Storage.Mongo.Exporting; using StellaOps.Feedser.Storage.Mongo.JpFlags; using StellaOps.Feedser.Storage.Mongo.MergeEvents; using StellaOps.Feedser.Storage.Mongo.PsirtFlags; using StellaOps.Feedser.Storage.Mongo.Migrations; namespace StellaOps.Feedser.Storage.Mongo; public static class ServiceCollectionExtensions { public static IServiceCollection AddMongoStorage(this IServiceCollection services, Action configureOptions) { ArgumentNullException.ThrowIfNull(services); ArgumentNullException.ThrowIfNull(configureOptions); services.AddOptions() .Configure(configureOptions) .PostConfigure(static options => options.EnsureValid()); services.TryAddSingleton(TimeProvider.System); services.AddSingleton(static sp => { var options = sp.GetRequiredService>().Value; return new MongoClient(options.ConnectionString); }); services.AddSingleton(static sp => { var options = sp.GetRequiredService>().Value; var client = sp.GetRequiredService(); var settings = new MongoDatabaseSettings { ReadConcern = ReadConcern.Majority, WriteConcern = WriteConcern.WMajority, ReadPreference = ReadPreference.PrimaryPreferred, }; var database = client.GetDatabase(options.GetDatabaseName(), settings); var writeConcern = database.Settings.WriteConcern.With(wTimeout: options.CommandTimeout); return database.WithWriteConcern(writeConcern); }); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.TryAddSingleton(); services.AddSingleton>(static sp => { var database = sp.GetRequiredService(); return database.GetCollection(MongoStorageDefaults.Collections.Jobs); }); services.AddSingleton>(static sp => { var database = sp.GetRequiredService(); return database.GetCollection(MongoStorageDefaults.Collections.Locks); }); services.AddHostedService(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); return services; } }