3 Commits

Author SHA1 Message Date
398ca3d7b6 fix: updated namespaces
- code cleanup, removed unused usings
2025-05-19 10:32:59 -06:00
ffed92e85c feat: updated caching support
- feat: Added memory caching support
- feat: refactored dependency injection methods
2025-05-19 10:29:52 -06:00
Sergio Matias Urquin
f694b9a41a change copyright and rename azure identity provider 2025-05-17 23:14:35 -06:00
27 changed files with 142 additions and 53 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.Redis", "Core.Blueprint.Redis\Core.Blueprint.Redis.csproj", "{11F2AA11-FB98-4A33-AEE4-CD49588D2FE1}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Core.Blueprint.Caching", "Core.Blueprint.Redis\Core.Blueprint.Caching.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

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="ErrorDetailsDto.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="HttpErrorDto.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="HttpException.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="LogDetail.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="LogOperation.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="LogSeverity.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="LogTarget.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="ServiceSettings.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="Claims.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************
namespace Core.Blueprint.Logging

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="DisplayNames.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="EnvironmentVariables.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="ErrorCodes.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="MimeTypes.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="Responses.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="HttpErrorMiddleware.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="HttpLogger.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -1,6 +1,6 @@
// ***********************************************************************
// <copyright file="HttpLoggingMiddleware.cs">
// Heath
// AgileWebs
// </copyright>
// ***********************************************************************

View File

@@ -5,10 +5,10 @@ using MongoDB.Driver.Authentication.Oidc;
namespace Core.Blueprint.Mongo.Configuration
{
/// <summary>
/// The <see cref="HeathIdentityProvider"/> class is responsible for acquiring an OpenID Connect (OIDC)
/// The <see cref="AzureIdentityProvider"/> class is responsible for acquiring an OpenID Connect (OIDC)
/// access token for MongoDB authentication using Azure Identity and Managed Identity credentials.
/// </summary>
public class HeathIdentityProvider : IOidcCallback
public class AzureIdentityProvider : IOidcCallback
{
/// <summary>
/// The audience (resource identifier) for which the OIDC token is being requested.
@@ -21,10 +21,10 @@ namespace Core.Blueprint.Mongo.Configuration
private readonly string _environment;
/// <summary>
/// Initializes a new instance of the <see cref="HeathIdentityProvider"/> class with the specified audience.
/// Initializes a new instance of the <see cref="AzureIdentityProvider"/> class with the specified audience.
/// </summary>
/// <param name="audience">The audience (resource identifier) for which the OIDC token is being requested.</param>
public HeathIdentityProvider(string audience)
public AzureIdentityProvider(string audience)
{
_audience = audience;
_environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? string.Empty;

View File

@@ -46,7 +46,7 @@ namespace Core.Blueprint.DAL.Mongo.Configuration
{
var settings = serviceProvider.GetRequiredService<IOptions<MongoDbSettings>>().Value;
var mongoClientSettings = MongoClientSettings.FromConnectionString(settings.ConnectionString);
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new HeathIdentityProvider(settings.Audience));
mongoClientSettings.Credential = MongoCredential.CreateOidcCredential(new AzureIdentityProvider(settings.Audience));
return new MongoClient(mongoClientSettings);
});

View File

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Core.Blueprint.Redis
namespace Core.Blueprint.Caching.Adapters
{
public interface ICacheSettings
{

View File

@@ -1,8 +1,10 @@
using Microsoft.Extensions.Configuration;
using Core.Blueprint.Caching.Adapters;
using Core.Blueprint.Caching.Contracts;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Core.Blueprint.Redis.Configuration
namespace Core.Blueprint.Caching.Configuration
{
/// <summary>
/// Provides extension methods for registering Redis-related services in the DI container.
@@ -17,23 +19,32 @@ namespace Core.Blueprint.Redis.Configuration
/// <returns>The updated service collection.</returns>
public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
{
// Retrieve the Redis connection string from the configuration.
// Get Redis configuration section
var redisConnectionString = configuration.GetSection("ConnectionStrings:Redis").Value;
if (string.IsNullOrEmpty(redisConnectionString))
// 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)
{
throw new InvalidOperationException("Redis connection is not configured.");
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>();
}
// Register RedisCacheProvider
services.AddSingleton<IRedisCacheProvider>(provider =>
new RedisCacheProvider(redisConnectionString, provider.GetRequiredService<ILogger<RedisCacheProvider>>()));
// Get CacheSettings and register with the ICacheSettings interface
var cacheSettings = configuration.GetSection("CacheSettings").Get<CacheSettings>();
if (cacheSettings == null)
{
throw new InvalidOperationException("Redis CacheSettings section is not configured.");
throw new InvalidOperationException("CacheSettings section is not configured.");
}
services.AddSingleton<ICacheSettings>(cacheSettings);

View File

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

View File

@@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="Microsoft.Azure.StackExchangeRedis" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />

View File

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

View File

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