using System.Collections.Concurrent;
using Backend.Maintenance;
namespace Backend.Tests;
/// An S3 store in memory for database backups; "not configured" until is cleared.
public sealed class FakeBackupObjectStore : IBackupObjectStore
{
public ConcurrentDictionary Objects { get; } = new(StringComparer.Ordinal);
public string? Unavailable { get; set; } = "S3 is not configured.";
/// When set, uploads fail with this message.
public string? FailUploads { get; set; }
public Task UnavailableAsync(CancellationToken cancellationToken) => Task.FromResult(Unavailable);
public Task> ListAsync(string prefix, CancellationToken cancellationToken)
=> Task.FromResult>(Objects
.Where(o => o.Key.StartsWith(prefix, StringComparison.Ordinal))
.Select(o => new BackupObject(o.Key, o.Value.Content.Length, o.Value.Modified))
.ToList());
public async Task PutAsync(string key, string filePath, CancellationToken cancellationToken)
{
if (FailUploads is { } failure)
{
throw new InvalidOperationException(failure);
}
Objects[key] = (await File.ReadAllBytesAsync(filePath, cancellationToken), DateTimeOffset.UtcNow);
}
public Task<(Stream Content, long Length)?> OpenAsync(string key, CancellationToken cancellationToken)
=> Task.FromResult<(Stream, long)?>(Objects.TryGetValue(key, out var found) ? (new MemoryStream(found.Content), found.Content.Length) : null);
public Task DeleteAsync(string key, CancellationToken cancellationToken)
{
Objects.TryRemove(key, out _);
return Task.CompletedTask;
}
}