Files
Heimdall/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs
T

87 lines
3.2 KiB
C#
Raw Normal View History

using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Infrastructure.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Storage;
/// <summary>
/// Resolves the active storage provider from the global settings
/// (<c>storage.provider</c> = Local | S3) with env fallback
/// (<c>STORAGE__PROVIDER</c>). Reads the DB each resolution so a change made
/// in the UI is picked up without restart (broadcast reload on top).
/// </summary>
public sealed class StorageProviderFactory : IStorageProvider
{
private readonly IServiceProvider _services;
private readonly ILogger<StorageProviderFactory> _logger;
public StorageProviderFactory(IServiceProvider services, ILogger<StorageProviderFactory> logger)
{
_services = services;
_logger = logger;
}
public string Provider => Resolve().Provider;
public bool IsConfigured => Resolve().IsConfigured;
public Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
=> Resolve().UploadAsync(key, content, contentType, ct);
public Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
=> Resolve().DownloadAsync(key, ct);
public Task DeleteAsync(string key, CancellationToken ct = default)
=> Resolve().DeleteAsync(key, ct);
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
=> Resolve().DeleteBatchAsync(keys, ct);
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
=> Resolve().HealthCheckAsync(ct);
private IStorageProvider Resolve()
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var provider = GetSetting(db, "storage.provider")
?? Environment.GetEnvironmentVariable("STORAGE__PROVIDER")
?? "Local";
if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
{
var s3 = new AlarikStorageProvider(
GetSetting(db, "storage.s3.endpoint"),
GetSetting(db, "storage.s3.bucket"),
GetSetting(db, "storage.s3.accessKey"),
GetSetting(db, "storage.s3.secretKey"),
GetSetting(db, "storage.s3.region"),
scope.ServiceProvider.GetRequiredService<ILogger<AlarikStorageProvider>>());
if (s3.IsConfigured)
return s3;
_logger.LogWarning("storage.provider=S3 mais S3 non configuré — fallback Local");
}
return new LocalStorageProvider(
GetSetting(db, "storage.local.path"),
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
}
private static string? GetSetting(IApplicationDbContext db, string key)
{
try
{
var setting = db.AppSettings
.AsNoTracking()
.FirstOrDefault(s => s.Key == key);
return setting?.Value;
}
catch
{
return null;
}
}
}