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:
Paul Schneider 2026-11-08 05:02:23 +00:00
commit 650e5f5e30
Signed by: notazof
GPG key ID: AD4B9B545FBD7D12
69 changed files with 19111 additions and 203 deletions

View file

@ -166,6 +166,12 @@ namespace Yavsc.Server.Helpers
}
public static FileReceivedInfo ReceiveUserFile(this ApplicationUser user, string root, IFormFile f, string destFileName = null)
{
var name = AbstractFileSystemHelpers.FilterFileName(destFileName ?? f.FileName);
var destination = new FileInfo(Path.Combine(root, name));
var replacedBytes = destination.Exists ? destination.Length : 0L;
var available = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow) - user.DiskUsage + replacedBytes;
if (f.Length > available)
return new FileReceivedInfo(root, name) { QuotaOffense = true };
// f.FileName is parsed by ASP.NET Core from the
// Content-Disposition header: it handles unquoted
// values and the RFC 5987 filename* parameter that
@ -203,6 +209,7 @@ namespace Yavsc.Server.Helpers
// TODO lock user's disk usage for this scope,
// this process is not safe at concurrent access.
long usage = user.DiskUsage;
var quota = user.GetEffectiveDiskQuota(DateTimeOffset.UtcNow);
var item = new FileReceivedInfo
(root, AbstractFileSystemHelpers.FilterFileName(destFileName));
@ -212,8 +219,15 @@ namespace Yavsc.Server.Helpers
item.Overridden = true;
usage -= fi.Length;
}
if (usage >= quota)
{
inputStream.Dispose();
item.QuotaOffense = true;
return item;
}
using (var dest = fi.OpenWrite())
{
dest.SetLength(0);
using (inputStream)
{
const int blen = 1024;
@ -221,16 +235,20 @@ namespace Yavsc.Server.Helpers
int len = 0;
while (!token.IsCancellationRequested && (len = inputStream.Read(buffer, 0, blen)) > 0)
{
if (len > quota - usage)
{
item.QuotaOffense = true;
break;
}
dest.Write(buffer, 0, len);
usage += len;
if (usage >= user.DiskQuota) break;
}
user.DiskUsage = usage;
dest.Close();
inputStream.Close();
}
}
if (usage >= user.DiskQuota)
if (usage > quota)
{
item.QuotaOffense = true;
}

View file

