- 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
109 lines
3.6 KiB
C#
109 lines
3.6 KiB
C#
using Heimdall.Application.Common;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Heimdall.Infrastructure.Storage;
|
|
|
|
/// <summary>
|
|
/// Local filesystem storage provider. Files are written under the configured
|
|
/// root (default <c>storage.local.path</c> → env <c>STORAGE__LOCAL__PATH</c>,
|
|
/// fallback <c>./data/storage</c>). Uploads are atomic: write to a staging
|
|
/// temp file, then move to the final path.
|
|
/// </summary>
|
|
public sealed class LocalStorageProvider : IStorageProvider
|
|
{
|
|
private readonly string _root;
|
|
private readonly ILogger<LocalStorageProvider> _logger;
|
|
|
|
public string Provider => "Local";
|
|
public bool IsConfigured => !string.IsNullOrEmpty(_root);
|
|
|
|
public LocalStorageProvider(string? rootPath, ILogger<LocalStorageProvider> logger)
|
|
{
|
|
_root = Path.GetFullPath(string.IsNullOrWhiteSpace(rootPath)
|
|
? "./data/storage"
|
|
: rootPath);
|
|
_logger = logger;
|
|
}
|
|
|
|
private string ResolvePath(string key)
|
|
{
|
|
// Clé "snapshots/{site}/{camera}/{date}/{id}.jpg" → chemin sous la racine.
|
|
var safe = key.Replace('\\', '/').TrimStart('/');
|
|
var path = Path.GetFullPath(Path.Combine(_root, safe.Replace('/', Path.DirectorySeparatorChar)));
|
|
|
|
// Sécurité : ne jamais sortir de la racine via "..".
|
|
if (!path.StartsWith(_root, StringComparison.Ordinal))
|
|
throw new InvalidOperationException($"Storage key escapes root: {key}");
|
|
|
|
return path;
|
|
}
|
|
|
|
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
|
|
{
|
|
var finalPath = ResolvePath(key);
|
|
var dir = Path.GetDirectoryName(finalPath);
|
|
if (!string.IsNullOrEmpty(dir))
|
|
Directory.CreateDirectory(dir);
|
|
|
|
// Écriture atomique : fichier temporaire + move.
|
|
var staging = finalPath + $".tmp-{Guid.NewGuid():N}";
|
|
try
|
|
{
|
|
await using (var fs = new FileStream(staging, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, useAsync: true))
|
|
{
|
|
await content.CopyToAsync(fs, ct).ConfigureAwait(false);
|
|
}
|
|
File.Move(staging, finalPath, overwrite: true);
|
|
}
|
|
catch
|
|
{
|
|
try { File.Delete(staging); } catch { /* best effort */ }
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
|
|
{
|
|
var path = ResolvePath(key);
|
|
if (!File.Exists(path))
|
|
return Task.FromResult<Stream?>(null);
|
|
return Task.FromResult<Stream?>(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true));
|
|
}
|
|
|
|
public Task DeleteAsync(string key, CancellationToken ct = default)
|
|
{
|
|
var path = ResolvePath(key);
|
|
try
|
|
{
|
|
if (File.Exists(path))
|
|
File.Delete(path);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug(ex, "Local storage delete failed for {Key}", key);
|
|
}
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
|
{
|
|
foreach (var key in keys)
|
|
DeleteAsync(key, ct);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
|
{
|
|
try
|
|
{
|
|
Directory.CreateDirectory(_root);
|
|
return Task.FromResult(true);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "Local storage health check failed");
|
|
return Task.FromResult(false);
|
|
}
|
|
}
|
|
}
|