2026-08-12 10:14:40 +02:00
|
|
|
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>
|
2026-10-22 19:58:05 +02:00
|
|
|
public sealed class StorageProviderFactory : IStorageProvider, Heimdall.Application.Common.IStorageObjectDeletion
|
2026-08-12 10:14:40 +02:00
|
|
|
{
|
|
|
|
|
private readonly IServiceProvider _services;
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public StorageProviderFactory(IServiceProvider services)
|
2026-08-12 10:14:40 +02:00
|
|
|
{
|
|
|
|
|
_services = services;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public string Provider
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { return provider.Provider; }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public bool IsConfigured
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { return provider.IsConfigured; }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
|
|
|
|
|
{
|
2026-10-22 19:58:05 +02:00
|
|
|
var location = CaptureCurrentLocation();
|
|
|
|
|
await UploadAsync(key, content, contentType, location, ct).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Captures the current destination for persistence alongside an object reference.</summary>
|
|
|
|
|
public Heimdall.Domain.Entities.StorageLocation CaptureCurrentLocation()
|
|
|
|
|
{
|
|
|
|
|
using var scope = _services.CreateScope();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
|
|
|
|
var provider = GetSetting(db, "storage.provider");
|
|
|
|
|
if (string.IsNullOrWhiteSpace(provider))
|
|
|
|
|
provider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER");
|
|
|
|
|
if (string.IsNullOrWhiteSpace(provider))
|
|
|
|
|
provider = "Local";
|
|
|
|
|
|
|
|
|
|
if (provider.Equals("Local", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
var root = GetSetting(db, "storage.local.path");
|
|
|
|
|
root = string.IsNullOrWhiteSpace(root)
|
|
|
|
|
? Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage"
|
|
|
|
|
: root;
|
|
|
|
|
return new Heimdall.Domain.Entities.StorageLocation(
|
|
|
|
|
Heimdall.Domain.Enums.StorageProvider.Local,
|
|
|
|
|
LocalRoot: Path.GetFullPath(root));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
var endpoint = GetSetting(db, "storage.s3.endpoint");
|
|
|
|
|
if (string.IsNullOrWhiteSpace(endpoint))
|
|
|
|
|
endpoint = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT");
|
|
|
|
|
if (string.IsNullOrWhiteSpace(endpoint))
|
|
|
|
|
endpoint = Environment.GetEnvironmentVariable("S3_ENDPOINT");
|
|
|
|
|
var bucket = GetSetting(db, "storage.s3.bucket");
|
|
|
|
|
bucket = string.IsNullOrWhiteSpace(bucket) ? "heimdall" : bucket;
|
|
|
|
|
var location = new Heimdall.Domain.Entities.StorageLocation(
|
|
|
|
|
Heimdall.Domain.Enums.StorageProvider.S3,
|
|
|
|
|
S3Endpoint: endpoint,
|
|
|
|
|
S3Bucket: bucket);
|
|
|
|
|
if (!location.IsComplete)
|
|
|
|
|
throw new InvalidOperationException("S3 storage is not configured; no object can be written.");
|
|
|
|
|
return location;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new InvalidOperationException($"Unknown storage provider '{provider}'.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Uploads to an explicitly captured destination so persisted metadata matches the object.</summary>
|
|
|
|
|
public async Task UploadAsync(
|
|
|
|
|
string key,
|
|
|
|
|
Stream content,
|
|
|
|
|
string contentType,
|
|
|
|
|
Heimdall.Domain.Entities.StorageLocation location,
|
|
|
|
|
CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve(location);
|
2026-10-22 19:48:41 +02:00
|
|
|
try { await provider.UploadAsync(key, content, contentType, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public async Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var stream = await provider.DownloadAsync(key, ct).ConfigureAwait(false);
|
|
|
|
|
if (stream is null)
|
|
|
|
|
{
|
|
|
|
|
DisposeProvider(provider);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return new ProviderOwnedStream(stream, provider as IDisposable);
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
DisposeProvider(provider);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 20:50:40 +02:00
|
|
|
/// <summary>Reads an object from the destination recorded with its owning event.</summary>
|
|
|
|
|
public async Task<Stream?> DownloadAsync(
|
|
|
|
|
string key,
|
|
|
|
|
Heimdall.Domain.Entities.StorageLocation location,
|
|
|
|
|
CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve(location);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var stream = await provider.DownloadAsync(key, ct).ConfigureAwait(false);
|
|
|
|
|
if (stream is null)
|
|
|
|
|
{
|
|
|
|
|
DisposeProvider(provider);
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return new ProviderOwnedStream(stream, provider as IDisposable);
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
DisposeProvider(provider);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public async Task DeleteAsync(string key, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { await provider.DeleteAsync(key, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
/// <summary>Deletes an object from the provider recorded with its owning row.</summary>
|
|
|
|
|
public async Task DeleteAsync(string key, Heimdall.Domain.Enums.StorageProvider provider, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var resolved = Resolve(provider.ToString());
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await resolved.DeleteAsync(key, ct).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
finally { DisposeProvider(resolved); }
|
|
|
|
|
}
|
2026-08-12 10:14:40 +02:00
|
|
|
|
2026-10-22 19:58:05 +02:00
|
|
|
/// <summary>Deletes using the exact non-secret destination captured on the owning object.</summary>
|
|
|
|
|
public async Task DeleteAsync(string key, Heimdall.Domain.Entities.StorageLocation location, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var resolved = Resolve(location);
|
|
|
|
|
try { await resolved.DeleteAsync(key, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(resolved); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task DeleteBatchAsync(
|
|
|
|
|
IReadOnlyCollection<string> keys,
|
|
|
|
|
Heimdall.Domain.Enums.StorageProvider providerType,
|
|
|
|
|
CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve(providerType.ToString());
|
|
|
|
|
try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:58:05 +02:00
|
|
|
/// <summary>Deletes a batch from the exact non-secret destination captured on the owning objects.</summary>
|
|
|
|
|
public async Task DeleteBatchAsync(
|
|
|
|
|
IReadOnlyCollection<string> keys,
|
|
|
|
|
Heimdall.Domain.Entities.StorageLocation location,
|
|
|
|
|
CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve(location);
|
|
|
|
|
try { await provider.DeleteBatchAsync(keys, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
public async Task<bool> HealthCheckAsync(CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { return await provider.HealthCheckAsync(ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-23 07:30:58 +02:00
|
|
|
public async Task<int> CleanupStagingAsync(DateTime olderThanUtc, CancellationToken ct = default)
|
|
|
|
|
{
|
|
|
|
|
var provider = Resolve();
|
|
|
|
|
try { return await provider.CleanupStagingAsync(olderThanUtc, ct).ConfigureAwait(false); }
|
|
|
|
|
finally { DisposeProvider(provider); }
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
private static void DisposeProvider(IStorageProvider provider) => (provider as IDisposable)?.Dispose();
|
|
|
|
|
|
|
|
|
|
private IStorageProvider Resolve(string? providerOverride = null)
|
2026-08-12 10:14:40 +02:00
|
|
|
{
|
|
|
|
|
using var scope = _services.CreateScope();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
var configuredProvider = GetSetting(db, "storage.provider");
|
|
|
|
|
var environmentProvider = Environment.GetEnvironmentVariable("STORAGE__PROVIDER");
|
|
|
|
|
var provider = !string.IsNullOrWhiteSpace(providerOverride)
|
|
|
|
|
? providerOverride
|
|
|
|
|
: !string.IsNullOrWhiteSpace(configuredProvider)
|
|
|
|
|
? configuredProvider
|
|
|
|
|
: !string.IsNullOrWhiteSpace(environmentProvider) ? environmentProvider : "Local";
|
2026-08-12 10:14:40 +02:00
|
|
|
|
|
|
|
|
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;
|
2026-10-22 19:48:41 +02:00
|
|
|
s3.Dispose();
|
|
|
|
|
throw new InvalidOperationException($"Storage provider '{provider}' is not configured; refusing to route an object to another provider.");
|
2026-08-12 10:14:40 +02:00
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:48:41 +02:00
|
|
|
if (!provider.Equals("Local", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
throw new InvalidOperationException($"Unknown storage provider '{provider}'.");
|
|
|
|
|
|
2026-08-12 10:14:40 +02:00
|
|
|
return new LocalStorageProvider(
|
|
|
|
|
GetSetting(db, "storage.local.path"),
|
|
|
|
|
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-22 19:58:05 +02:00
|
|
|
private IStorageProvider Resolve(Heimdall.Domain.Entities.StorageLocation location)
|
|
|
|
|
{
|
|
|
|
|
ArgumentNullException.ThrowIfNull(location);
|
|
|
|
|
if (!location.IsComplete)
|
|
|
|
|
throw new InvalidOperationException("Recorded storage location is incomplete; refusing to use current storage settings.");
|
|
|
|
|
|
|
|
|
|
using var scope = _services.CreateScope();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
|
|
|
|
|
if (location.Provider == Heimdall.Domain.Enums.StorageProvider.Local)
|
|
|
|
|
return new LocalStorageProvider(location.LocalRoot,
|
|
|
|
|
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
|
|
|
|
|
|
|
|
|
|
if (location.Provider == Heimdall.Domain.Enums.StorageProvider.S3)
|
|
|
|
|
{
|
|
|
|
|
var s3 = new AlarikStorageProvider(
|
|
|
|
|
location.S3Endpoint,
|
|
|
|
|
location.S3Bucket,
|
|
|
|
|
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;
|
|
|
|
|
s3.Dispose();
|
|
|
|
|
throw new InvalidOperationException("Recorded S3 destination is not configured; refusing to use current storage settings.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
throw new InvalidOperationException($"Unknown recorded storage provider '{location.Provider}'.");
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-12 10:14:40 +02:00
|
|
|
private static string? GetSetting(IApplicationDbContext db, string key)
|
|
|
|
|
{
|
2026-10-22 19:48:41 +02:00
|
|
|
var setting = db.AppSettings
|
|
|
|
|
.AsNoTracking()
|
|
|
|
|
.FirstOrDefault(s => s.Key == key);
|
|
|
|
|
return setting?.Value;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private sealed class ProviderOwnedStream(Stream inner, IDisposable? owner) : Stream
|
|
|
|
|
{
|
|
|
|
|
private bool _disposed;
|
|
|
|
|
|
|
|
|
|
public override bool CanRead => !_disposed && inner.CanRead;
|
|
|
|
|
public override bool CanSeek => !_disposed && inner.CanSeek;
|
|
|
|
|
public override bool CanWrite => !_disposed && inner.CanWrite;
|
|
|
|
|
public override long Length => inner.Length;
|
|
|
|
|
public override long Position { get => inner.Position; set => inner.Position = value; }
|
|
|
|
|
public override void Flush() => inner.Flush();
|
|
|
|
|
public override int Read(byte[] buffer, int offset, int count) => inner.Read(buffer, offset, count);
|
|
|
|
|
public override int Read(Span<byte> buffer) => inner.Read(buffer);
|
|
|
|
|
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
|
|
|
|
|
=> inner.ReadAsync(buffer, cancellationToken);
|
|
|
|
|
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
|
|
|
|
=> inner.ReadAsync(buffer, offset, count, cancellationToken);
|
|
|
|
|
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
|
|
|
|
|
public override void SetLength(long value) => inner.SetLength(value);
|
|
|
|
|
public override void Write(byte[] buffer, int offset, int count) => inner.Write(buffer, offset, count);
|
|
|
|
|
public override void Write(ReadOnlySpan<byte> buffer) => inner.Write(buffer);
|
|
|
|
|
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
|
|
|
|
|
=> inner.WriteAsync(buffer, cancellationToken);
|
|
|
|
|
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
|
|
|
|
|
=> inner.WriteAsync(buffer, offset, count, cancellationToken);
|
|
|
|
|
|
|
|
|
|
protected override void Dispose(bool disposing)
|
2026-08-12 10:14:40 +02:00
|
|
|
{
|
2026-10-22 19:48:41 +02:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (disposing && !_disposed)
|
|
|
|
|
{
|
|
|
|
|
_disposed = true;
|
|
|
|
|
try { inner.Dispose(); }
|
|
|
|
|
finally { owner?.Dispose(); }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
finally { base.Dispose(disposing); }
|
2026-08-12 10:14:40 +02:00
|
|
|
}
|
2026-10-22 19:48:41 +02:00
|
|
|
|
|
|
|
|
public override async ValueTask DisposeAsync()
|
2026-08-12 10:14:40 +02:00
|
|
|
{
|
2026-10-22 19:48:41 +02:00
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (!_disposed)
|
|
|
|
|
{
|
|
|
|
|
_disposed = true;
|
|
|
|
|
try { await inner.DisposeAsync().ConfigureAwait(false); }
|
|
|
|
|
finally { owner?.Dispose(); }
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
finally { await base.DisposeAsync().ConfigureAwait(false); }
|
2026-08-12 10:14:40 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|