@ -0,0 +1,51 @@
#nullable enable
namespace Yavsc.Server.Helpers;
internal sealed class ResourceUsageCountingStream(Stream inner) : Stream
{
private long _bytesRead;
private long _bytesWritten;
public long BytesRead => Interlocked.Read(ref _bytesRead);
public long BytesWritten => Interlocked.Read(ref _bytesWritten);
public override bool CanRead => inner.CanRead;
public override bool CanSeek => inner.CanSeek;
public override bool CanWrite => inner.CanWrite;
public override long Length => inner.Length;
public override long Position { get => inner.Position; set => inner.Position = value; }
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override long Seek(long offset, SeekOrigin origin) => inner.Seek(offset, origin);
public override void SetLength(long value) => inner.SetLength(value);
public override int Read(byte[] buffer, int offset, int count)
{
var read = inner.Read(buffer, offset, count);
Interlocked.Add(ref _bytesRead, read);
return read;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var read = await inner.ReadAsync(buffer, cancellationToken);
Interlocked.Add(ref _bytesRead, read);
return read;
}
public override void Write(byte[] buffer, int offset, int count)
{
inner.Write(buffer, offset, count);
Interlocked.Add(ref _bytesWritten, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
await inner.WriteAsync(buffer, cancellationToken);
Interlocked.Add(ref _bytesWritten, buffer.Length);
}
}

View file

@ -0,0 +1,26 @@
namespace Yavsc.Server.Helpers;
public static class ResourceUsageCredit
{
public static decimal NetConsumption(decimal gross, decimal credits) => Math.Max(0m, gross - credits);
public static decimal Balance(decimal gross, decimal credits) => Math.Max(0m, credits - gross);
public static decimal MonthlyGrant(decimal gross, decimal existingCredits, decimal allowance)
{
ArgumentOutOfRangeException.ThrowIfNegative(gross);
ArgumentOutOfRangeException.ThrowIfNegative(existingCredits);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(allowance);
var erased = Math.Min(allowance, NetConsumption(gross, existingCredits));
// Round down only the carried credit to the persistence precision.
var carried = decimal.Round((allowance - erased) * 2m / 3m, 8, MidpointRounding.ToZero);
return decimal.Round(erased + carried, 8, MidpointRounding.ToZero);
}
public static int BillingCycle(DateTimeOffset anchor, DateTimeOffset paidAt)
{
if (paidAt < anchor) throw new ArgumentOutOfRangeException(nameof(paidAt));
var cycle = (paidAt.Year - anchor.Year) * 12 + paidAt.Month - anchor.Month;
if (anchor.AddMonths(cycle) > paidAt) cycle--;
return cycle;
}
}

View file

@ -0,0 +1,4 @@
namespace Yavsc.Server.Helpers;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class ResourceUsageExemptAttribute : Attribute;

View file

@ -0,0 +1,98 @@
#nullable enable
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Yavsc.Abstract.Resources;
using Yavsc.Models;
using Yavsc.Settings;
namespace Yavsc.Server.Helpers;
public interface IResourceUsageService
{
Task<ResourceUsageSummary> GetCurrentAsync(string userId, string userName, CancellationToken cancellationToken);
Task<List<ResourceUsageSummary>> GetOverviewAsync(CancellationToken cancellationToken);
Task<bool> TryAdmitAsync(string userId, string userName, decimal apiCalls, decimal bandwidthMb,
long anticipatedStorageBytes, CancellationToken cancellationToken);
}
public sealed class ResourceUsageService(
ApplicationDbContext dbContext,
IOptions<ResourceUsageOptions> options,
TimeProvider? clock = null) : IResourceUsageService
{
private readonly ResourceUsageOptions _options = options.Value;
public async Task<ResourceUsageSummary> GetCurrentAsync(
string userId, string userName, CancellationToken cancellationToken)
{
var record = await ResourceUsageTracker.UpdateAsync(dbContext, userId, userName,
cancellationToken: cancellationToken);
var user = await dbContext.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == userId, cancellationToken);
return ToSummary(record ?? throw new InvalidOperationException("Usage initialization failed."), user);
}
public async Task<List<ResourceUsageSummary>> GetOverviewAsync(CancellationToken cancellationToken)
{
var records = await dbContext.ResourceUsageRecords.AsNoTracking()
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id)
.ToListAsync(cancellationToken);
var ids = records.Select(r => r.UserId).Distinct().ToArray();
var users = await dbContext.Users.AsNoTracking().Where(u => ids.Contains(u.Id)).ToDictionaryAsync(u => u.Id, cancellationToken);
return records.GroupBy(r => r.UserId).Select(g => ToSummary(g.First(), users.GetValueOrDefault(g.Key))).ToList();
}
public async Task<bool> TryAdmitAsync(
string userId, string userName, decimal apiCalls, decimal bandwidthMb,
long anticipatedStorageBytes, CancellationToken cancellationToken)
=> await ResourceUsageTracker.UpdateAsync(dbContext, userId, userName,
apiCalls: apiCalls, bandwidthMb: bandwidthMb,
policy: _options, anticipatedStorageBytes: anticipatedStorageBytes,
cancellationToken: cancellationToken) is not null;
private ResourceUsageSummary ToSummary(ResourceUsageRecord record, ApplicationUser? user)
{
var gross = _options.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
var consumption = ResourceUsageCredit.NetConsumption(gross, record.CreditPoints);
var limit = _options.GetLimit(record.UserId);
return new ResourceUsageSummary
{
UserId = record.UserId,
UserName = record.UserName,
RecordedAtUtc = new DateTimeOffset(DateTime.SpecifyKind(record.RecordedAtUtc, DateTimeKind.Utc)),
ApiCalls = record.ApiCalls,
CpuSeconds = record.CpuSeconds,
BandwidthMb = record.BandwidthMb,
StorageMb = record.StorageMb,
EstimatedCompensation = record.EstimatedCompensation,
Currency = record.Currency,
Consumption = consumption,
GrossConsumption = gross,
CreditBalance = ResourceUsageCredit.Balance(gross, record.CreditPoints),
AppliedCredits = Math.Min(gross, record.CreditPoints),
ConsumptionLimit = limit,
RemainingConsumption = Math.Max(0m, limit - consumption) + ResourceUsageCredit.Balance(gross, record.CreditPoints),
IsQuotaReached = consumption >= limit,
DiskQuota = user?.GetEffectiveDiskQuota((clock ?? TimeProvider.System).GetUtcNow()),
PremiumDiskQuotaUntil = user?.PremiumDiskQuotaUntil,
DiscoveryDiskQuotaUntil = user?.DiscoveryDiskQuotaUntil
};
}
}
public static class ResourceUsageServiceCollectionExtensions
{
public static IServiceCollection AddResourceUsage(this IServiceCollection services, IConfiguration configuration)
{
services.AddOptions<ResourceUsageOptions>()
.Bind(configuration.GetSection(ResourceUsageOptions.SectionName))
.Validate(o => o.ApiCallWeight > 0m && o.CpuSecondWeight >= 0m
&& o.BandwidthMbWeight >= 0m && o.StorageMbWeight >= 0m,
"ResourceUsage weights must be non-negative and ApiCallWeight must be positive.")
.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();
return services.AddScoped<IResourceUsageService, ResourceUsageService>();
}
}

View file

@ -1,54 +1,86 @@
#nullable enable
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Yavsc.Models;
namespace Yavsc.Server.Helpers;
public sealed class ResourceUsageTelemetryMiddleware
public sealed class ResourceUsageTelemetryMiddleware(
RequestDelegate next,
IServiceScopeFactory scopeFactory,
ILogger<ResourceUsageTelemetryMiddleware> logger)
{
private readonly RequestDelegate _next;
private readonly IServiceScopeFactory _scopeFactory;
public ResourceUsageTelemetryMiddleware(
RequestDelegate next,
IServiceScopeFactory scopeFactory)
{
_next = next;
_scopeFactory = scopeFactory;
}
public async Task InvokeAsync(HttpContext context)
public async Task InvokeAsync(HttpContext context, IResourceUsageService usage)
{
var userId = context.User.GetUserId();
if (string.IsNullOrWhiteSpace(userId))
if (string.IsNullOrWhiteSpace(userId) || IsExempt(context))
{
await _next(context);
await next(context);
return;
}
var userName = context.User.Identity?.Name ?? userId;
var requestBytes = context.Request.ContentLength ?? 0L;
if (!await usage.TryAdmitAsync(userId, userName, 1m, ToMb(requestBytes), 0,
context.RequestAborted))
{
logger.LogWarning("Resource quota refused a request for user {UserId}", userId);
await WriteQuotaProblemAsync(context);
return;
}
var originalRequest = context.Request.Body;
var originalResponse = context.Response.Body;
using var request = new ResourceUsageCountingStream(originalRequest);
using var response = new ResourceUsageCountingStream(originalResponse);
context.Request.Body = request;
context.Response.Body = response;
try
{
await _next(context);
await next(context);
}
finally
{
var responseBytes = context.Response.ContentLength ?? 0L;
var totalBytes = requestBytes + responseBytes;
var bandwidthMb = totalBytes <= 0 ? 0m : (decimal)totalBytes / (1024m * 1024m);
using var scope = _scopeFactory.CreateScope();
context.Request.Body = originalRequest;
context.Response.Body = originalResponse;
// Known ingress was charged at admission. Count streamed responses
// and unknown-length ingress once, even on failure or cancellation.
var extraBytes = Math.Max(0L, request.BytesRead - requestBytes) + response.BytesWritten;
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await ResourceUsageTracker.RecordAsync(
db,
userId,
userName,
apiCalls: 1m,
bandwidthMb: bandwidthMb,
actorUserId: userId);
await ResourceUsageTracker.RecordAsync(db, userId, userName,
bandwidthMb: ToMb(extraBytes), actorUserId: userId);
}
}
public static async Task WriteQuotaProblemAsync(HttpContext context)
{
var site = context.RequestServices.GetRequiredService<IOptions<SiteSettings>>().Value;
var termsUrl = new Uri(new Uri(site.Authority.TrimEnd('/') + "/"), "Home/CGU").AbsoluteUri;
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
var problem = new ProblemDetails
{
Status = StatusCodes.Status429TooManyRequests,
Title = "Quota de consommation insuffisant",
Detail = "Cette opération dépasse le quota disponible. Consultez votre consommation ou contactez l'administration.",
Instance = context.Request.Path
};
problem.Extensions["code"] = "resource_quota_exceeded";
problem.Extensions["usagePath"] = Constants.APIPrefix + "/" + Constants.ResourceUsagePath + "/me";
problem.Extensions["termsUrl"] = termsUrl;
problem.Extensions["subscriptionUrl"] = new Uri(new Uri(site.Authority.TrimEnd('/') + "/"), "ResourceSubscription").AbsoluteUri;
await context.Response.WriteAsJsonAsync(problem,
options: null, contentType: "application/problem+json", cancellationToken: context.RequestAborted);
}
private static decimal ToMb(long bytes) => (decimal)bytes / (1024m * 1024m);
private static bool IsExempt(HttpContext context)
=> context.GetEndpoint()?.Metadata.GetMetadata<ResourceUsageExemptAttribute>() is not null
|| context.Request.Path.Equals("/login", StringComparison.OrdinalIgnoreCase)
|| context.Request.Path.Equals("/refresh", StringComparison.OrdinalIgnoreCase)
|| context.Request.Path.Equals("/logout", StringComparison.OrdinalIgnoreCase);
}

