using Azure; using Azure.Core; using Azure.Identity; using Azure.ResourceManager; using Azure.ResourceManager.CosmosDB; using Azure.ResourceManager.CosmosDB.Models; using Azure.ResourceManager.Resources; using MongoDB.Driver; namespace LCU.API.Internal.Document.PerformanceTest.DB; public class AzureCosmosDb : IDatabase { private readonly string _performanceTestingResourceName = "Perf_MongoDb"; public async Task SpinUp() { Console.WriteLine("Currently in Azure Spin Up."); //todo test this - cd: I'm not connected to the landmark subscription in the portal, only AD var azureClient = new ArmClient(new DefaultAzureCredential()); var subscription = await azureClient.GetDefaultSubscriptionAsync(); var resourceGroup = ( await subscription .GetResourceGroups() .CreateOrUpdateAsync ( WaitUntil.Completed, _performanceTestingResourceName, new ResourceGroupData(AzureLocation.CentralUS) ) ) .Value; var cosmosAccount = ( await resourceGroup .GetCosmosDBAccounts() .CreateOrUpdateAsync ( WaitUntil.Completed, _performanceTestingResourceName.ToLower().Replace("_",""), new CosmosDBAccountCreateOrUpdateContent ( AzureLocation.CentralUS, new CosmosDBAccountLocation[] { new CosmosDBAccountLocation { LocationName = AzureLocation.CentralUS, FailoverPriority = 0, IsZoneRedundant = false }, new CosmosDBAccountLocation { LocationName = AzureLocation.EastUS2, FailoverPriority = 1, IsZoneRedundant = false } } ) { Kind = "MongoDB"} ) ) .Value; var mongoDb = cosmosAccount.GetMongoDBDatabases(); await mongoDb .CreateOrUpdateAsync ( WaitUntil.Completed, _performanceTestingResourceName, new MongoDBDatabaseCreateOrUpdateContent ( AzureLocation.CentralUS, new MongoDBDatabaseResourceInfo(_performanceTestingResourceName) ) ); //todo test to ensure that there's only one connection string or that it can be determined which is the one we need for mongo var allConnections = cosmosAccount .GetConnectionStrings() .AsPages() .ToArray() .SelectMany(p => p.Values) .ToArray(); if (allConnections.Length == 0) throw new Exception("No Connection Strings Found."); _connectionString = cosmosAccount.GetConnectionStrings().AsPages().ToArray()[0].Values[0].ConnectionString; return new MongoClient(ConnectionString); } public async Task TearDown() { var azureClient = new ArmClient(new DefaultAzureCredential()); var subscription = await azureClient.GetDefaultSubscriptionAsync(); var resourceGroup = (await subscription.GetResourceGroupAsync(_performanceTestingResourceName)).Value; await resourceGroup.DeleteAsync(WaitUntil.Completed); } public string ConnectionString => _connectionString ?? throw new InvalidOperationException("spin up the database first"); private string? _connectionString; }