using Heimdall.Application.Common;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Storage;
///
/// Local filesystem storage provider. Files are written under the configured
/// root (default storage.local.path → env STORAGE__LOCAL__PATH,
/// fallback ./data/storage). Uploads are atomic: write to a staging
/// temp file, then move to the final path.
///
public sealed class LocalStorageProvider : IStorageProvider
{
private readonly string _root;
private readonly ILogger _logger;
public string Provider => "Local";
public bool IsConfigured => !string.IsNullOrEmpty(_root);
public LocalStorageProvider(string? rootPath, ILogger 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 DownloadAsync(string key, CancellationToken ct = default)
{
var path = ResolvePath(key);
if (!File.Exists(path))
return Task.FromResult(null);
return Task.FromResult(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 keys, CancellationToken ct = default)
{
foreach (var key in keys)
DeleteAsync(key, ct);
return Task.CompletedTask;
}
public Task 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);
}
}
}