View file

@ -1,11 +1,14 @@
#nullable enable
using Microsoft.EntityFrameworkCore;
using Yavsc.Models;
using Yavsc.Settings;
namespace Yavsc.Server.Helpers;
public static class ResourceUsageTracker
{
private static readonly SemaphoreSlim LocalGate = new(1, 1);
public static async Task RecordAsync(
ApplicationDbContext dbContext,
string userId,
@ -15,55 +18,103 @@ public static class ResourceUsageTracker
decimal apiCalls = 0m,
decimal bandwidthMb = 0m,
string? actorUserId = null,
string currency = Constants.ResourceUsageDefaultCurrency)
string currency = Constants.ResourceUsageDefaultCurrency,
CancellationToken cancellationToken = default)
{
if (dbContext is null || string.IsNullOrWhiteSpace(userId))
await UpdateAsync(dbContext, userId, userName, cpuSeconds, storageBytes,
apiCalls, bandwidthMb, actorUserId, currency, cancellationToken: cancellationToken);
}
internal static async Task<ResourceUsageRecord?> UpdateAsync(
ApplicationDbContext dbContext, string userId, string userName,
decimal cpuSeconds = 0m, long storageBytes = 0, decimal apiCalls = 0m,
decimal bandwidthMb = 0m, string? actorUserId = null,
string currency = Constants.ResourceUsageDefaultCurrency,
ResourceUsageOptions? policy = null, long anticipatedStorageBytes = 0,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(dbContext);
ArgumentException.ThrowIfNullOrWhiteSpace(userId);
ArgumentOutOfRangeException.ThrowIfNegative(cpuSeconds);
ArgumentOutOfRangeException.ThrowIfNegative(storageBytes);
ArgumentOutOfRangeException.ThrowIfNegative(apiCalls);
ArgumentOutOfRangeException.ThrowIfNegative(bandwidthMb);
ArgumentOutOfRangeException.ThrowIfNegative(anticipatedStorageBytes);
return await WithUserLockAsync(dbContext, userId, async () =>
{
return;
}
var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId;
var now = DateTime.UtcNow;
var storageMb = (decimal)storageBytes / (1024m * 1024m);
var record = await dbContext.ResourceUsageRecords
.Where(r => r.UserId == userId)
.OrderByDescending(r => r.RecordedAtUtc).ThenByDescending(r => r.Id)
.FirstOrDefaultAsync(cancellationToken);
if (record is not null)
await dbContext.Entry(record).ReloadAsync(cancellationToken);
var effectiveActor = string.IsNullOrWhiteSpace(actorUserId) ? userId : actorUserId;
var now = DateTime.UtcNow;
var storageMb = storageBytes <= 0 ? 0m : (decimal)storageBytes / (1024m * 1024m);
var record = await dbContext.ResourceUsageRecords
.Where(r => r.UserId == userId)
.OrderByDescending(r => r.RecordedAtUtc)
.FirstOrDefaultAsync();
if (record is null)
{
record = new ResourceUsageRecord
if (policy is not null)
{
UserId = userId,
UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName,
RecordedAtUtc = now,
ApiCalls = apiCalls,
CpuSeconds = cpuSeconds,
BandwidthMb = bandwidthMb,
StorageMb = storageMb,
EstimatedCompensation = 0m,
Currency = currency,
UserCreated = effectiveActor,
UserModified = effectiveActor,
DateCreated = now,
DateModified = now,
};
dbContext.ResourceUsageRecords.Add(record);
await dbContext.SaveChangesAsync(effectiveActor);
return;
var gross = record is null ? 0m :
policy.Calculate(record.ApiCalls, record.CpuSeconds, record.BandwidthMb, record.StorageMb);
var current = ResourceUsageCredit.NetConsumption(gross, record?.CreditPoints ?? 0m);
var projected = ResourceUsageCredit.NetConsumption(gross + policy.Calculate(apiCalls, cpuSeconds, bandwidthMb,
storageMb + (decimal)anticipatedStorageBytes / (1024m * 1024m)), record?.CreditPoints ?? 0m);
var limit = policy.GetLimit(userId);
if (current >= limit || projected > limit) return null;
}
if (record is not null && apiCalls == 0m && cpuSeconds == 0m && bandwidthMb == 0m && storageBytes == 0)
return record;
if (record is null)
{
record = new ResourceUsageRecord
{
UserId = userId,
UserName = string.IsNullOrWhiteSpace(userName) ? userId : userName,
Currency = currency,
UserCreated = effectiveActor,
DateCreated = now
};
dbContext.ResourceUsageRecords.Add(record);
}
record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName;
record.RecordedAtUtc = now;
record.ApiCalls += apiCalls;
record.CpuSeconds += cpuSeconds;
record.BandwidthMb += bandwidthMb;
record.StorageMb += storageMb;
record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency;
record.DateModified = now;
record.UserModified = effectiveActor;
await dbContext.SaveChangesAsync(effectiveActor, cancellationToken);
return record;
}, cancellationToken);
}
public static async Task<T> WithUserLockAsync<T>(ApplicationDbContext dbContext, string userId,
Func<Task<T>> action, CancellationToken cancellationToken)
{
// This lock is shared by accounting and subscription credits on all hosts.
var postgres = dbContext.Database.IsNpgsql();
if (!postgres) await LocalGate.WaitAsync(cancellationToken);
try
{
await using var transaction = postgres && dbContext.Database.CurrentTransaction is null
? await dbContext.Database.BeginTransactionAsync(cancellationToken) : null;
if (postgres)
await dbContext.Database.ExecuteSqlInterpolatedAsync(
$"SELECT pg_advisory_xact_lock(hashtextextended({userId}, 781932))", cancellationToken);
var result = await action();
if (transaction is not null) await transaction.CommitAsync(cancellationToken);
return result;
}
finally
{
if (!postgres) LocalGate.Release();
}
record.UserName = string.IsNullOrWhiteSpace(userName) ? record.UserName : userName;
record.RecordedAtUtc = now;
record.ApiCalls += apiCalls;
record.CpuSeconds += cpuSeconds;
record.BandwidthMb += bandwidthMb;
record.StorageMb += storageMb;
record.Currency = string.IsNullOrWhiteSpace(currency) ? record.Currency : currency;
record.DateModified = now;
record.UserModified = effectiveActor;
await dbContext.SaveChangesAsync(effectiveActor);
}
}

