feat: add resource quotas, PayPal subscriptions and paid disk allowances
Calculate and enforce configurable resource consumption, expose balances in PostIt and document the rule in CGU. Add confirmed monthly PayPal credits and disk quotas of twice the free default for Discovery and five times for Premium, with payment reconciliation, migrations and regression tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
0728d2a3f7
commit
650e5f5e30
69 changed files with 19111 additions and 203 deletions
208
src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs
Normal file
208
src/test/Yavsc.Server.Tests/PayPalSubscriptionGatewayTests.cs
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Settings;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public sealed class PayPalSubscriptionGatewayTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
private sealed class Handler : HttpMessageHandler
|
||||
{
|
||||
public string PlanCurrency { get; set; } = "EUR";
|
||||
public string PlanPrice { get; set; } = "1.20";
|
||||
public string Frequency { get; set; } = "MONTH";
|
||||
public bool AutoBillOutstanding { get; set; }
|
||||
public string? RawResponse { get; set; }
|
||||
public string Verification { get; set; } = "SUCCESS";
|
||||
public string ApprovalUrl { get; set; } = "https://www.sandbox.paypal.com/webapps/billing/subscriptions?ba_token=test";
|
||||
public string CustomId { get; set; } = "";
|
||||
public HttpStatusCode Status { get; set; } = HttpStatusCode.OK;
|
||||
public List<(string Path, string Body, string? RequestId, string Host)> Requests { get; } = [];
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
|
||||
{
|
||||
var path = request.RequestUri!.AbsolutePath;
|
||||
var body = request.Content is null ? "" : await request.Content.ReadAsStringAsync(ct);
|
||||
Requests.Add((path, body, request.Headers.TryGetValues("PayPal-Request-Id", out var ids) ? ids.Single() : null, request.RequestUri.Host));
|
||||
if (Status != HttpStatusCode.OK) return new(Status) { Content = new StringContent("unavailable") };
|
||||
if (RawResponse is not null && path != "/v1/oauth2/token")
|
||||
return new(HttpStatusCode.OK) { Content = new StringContent(RawResponse) };
|
||||
object response = path switch
|
||||
{
|
||||
"/v1/oauth2/token" => new { access_token = "synthetic-token" },
|
||||
"/v1/billing/plans/P-DISCOVERY" => new
|
||||
{
|
||||
id = "P-DISCOVERY", status = "ACTIVE",
|
||||
billing_cycles = new[] { new
|
||||
{
|
||||
tenure_type = "REGULAR", total_cycles = 0,
|
||||
frequency = new { interval_unit = Frequency, interval_count = 1 },
|
||||
pricing_scheme = new { fixed_price = new { currency_code = PlanCurrency, value = PlanPrice } }
|
||||
}},
|
||||
payment_preferences = new { auto_bill_outstanding = AutoBillOutstanding, setup_fee = new { value = "0" } }
|
||||
},
|
||||
"/v1/notifications/verify-webhook-signature" => new { verification_status = Verification },
|
||||
"/v1/billing/subscriptions/I-TEST/transactions" => new
|
||||
{
|
||||
transactions = new[] { new
|
||||
{
|
||||
id = "PAY-1", status = "COMPLETED", time = "2026-01-31T12:00:00Z",
|
||||
amount_with_breakdown = new { gross_amount = new { value = "1.20", currency_code = "EUR" } }
|
||||
}}
|
||||
},
|
||||
_ => new
|
||||
{
|
||||
id = "I-TEST", custom_id = CustomId, plan_id = "P-DISCOVERY", status = "APPROVAL_PENDING",
|
||||
start_time = "2026-01-31T12:00:00Z",
|
||||
links = new[] { new { rel = "approve", href = ApprovalUrl } }
|
||||
}
|
||||
};
|
||||
return new(HttpStatusCode.OK) { Content = JsonContent.Create(response) };
|
||||
}
|
||||
}
|
||||
|
||||
private static PayPalSubscriptionGateway Gateway(HttpClient http, string mode = "sandbox")
|
||||
=> new(http, Options.Create(new PayPalSettings { Mode = mode, ClientId = "test-client", ClientSecret = "test-secret" }),
|
||||
Options.Create(new ResourceSubscriptionOptions { WebhookId = "test-webhook" }));
|
||||
|
||||
private static ResourceSubscription Subscription() => new()
|
||||
{
|
||||
Id = Guid.NewGuid(), UserId = "alice", Pack = "Discovery", PlanId = "P-DISCOVERY",
|
||||
PriceExcludingTax = 1m, PriceIncludingTax = 1.2m
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[InlineData("sandbox", "api-m.sandbox.paypal.com")]
|
||||
[InlineData("production", "api-m.paypal.com")]
|
||||
public async Task Creation_checks_monthly_ttc_plan_and_uses_local_idempotency_reference(string mode, string host)
|
||||
{
|
||||
var subscription = Subscription();
|
||||
using var handler = new Handler { CustomId = subscription.Id.ToString("N") };
|
||||
using var http = new HttpClient(handler);
|
||||
var result = await Gateway(http, mode).CreateAsync(subscription, "https://site.example/return", "https://site.example/cancel", Ct);
|
||||
Assert.Equal("I-TEST", result.Id);
|
||||
var creation = Assert.Single(handler.Requests.Where(r => r.Path == "/v1/billing/subscriptions"));
|
||||
Assert.Equal(subscription.Id.ToString("N"), creation.RequestId);
|
||||
Assert.Contains(subscription.Id.ToString("N"), creation.Body);
|
||||
Assert.Contains("P-DISCOVERY", creation.Body);
|
||||
Assert.Contains("SUBSCRIBE_NOW", creation.Body);
|
||||
Assert.All(handler.Requests, r => Assert.Equal(host, r.Host));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("EUR", "1.00", "MONTH")]
|
||||
[InlineData("USD", "1.20", "MONTH")]
|
||||
[InlineData("EUR", "1.20", "YEAR")]
|
||||
public async Task Wrong_plan_price_currency_or_period_is_refused_before_checkout(string currency, string price, string period)
|
||||
{
|
||||
using var handler = new Handler { PlanCurrency = currency, PlanPrice = price, Frequency = period };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct));
|
||||
Assert.Equal(503, error.StatusCode);
|
||||
Assert.DoesNotContain(handler.Requests, r => r.Path == "/v1/billing/subscriptions");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Automatic_collection_of_outstanding_payments_is_refused_before_checkout()
|
||||
{
|
||||
using var handler = new Handler { AutoBillOutstanding = true };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct));
|
||||
Assert.Equal(503, error.StatusCode);
|
||||
Assert.DoesNotContain(handler.Requests, r => r.Path == "/v1/billing/subscriptions");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""[]""")]
|
||||
[InlineData("""{"id":"I-TEST","links":{}}""")]
|
||||
[InlineData("""{"id":"I-TEST","plan_overridden":"false"}""")]
|
||||
[InlineData("""{"id":"I-TEST","billing_info":[]}""")]
|
||||
[InlineData("""{"id":"I-TEST","links":[{"rel":"approve","href":"https://www.paypal.com/a"},{"rel":"approve","href":"https://www.paypal.com/b"}]}""")]
|
||||
public async Task Malformed_subscription_shapes_are_explicit_upstream_errors(string response)
|
||||
{
|
||||
using var handler = new Handler { RawResponse = response };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() => Gateway(http).GetAsync("I-TEST", Ct));
|
||||
Assert.Equal(502, error.StatusCode);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"billing_cycles":{}}""")]
|
||||
[InlineData("""{"id":"P-DISCOVERY","status":"ACTIVE","billing_cycles":[{"tenure_type":"REGULAR","total_cycles":"0","frequency":{"interval_unit":"MONTH","interval_count":1},"pricing_scheme":{"fixed_price":{"currency_code":"EUR","value":"1.20"}}}],"payment_preferences":{"auto_bill_outstanding":false}}""")]
|
||||
public async Task Malformed_plan_shapes_are_explicit_upstream_errors(string response)
|
||||
{
|
||||
using var handler = new Handler { RawResponse = response };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
Gateway(http).CreateAsync(Subscription(), "https://site.example/return", "https://site.example/cancel", Ct));
|
||||
Assert.Equal(502, error.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Approval_redirect_cannot_point_to_an_untrusted_site()
|
||||
{
|
||||
using var handler = new Handler { ApprovalUrl = "https://attacker.example/" };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() => Gateway(http).GetAsync("I-TEST", Ct));
|
||||
Assert.Equal(502, error.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Webhook_verification_uses_the_configured_id_and_requires_paypal_success()
|
||||
{
|
||||
using var handler = new Handler { Verification = "FAILURE" };
|
||||
using var http = new HttpClient(handler);
|
||||
using var notification = JsonDocument.Parse("""{"id":"WH-TEST","event_type":"PAYMENT.SALE.COMPLETED"}""");
|
||||
var headers = new Dictionary<string, string>
|
||||
{
|
||||
["PAYPAL-AUTH-ALGO"] = "SHA256withRSA", ["PAYPAL-CERT-URL"] = "https://api.paypal.com/cert",
|
||||
["PAYPAL-TRANSMISSION-ID"] = "test-transmission", ["PAYPAL-TRANSMISSION-SIG"] = "test-signature",
|
||||
["PAYPAL-TRANSMISSION-TIME"] = "2026-01-31T12:00:00Z"
|
||||
};
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
Gateway(http).VerifyWebhookAsync(notification.RootElement, headers, Ct));
|
||||
Assert.Equal(400, error.StatusCode);
|
||||
var verification = Assert.Single(handler.Requests.Where(r => r.Path.EndsWith("verify-webhook-signature")));
|
||||
Assert.Contains("test-webhook", verification.Body);
|
||||
Assert.Contains("test-signature", verification.Body);
|
||||
handler.Verification = "SUCCESS";
|
||||
await Gateway(http).VerifyWebhookAsync(notification.RootElement, headers, Ct);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Transaction_history_is_read_with_bounded_ranges_and_invariant_euro_amounts()
|
||||
{
|
||||
using var handler = new Handler();
|
||||
using var http = new HttpClient(handler);
|
||||
var from = new DateTimeOffset(2026, 1, 31, 12, 0, 0, TimeSpan.Zero);
|
||||
var payments = await Gateway(http).TransactionsAsync("I-TEST", from, from.AddDays(61), Ct);
|
||||
Assert.Equal(3, handler.Requests.Count(r => r.Path.EndsWith("/transactions")));
|
||||
Assert.All(payments, p => Assert.Equal(1.2m, p.Amount));
|
||||
Assert.All(payments, p => Assert.Equal("EUR", p.Currency));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Http_failure_is_an_explicit_payment_failure_not_a_successful_subscription()
|
||||
{
|
||||
using var handler = new Handler { Status = HttpStatusCode.ServiceUnavailable };
|
||||
using var http = new HttpClient(handler);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() => Gateway(http).GetAsync("I-TEST", Ct));
|
||||
Assert.Equal(502, error.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Invalid_paypal_id_is_refused_without_network_access()
|
||||
{
|
||||
using var handler = new Handler();
|
||||
using var http = new HttpClient(handler);
|
||||
await Assert.ThrowsAsync<SubscriptionOperationException>(() => Gateway(http).GetAsync("../other", Ct));
|
||||
Assert.Empty(handler.Requests);
|
||||
}
|
||||
}
|
||||
486
src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs
Normal file
486
src/test/Yavsc.Server.Tests/ResourceSubscriptionTests.cs
Normal file
|
|
@ -0,0 +1,486 @@
|
|||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System.Text.Json;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Models.Payment;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Settings;
|
||||
using Yavsc.Web.Services;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public sealed class ResourceSubscriptionTests
|
||||
{
|
||||
private static readonly DateTimeOffset Start = new(2026, 1, 31, 12, 0, 0, TimeSpan.Zero);
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
public DateTimeOffset Now { get; set; } = Start;
|
||||
public override DateTimeOffset GetUtcNow() => Now;
|
||||
}
|
||||
|
||||
private sealed class Gateway : IPayPalSubscriptionGateway
|
||||
{
|
||||
public PayPalSubscriptionDetails Remote { get; set; } = null!;
|
||||
public List<PayPalSubscriptionTransaction> Payments { get; } = [];
|
||||
public Task<PayPalSubscriptionDetails> GetAsync(string id, CancellationToken ct) => Task.FromResult(Remote);
|
||||
public Task<IReadOnlyList<PayPalSubscriptionTransaction>> TransactionsAsync(string id, DateTimeOffset from, DateTimeOffset to, CancellationToken ct)
|
||||
=> Task.FromResult<IReadOnlyList<PayPalSubscriptionTransaction>>(Payments.ToArray());
|
||||
public Task<PayPalSubscriptionDetails> CreateAsync(ResourceSubscription subscription, string returnUrl, string cancelUrl, CancellationToken ct)
|
||||
=> throw new NotSupportedException();
|
||||
public Task CancelAsync(string id, CancellationToken ct) => throw new NotSupportedException();
|
||||
public Task VerifyWebhookAsync(JsonElement notification, IReadOnlyDictionary<string, string> headers, CancellationToken ct)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private static ServiceProvider Provider(Clock clock, Gateway gateway, bool useBackendDefaults = false)
|
||||
{
|
||||
var name = Guid.NewGuid().ToString();
|
||||
var services = new ServiceCollection();
|
||||
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(name));
|
||||
services.AddResourceUsage(new ConfigurationBuilder().Build());
|
||||
if (!useBackendDefaults)
|
||||
services.Configure<ResourceUsageOptions>(o =>
|
||||
{
|
||||
o.ApiCallWeight = 0.02m;
|
||||
o.CpuSecondWeight = 1m;
|
||||
o.BandwidthMbWeight = 0.1m;
|
||||
o.StorageMbWeight = 0.3m;
|
||||
o.DefaultLimit = 10000m;
|
||||
});
|
||||
services.Configure<ResourceSubscriptionOptions>(o =>
|
||||
{
|
||||
o.DiscoveryPlanId = "P-DISCOVERY";
|
||||
o.PremiumPlanId = "P-PREMIUM";
|
||||
});
|
||||
services.AddSingleton<TimeProvider>(clock);
|
||||
services.AddSingleton<IPayPalSubscriptionGateway>(gateway);
|
||||
services.AddScoped<IResourceSubscriptionService, ResourceSubscriptionService>();
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
private static async Task<ResourceSubscription> BeginAsync(IServiceProvider services, Gateway gateway, string pack = "Discovery", decimal gross = 0m)
|
||||
{
|
||||
var db = services.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: gross, cancellationToken: Ct);
|
||||
var service = services.GetRequiredService<IResourceSubscriptionService>();
|
||||
var subscription = await service.PrepareAsync("alice", pack, Ct);
|
||||
gateway.Remote = new("I-TEST", subscription.Id.ToString("N"), subscription.PlanId, "ACTIVE", Start, Start.AddMonths(1), null);
|
||||
await service.BindAsync(subscription, gateway.Remote, Ct);
|
||||
return subscription;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(4000, 0, 10000, 8000)]
|
||||
[InlineData(15000, 0, 10000, 10000)]
|
||||
[InlineData(0, 0, 30000, 20000)]
|
||||
[InlineData(4000, 5000, 30000, 20000)]
|
||||
public void Monthly_credit_erases_usage_then_carries_two_thirds_of_unused_allowance(
|
||||
decimal gross, decimal previous, decimal allowance, decimal grant)
|
||||
=> Assert.Equal(grant, ResourceUsageCredit.MonthlyGrant(gross, previous, allowance));
|
||||
|
||||
[Theory]
|
||||
[InlineData("Premium", 2.4, 5)]
|
||||
[InlineData("Discovery", 1.2, 2)]
|
||||
public async Task Paid_disk_quota_uses_standard_reference_and_survives_cancellation_until_anniversary(
|
||||
string pack, decimal amount, long multiplier)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack);
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var user = await db.Users.SingleAsync(Ct);
|
||||
user.DiskQuota = 1234L;
|
||||
user.DiskUsage = 5000L;
|
||||
await db.SaveChangesAsync(Ct);
|
||||
gateway.Payments.Add(new("PAY-DISK", "COMPLETED", amount, "EUR", Start));
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, user.GetEffectiveDiskQuota(clock.Now));
|
||||
Assert.Equal(Start.AddMonths(1), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, usage.DiskQuota);
|
||||
Assert.Equal(user.PremiumDiskQuotaUntil, usage.PremiumDiskQuotaUntil);
|
||||
Assert.Equal(user.DiscoveryDiskQuotaUntil, usage.DiscoveryDiskQuotaUntil);
|
||||
gateway.Remote = gateway.Remote with { State = "CANCELLED", NextBillingAt = null };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ * multiplier, user.GetEffectiveDiskQuota(Start.AddMonths(1).AddTicks(-1)));
|
||||
Assert.Equal(1234L, user.GetEffectiveDiskQuota(Start.AddMonths(1)));
|
||||
Assert.Equal(1234L, user.DiskQuota);
|
||||
Assert.Equal(5000L, user.DiskUsage);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Discovery", "PENDING", 1.2)]
|
||||
[InlineData("Discovery", "FAILED", 1.2)]
|
||||
[InlineData("Premium", "PENDING", 2.4)]
|
||||
[InlineData("Premium", "FAILED", 2.4)]
|
||||
public async Task Unpaid_subscriptions_do_not_grant_disk_bonus(string pack, string state, decimal amount)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack);
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
gateway.Payments.Add(new("PAY-DISK", state, amount, "EUR", Start));
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct);
|
||||
var user = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Users.SingleAsync(Ct);
|
||||
Assert.Null(user.PremiumDiskQuotaUntil);
|
||||
Assert.Null(user.DiscoveryDiskQuotaUntil);
|
||||
Assert.Equal(user.DiskQuota, user.GetEffectiveDiskQuota(clock.Now));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Premium", 2.4)]
|
||||
[InlineData("Discovery", 1.2)]
|
||||
public async Task Refund_revokes_disk_bonus_but_not_another_paid_period(string pack, decimal amount)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack);
|
||||
clock.Now = Start.AddMonths(1).AddMinutes(1);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", amount, "EUR", Start));
|
||||
gateway.Payments.Add(new("PAY-2", "COMPLETED", amount, "EUR", Start.AddMonths(1)));
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
var user = await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Users.SingleAsync(Ct);
|
||||
Assert.Equal(Start.AddMonths(2), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil);
|
||||
gateway.Payments[0] = gateway.Payments[0] with { State = "REFUNDED" };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
Assert.Equal(Start.AddMonths(2), pack == "Premium" ? user.PremiumDiskQuotaUntil : user.DiscoveryDiskQuotaUntil);
|
||||
gateway.Payments[1] = gateway.Payments[1] with { State = "PARTIALLY_REFUNDED" };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
Assert.Null(user.PremiumDiskQuotaUntil);
|
||||
Assert.Null(user.DiscoveryDiskQuotaUntil);
|
||||
Assert.Equal(user.DiskQuota, user.GetEffectiveDiskQuota(clock.Now));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cached_disk_tracker_refreshes_paid_entitlement_before_admission()
|
||||
{
|
||||
using var provider = Provider(new Clock(), new Gateway());
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.Users.Add(new ApplicationUser
|
||||
{
|
||||
Id = "alice", UserName = "Alice", Email = "alice@example.test", DiskQuota = 10L, DiskUsage = 11L,
|
||||
PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddDays(1)
|
||||
});
|
||||
await db.SaveChangesAsync(Ct);
|
||||
var tracker = new DiskUsageTracker(Options.Create(new SiteSettings { DUUserListLen = 10 }), db);
|
||||
Assert.False(tracker.GetSpace("Alice", Yavsc.Constants.DefaultFSQ * 5L));
|
||||
using var other = provider.CreateScope();
|
||||
var otherDb = other.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var user = await otherDb.Users.SingleAsync(Ct);
|
||||
user.PremiumDiskQuotaUntil = DateTimeOffset.UtcNow.AddSeconds(-1);
|
||||
await otherDb.SaveChangesAsync(Ct);
|
||||
Assert.False(tracker.GetSpace("Alice", 1L));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Discovery", 1.2, 1000, 3000)]
|
||||
[InlineData("Premium", 2.4, 3000, 1000)]
|
||||
public async Task Current_backend_defaults_give_one_or_three_thousand_monthly_points(
|
||||
string pack, decimal amount, decimal monthlyPoints, decimal remainingUsage)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway, useBackendDefaults: true);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, pack, 40000m);
|
||||
Assert.Equal(monthlyPoints, subscription.MonthlyPoints);
|
||||
gateway.Payments.Add(new("PAY-DEFAULT", "COMPLETED", amount, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(4000m, usage.GrossConsumption);
|
||||
Assert.Equal(remainingUsage, usage.Consumption);
|
||||
Assert.Equal(1000m, usage.ConsumptionLimit);
|
||||
Assert.Equal(0m, usage.RemainingConsumption);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Overlapping_paid_periods_fall_back_from_premium_to_discovery_then_base_quota()
|
||||
{
|
||||
var user = new ApplicationUser
|
||||
{
|
||||
PremiumDiskQuotaUntil = Start.AddDays(1),
|
||||
DiscoveryDiskQuotaUntil = Start.AddDays(2)
|
||||
};
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ * 5L, user.GetEffectiveDiskQuota(Start));
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ * 2L, user.GetEffectiveDiskQuota(Start.AddDays(1)));
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ, user.GetEffectiveDiskQuota(Start.AddDays(2)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Free_disk_quota_matches_the_standard_database_default()
|
||||
{
|
||||
var user = new ApplicationUser();
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ, user.DiskQuota);
|
||||
Assert.Equal(Yavsc.Constants.DefaultFSQ, user.GetEffectiveDiskQuota(Start));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Carried_credit_is_rounded_down_at_database_precision()
|
||||
=> Assert.Equal(6666.66666666m, ResourceUsageCredit.MonthlyGrant(0m, 0m, 10000m));
|
||||
|
||||
[Theory]
|
||||
[InlineData("2026-02-28T00:00:00Z", 1)]
|
||||
[InlineData("2026-03-30T23:59:59Z", 1)]
|
||||
[InlineData("2026-03-31T00:00:00Z", 2)]
|
||||
[InlineData("2027-01-31T00:00:00Z", 12)]
|
||||
public void Monthly_anniversaries_do_not_drift_after_a_short_month(string paidAt, int expected)
|
||||
=> Assert.Equal(expected, ResourceUsageCredit.BillingCycle(
|
||||
new DateTimeOffset(Start.UtcDateTime.Date, TimeSpan.Zero), DateTimeOffset.Parse(paidAt)));
|
||||
|
||||
[Fact]
|
||||
public async Task First_payment_preserves_counters_erases_usage_and_repeated_notifications_do_not_duplicate_credit()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 4000m);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(4000m, usage.CpuSeconds);
|
||||
Assert.Equal(4000m, usage.GrossConsumption);
|
||||
Assert.Equal(0m, usage.Consumption);
|
||||
Assert.Equal(4000m, usage.CreditBalance);
|
||||
Assert.Equal(14000m, usage.RemainingConsumption);
|
||||
Assert.Single(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().ResourceSubscriptionPayments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Premium_gives_three_default_quotas_not_three_individual_overrides()
|
||||
{
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(new Clock { Now = Start.AddMinutes(1) }, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
scope.ServiceProvider.GetRequiredService<IOptions<ResourceUsageOptions>>().Value.UserLimits["alice"] = 15000m;
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, "Premium", 35000m);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 2.4m, "EUR", Start.AddMinutes(1)));
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(30000m, subscription.MonthlyPoints);
|
||||
Assert.Equal(2m, subscription.PriceExcludingTax);
|
||||
Assert.Equal(2.4m, subscription.PriceIncludingTax);
|
||||
Assert.Equal(5000m, usage.Consumption);
|
||||
Assert.Equal(10000m, usage.RemainingConsumption);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Old_carry_is_not_reduced_again_and_remains_spendable_after_cancellation()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 4000m);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddDays(1);
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start.AddMonths(1)));
|
||||
clock.Now = Start.AddMonths(1).AddMinutes(1);
|
||||
gateway.Remote = gateway.Remote with { State = "CANCELLED", NextBillingAt = null };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
var usageService = scope.ServiceProvider.GetRequiredService<IResourceUsageService>();
|
||||
var usage = await usageService.GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(10666.66666666m, usage.CreditBalance);
|
||||
Assert.Equal("CANCELLED", subscription.State);
|
||||
await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "Alice", cpuSeconds: 5000m, cancellationToken: Ct);
|
||||
usage = await usageService.GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(5666.66666666m, usage.CreditBalance);
|
||||
Assert.Equal(0m, usage.Consumption);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("PENDING")]
|
||||
[InlineData("FAILED")]
|
||||
[InlineData("DECLINED")]
|
||||
public async Task Approval_and_unpaid_months_never_grant_points(string state)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m);
|
||||
gateway.Payments.Add(new("PAY-1", state, 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(12000m, usage.Consumption);
|
||||
Assert.True(usage.IsQuotaReached);
|
||||
Assert.Equal(0m, usage.CreditBalance);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("REFUNDED")]
|
||||
[InlineData("PARTIALLY_REFUNDED")]
|
||||
[InlineData("FAILED")]
|
||||
public async Task Reversal_removes_the_awarded_credit_once_without_deleting_history(string state)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
gateway.Payments[0] = gateway.Payments[0] with { State = state };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
var usage = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>().GetCurrentAsync("alice", "Alice", Ct);
|
||||
Assert.Equal(12000m, usage.Consumption);
|
||||
Assert.True(usage.IsQuotaReached);
|
||||
Assert.True(Assert.Single(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().ResourceSubscriptionPayments).Reversed);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_payment_unblocks_a_user_without_changing_the_free_limit()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m);
|
||||
var usage = scope.ServiceProvider.GetRequiredService<IResourceUsageService>();
|
||||
Assert.False(await usage.TryAdmitAsync("alice", "Alice", 1m, 0m, 0, Ct));
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
await scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct);
|
||||
Assert.True(await usage.TryAdmitAsync("alice", "Alice", 1m, 0m, 0, Ct));
|
||||
Assert.Equal(10000m, (await usage.GetCurrentAsync("alice", "Alice", Ct)).ConsumptionLimit);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("USD", 1.2)]
|
||||
[InlineData("EUR", 1)]
|
||||
public async Task Wrong_currency_or_net_instead_of_gross_price_does_not_grant_credit(string currency, decimal amount)
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", amount, currency, Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>().ReconcileAsync(subscription, Ct));
|
||||
Assert.Equal(409, error.StatusCode);
|
||||
Assert.Empty(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().ResourceSubscriptionPayments);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Another_custom_account_or_plan_cannot_be_bound()
|
||||
{
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(new Clock(), gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
service.BindAsync(subscription, gateway.Remote with { CustomId = Guid.NewGuid().ToString("N") }, Ct));
|
||||
await Assert.ThrowsAsync<SubscriptionOperationException>(() =>
|
||||
service.BindAsync(subscription, gateway.Remote with { PlanId = "P-OTHER" }, Ct));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_notifications_in_distinct_scopes_award_the_same_payment_once()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var initialScope = provider.CreateScope();
|
||||
await BeginAsync(initialScope.ServiceProvider, gateway, gross: 4000m);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
using var firstScope = provider.CreateScope();
|
||||
using var secondScope = provider.CreateScope();
|
||||
var first = firstScope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
var second = secondScope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
var firstSubscription = Assert.Single(await first.GetAllAsync("alice", Ct));
|
||||
var secondSubscription = Assert.Single(await second.GetAllAsync("alice", Ct));
|
||||
await Task.WhenAll(
|
||||
Task.Run(() => first.ReconcileAsync(firstSubscription, Ct), Ct),
|
||||
Task.Run(() => second.ReconcileAsync(secondSubscription, Ct), Ct));
|
||||
using var verificationScope = provider.CreateScope();
|
||||
var db = verificationScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Single(db.ResourceSubscriptionPayments);
|
||||
Assert.Equal(8000m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_older_pending_payment_can_complete_after_a_more_recent_month_without_double_credit()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway, gross: 12000m);
|
||||
gateway.Payments.Add(new("PAY-1", "PENDING", 1.2m, "EUR", Start));
|
||||
gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start.AddMonths(1)));
|
||||
clock.Now = Start.AddMonths(1).AddMinutes(1);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
gateway.Payments[0] = gateway.Payments[0] with { State = "COMPLETED" };
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Equal(2, await db.ResourceSubscriptionPayments.CountAsync(Ct));
|
||||
Assert.Equal(1, subscription.LastCreditedCycle);
|
||||
Assert.Equal(17333.33333333m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_different_payment_ids_in_the_same_month_do_not_award_two_credits()
|
||||
{
|
||||
var clock = new Clock();
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(clock, gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway);
|
||||
gateway.Payments.Add(new("PAY-1", "COMPLETED", 1.2m, "EUR", Start));
|
||||
clock.Now = Start.AddMinutes(1);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
await service.ReconcileAsync(subscription, Ct);
|
||||
gateway.Payments.Add(new("PAY-2", "COMPLETED", 1.2m, "EUR", Start));
|
||||
var error = await Assert.ThrowsAsync<SubscriptionOperationException>(() => service.ReconcileAsync(subscription, Ct));
|
||||
Assert.Equal(409, error.StatusCode);
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
Assert.Single(db.ResourceSubscriptionPayments);
|
||||
Assert.Equal(6666.66666666m, (await db.ResourceUsageRecords.SingleAsync(Ct)).CreditPoints);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Preparing_the_same_pack_is_idempotent_and_changing_pack_requires_cancellation()
|
||||
{
|
||||
var gateway = new Gateway();
|
||||
using var provider = Provider(new Clock(), gateway);
|
||||
using var scope = provider.CreateScope();
|
||||
var subscription = await BeginAsync(scope.ServiceProvider, gateway);
|
||||
var service = scope.ServiceProvider.GetRequiredService<IResourceSubscriptionService>();
|
||||
Assert.Equal(subscription.Id, (await service.PrepareAsync("alice", "Discovery", Ct)).Id);
|
||||
await Assert.ThrowsAsync<SubscriptionOperationException>(() => service.PrepareAsync("alice", "Premium", Ct));
|
||||
await Assert.ThrowsAsync<SubscriptionOperationException>(() => service.PrepareAsync("alice", "unknown", Ct));
|
||||
}
|
||||
}
|
||||
283
src/test/Yavsc.Server.Tests/ResourceUsageTests.cs
Normal file
283
src/test/Yavsc.Server.Tests/ResourceUsageTests.cs
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Yavsc.Models;
|
||||
using Yavsc.Server.Helpers;
|
||||
using Yavsc.Settings;
|
||||
|
||||
namespace Yavsc.Server.Tests;
|
||||
|
||||
public sealed class ResourceUsageTests
|
||||
{
|
||||
private static ServiceProvider NewProvider(Action<ResourceUsageOptions>? configure = null)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
var databaseName = Guid.NewGuid().ToString();
|
||||
services.AddLogging();
|
||||
services.AddDbContext<ApplicationDbContext>(o => o.UseInMemoryDatabase(databaseName));
|
||||
services.AddResourceUsage(new ConfigurationBuilder().Build());
|
||||
services.Configure<ResourceUsageOptions>(o =>
|
||||
{
|
||||
o.ApiCallWeight = 0.02m;
|
||||
o.CpuSecondWeight = 1m;
|
||||
o.BandwidthMbWeight = 0.1m;
|
||||
o.StorageMbWeight = 0.3m;
|
||||
o.DefaultLimit = 10000m;
|
||||
});
|
||||
services.Configure<SiteSettings>(o => o.Authority = "https://instance.example");
|
||||
if (configure is not null) services.Configure(configure);
|
||||
return services.BuildServiceProvider();
|
||||
}
|
||||
|
||||
private static DefaultHttpContext NewContext(IServiceProvider services)
|
||||
=> new()
|
||||
{
|
||||
RequestServices = services,
|
||||
User = new ClaimsPrincipal(new ClaimsIdentity([new Claim("sub", "alice")], "Bearer")),
|
||||
Response = { Body = new MemoryStream() }
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void Configured_formula_uses_exact_decimal_points()
|
||||
{
|
||||
var rule = new ResourceUsageOptions
|
||||
{
|
||||
ApiCallWeight = 0.2m, CpuSecondWeight = 0.1m,
|
||||
BandwidthMbWeight = 0.05m, StorageMbWeight = 0.5m, DefaultLimit = 1000m
|
||||
};
|
||||
Assert.Equal(29.34m, rule.Calculate(12.5m, 3.2m, 18.4m, 51.2m));
|
||||
Assert.Equal(0m, rule.Calculate(0m, 0m, 0m, 0m));
|
||||
Assert.Equal(0.002m, rule.Calculate(0.01m, 0m, 0m, 0m));
|
||||
Assert.Equal(1000m, rule.GetLimit("unknown-user"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Summary_uses_latest_snapshot_and_individual_limit_without_summing_snapshots()
|
||||
{
|
||||
using var provider = NewProvider(o => o.UserLimits["alice"] = 100m);
|
||||
using var scope = provider.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
db.ResourceUsageRecords.AddRange(
|
||||
new ResourceUsageRecord { UserId = "alice", UserName = "old", CpuSeconds = 500m, RecordedAtUtc = DateTime.UtcNow.AddDays(-1) },
|
||||
new ResourceUsageRecord { UserId = "alice", UserName = "alice", ApiCalls = 10m, CpuSeconds = 3m, BandwidthMb = 2m, StorageMb = 4m });
|
||||
await db.SaveChangesAsync();
|
||||
var usage = scope.ServiceProvider.GetRequiredService<IResourceUsageService>();
|
||||
var summary = await usage.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(4.6m, summary.Consumption);
|
||||
Assert.Equal(100m, summary.ConsumptionLimit);
|
||||
Assert.Equal(95.4m, summary.RemainingConsumption);
|
||||
Assert.False(summary.IsQuotaReached);
|
||||
var overview = await usage.GetOverviewAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Single(overview);
|
||||
Assert.Equal(summary.Consumption, overview[0].Consumption);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_admissions_allow_exact_limit_without_lost_updates_or_duplicate_snapshots()
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 0.04m);
|
||||
var results = await Task.WhenAll(Enumerable.Range(0, 20).Select(async _ =>
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken);
|
||||
}));
|
||||
Assert.Equal(2, results.Count(accepted => accepted));
|
||||
using var finalScope = provider.CreateScope();
|
||||
var db = finalScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
var record = Assert.Single(await db.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal(2m, record.ApiCalls);
|
||||
var summary = await finalScope.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken);
|
||||
Assert.True(summary.IsQuotaReached);
|
||||
Assert.Equal(0m, summary.RemainingConsumption);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Concurrent_accounting_preserves_all_resource_deltas()
|
||||
{
|
||||
using var provider = NewProvider();
|
||||
await Task.WhenAll(Enumerable.Range(0, 20).Select(async _ =>
|
||||
{
|
||||
using var scope = provider.CreateScope();
|
||||
await ResourceUsageTracker.RecordAsync(
|
||||
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "alice", cpuSeconds: 0.1m, apiCalls: 1m,
|
||||
storageBytes: 1048576, bandwidthMb: 0.5m);
|
||||
}));
|
||||
using var finalScope = provider.CreateScope();
|
||||
var record = Assert.Single(await finalScope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal(20m, record.ApiCalls);
|
||||
Assert.Equal(2m, record.CpuSeconds);
|
||||
Assert.Equal(20m, record.StorageMb);
|
||||
Assert.Equal(10m, record.BandwidthMb);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Known_ingress_or_storage_cost_is_refused_before_consumption()
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 0.11m);
|
||||
using var scope = provider.CreateScope();
|
||||
var usage = scope.ServiceProvider.GetRequiredService<IResourceUsageService>();
|
||||
Assert.False(await usage.TryAdmitAsync("alice", "alice", 1m, 1m, 0, TestContext.Current.CancellationToken));
|
||||
Assert.False(await usage.TryAdmitAsync("alice", "alice", 0m, 0m, 1048576, TestContext.Current.CancellationToken));
|
||||
Assert.Empty(await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Observed_cost_can_exceed_limit_then_new_operations_are_refused_until_limit_is_increased()
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 1m);
|
||||
using var scope = provider.CreateScope();
|
||||
var usage = scope.ServiceProvider.GetRequiredService<IResourceUsageService>();
|
||||
Assert.True(await usage.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken));
|
||||
await ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "alice", cpuSeconds: 2m, cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.False(await usage.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken));
|
||||
var summary = await usage.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(2.02m, summary.Consumption);
|
||||
Assert.Equal(0m, summary.RemainingConsumption);
|
||||
Assert.True(summary.IsQuotaReached);
|
||||
|
||||
var raised = new ResourceUsageService(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
Options.Create(new ResourceUsageOptions
|
||||
{
|
||||
DefaultLimit = 3m, ApiCallWeight = 0.02m, CpuSecondWeight = 1m,
|
||||
BandwidthMbWeight = 0.1m, StorageMbWeight = 0.3m
|
||||
}));
|
||||
Assert.True(await raised.TryAdmitAsync("alice", "alice", 1m, 0m, 0, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Middleware_counts_streamed_bodies_once_with_or_without_declared_ingress(bool declared)
|
||||
{
|
||||
using var provider = NewProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
var context = NewContext(scope.ServiceProvider);
|
||||
using var originalRequest = new MemoryStream(new byte[1048576]);
|
||||
using var originalResponse = new MemoryStream();
|
||||
context.Request.Body = originalRequest;
|
||||
context.Response.Body = originalResponse;
|
||||
if (declared) context.Request.ContentLength = 1048576;
|
||||
var middleware = new ResourceUsageTelemetryMiddleware(
|
||||
async ctx =>
|
||||
{
|
||||
await ctx.Request.Body.CopyToAsync(Stream.Null);
|
||||
await ctx.Response.BodyWriter.WriteAsync(new byte[2 * 1048576]);
|
||||
},
|
||||
provider.GetRequiredService<IServiceScopeFactory>(),
|
||||
NullLogger<ResourceUsageTelemetryMiddleware>.Instance);
|
||||
await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService<IResourceUsageService>());
|
||||
Assert.Same(originalRequest, context.Request.Body);
|
||||
Assert.Same(originalResponse, context.Response.Body);
|
||||
Assert.True(originalRequest.CanRead);
|
||||
Assert.True(originalResponse.CanWrite);
|
||||
var summary = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(1m, summary.ApiCalls);
|
||||
Assert.Equal(3m, summary.BandwidthMb);
|
||||
Assert.Equal(0.32m, summary.Consumption);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Failed_execution_is_accounted_and_original_streams_are_restored()
|
||||
{
|
||||
using var provider = NewProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
var context = NewContext(scope.ServiceProvider);
|
||||
var originalResponse = context.Response.Body;
|
||||
var middleware = new ResourceUsageTelemetryMiddleware(
|
||||
async ctx =>
|
||||
{
|
||||
await ctx.Response.Body.WriteAsync(new byte[1048576]);
|
||||
throw new InvalidOperationException("Expected test failure");
|
||||
}, provider.GetRequiredService<IServiceScopeFactory>(),
|
||||
NullLogger<ResourceUsageTelemetryMiddleware>.Instance);
|
||||
await Assert.ThrowsAsync<InvalidOperationException>(() =>
|
||||
middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService<IResourceUsageService>()));
|
||||
Assert.Same(originalResponse, context.Response.Body);
|
||||
var summary = await scope.ServiceProvider.GetRequiredService<IResourceUsageService>()
|
||||
.GetCurrentAsync("alice", "alice", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(0.12m, summary.Consumption);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("/login", false)]
|
||||
[InlineData("/refresh", false)]
|
||||
[InlineData("/logout", false)]
|
||||
[InlineData("/api/v1/resource-usage/me", true)]
|
||||
public async Task Exempt_endpoints_remain_available_without_consumption(string path, bool metadata)
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 0.01m);
|
||||
using var scope = provider.CreateScope();
|
||||
var context = NewContext(scope.ServiceProvider);
|
||||
context.Request.Path = path;
|
||||
if (metadata)
|
||||
context.SetEndpoint(new Endpoint(_ => Task.CompletedTask,
|
||||
new EndpointMetadataCollection(new ResourceUsageExemptAttribute()), "usage"));
|
||||
var ran = false;
|
||||
var middleware = new ResourceUsageTelemetryMiddleware(
|
||||
_ => { ran = true; return Task.CompletedTask; },
|
||||
provider.GetRequiredService<IServiceScopeFactory>(),
|
||||
NullLogger<ResourceUsageTelemetryMiddleware>.Instance);
|
||||
await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService<IResourceUsageService>());
|
||||
Assert.True(ran);
|
||||
Assert.Empty(await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Rejected_request_returns_problem_details_without_running_or_charging()
|
||||
{
|
||||
using var provider = NewProvider(o => o.DefaultLimit = 0.01m);
|
||||
using var scope = provider.CreateScope();
|
||||
var context = NewContext(scope.ServiceProvider);
|
||||
var middleware = new ResourceUsageTelemetryMiddleware(
|
||||
_ => throw new InvalidOperationException("Must not run"),
|
||||
provider.GetRequiredService<IServiceScopeFactory>(),
|
||||
NullLogger<ResourceUsageTelemetryMiddleware>.Instance);
|
||||
await middleware.InvokeAsync(context, scope.ServiceProvider.GetRequiredService<IResourceUsageService>());
|
||||
Assert.Equal(429, context.Response.StatusCode);
|
||||
Assert.StartsWith("application/problem+json", context.Response.ContentType);
|
||||
context.Response.Body.Position = 0;
|
||||
using var reader = new StreamReader(context.Response.Body);
|
||||
var payload = await reader.ReadToEndAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Contains("resource_quota_exceeded", payload);
|
||||
Assert.Contains("https://instance.example/Home/CGU", payload);
|
||||
Assert.Empty(await scope.ServiceProvider.GetRequiredService<ApplicationDbContext>()
|
||||
.ResourceUsageRecords.ToListAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Negative_counter_deltas_are_explicitly_rejected()
|
||||
{
|
||||
using var provider = NewProvider();
|
||||
using var scope = provider.CreateScope();
|
||||
await Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
|
||||
ResourceUsageTracker.RecordAsync(scope.ServiceProvider.GetRequiredService<ApplicationDbContext>(),
|
||||
"alice", "alice", cpuSeconds: -1m, cancellationToken: TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("ResourceUsage:ApiCallWeight", "0")]
|
||||
[InlineData("ResourceUsage:BandwidthMbWeight", "-1")]
|
||||
[InlineData("ResourceUsage:DefaultLimit", "0")]
|
||||
[InlineData("ResourceUsage:UserLimits:alice", "-1")]
|
||||
public void Invalid_configuration_is_rejected(string key, string value)
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(new Dictionary<string, string?> { [key] = value }).Build();
|
||||
var services = new ServiceCollection().AddResourceUsage(configuration);
|
||||
using var provider = services.BuildServiceProvider();
|
||||
Assert.Throws<OptionsValidationException>(() =>
|
||||
provider.GetRequiredService<IOptions<ResourceUsageOptions>>().Value);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue