12 Commits

15 changed files with 168 additions and 162 deletions

View File

@@ -7,7 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Core.Blueprint.KeyVault", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Mongo", "Core.Blueprint.Mongo\Core.Blueprint.Mongo.csproj", "{27A8E3E1-D613-4D5B-8105-485699409F1E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Caching", "Core.Blueprint.Redis\Core.Blueprint.Caching.csproj", "{11F2AA11-FB98-4A33-AEE4-CD49588D2FE1}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Redis", "Core.Blueprint.Redis\Core.Blueprint.Redis.csproj", "{11F2AA11-FB98-4A33-AEE4-CD49588D2FE1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Storage", "Core.Blueprint.Storage\Core.Blueprint.Storage.csproj", "{636E4520-79F9-46C8-990D-08F2D24A151C}"
EndProject

View File

@@ -13,6 +13,8 @@ namespace Core.Blueprint.Logging
/// </summary>
public static class MimeTypes
{
public const string ApplicationVersion = "1.0";
/// <summary>
/// The service application/json mime type.
/// </summary>

View File

@@ -4,6 +4,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using static MongoDB.Driver.WriteConcern;
namespace Core.Blueprint.DAL.Mongo.Configuration
{
@@ -25,40 +26,48 @@ namespace Core.Blueprint.DAL.Mongo.Configuration
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
services.AddSingleton<IMongoContext, MongoContext>();
string ConnectionString = configuration.GetSection("ConnectionStrings:MongoDB").Value ?? string.Empty;
string Databasename = configuration.GetSection("MongoDb:DatabaseName").Value ?? string.Empty;
string Audience = string.Empty;
var ConnectionString = configuration.GetSection("ConnectionStrings:MongoDB").Value ?? string.Empty;
var Databasename = configuration.GetSection("MongoDb:DatabaseName").Value ?? string.Empty;
var Audience = (environment == "Local")
? configuration.GetSection("MongoDb:LocalAudience").Value
: configuration.GetSection("MongoDb:Audience").Value;
if (!environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
{
Audience = configuration.GetSection("MongoDb:Audience").Value ?? string.Empty;
}
if (string.IsNullOrEmpty(ConnectionString) || string.IsNullOrEmpty(Databasename) || string.IsNullOrEmpty(Audience))
if (string.IsNullOrEmpty(ConnectionString) || string.IsNullOrEmpty(Databasename))
{
throw new InvalidOperationException("Mongo connection is not configured correctly.");
}
services.Configure<MongoDbSettings>(options =>
services.Configure(delegate (MongoDbSettings options)
{
options.ConnectionString = ConnectionString;
options.Databasename = Databasename;
options.Audience = Audience;
});
services.AddSingleton<IMongoClient>(serviceProvider =>
if (!environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
{
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
var mongoClientSettings = MongoClientSettings.FromConnectionString(settings.ConnectionString);
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new AzureIdentityProvider(settings.Audience));
options.Audience = Audience;
}
});
services.AddSingleton((Func<IServiceProvider, IMongoClient>)delegate (IServiceProvider serviceProvider)
{
MongoDbSettings value2 = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
MongoClientSettings mongoClientSettings = MongoClientSettings.FromConnectionString(value2.ConnectionString);
if (!environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
{
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new AzureIdentityProvider(value2.Audience));
}
return new MongoClient(mongoClientSettings);
});
services.AddSingleton<IMongoDatabase>(serviceProvider =>
services.AddSingleton(delegate (IServiceProvider serviceProvider)
{
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
var client = serviceProvider.GetRequiredService<IMongoClient>();
return client.GetDatabase(settings.Databasename);
MongoDbSettings value = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
return serviceProvider.GetRequiredService<IMongoClient>().GetDatabase(value.Databasename);
});
services.AddSingleton<IMongoDbSettings>(serviceProvider => serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value);
services.AddSingleton((Func<IServiceProvider, IMongoDbSettings>)((IServiceProvider serviceProvider) => serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value));
return services;
}
}

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="Gitea" value="https://gitea.white-enciso.pro/api/packages/AgileWebs/nuget" />
</packageSources>
<packageSourceCredentials>
<Gitea>
<Username>oscarmmtz</Username>
<ClearTextPassword>544831e1ceaf52958e02c5de4d23cbde9e7a860a</ClearTextPassword>
</Gitea>
</packageSourceCredentials>
</configuration>

View File

@@ -1,4 +1,4 @@
namespace Core.Blueprint.Caching.Adapters
namespace Core.Blueprint.Redis
{
public interface ICacheSettings
{

View File

@@ -1,10 +1,8 @@
using Core.Blueprint.Caching.Adapters;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Core.Blueprint.Caching.Configuration
namespace Core.Blueprint.Redis.Configuration
{
/// <summary>
/// Provides extension methods for registering Redis-related services in the DI container.
@@ -19,32 +17,23 @@ namespace Core.Blueprint.Caching.Configuration
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{
// TODO for the following variable we'll need to add in the appsettings.json the following config: "UseRedisCache": true,
bool useRedis = configuration.GetValue<bool>("UseRedisCache");
//TODO decide wheter to use appsettings or the following ENV variable
useRedis = Environment.GetEnvironmentVariable("CORE_BLUEPRINT_PACKAGES_USE_REDIS")?.ToLower() == "true";
if (useRedis)
{
// Retrieve the Redis connection string from the configuration.
// Get Redis configuration section
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString))
{
throw new InvalidOperationException("Redis connection is not configured.");
}
services.AddSingleton<ICacheProvider>(provider =>
// Register RedisCacheProvider
services.AddSingleton<IRedisCacheProvider>(provider =>
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddMemoryCache();
services.AddSingleton<ICacheProvider, MemoryCacheProvider>();
}
// Get CacheSettings and register with the ICacheSettings interface
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null)
{
throw new InvalidOperationException("CacheSettings section is not configured.");
throw new InvalidOperationException("Redis CacheSettings section is not configured.");
}
services.AddSingleton<ICacheSettings>(cacheSettings);

View File

@@ -1,9 +1,9 @@
namespace Core.Blueprint.Caching.Contracts
namespace Core.Blueprint.Redis
{
/// <summary>
/// Interface for managing Redis cache operations.
/// </summary>
public interface ICacheProvider
public interface IRedisCacheProvider
{
/// <summary>
/// Retrieves a cache item by its key.

View File

@@ -4,11 +4,11 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PackageId>Core.Blueprint.Redis</PackageId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.StackExchangeRedis" Version="3.2.1" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="9.0.5" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.5" />

View File

@@ -1,7 +1,11 @@
using System.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Core.Blueprint.Caching.Helpers
namespace Core.Blueprint.Redis.Helpers
{
/// <summary>
/// Helper class for generating consistent and normalized cache keys.

View File

@@ -1,86 +0,0 @@
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Caching.Memory;
using System.Text.Json;
namespace Core.Blueprint.Caching
{
public sealed class MemoryCacheProvider : ICacheProvider
{
private readonly IMemoryCache _cache;
private readonly ILogger<MemoryCacheProvider> _logger;
public MemoryCacheProvider(IMemoryCache cache, ILogger<MemoryCacheProvider> logger)
{
_cache = cache;
_logger = logger;
}
public ValueTask<TEntity> GetAsync<TEntity>(string key)
{
if (_cache.TryGetValue(key, out var value))
{
if (value is TEntity typedValue)
{
return ValueTask.FromResult(typedValue);
}
try
{
var json = value?.ToString();
var deserialized = JsonSerializer.Deserialize<TEntity>(json);
return ValueTask.FromResult(deserialized);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Error deserializing cache value for key {Key}", key);
}
}
return ValueTask.FromResult(default(TEntity));
}
public ValueTask SetAsync<TEntity>(string key, TEntity value, TimeSpan? expiry = null)
{
var options = new MemoryCacheEntryOptions();
if (expiry.HasValue)
{
options.SetAbsoluteExpiration(expiry.Value);
}
_cache.Set(key, value, options);
return ValueTask.CompletedTask;
}
public ValueTask RemoveAsync(string key)
{
_cache.Remove(key);
return ValueTask.CompletedTask;
}
public ValueTask<bool> ExistsAsync(string key)
{
return ValueTask.FromResult(_cache.TryGetValue(key, out _));
}
public ValueTask RefreshAsync(string key, TimeSpan? expiry = null)
{
// MemoryCache does not support sliding expiration refresh like Redis,
// so we must re-set the value manually if required.
if (_cache.TryGetValue(key, out var value))
{
_cache.Remove(key);
var options = new MemoryCacheEntryOptions();
if (expiry.HasValue)
{
options.SetAbsoluteExpiration(expiry.Value);
}
_cache.Set(key, value, options);
}
return ValueTask.CompletedTask;
}
}
}

View File

@@ -1,15 +1,14 @@
using Azure.Identity;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System.Text.Json;
namespace Core.Blueprint.Caching
namespace Core.Blueprint.Redis
{
/// <summary>
/// Redis cache provider for managing cache operations.
/// </summary>
public sealed class RedisCacheProvider : ICacheProvider
public sealed class RedisCacheProvider : IRedisCacheProvider
{
private IDatabase _cacheDatabase = null!;
private readonly ILogger<RedisCacheProvider> _logger;

View File

@@ -17,6 +17,10 @@ namespace Core.Blueprint.SQLServer.Configuration
/// <param name="configuration">The application configuration object for accessing settings such as connection strings.</param>
/// <returns>An updated <see cref="IServiceCollection"/> with SQL Server services registered.</returns>
public static IServiceCollection AddSQLServer(this IServiceCollection services, IConfiguration configuration)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
if (environment != "Local")
{
var chainedCredentials = new ChainedTokenCredential(
new ManagedIdentityCredential(),
@@ -24,6 +28,7 @@ namespace Core.Blueprint.SQLServer.Configuration
new VisualStudioCredential(),
new VisualStudioCodeCredential()
);
}
services.AddScoped(typeof(IEntityRepository<,>), typeof(EntityRepository<,>));

View File

@@ -11,23 +11,37 @@ namespace Core.Blueprint.Storage.Configuration
{
public static IServiceCollection AddBlobStorage(this IServiceCollection services, IConfiguration configuration)
{
var blobConnection = configuration.GetConnectionString("BlobStorage");
if (blobConnection == null || string.IsNullOrWhiteSpace(blobConnection))
{
if (string.IsNullOrWhiteSpace(blobConnection))
throw new ArgumentException("The BlobStorage configuration section is missing or empty.");
}
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
services.AddAzureClients(cfg =>
{
if (environment == "Local")
{
var accountKey = configuration.GetSection("BlobStorage:AccountKey").Value;
var accountName = configuration.GetSection("BlobStorage:AccountName").Value;
if(string.IsNullOrEmpty(accountKey) && string.IsNullOrEmpty(accountName))
throw new ArgumentException("The BlobStorage configuration section is missing or empty.");
cfg.AddBlobServiceClient(configuration.GetConnectionString("BlobStorage"));
}
else
{
var chainedCredentials = new ChainedTokenCredential(
new ManagedIdentityCredential(),
new SharedTokenCacheCredential(),
new VisualStudioCredential(),
new VisualStudioCodeCredential()
);
services.AddAzureClients(cfg =>
{
cfg.AddBlobServiceClient(new Uri(blobConnection)).WithCredential(chainedCredentials);
cfg.AddBlobServiceClient(new Uri(blobConnection))
.WithCredential(chainedCredentials);
}
});
services.AddScoped<IBlobStorageProvider, BlobStorageProvider>();

View File

@@ -162,7 +162,7 @@ namespace Core.Blueprint.Storage.Contracts
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName);
ValueTask<BlobDownloadUriAdapter?> GenerateBlobDownloadUri(string blobName);
/// <summary>
/// Retrieves the hierarchical folder structure.

View File

@@ -1,4 +1,5 @@
using Azure;
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
@@ -6,6 +7,7 @@ using Azure.Storage.Sas;
using Core.Blueprint.Storage.Adapters;
using Core.Blueprint.Storage.Contracts;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
namespace Core.Blueprint.Storage.Provider
{
@@ -15,10 +17,12 @@ namespace Core.Blueprint.Storage.Provider
private readonly BlobContainerClient _blobContainerClient;
private readonly string _containerName;
private readonly Trie _trie = new Trie();
private readonly IConfiguration _configuration;
public BlobStorageProvider(BlobServiceClient blobServiceClient, IConfiguration configuration)
{
_blobServiceClient = blobServiceClient;
_configuration = configuration;
_containerName = configuration.GetSection("BlobStorage:ContainerName").Value ?? "";
if (string.IsNullOrEmpty(_containerName))
@@ -278,7 +282,8 @@ namespace Core.Blueprint.Storage.Provider
/// </summary>
/// <param name="blobName">The name of the blob for which the download URI is being generated.</param>
/// <returns>
/// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status.
/// An instance of <see cref="BlobDownloadUriAdapter"/> containing the generated URI, blob name, and status,
/// or <c>null</c> if the blob does not exist.
/// </returns>
/// <remarks>
/// The generated URI includes a Shared Access Signature (SAS) token, which allows secure, time-limited access to the blob.
@@ -286,22 +291,36 @@ namespace Core.Blueprint.Storage.Provider
/// </remarks>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="blobName"/> is null or empty.</exception>
/// <exception cref="StorageException">Thrown if there is an issue communicating with the Azure Blob service.</exception>
public BlobDownloadUriAdapter GenerateBlobDownloadUri(string blobName)
public async ValueTask<BlobDownloadUriAdapter?> GenerateBlobDownloadUri(string blobName)
{
var delegationKey = _blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddHours(2));
if (string.IsNullOrWhiteSpace(blobName))
throw new ArgumentNullException(nameof(blobName), "Blob name cannot be null or empty.");
var blob = _blobContainerClient.GetBlobClient(blobName);
var sasBuilder = new BlobSasBuilder()
if (!await blob.ExistsAsync())
return null;
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
if (environment == "Local")
{
return GenerateDownloadUri(blob);
}
var delegationKey = await _blobServiceClient.GetUserDelegationKeyAsync(
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddHours(2));
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5),
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5)
};
sasBuilder.SetPermissions(BlobAccountSasPermissions.Read);
sasBuilder.SetPermissions(BlobSasPermissions.Read);
sasBuilder.Protocol = SasProtocol.Https;
var blobUriBuilder = new BlobUriBuilder(blob.Uri)
@@ -317,6 +336,45 @@ namespace Core.Blueprint.Storage.Provider
};
}
/// <summary>
/// Generates a download URI for a blob using a Shared Access Signature in local (Azurite) environment.
/// </summary>
/// <param name="blob">The blob client for which the URI is being generated.</param>
/// <returns>An instance of <see cref="BlobDownloadUriAdapter"/> containing the SAS URI and metadata.</returns>
private BlobDownloadUriAdapter GenerateDownloadUri(BlobClient blob)
{
var sasBuilder = new BlobSasBuilder
{
BlobContainerName = blob.BlobContainerName,
BlobName = blob.Name,
Resource = "b",
StartsOn = DateTimeOffset.UtcNow,
ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5)
};
sasBuilder.SetPermissions(BlobSasPermissions.Read);
sasBuilder.Protocol = SasProtocol.HttpsAndHttp;
var accountName = _configuration["BlobStorage:AccountName"];
var accountKey = _configuration["BlobStorage:AccountKey"];
var storageCredentials = new StorageSharedKeyCredential(accountName, accountKey);
var sasToken = sasBuilder.ToSasQueryParameters(storageCredentials);
var blobUriBuilder = new BlobUriBuilder(blob.Uri)
{
Sas = sasToken
};
return new BlobDownloadUriAdapter
{
Uri = blobUriBuilder.ToUri(),
Name = blob.Name,
Status = "Available"
};
}
/// <summary>
/// Retrieves the hierarchical folder structure.
/// </summary>