View file

@ -96,6 +96,21 @@ namespace Yavsc.Models
entity.HasIndex(r => new { r.UserId, r.RecordedAtUtc });
entity.Property(r => r.Currency).HasMaxLength(8).HasDefaultValue(Constants.ResourceUsageDefaultCurrency);
entity.Property(r => r.UserName).HasMaxLength(256);
entity.Property(r => r.CreditPoints).HasPrecision(28, 8).HasDefaultValue(0m);
});
builder.Entity<ResourceSubscription>(entity =>
{
entity.HasIndex(s => s.PayPalId).IsUnique();
entity.HasIndex(s => s.UserId);
entity.HasOne<ApplicationUser>().WithMany().HasForeignKey(s => s.UserId).OnDelete(DeleteBehavior.Restrict);
entity.Property(s => s.MonthlyPoints).HasPrecision(28, 8);
});
builder.Entity<ResourceSubscriptionPayment>(entity =>
{
entity.HasIndex(p => new { p.SubscriptionId, p.Cycle }).IsUnique();
entity.HasOne<ResourceSubscription>().WithMany().HasForeignKey(p => p.SubscriptionId).OnDelete(DeleteBehavior.Restrict);
entity.Property(p => p.GrantedPoints).HasPrecision(28, 8);
});
// Customize the ASP.NET Identity model and override the defaults if needed.
@ -365,6 +380,8 @@ namespace Yavsc.Models
public DbSet<Estimate> Estimates { get; set; }
public DbSet<Signature> Signatures { get; set; }
public DbSet<ResourceUsageRecord> ResourceUsageRecords { get; set; }
public DbSet<ResourceSubscription> ResourceSubscriptions { get; set; }
public DbSet<ResourceSubscriptionPayment> ResourceSubscriptionPayments { get; set; }
public DbSet<AccountBalance> BankStatus { get; set; }
public DbSet<BalanceImpact> BalanceImpact { get; set; }

