feat(resources): notify users at consumption thresholds
Persist private alerts at 50, 75, 90, 95 and 99 percent of net consumption, reporting only the highest crossed threshold and rearming after consumption decreases. Keep notification reading and dismissal accessible at quota. Add crossing, concurrency, rollback and privacy tests. Verified 229 API and 238 server tests pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
9a0b5cc06c
commit
5dc991b885
9 changed files with 274 additions and 3 deletions
|
|
@ -12,6 +12,7 @@ namespace Yavsc.ApiControllers.Administration;
|
|||
/// Notifications dismissed by the authenticated user.
|
||||
/// </summary>
|
||||
[Authorize]
|
||||
[ResourceUsageExempt]
|
||||
[Produces("application/json")]
|
||||
[Route(Constants.APIPrefix + "/" + Constants.NotificationsDismissPath)]
|
||||
public sealed class DismissClicksApiController : Controller
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ using Yavsc.Server.Helpers;
|
|||
namespace Yavsc.ApiControllers.Administration;
|
||||
|
||||
[Produces("application/json")]
|
||||
[ResourceUsageExempt]
|
||||
[Route(Constants.APIPrefix + "/" + Constants.NotificationsPath)]
|
||||
public sealed class NotificationsApiController : Controller
|
||||
{
|
||||
|
|
|
|||
|
|
@ -0,0 +1,67 @@
|
|||
#nullable enable
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Abstract.Models.Messaging;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Server.Helpers;
|
||||
|
||||
public sealed class ResourceUsageNotificationInterceptor(IOptions<ResourceUsageOptions> options) : SaveChangesInterceptor
|
||||
{
|
||||
private static readonly int[] Thresholds = [50, 75, 90, 95, 99];
|
||||
|
||||
public override InterceptionResult<int> SavingChanges(DbContextEventData eventData, InterceptionResult<int> result)
|
||||
{
|
||||
AddNotifications(eventData.Context);
|
||||
return result;
|
||||
}
|
||||
|
||||
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
AddNotifications(eventData.Context);
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
|
||||
private void AddNotifications(DbContext? context)
|
||||
{
|
||||
if (context is not ApplicationDbContext db) return;
|
||||
db.ChangeTracker.DetectChanges();
|
||||
var policy = options.Value;
|
||||
foreach (var entry in db.ChangeTracker.Entries<ResourceUsageRecord>()
|
||||
.Where(e => e.State is EntityState.Added or EntityState.Modified).ToArray())
|
||||
{
|
||||
var record = entry.Entity;
|
||||
var previous = entry.State == EntityState.Added ? 0m :
|
||||
ResourceUsageCredit.NetConsumption(policy.Calculate(
|
||||
entry.OriginalValues.GetValue<decimal>(nameof(record.ApiCalls)),
|
||||
entry.OriginalValues.GetValue<decimal>(nameof(record.CpuSeconds)),
|
||||
entry.OriginalValues.GetValue<decimal>(nameof(record.BandwidthMb)),
|
||||
entry.OriginalValues.GetValue<decimal>(nameof(record.StorageMb))),
|
||||
entry.OriginalValues.GetValue<decimal>(nameof(record.CreditPoints)));
|
||||
var current = ResourceUsageCredit.NetConsumption(policy.Calculate(
|
||||
record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb), record.CreditPoints);
|
||||
var limit = policy.GetLimit(record.UserId);
|
||||
var threshold = Thresholds.LastOrDefault(value =>
|
||||
previous < limit * value / 100m && current >= limit * value / 100m);
|
||||
if (threshold == 0) continue;
|
||||
|
||||
var target = $"user/{record.UserId}";
|
||||
var tag = $"resource-usage/{threshold}";
|
||||
// A failed save may be retried with the same pending notification.
|
||||
if (db.ChangeTracker.Entries<Notification>().Any(e =>
|
||||
e.State == EntityState.Added && e.Entity.Target == target && e.Entity.tag == tag))
|
||||
continue;
|
||||
db.Notification.Add(new Notification
|
||||
{
|
||||
Target = target,
|
||||
tag = tag,
|
||||
title = $"Consommation des ressources : seuil de {threshold} % atteint",
|
||||
body = $"Votre consommation globale de ressources, après déduction des crédits, a atteint {threshold} % de votre limite. Consultez votre consommation et vos abonnements pour éviter le blocage des opérations à la limite.",
|
||||
click_action = "Fermer"
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -147,6 +147,9 @@ public static class ResourceUsageServiceCollectionExtensions
|
|||
.Validate(o => o.DefaultLimit > 0m && o.UserLimits.All(p => !string.IsNullOrWhiteSpace(p.Key) && p.Value > 0m),
|
||||
"ResourceUsage limits must be positive and keyed by user ID.")
|
||||
.ValidateOnStart();
|
||||
services.AddSingleton<ResourceUsageNotificationInterceptor>();
|
||||
services.ConfigureDbContext<ApplicationDbContext>((provider, options) =>
|
||||
options.AddInterceptors(provider.GetRequiredService<ResourceUsageNotificationInterceptor>()));
|
||||
return services.AddScoped<IResourceUsageService, ResourceUsageService>();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -41,6 +41,72 @@ public sealed class ResourceUsageApiControllerTests : IClassFixture<ApiWebServer
|
|||
return http;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resource_alert_is_rolled_back_with_its_usage_update()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var userId = "resource-alert-rollback-" + Guid.NewGuid().ToString("N");
|
||||
using (var scope = _fixture.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<Yavsc.Models.ApplicationDbContext>();
|
||||
await using var transaction = await db.Database.BeginTransactionAsync(ct);
|
||||
await ResourceUsageTracker.RecordAsync(db, userId, userId, cpuSeconds: 5000m, cancellationToken: ct);
|
||||
Assert.Single(db.Notification, note => note.Target == $"user/{userId}");
|
||||
await transaction.RollbackAsync(ct);
|
||||
}
|
||||
using var verification = _fixture.Services.CreateScope();
|
||||
var persisted = verification.ServiceProvider.GetRequiredService<Yavsc.Models.ApplicationDbContext>();
|
||||
Assert.False(await persisted.ResourceUsageRecords.AnyAsync(record => record.UserId == userId, ct));
|
||||
Assert.False(await persisted.Notification.AnyAsync(note => note.Target == $"user/{userId}", ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resource_alerts_are_private_persistent_dismissible_at_quota_and_reappear_on_a_new_crossing()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
var userId = "resource-alert-" + Guid.NewGuid().ToString("N");
|
||||
using var seed = _fixture.Services.CreateScope();
|
||||
var db = seed.ServiceProvider.GetRequiredService<Yavsc.Models.ApplicationDbContext>();
|
||||
db.Users.Add(new Yavsc.Models.ApplicationUser
|
||||
{
|
||||
Id = userId, UserName = userId, Email = userId + "@example.test"
|
||||
});
|
||||
await db.SaveChangesAsync(ct);
|
||||
await ResourceUsageTracker.RecordAsync(db, userId, userId, cpuSeconds: 5000m, cancellationToken: ct);
|
||||
var first = await db.Notification.SingleAsync(n => n.Target == $"user/{userId}", ct);
|
||||
Assert.Equal("resource-usage/50", first.tag);
|
||||
await ResourceUsageTracker.RecordAsync(db, userId, userId, cpuSeconds: 5000m, cancellationToken: ct);
|
||||
|
||||
using var owner = NewClient(_fixture, userId);
|
||||
using var other = NewClient(_fixture, "other-resource-user");
|
||||
using var anonymous = NewClient(_fixture);
|
||||
anonymous.DefaultRequestHeaders.Authorization = null;
|
||||
var ownerNotes = await owner.GetFromJsonAsync<List<Notification>>("/api/v1/notifications/me", ct);
|
||||
Assert.NotNull(ownerNotes);
|
||||
Assert.Equal(2, ownerNotes.Count(n => n.Target == $"user/{userId}"));
|
||||
Assert.DoesNotContain((await other.GetFromJsonAsync<List<Notification>>("/api/v1/notifications/me", ct))!,
|
||||
n => n.Target == $"user/{userId}");
|
||||
Assert.DoesNotContain((await anonymous.GetFromJsonAsync<List<Notification>>("/api/v1/notifications", ct))!,
|
||||
n => n.Target == $"user/{userId}");
|
||||
using var dismissed = await owner.PostAsync($"/api/v1/dismiss/click/{first.Id}", null, ct);
|
||||
Assert.Equal(HttpStatusCode.OK, dismissed.StatusCode);
|
||||
Assert.DoesNotContain((await owner.GetFromJsonAsync<List<Notification>>("/api/v1/notifications/me", ct))!,
|
||||
n => n.Id == first.Id);
|
||||
var summary = await owner.GetFromJsonAsync<ResourceUsageSummary>("/api/v1/resource-usage/me", ct);
|
||||
Assert.NotNull(summary);
|
||||
Assert.True(summary.IsQuotaReached);
|
||||
Assert.Equal(0m, summary.ApiCalls);
|
||||
Assert.Equal(0m, summary.BandwidthMb);
|
||||
|
||||
await seed.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.EraseAsync(userId, "admin", new() { Points = 501m }, ct);
|
||||
await ResourceUsageTracker.RecordAsync(db, userId, userId, cpuSeconds: 10m, cancellationToken: ct);
|
||||
var visible = await owner.GetFromJsonAsync<List<Notification>>("/api/v1/notifications/me", ct);
|
||||
Assert.NotNull(visible);
|
||||
Assert.DoesNotContain(visible, n => n.Id == first.Id);
|
||||
Assert.Single(visible, n => n.Target == $"user/{userId}" && n.tag == "resource-usage/50" && n.Id != first.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true, 5)]
|
||||
[InlineData(false, 2)]
|
||||
|
|
@ -155,7 +221,7 @@ public sealed class ResourceUsageApiControllerTests : IClassFixture<ApiWebServer
|
|||
await ResourceUsageTracker.RecordAsync(db, "exhausted-quota-user", "exhausted-quota-user", cpuSeconds: 10000m);
|
||||
using var http = NewClient(_fixture, "exhausted-quota-user");
|
||||
|
||||
var refused = await http.GetAsync("/api/v1/notifications/me", TestContext.Current.CancellationToken);
|
||||
var refused = await http.GetAsync("/api/v1/activity", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, refused.StatusCode);
|
||||
Assert.Equal("application/problem+json", refused.Content.Headers.ContentType?.MediaType);
|
||||
Assert.Contains("resource_quota_exceeded",
|
||||
|
|
|
|||
|
|
@ -72,7 +72,7 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
|
|||
"relief-admin-exhausted", "Admin", cpuSeconds: 20000m, cancellationToken: Ct);
|
||||
using var admin = Client(subject: "relief-admin-exhausted");
|
||||
using var target = Client("Performer", id);
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, (await target.GetAsync("/api/v1/notifications/me", Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.TooManyRequests, (await target.GetAsync("/api/v1/activity", Ct)).StatusCode);
|
||||
var request = new EraseResourceUsageRequest { Points = 200.12545678m, ExpectedCredits = 0m };
|
||||
using var response = await admin.PostAsJsonAsync($"{Root}/{id}/erase", request, Ct);
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
|
|
@ -83,7 +83,7 @@ public sealed class ResourceUsageReliefApiTests(ApiWebServerFixture fixture) : I
|
|||
Assert.Equal(799.87454322m, summary.Consumption);
|
||||
Assert.Equal(0m, summary.CreditBalance);
|
||||
Assert.False(summary.IsQuotaReached);
|
||||
Assert.Equal(HttpStatusCode.OK, (await target.GetAsync("/api/v1/notifications/me", Ct)).StatusCode);
|
||||
Assert.Equal(HttpStatusCode.OK, (await target.GetAsync("/api/v1/activity", Ct)).StatusCode);
|
||||
using var scope = fixture.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var record = await db.ResourceUsageRecords.SingleAsync(r => r.UserId == id, Ct);
|
||||
|
|
|
|||
|
|
@ -15,6 +15,124 @@ namespace Yavsc.Server.Tests;
|
|||
[Trait("Category", "non-reg")]
|
||||
public sealed class ResourceUsageTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData(50)]
|
||||
[InlineData(75)]
|
||||
[InlineData(90)]
|
||||
[InlineData(95)]
|
||||
[InlineData(99)]
|
||||
public async Task Resource_alert_is_created_at_the_exact_threshold_and_not_repeated_above_it(int threshold)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 1000m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: threshold * 10m - 0.001m,
|
||||
cancellationToken: ct);
|
||||
db.Notification.RemoveRange(db.Notification);
|
||||
await db.SaveChangesAsync(ct);
|
||||
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 0.001m, cancellationToken: ct);
|
||||
var notification = Assert.Single(db.Notification);
|
||||
Assert.Equal("user/alice", notification.Target);
|
||||
Assert.Equal($"resource-usage/{threshold}", notification.tag);
|
||||
Assert.Contains($"{threshold} %", notification.title);
|
||||
Assert.Equal("Fermer", notification.click_action);
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 0.001m, cancellationToken: ct);
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "alice", ct);
|
||||
Assert.Single(db.Notification);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resource_alert_uses_personal_limit_all_resource_weights_and_net_credits()
|
||||
{
|
||||
using var provider = NewProvider(o => o.UserLimits["alice"] = 100m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var record = new ResourceUsageRecord
|
||||
{
|
||||
UserId = "alice", UserName = "alice",
|
||||
ApiCalls = 500m, CpuSeconds = 40m, BandwidthMb = 100m, StorageMb = 100m,
|
||||
CreditPoints = 41m
|
||||
};
|
||||
db.ResourceUsageRecords.Add(record);
|
||||
db.SaveChanges();
|
||||
Assert.Empty(db.Notification);
|
||||
record.ApiCalls += 50m;
|
||||
db.SaveChanges();
|
||||
Assert.Equal("resource-usage/50", Assert.Single(db.Notification).tag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resource_alert_for_a_jump_only_reports_the_highest_crossed_threshold()
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 1000m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 1000m,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal("resource-usage/99", Assert.Single(db.Notification).tag);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resource_alert_rearms_after_administrative_credits_lower_consumption()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 1000m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.Users.Add(new ApplicationUser { Id = "alice", UserName = "alice", Email = "alice@example.test" });
|
||||
await db.SaveChangesAsync(ct);
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 500m, cancellationToken: ct);
|
||||
var firstId = Assert.Single(db.Notification).Id;
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 500m, cancellationToken: ct);
|
||||
var count = db.Notification.Count();
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.EraseAsync("alice", "admin", new() { Points = 501m }, ct);
|
||||
Assert.Equal(count, db.Notification.Count());
|
||||
await ResourceUsageTracker.RecordAsync(db, "alice", "alice", cpuSeconds: 1m, cancellationToken: ct);
|
||||
var alerts = db.Notification.Where(n => n.tag == "resource-usage/50").OrderBy(n => n.Id).ToArray();
|
||||
Assert.Equal(2, alerts.Length);
|
||||
Assert.Equal(firstId, alerts[0].Id);
|
||||
Assert.NotEqual(firstId, alerts[1].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resource_alert_rearms_after_storage_is_released()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 60m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
const long bytes = 100 * 1024 * 1024;
|
||||
await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "test-file", bytes, ct);
|
||||
Assert.Single(db.Notification);
|
||||
await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "test-file", 0, ct);
|
||||
Assert.Single(db.Notification);
|
||||
await ResourceUsageTracker.RecordStorageAsync(db, "alice", "alice", "test-file", bytes, ct);
|
||||
Assert.Equal(2, db.Notification.Count());
|
||||
Assert.All(db.Notification, note => Assert.Equal("resource-usage/50", note.tag));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_resource_updates_only_create_one_alert_per_crossing()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 1000m);
|
||||
using (var seed = provider.CreateScope())
|
||||
await ResourceUsageTracker.RecordAsync(seed.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "alice", cpuSeconds: 499m, cancellationToken: ct);
|
||||
await Task.WhenAll(Enumerable.Range(0, 10).Select(async _ =>
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "alice", cpuSeconds: 1m, cancellationToken: ct);
|
||||
}));
|
||||
using var verification = provider.CreateScope();
|
||||
Assert.Equal("resource-usage/50",
|
||||
Assert.Single(verification.ServiceProvider.GetRequiredService<ApplicationDbContext>().Notification).tag);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("125.12345678", "1874.87654322", true)]
|
||||
[InlineData("2000", "0", false)]
|
||||
|
|
|
|||
Loading…
Reference in a new issue