Compare commits
18 Commits
feature/im
...
developmen
| Author | SHA1 | Date | |
|---|---|---|---|
| 2ede7baae6 | |||
| c42fb5eb00 | |||
| dbc21959eb | |||
| a97e4e2219 | |||
| 35965591f5 | |||
| 38b63455d4 | |||
| fbfa21f89a | |||
| e3cdf1fb32 | |||
| 351cc28181 | |||
| 4e6bf79656 | |||
| 73b909f780 | |||
| 7b326051bb | |||
| ff24c06934 | |||
| 31b26399a9 | |||
|
|
5935e87704 | ||
| 73f9d8550f | |||
|
|
852560d0e2 | ||
|
|
4103c4da8d |
@@ -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
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace Core.Blueprint.KeyVault
|
||||
/// <returns>
|
||||
/// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted.
|
||||
/// </returns>
|
||||
ValueTask<Tuple<string, bool>> DeleteSecretAsync(string secretName, CancellationToken cancellationToken);
|
||||
ValueTask<(string Message, bool Deleted)> DeleteSecretAsync(string secretName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves a secret from Azure Key Vault.
|
||||
@@ -33,7 +33,7 @@ namespace Core.Blueprint.KeyVault
|
||||
/// A <see cref="Tuple"/> containing the <see cref="KeyVaultResponse"/> with secret details
|
||||
/// and an optional error message if the secret was not found.
|
||||
/// </returns>
|
||||
ValueTask<Tuple<KeyVaultResponse, string?>> GetSecretAsync(string secretName, CancellationToken cancellationToken);
|
||||
ValueTask<(KeyVaultResponse Secret, string? Message)> GetSecretAsync(string secretName, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing secret in Azure Key Vault. If the secret does not exist, an error is returned.
|
||||
@@ -43,6 +43,6 @@ namespace Core.Blueprint.KeyVault
|
||||
/// <returns>
|
||||
/// A <see cref="Tuple"/> containing the updated <see cref="KeyVaultResponse"/> and an optional error message if the secret was not found.
|
||||
/// </returns>
|
||||
ValueTask<Tuple<KeyVaultResponse, string>> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken);
|
||||
ValueTask<(KeyVaultResponse Secret, string? Message)> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
using Azure.Security.KeyVault.Secrets;
|
||||
using VaultSharp;
|
||||
using VaultSharp.V1.AuthMethods.Token;
|
||||
using Core.Blueprint.KeyVault.Configuration;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System.Net.Http.Json;
|
||||
using VaultSharp;
|
||||
using VaultSharp.Core;
|
||||
using VaultSharp.V1.AuthMethods.Token;
|
||||
|
||||
namespace Core.Blueprint.KeyVault;
|
||||
|
||||
@@ -67,7 +67,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
|
||||
/// <returns>
|
||||
/// A <see cref="Tuple"/> containing a status message and a boolean indicating whether the secret was successfully deleted.
|
||||
/// </returns>
|
||||
public async ValueTask<Tuple<string, bool>> DeleteSecretAsync(string secretName, CancellationToken cancellationToken)
|
||||
public async ValueTask<(string Message, bool Deleted)> DeleteSecretAsync(string secretName, CancellationToken cancellationToken)
|
||||
{
|
||||
if (environment == "Local")
|
||||
{
|
||||
@@ -88,7 +88,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
|
||||
/// <summary>
|
||||
/// Retrieves a secret from Azure Key Vault or HashiCorp Vault.
|
||||
/// </summary>
|
||||
public async ValueTask<Tuple<KeyVaultResponse, string?>> GetSecretAsync(string secretName, CancellationToken cancellationToken)
|
||||
public async ValueTask<(KeyVaultResponse Secret, string? Message)> GetSecretAsync(string secretName, CancellationToken cancellationToken)
|
||||
{
|
||||
if (environment == "Local")
|
||||
{
|
||||
@@ -108,7 +108,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
|
||||
}
|
||||
catch (VaultSharp.Core.VaultApiException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
return new(new KeyVaultResponse(), "Key Not Found");
|
||||
return new(new KeyVaultResponse { }, "Key Not Found");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ public sealed class KeyVaultProvider : IKeyVaultProvider
|
||||
/// <summary>
|
||||
/// Updates an existing secret in Azure Key Vault or HashiCorp Vault. If the secret does not exist, an error is returned.
|
||||
/// </summary>
|
||||
public async ValueTask<Tuple<KeyVaultResponse, string>> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken)
|
||||
public async ValueTask<(KeyVaultResponse Secret, string? Message)> UpdateSecretAsync(KeyVaultRequest newSecret, CancellationToken cancellationToken)
|
||||
{
|
||||
var existingSecret = await this.GetSecretAsync(newSecret.Name, cancellationToken);
|
||||
if (!string.IsNullOrEmpty(existingSecret.Item2))
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
options.Audience = Audience;
|
||||
}
|
||||
});
|
||||
services.AddSingleton((Func<IServiceProvider, IMongoClient>)delegate (IServiceProvider serviceProvider)
|
||||
{
|
||||
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
|
||||
var mongoClientSettings = MongoClientSettings.FromConnectionString(settings.ConnectionString);
|
||||
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new AzureIdentityProvider(settings.Audience));
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,11 +104,13 @@ namespace Core.Blueprint.Mongo
|
||||
void ReplaceOne(TDocument document);
|
||||
|
||||
/// <summary>
|
||||
/// Asynchronously replaces an existing document with a new one.
|
||||
/// Asynchronously replaces an existing document in the collection and returns the updated version.
|
||||
/// </summary>
|
||||
/// <param name="document">The document to replace the existing one.</param>
|
||||
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
|
||||
Task ReplaceOneAsync(TDocument document);
|
||||
/// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
|
||||
/// <returns>
|
||||
/// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
|
||||
/// </returns>
|
||||
Task<TDocument?> ReplaceOneAsync(TDocument document);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a single document by the provided filter expression.
|
||||
|
||||
@@ -175,16 +175,27 @@ namespace Core.Blueprint.Mongo
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asynchronously replaces an existing document in the collection.
|
||||
/// Asynchronously replaces an existing document in the collection and returns the updated version.
|
||||
/// </summary>
|
||||
/// <param name="document">The document with the updated data.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public virtual async Task ReplaceOneAsync(TDocument document)
|
||||
/// <param name="document">The document with the updated data. Its _Id is used to locate the existing document.</param>
|
||||
/// <returns>
|
||||
/// The updated document if the replacement was successful; otherwise, <c>null</c> if no matching document was found.
|
||||
/// </returns>
|
||||
public virtual async Task<TDocument?> ReplaceOneAsync(TDocument document)
|
||||
{
|
||||
var filter = Builders<TDocument>.Filter.Eq(doc => doc._Id, document._Id);
|
||||
await _collection.FindOneAndReplaceAsync(filter, document);
|
||||
|
||||
var options = new FindOneAndReplaceOptions<TDocument>
|
||||
{
|
||||
ReturnDocument = ReturnDocument.After // return the updated document
|
||||
};
|
||||
|
||||
var result = await _collection.FindOneAndReplaceAsync(filter, document, options);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a single document from the collection based on the provided filter expression.
|
||||
/// </summary>
|
||||
|
||||
12
Core.Blueprint.Mongo/nuget.config
Normal file
12
Core.Blueprint.Mongo/nuget.config
Normal 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>
|
||||
@@ -1,4 +1,4 @@
|
||||
namespace Core.Blueprint.Caching.Adapters
|
||||
namespace Core.Blueprint.Redis
|
||||
{
|
||||
public interface ICacheSettings
|
||||
{
|
||||
|
||||
@@ -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))
|
||||
{
|
||||
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
|
||||
if (string.IsNullOrEmpty(redisConnectionString))
|
||||
{
|
||||
throw new InvalidOperationException("Redis connection is not configured.");
|
||||
}
|
||||
|
||||
services.AddSingleton<ICacheProvider>(provider =>
|
||||
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddMemoryCache();
|
||||
services.AddSingleton<ICacheProvider, MemoryCacheProvider>();
|
||||
throw new InvalidOperationException("Redis connection is not configured.");
|
||||
}
|
||||
|
||||
// Register RedisCacheProvider
|
||||
services.AddSingleton<IRedisCacheProvider>(provider =>
|
||||
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>(), configuration));
|
||||
|
||||
// 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);
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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" />
|
||||
@@ -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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
using Azure.Identity;
|
||||
using Core.Blueprint.Caching.Contracts;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
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;
|
||||
private readonly bool _useRedis;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RedisCacheProvider"/> class.
|
||||
@@ -20,34 +21,52 @@ namespace Core.Blueprint.Caching
|
||||
/// <param name="connectionString">The Redis connection string.</param>
|
||||
/// <param name="logger">The logger instance for logging operations.</param>
|
||||
/// <exception cref="ArgumentNullException">Thrown when connection string is null or empty.</exception>
|
||||
public RedisCacheProvider(string connectionString, ILogger<RedisCacheProvider> logger)
|
||||
public RedisCacheProvider(string connectionString, ILogger<RedisCacheProvider> logger, IConfiguration configuration)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(connectionString))
|
||||
throw new ArgumentNullException(nameof(connectionString), "Redis connection string cannot be null or empty.");
|
||||
|
||||
_logger = logger;
|
||||
_useRedis = configuration.GetValue<bool>("UseRedisCache", false);
|
||||
_cacheDatabase = InitializeRedisAsync(connectionString).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes and establishes a connection to Redis using the provided connection string.
|
||||
/// Initializes and establishes a connection to Redis based on the environment.
|
||||
/// Uses a local connection in development, and Azure with token credentials in other environments.
|
||||
/// </summary>
|
||||
/// <param name="connectionString">The Redis connection string.</param>
|
||||
/// <returns>An <see cref="IDatabase"/> instance representing the Redis cache database.</returns>
|
||||
/// <exception cref="Exception">Thrown when the connection to Redis fails.</exce
|
||||
async Task<IDatabase> InitializeRedisAsync(string connectionString)
|
||||
/// <exception cref="Exception">Thrown when the connection to Redis fails.</exception>
|
||||
async Task<IDatabase?> InitializeRedisAsync(string connectionString)
|
||||
{
|
||||
try
|
||||
{
|
||||
var configurationOptions = await ConfigurationOptions.Parse($"{connectionString}")
|
||||
.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
|
||||
if (_useRedis)
|
||||
{
|
||||
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
|
||||
ConnectionMultiplexer connectionMultiplexer;
|
||||
|
||||
configurationOptions.AbortOnConnectFail = false;
|
||||
var connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
|
||||
if (environment.Equals("Local", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(connectionString);
|
||||
}
|
||||
else
|
||||
{
|
||||
var configurationOptions = await ConfigurationOptions.Parse(connectionString)
|
||||
.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
|
||||
|
||||
_logger.LogInformation("Successfully connected to Redis.");
|
||||
configurationOptions.AbortOnConnectFail = false;
|
||||
|
||||
return connectionMultiplexer.GetDatabase();
|
||||
connectionMultiplexer = await ConnectionMultiplexer.ConnectAsync(configurationOptions);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Successfully connected to Redis.");
|
||||
|
||||
return connectionMultiplexer.GetDatabase();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -66,15 +85,21 @@ namespace Core.Blueprint.Caching
|
||||
{
|
||||
try
|
||||
{
|
||||
var value = await _cacheDatabase.StringGetAsync(key);
|
||||
if (value.IsNullOrEmpty)
|
||||
if (_useRedis is not false)
|
||||
{
|
||||
_logger.LogInformation($"Cache miss for key: {key}");
|
||||
return default;
|
||||
var value = await _cacheDatabase.StringGetAsync(key);
|
||||
|
||||
if (value.IsNullOrEmpty)
|
||||
{
|
||||
_logger.LogInformation($"Cache miss for key: {key}");
|
||||
return default;
|
||||
}
|
||||
|
||||
_logger.LogInformation($"Cache hit for key: {key}");
|
||||
return JsonSerializer.Deserialize<TEntity>(value);
|
||||
}
|
||||
|
||||
_logger.LogInformation($"Cache hit for key: {key}");
|
||||
return JsonSerializer.Deserialize<TEntity>(value);
|
||||
return default;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -93,9 +118,12 @@ namespace Core.Blueprint.Caching
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonSerializer.Serialize(value);
|
||||
await _cacheDatabase.StringSetAsync(key, json, expiry);
|
||||
_logger.LogInformation($"Cache item set with key: {key}");
|
||||
if (_useRedis is not false)
|
||||
{
|
||||
var json = JsonSerializer.Serialize(value);
|
||||
await _cacheDatabase.StringSetAsync(key, json, expiry);
|
||||
_logger.LogInformation($"Cache item set with key: {key}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -112,8 +140,11 @@ namespace Core.Blueprint.Caching
|
||||
{
|
||||
try
|
||||
{
|
||||
await _cacheDatabase.KeyDeleteAsync(key);
|
||||
_logger.LogInformation($"Cache item removed with key: {key}");
|
||||
if (_useRedis is not false)
|
||||
{
|
||||
await _cacheDatabase.KeyDeleteAsync(key);
|
||||
_logger.LogInformation($"Cache item removed with key: {key}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -131,9 +162,13 @@ namespace Core.Blueprint.Caching
|
||||
{
|
||||
try
|
||||
{
|
||||
var exists = await _cacheDatabase.KeyExistsAsync(key);
|
||||
_logger.LogInformation($"Cache item exists check for key: {key} - {exists}");
|
||||
return exists;
|
||||
if (_useRedis is not false)
|
||||
{
|
||||
var exists = await _cacheDatabase.KeyExistsAsync(key);
|
||||
_logger.LogInformation($"Cache item exists check for key: {key} - {exists}");
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -151,15 +186,18 @@ namespace Core.Blueprint.Caching
|
||||
{
|
||||
try
|
||||
{
|
||||
var value = await _cacheDatabase.StringGetAsync(key);
|
||||
if (!value.IsNullOrEmpty)
|
||||
if (_useRedis is not false)
|
||||
{
|
||||
await _cacheDatabase.StringSetAsync(key, value, expiry);
|
||||
_logger.LogInformation($"Cache item refreshed with key: {key}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh");
|
||||
var value = await _cacheDatabase.StringGetAsync(key);
|
||||
if (!value.IsNullOrEmpty)
|
||||
{
|
||||
await _cacheDatabase.StringSetAsync(key, value, expiry);
|
||||
_logger.LogInformation($"Cache item refreshed with key: {key}");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogWarning($"Cache item with key: {key} does not exist, cannot refresh");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
@@ -18,7 +18,9 @@ namespace Core.Blueprint.SQLServer.Configuration
|
||||
/// <returns>An updated <see cref="IServiceCollection"/> with SQL Server services registered.</returns>
|
||||
public static IServiceCollection AddSQLServer(this IServiceCollection services, IConfiguration configuration)
|
||||
{
|
||||
var chainedCredentials = new ChainedTokenCredential(
|
||||
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;
|
||||
|
||||
var chainedCredentials = new ChainedTokenCredential(
|
||||
new ManagedIdentityCredential(),
|
||||
new SharedTokenCacheCredential(),
|
||||
new VisualStudioCredential(),
|
||||
|
||||
9
nuget.config
Normal file
9
nuget.config
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<packageSources>
|
||||
<!-- Tu BaGet primero -->
|
||||
<add key="BaGet" value="https://nuget.dream-views.com/v3/index.json" protocolVersion="3" />
|
||||
<!-- NuGet oficial como fallback (si quieres) -->
|
||||
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
|
||||
</packageSources>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user