feat(storage): stockage configurable par l'IHM — providers Fichier + S3 (Fixes #78)
- IStorageProvider (Application) : Upload/Download/Delete/DeleteBatch/Health - LocalStorageProvider : écriture atomique (tmp + move), anti path-traversal - AlarikStorageProvider : S3-compatible (AWS SDK, ForcePathStyle), upload staging→final (atomique), batch delete 1000/appel (Correctif D6) - StorageProviderFactory : provider résolu depuis les settings DB (storage.provider = Local|S3) avec fallback env, re-résolu à chaque appel - Seed idempotent des clés storage.* (catégorie 'storage') au démarrage - UI : section 'Stockage' dédiée dans SettingsPage (sélecteur Local/S3, champs conditionnels, clé secrète masquée, bouton Tester → POST /api/settings/storage/test) - Tests : 6 LocalStorageProvider (roundtrip, delete, batch, traversal, health) ; Web 217/217, Infrastructure 177/177, Application 391/391
This commit is contained in:
1 parent
2e188e4dda
commit
7d6213696f
11 files changed
+685
-1
No files matched your search
@@ -0,0 +1,166 @@
|
||||
using Amazon.S3;
|
||||
using Amazon.S3.Model;
|
||||
using Heimdall.Application.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Heimdall.Infrastructure.Storage;
|
||||
|
||||
/// <summary>
|
||||
/// S3-compatible storage provider (Alarik / MinIO / AWS). Configured via the
|
||||
/// global settings (<c>storage.s3.endpoint</c>, <c>storage.s3.bucket</c>,
|
||||
/// <c>storage.s3.accessKey</c>, <c>storage.s3.secretKey</c>, …) with env-var
|
||||
/// fallback (<c>ALARIK_ENDPOINT</c> / <c>S3_ENDPOINT</c>). Uploads use a
|
||||
/// staging prefix then a copy (atomic move semantics for the consumers).
|
||||
/// </summary>
|
||||
public sealed class AlarikStorageProvider : IStorageProvider
|
||||
{
|
||||
private readonly AmazonS3Client? _client;
|
||||
private readonly string _bucket = string.Empty;
|
||||
private readonly ILogger<AlarikStorageProvider> _logger;
|
||||
|
||||
public string Provider => "S3";
|
||||
public bool IsConfigured => _client is not null && !string.IsNullOrEmpty(_bucket);
|
||||
|
||||
public AlarikStorageProvider(
|
||||
string? endpoint,
|
||||
string? bucket,
|
||||
string? accessKey,
|
||||
string? secretKey,
|
||||
string? region,
|
||||
ILogger<AlarikStorageProvider> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
|
||||
endpoint = string.IsNullOrWhiteSpace(endpoint)
|
||||
? Environment.GetEnvironmentVariable("ALARIK_ENDPOINT")
|
||||
?? Environment.GetEnvironmentVariable("S3_ENDPOINT")
|
||||
: endpoint;
|
||||
bucket = string.IsNullOrWhiteSpace(bucket) ? "heimdall" : bucket;
|
||||
accessKey ??= Environment.GetEnvironmentVariable("S3_ACCESS_KEY");
|
||||
secretKey ??= Environment.GetEnvironmentVariable("S3_SECRET_KEY");
|
||||
region ??= Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1";
|
||||
|
||||
if (string.IsNullOrWhiteSpace(endpoint))
|
||||
{
|
||||
_logger.LogWarning("Alarik/S3 storage not configured (missing storage.s3.endpoint)");
|
||||
return;
|
||||
}
|
||||
|
||||
var config = new AmazonS3Config
|
||||
{
|
||||
ServiceURL = endpoint,
|
||||
ForcePathStyle = true, // Alarik/MinIO exigent le style path
|
||||
AuthenticationRegion = region,
|
||||
};
|
||||
|
||||
// Credentials vides → on tente anonyme (Alarik local par défaut).
|
||||
_client = string.IsNullOrEmpty(accessKey) && string.IsNullOrEmpty(secretKey)
|
||||
? new AmazonS3Client(config)
|
||||
: new AmazonS3Client(accessKey, secretKey, config);
|
||||
_bucket = bucket;
|
||||
}
|
||||
|
||||
private static string StagingKey(string key) => key.StartsWith("staging/", StringComparison.Ordinal)
|
||||
? key
|
||||
: $"staging/{key}";
|
||||
|
||||
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null)
|
||||
throw new InvalidOperationException("Alarik/S3 storage is not configured");
|
||||
|
||||
// 1) upload staging
|
||||
var staging = StagingKey(key);
|
||||
content.Position = 0;
|
||||
await _client.PutObjectAsync(new PutObjectRequest
|
||||
{
|
||||
BucketName = _bucket,
|
||||
Key = staging,
|
||||
InputStream = content,
|
||||
ContentType = contentType,
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
// 2) move atomique staging → final (copy + delete staging)
|
||||
await _client.CopyObjectAsync(new CopyObjectRequest
|
||||
{
|
||||
SourceBucket = _bucket,
|
||||
SourceKey = staging,
|
||||
DestinationBucket = _bucket,
|
||||
DestinationKey = key,
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
await _client.DeleteObjectAsync(new DeleteObjectRequest
|
||||
{
|
||||
BucketName = _bucket,
|
||||
Key = staging,
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null)
|
||||
return null;
|
||||
try
|
||||
{
|
||||
var response = await _client.GetObjectAsync(new GetObjectRequest
|
||||
{
|
||||
BucketName = _bucket,
|
||||
Key = key,
|
||||
}, ct).ConfigureAwait(false);
|
||||
return response.ResponseStream;
|
||||
}
|
||||
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DeleteAsync(string key, CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null)
|
||||
return;
|
||||
try
|
||||
{
|
||||
await _client.DeleteObjectAsync(new DeleteObjectRequest
|
||||
{
|
||||
BucketName = _bucket,
|
||||
Key = key,
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (AmazonS3Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "S3 delete failed for {Key}", key);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null || keys.Count == 0)
|
||||
return;
|
||||
|
||||
// 1000 objets max par appel (spécification Correctif D6).
|
||||
foreach (var chunk in keys.Chunk(1000))
|
||||
{
|
||||
var request = new DeleteObjectsRequest { BucketName = _bucket };
|
||||
foreach (var key in chunk)
|
||||
request.AddKey(key);
|
||||
await _client.DeleteObjectsAsync(request, ct).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_client is null)
|
||||
return false;
|
||||
try
|
||||
{
|
||||
await _client.ListBucketsAsync(ct).ConfigureAwait(false);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Alarik/S3 health check failed");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user