using System.Net; using Amazon.S3; using Messenger.Api.Data; using Messenger.Api.Services; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; using static Messenger.Api.Tests.ApiHelpers; namespace Messenger.Api.Tests; [Collection("api")] public class UploadCleanupTests(ApiFixture fixture) { private static byte[] Png => File.ReadAllBytes(Path.Combine(FindRoot(), "tests/fixtures/sample.png")); private static string FindRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "lab.json"))) dir = dir.Parent; return dir?.FullName ?? throw new InvalidOperationException("Repository root missing"); } private static async Task Upload(HttpClient client, TestUser user, Guid chat, string filename) { using var content = new ByteArrayContent(Png); content.Headers.ContentType = new("image/png"); using var request = Request(HttpMethod.Post, $"/api/v1/chats/{chat}/attachments?filename={filename}", user, content); return await client.SendAsync(request); } private sealed class MetadataFailure : SaveChangesInterceptor { public override ValueTask> SavingChangesAsync(DbContextEventData data, InterceptionResult result, CancellationToken ct = default) { if (data.Context!.ChangeTracker.Entries().Any(e => e.State == EntityState.Added)) throw new InvalidOperationException("injected metadata commit failure"); return ValueTask.FromResult(result); } } private sealed class StorageDecorator(IAttachmentStorage inner) : IAttachmentStorage, IDisposable { public bool FailDelete { get; set; } public Func? AfterPut { get; set; } public Task CheckAsync(CancellationToken ct) => inner.CheckAsync(ct); public async Task PutAsync(string key, Stream content, string mime, CancellationToken ct) { await inner.PutAsync(key, content, mime, ct); if (AfterPut is not null) await AfterPut(key); } public Task CopyToAsync(string key, Stream output, CancellationToken ct) => inner.CopyToAsync(key, output, ct); public Task DeleteAsync(string key, CancellationToken ct) => FailDelete ? throw new HttpRequestException("injected S3 outage") : inner.DeleteAsync(key, ct); public void Dispose() => (inner as IDisposable)?.Dispose(); } private async Task Seed(IServiceProvider services, bool expired = true) { using var scope = services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var id = Guid.NewGuid(); var now = Timestamps.UtcNowMilliseconds(); var intent = new UploadIntentEntity { Id = id, ObjectKey = $"originals/{id:N}", CreatedAt = now, ExpiresAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5), NextAttemptAt = expired ? now.AddMinutes(-1) : now.AddMinutes(5) }; db.UploadIntents.Add(intent); await db.SaveChangesAsync(); await scope.ServiceProvider.GetRequiredService().PutAsync(intent.ObjectKey, new MemoryStream(Png), "image/png", CancellationToken.None); return intent; } private static async Task AssertMissing(IServiceProvider services, string key) { var storage = services.GetRequiredService(); var error = await Assert.ThrowsAnyAsync(() => storage.CopyToAsync(key, Stream.Null, CancellationToken.None)); Assert.Equal(HttpStatusCode.NotFound, error.StatusCode); } [Fact] public async Task MetadataFailureAfterS3Put_SurvivesApiRecreation_AndIsCleaned() { Guid pendingId; string key; var filename = $"fault-{Guid.NewGuid():N}.png"; await using (var broken = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => services.AddDbContext(options => options.AddInterceptors(new MetadataFailure()))))) { using var client = broken.CreateClient(); var user = await CreateUserAsync(client); var chat = await CreateChatAsync(client, user); var response = await Upload(client, user, chat, filename); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); using var scope = broken.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); Assert.False(await db.Attachments.AnyAsync(a => a.Filename == filename)); var intent = await db.UploadIntents.OrderByDescending(i => i.CreatedAt).FirstAsync(); pendingId = intent.Id; key = intent.ObjectKey; using var output = new MemoryStream(); await broken.Services.GetRequiredService().CopyToAsync(key, output, CancellationToken.None); Assert.Equal(Png, output.ToArray()); } // Новый экземпляр приложения читает тот же устойчивый журнал. await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{pendingId}'"); await using var recovered = fixture.WithWebHostBuilder(_ => { }); using var recoveredClient = recovered.CreateClient(); var deadline = DateTime.UtcNow.AddSeconds(10); while (await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",pendingId)) == 0 && DateTime.UtcNow < deadline) await Task.Delay(50); await AssertMissing(recovered.Services, key); Assert.Equal(1L, await fixture.ScalarAsync("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0", ("id",pendingId))); } [Fact] public async Task FreshIntent_IsProtectedByGracePeriod() { using var client = fixture.CreateClient(); var intent = await Seed(fixture.Services, expired: false); await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); using var result = new MemoryStream(); await fixture.Services.GetRequiredService().CopyToAsync(intent.ObjectKey, result, CancellationToken.None); Assert.Equal(Png, result.ToArray()); Assert.Equal(0, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); } [Fact] public async Task PublishedAttachment_IsNeverDeleted_EvenWithAnExpiredIntent() { using var client = fixture.CreateClient(); var user = await CreateUserAsync(client); var chat = await CreateChatAsync(client, user); var response = await Upload(client, user, chat, "protected.png"); Assert.Equal(HttpStatusCode.Created, response.StatusCode); var id = (await ReadJsonAsync(response)).GetProperty("id").GetGuid(); using var scope = fixture.Services.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var attachment = await db.Attachments.SingleAsync(a => a.Id == id); var old = DateTimeOffset.UtcNow.AddMinutes(-1); db.UploadIntents.Add(new() { Id = id, ObjectKey = attachment.ObjectKey, CreatedAt = old, ExpiresAt = old, NextAttemptAt = old }); await db.SaveChangesAsync(); var cleanup = await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); Assert.True(cleanup.Protected >= 1); using var request = Request(HttpMethod.Get,$"/api/v1/attachments/{id}/content",user); Assert.Equal(Png, await (await client.SendAsync(request)).Content.ReadAsByteArrayAsync()); Assert.False(await db.UploadIntents.AsNoTracking().AnyAsync(i => i.Id == id)); } [Fact] public async Task CleanupRetriesAfterS3Failure_AndDeletesALatePutAgain() { StorageDecorator? decorator = null; await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => services.AddSingleton(sp => decorator = new(new S3AttachmentStorage(sp.GetRequiredService()))))); using var client = app.CreateClient(); var intent = await Seed(app.Services); decorator!.FailDelete = true; var failed = await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); Assert.True(failed.Failed >= 1); Assert.Equal(0, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); decorator.FailDelete = false; await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'"); await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); await AssertMissing(app.Services,intent.ObjectKey); // Имитация PUT, завершившегося с задержкой после первого DELETE. await decorator.PutAsync(intent.ObjectKey,new MemoryStream(Png),"image/png",CancellationToken.None); await fixture.ExecuteAsync($"UPDATE upload_intents SET next_attempt_at=now()-interval '1 minute' WHERE id='{intent.Id}'"); await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); await AssertMissing(app.Services,intent.ObjectKey); Assert.Equal(2, await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); } [Fact] public async Task ExpiredUploadCannotPublish_AfterItsLeaseWasRevoked() { await using var app = fixture.WithWebHostBuilder(b => b.ConfigureServices(services => services.AddSingleton(sp => new StorageDecorator(new S3AttachmentStorage(sp.GetRequiredService())) { AfterPut = async key => { var id = Guid.ParseExact(key["originals/".Length..],"N"); await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '1 minute', next_attempt_at=now()-interval '1 minute' WHERE id='{id}'"); } }))); using var client = app.CreateClient(); var user = await CreateUserAsync(client); var chat = await CreateChatAsync(client,user); var name = $"expired-{Guid.NewGuid():N}.png"; Assert.Equal(HttpStatusCode.ServiceUnavailable,(await Upload(client,user,chat,name)).StatusCode); using var scope = app.Services.CreateScope(); Assert.False(await scope.ServiceProvider.GetRequiredService().Attachments.AnyAsync(a=>a.Filename==name)); await app.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); } [Fact] public async Task ConcurrentCleaners_ClaimAnIntentOnce() { using var client = fixture.CreateClient(); var intent = await Seed(fixture.Services); var cleaner = fixture.Services.GetRequiredService(); await Task.WhenAll(cleaner.RunOnceAsync(CancellationToken.None),cleaner.RunOnceAsync(CancellationToken.None)); await AssertMissing(fixture.Services,intent.ObjectKey); Assert.Equal(1,await fixture.ScalarAsync("SELECT delete_count FROM upload_intents WHERE id=@id",("id",intent.Id))); } [Fact] public async Task OldTombstone_RemainsSoALatePutCannotBeForgotten() { using var client = fixture.CreateClient(); var intent = await Seed(fixture.Services); await fixture.ExecuteAsync($"UPDATE upload_intents SET expires_at=now()-interval '2 days' WHERE id='{intent.Id}'"); await fixture.Services.GetRequiredService().RunOnceAsync(CancellationToken.None); await AssertMissing(fixture.Services,intent.ObjectKey); Assert.Equal(1L,await fixture.ScalarAsync("SELECT count(*) FROM upload_intents WHERE id=@id AND delete_count>0",("id",intent.Id))); } }