Heimdall Gitea / Build and tests (pull_request) Successful in 15m57s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 7m56s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 9m9s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
217 lines
7.8 KiB
C#
217 lines
7.8 KiB
C#
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, IDisposable
|
|
{
|
|
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;
|
|
await _client.DeleteObjectAsync(new DeleteObjectRequest
|
|
{
|
|
BucketName = _bucket,
|
|
Key = key,
|
|
}, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
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);
|
|
var response = await _client.DeleteObjectsAsync(request, ct).ConfigureAwait(false);
|
|
if (response.DeleteErrors is { Count: > 0 } errors)
|
|
throw new InvalidOperationException($"S3 rejected deletion of {errors.Count} object(s).");
|
|
}
|
|
}
|
|
|
|
public async Task<int> CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default)
|
|
{
|
|
if (_client is null)
|
|
throw new InvalidOperationException("Alarik/S3 storage is not configured");
|
|
|
|
var deleted = 0;
|
|
string? continuationToken = null;
|
|
do
|
|
{
|
|
var page = await _client.ListObjectsV2Async(new ListObjectsV2Request
|
|
{
|
|
BucketName = _bucket,
|
|
Prefix = "staging/",
|
|
ContinuationToken = continuationToken,
|
|
}, ct).ConfigureAwait(false);
|
|
var expired = page.S3Objects
|
|
.Where(obj => obj.LastModified is DateTime modified && modified.ToUniversalTime() < olderThanUtc)
|
|
.Select(obj => obj.Key)
|
|
.ToArray();
|
|
await DeleteBatchAsync(expired, ct).ConfigureAwait(false);
|
|
deleted += expired.Length;
|
|
continuationToken = page.IsTruncated == true ? page.NextContinuationToken : null;
|
|
} while (continuationToken is not null);
|
|
return deleted;
|
|
}
|
|
|
|
public async Task<StorageObjectPage> ListObjectsPageAsync(string prefix, string? cursor, int pageSize,
|
|
CancellationToken ct = default)
|
|
{
|
|
if (_client is null) throw new InvalidOperationException("Alarik/S3 storage is not configured");
|
|
if (pageSize is < 1 or > 1000) throw new ArgumentOutOfRangeException(nameof(pageSize));
|
|
var page = await _client.ListObjectsV2Async(new ListObjectsV2Request
|
|
{
|
|
BucketName = _bucket,
|
|
Prefix = prefix,
|
|
StartAfter = cursor,
|
|
MaxKeys = pageSize,
|
|
}, ct).ConfigureAwait(false);
|
|
var objects = page.S3Objects.Select(x => new StorageObjectInfo(x.Key,
|
|
x.LastModified is DateTime modified ? modified.ToUniversalTime() : DateTime.MaxValue))
|
|
.ToArray();
|
|
return new StorageObjectPage(objects,
|
|
page.IsTruncated == true ? objects.LastOrDefault()?.Key : null);
|
|
}
|
|
|
|
public async Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
|
{
|
|
if (_client is null)
|
|
return false;
|
|
try
|
|
{
|
|
await _client.ListObjectsV2Async(new ListObjectsV2Request
|
|
{
|
|
BucketName = _bucket,
|
|
MaxKeys = 1,
|
|
}, ct).ConfigureAwait(false);
|
|
return true;
|
|
}
|
|
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "S3 storage bucket health check failed");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public void Dispose() => _client?.Dispose();
|
|
}
|