View file

@ -93,7 +93,16 @@ namespace Yavsc.Models
public virtual List<BankIdentity>? BankInfo { get; set; }
public long DiskQuota { get; set; } = 512 * 1024 * 1024;
public long DiskQuota { get; set; } = Constants.DefaultFSQ;
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? PremiumDiskQuotaUntil { get; set; }
[JsonIgnore, System.Text.Json.Serialization.JsonIgnore]
public DateTimeOffset? DiscoveryDiskQuotaUntil { get; set; }
public long GetEffectiveDiskQuota(DateTimeOffset now)
=> PremiumDiskQuotaUntil > now ? checked(Constants.DefaultFSQ * 5L)
: DiscoveryDiskQuotaUntil > now ? checked(Constants.DefaultFSQ * 2L) : DiskQuota;
public long DiskUsage { get; set; } = 0;
public long MaxFileSize { get; set; } = 512 * 1024 * 1024;

View file

@ -0,0 +1,41 @@
#nullable enable
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Yavsc.Models.Payment;
public sealed class ResourceSubscription
{
public Guid Id { get; set; }
[MaxLength(450)]
public string UserId { get; set; } = "";
[MaxLength(32)]
public string Pack { get; set; } = "";
[MaxLength(64)]
public string PlanId { get; set; } = "";
[MaxLength(64)]
public string? PayPalId { get; set; }
[MaxLength(32)]
public string State { get; set; } = "CREATING";
public decimal MonthlyPoints { get; set; }
[Column(TypeName = "numeric(18,2)")]
public decimal PriceExcludingTax { get; set; }
public decimal VatPercent { get; set; }
[Column(TypeName = "numeric(18,2)")]
public decimal PriceIncludingTax { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? StartsAt { get; set; }
public DateTimeOffset? NextBillingAt { get; set; }
public int LastCreditedCycle { get; set; } = -1;
}
public sealed class ResourceSubscriptionPayment
{
[MaxLength(64)]
public string Id { get; set; } = "";
public Guid SubscriptionId { get; set; }
public int Cycle { get; set; }
public DateTimeOffset PaidAt { get; set; }
public decimal GrantedPoints { get; set; }
public bool Reversed { get; set; }
}

View file

@ -23,6 +23,7 @@ public sealed class ResourceUsageRecord : ITrackedEntity
public decimal CpuSeconds { get; set; }
public decimal BandwidthMb { get; set; }
public decimal StorageMb { get; set; }
public decimal CreditPoints { get; set; }
public decimal EstimatedCompensation { get; set; }
[Required]

View file

@ -447,13 +447,18 @@ public sealed class LiveProcessor : ILiveProcessor, IDisposable
var path = Path.Combine(destDir, Path.GetFileName(fileName));
var oldLength = File.Exists(path) ? new FileInfo(path).Length : 0;
var usage = user.DiskUsage - oldLength;
if (usage >= user.GetEffectiveDiskQuota(_clock.GetUtcNow()))
{
await handler.Socket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation, "Available quota required.", ct);
return false;
}
await using var file = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
var buffer = new byte[Constants.WebSocketsMaxBufLen];
while (handler.Socket.State == WebSocketState.Open)
{
var received = await handler.Socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
if (received.MessageType == WebSocketMessageType.Close) break;
if (received.MessageType != WebSocketMessageType.Binary || usage + received.Count > user.DiskQuota)
if (received.MessageType != WebSocketMessageType.Binary || usage + received.Count > user.GetEffectiveDiskQuota(_clock.GetUtcNow()))
{
await handler.Socket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation, "Binary data and available quota required.", ct);
return false;

View file

@ -0,0 +1,15 @@
#nullable enable
namespace Yavsc.Settings;
public sealed class ResourceSubscriptionOptions
{
public const string SectionName = "ResourceSubscriptions";
public string DiscoveryPlanId { get; set; } = "";
public string PremiumPlanId { get; set; } = "";
public string WebhookId { get; set; } = "";
public decimal DiscoveryPriceExcludingTax { get; set; } = 1m;
public decimal PremiumPriceExcludingTax { get; set; } = 2m;
public decimal VatPercent { get; set; } = 20m;
public decimal TotalPrice(decimal net) => decimal.Round(net * (1m + VatPercent / 100m), 2, MidpointRounding.AwayFromZero);
}

View file

@ -0,0 +1,21 @@
#nullable enable
namespace Yavsc.Settings;
public sealed class ResourceUsageOptions
{
public const string SectionName = "ResourceUsage";
public decimal ApiCallWeight { get; set; } = 0.2m;
public decimal CpuSecondWeight { get; set; } = 0.1m;
public decimal BandwidthMbWeight { get; set; } = 0.05m;
public decimal StorageMbWeight { get; set; } = 0.5m;
public decimal DefaultLimit { get; set; } = 1000m;
public Dictionary<string, decimal> UserLimits { get; set; } = new();
public decimal GetLimit(string userId)
=> UserLimits.TryGetValue(userId, out var limit) ? limit : DefaultLimit;
public decimal Calculate(decimal apiCalls, decimal cpuSeconds, decimal bandwidthMb, decimal storageMb)
=> apiCalls * ApiCallWeight + cpuSeconds * CpuSecondWeight
+ bandwidthMb * BandwidthMbWeight + storageMb * StorageMbWeight;
}