Compare commits

...
Author SHA1 Message Date
b709d4dd6d
restores the blogs page header height, and fixes the bool 'is in a romm and connected'
Some checks failed
Forgejo Release / release (push) Has been cancelled
Dotnet build and test / build (pull_request) Has been cancelled
2026-11-13 10:10:35 +00:00
5dc991b885
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>
2026-11-12 18:33:28 +00:00
14 changed files with 292 additions and 13 deletions

View file

@ -6,6 +6,8 @@
### Added
* [Resources/Notifications] Persist private user alerts when net resource consumption crosses 50%, 75%, 90%, 95% or 99% of the personal limit, atomically with accounting. Report only the highest threshold crossed per update and rearm after credits or released storage lower consumption. Keep notification consultation and dismissal accessible at quota without consuming resources; no email or live push is sent.
* [Yavsc.Api] Preserve `application/problem+json` for resource-usage relief errors instead of overriding it with a JSON-only Produces attribute; document success/error media types in OpenAPI and verify error payloads. Restore the haircut and grouped-haircut commands removed from the test seed while retaining its three catalog prestations, with repeated-reset coverage.
* [Yavsc.Api/Tests] Reset the anchored shared SQLite in-memory database by dropping and recreating its tables before seeding, avoiding duplicate user emails across tests. Restore foreign-key enforcement after cleanup and cover repeated resets with a regression test; leave PostgreSQL cleanup unchanged.

View file

@ -160,6 +160,19 @@ Le contrôle admet les coûts connus puis constate les coûts restants :
il bloque les opérations suivantes, sans interrompre strictement celles
déjà en cours.
Au franchissement de 50 %, 75 %, 90 %, 95 % ou 99 % de la limite personnelle,
le serveur enregistre une notification privée `user/{UserId}`, visible dans
les notifications de l'accueil lors de leur prochain chargement. Le calcul
porte sur le total pondéré net des crédits, pas sur chaque compteur séparé.
Une mise à jour franchissant plusieurs paliers ne produit que l'avertissement
du plus haut palier atteint ; rester au-dessus ne répète pas l'alerte.
Après une baisse sous un palier (crédit ou suppression de stockage suivi),
un nouveau franchissement produit une nouvelle notification, même si la
précédente a été fermée. Les notifications et le comptage sont enregistrés
ensemble ; aucune migration de schéma n'est nécessaire.
La lecture et la fermeture des notifications restent accessibles au quota
atteint et ne consomment pas de points. Aucun email ni push immédiat n'est envoyé.
La page **À propos** ouvre les CGU dédiées de PostIt et de Yavsc sur
`Home/CGU` auprès de l'autorité configurée, y compris sans session.
Cette page publique présente les coefficients réellement configurés,

View file

@ -76,8 +76,11 @@ namespace PostIt.ViewModels.Chat
public partial string? SelectedUser { get; set; }
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsConnectedAndInARoom))]
public partial string CurrentRoom { get; set; } = "General";
public bool IsConnectedAndInARoom => IsConnected && !string.IsNullOrEmpty(CurrentRoom);
[ObservableProperty]
public partial string NickName { get; set; } = "";
@ -87,6 +90,7 @@ namespace PostIt.ViewModels.Chat
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SendMessageCommand))]
[NotifyCanExecuteChangedFor(nameof(OpenCallCommand), nameof(ShowCallCommand))]
[NotifyPropertyChangedFor(nameof(IsConnectedAndInARoom))]
public partial bool IsConnected { get; set; } = false;
[ObservableProperty]

View file

@ -2,20 +2,15 @@
x:Class="PostIt.Views.Blogs.BlogsPage"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:models="using:Yavsc.Blogspot"
xmlns:postitControls="using:PostIt.Controls"
xmlns:reader="clr-namespace:Markdown.Avalonia;assembly=Markdown.Avalonia"
xmlns:services="using:PostIt.Services"
xmlns:vm="using:PostIt.ViewModels"
x:Name="BlogsPageRoot"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
x:DataType="vm:BlogsViewModel"
AutomaticallyApplySafeAreaPadding="True"
Header="Billets de blog"
mc:Ignorable="d">
Header="Billets de blog">
<Design.DataContext>
<vm:BlogsViewModel />
</Design.DataContext>

View file

@ -88,7 +88,6 @@ public partial class BlogsPage : ContentPage
PostsSplitter.HorizontalAlignment = isWide ? HorizontalAlignment.Center : HorizontalAlignment.Stretch;
PostsSplitter.VerticalAlignment = isWide ? VerticalAlignment.Stretch : VerticalAlignment.Center;
PostsSplitter.Margin = isWide ? new Thickness(0, 12) : new Thickness(12, 0);
NavigationPage.SetBarHeightOverride(this, isWide ? 36 : null);
}
private static void SetArea(Control control, int row, int column, int rowSpan = 1, int columnSpan = 1)

View file

@ -30,7 +30,7 @@
Text="{Binding CurrentRoom}"
PlaceholderText="Nom du salon" />
<Button Command="{Binding JoinRoomCommand}" Content="Rejoindre Salon (Join)" />
<Button Command="{Binding LeaveRoomCommand}" Content="Quitter le salon" IsEnabled="{Binding !!SelectedRoom}" />
<Button Command="{Binding LeaveRoomCommand}" Content="Quitter le salon" IsEnabled="{Binding IsConnectedAndInARoom}" />
<!-- Choix de la salle en focus parmi celles jointes -->
<ComboBox
Width="180"
@ -85,7 +85,7 @@
Grid.Column="0"
VerticalAlignment="Center"
AcceptsReturn="False"
IsEnabled="{Binding !!SelectedRoom}"
IsEnabled="{Binding IsConnectedAndInARoom}"
PlaceholderText="Votre message..."
Text="{Binding MessageToSend}">
<TextBox.KeyBindings>

View file

@ -33,6 +33,16 @@
],
"PodcastCameraId": "/dev/video0",
"PodcastMicrophoneId": "default",
"PodcastKeepScreenOn": false,
"PodcastBlurBackground": false,
"LanCallAddress": null,
"AndroidKeepChatConnected": false,
"ChatRoomsByAccount": {
"1E801AB5E07C3365EDFE78054C60FB3A13A84182A65DDCC7F85DBE3F8B5D142D": [
"General"
]
},
"SelectedLanguage": "fr-FR",
"SaveCommand": {}
"SaveCommand": {},
"ApplyCommand": {}
}

View file

@ -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

View file

@ -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
{

View file

@ -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"
});
}
}
}

View file

@ -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>();
}
}

View file

@ -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",

View file

@ -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);

View file

@ -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)]