using Febe.Core.Abstractions;
using Febe.Core.Domain;
namespace Febe.Core.Engine;
/// Which reduction of the budgets is in force (spec §7.2 avvio graduale, §7.6 tetti dimezzati).
public enum BudgetReduction
{
None,
/// Gradual start: from half to full over the profile's ramp days.
GradualStart,
/// Halved for 48 hours after a throttle stop.
HalvedAfterThrottle,
}
/// The budgets in force at an instant, after the strongest reduction.
/// Hourly and daily budget per category (data excluded).
/// Daily download budget.
/// The profile's per-account backfill limit, reduced as the budgets.
/// Multiplier applied to the profile's values (1 = full).
/// The reduction that determined .
/// When the reduction ends (end of the ramp or of the 48 hours), if any.
public sealed record EffectiveBudgets(
IReadOnlyDictionary Budgets,
long DataPerDayBytes,
int BackfillPostsPerAccountPerDay,
double Factor,
BudgetReduction Reduction,
DateTimeOffset? Until)
{
/// Daily limit of a category (bytes for data).
public long DailyLimit(ActionKind kind) => kind == ActionKind.DataDownload ? DataPerDayBytes : Budgets[kind].PerDay;
/// Hourly limit of a category; null for data, which only has a daily budget.
public long? HourlyLimit(ActionKind kind) => kind == ActionKind.DataDownload ? null : Budgets[kind].PerHour;
}
///
/// Effective budgets (spec §7.4): when several reductions apply together (gradual start, halved budgets after a
/// throttle) the strongest wins, never their product.
///
public static class BudgetLimits
{
/// Gradual start factor: 0.5 at , rising linearly to 1 after the profile's ramp days.
public static double GradualStartFactor(CautionProfile profile, DateTimeOffset? rampStart, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(profile);
if (!profile.GradualStart || rampStart is not { } start || profile.RampUpDays <= 0)
{
return 1;
}
var elapsed = (now - start).TotalDays;
if (elapsed < 0)
{
return 0.5;
}
return elapsed >= profile.RampUpDays ? 1 : 0.5 + (0.5 * elapsed / profile.RampUpDays);
}
/// 0.5 while the 48 hours after a throttle stop last, otherwise 1.
public static double ThrottleFactor(DateTimeOffset? halvedUntil, DateTimeOffset now) =>
halvedUntil is { } until && now < until ? 0.5 : 1;
public static EffectiveBudgets Compute(CautionProfile profile, DateTimeOffset? rampStart, DateTimeOffset? halvedUntil, DateTimeOffset now)
{
ArgumentNullException.ThrowIfNull(profile);
var ramp = GradualStartFactor(profile, rampStart, now);
var throttle = ThrottleFactor(halvedUntil, now);
// The strongest reduction wins, never the product (spec §7.4).
var factor = Math.Min(ramp, throttle);
var reduction = factor >= 1 ? BudgetReduction.None
: throttle <= ramp ? BudgetReduction.HalvedAfterThrottle
: BudgetReduction.GradualStart;
DateTimeOffset? until = reduction switch
{
BudgetReduction.HalvedAfterThrottle => halvedUntil,
BudgetReduction.GradualStart => rampStart?.AddDays(profile.RampUpDays),
_ => null,
};
var budgets = new Dictionary();
foreach (var (kind, budget) in profile.Budgets)
{
budgets[kind] = new Budget(Scale(budget.PerHour, factor), Scale(budget.PerDay, factor));
}
foreach (var kind in Enum.GetValues())
{
if (kind != ActionKind.DataDownload && !budgets.ContainsKey(kind))
{
budgets[kind] = new Budget(0, 0);
}
}
return new EffectiveBudgets(
budgets,
ScaleBytes(profile.DataPerDayBytes, factor),
Scale(profile.BackfillPostsPerAccountPerDay, factor),
factor,
reduction,
until);
}
/// A budget times the factor, rounded down, never below 1 when the full budget is positive.
public static int Scale(int value, double factor) =>
value <= 0 ? 0 : Math.Max(1, (int)Math.Floor((value * factor) + 1e-9));
public static long ScaleBytes(long value, double factor) =>
value <= 0 ? 0 : Math.Max(1, (long)Math.Floor((value * factor) + 1e-6));
}
/// Use of one budget category, for the interface (spec §7.4, §7.9).
/// Category.
/// Actions (bytes for data) of the current local day.
/// Daily limit in force.
/// Actions in the rolling last 60 minutes (null for data).
/// Hourly limit in force (null for data).
public sealed record BudgetStatus(ActionKind Kind, long UsedToday, long LimitToday, long? UsedLastHour, long? LimitPerHour)
{
/// Amber threshold of the interface (spec §7.4).
public const double AmberThreshold = 0.8;
public double DailyRatio => LimitToday <= 0 ? 1 : (double)UsedToday / LimitToday;
public double HourlyRatio => LimitPerHour is not > 0 ? 0 : (double)(UsedLastHour ?? 0) / LimitPerHour.Value;
/// At or above 80% of the daily or of the hourly budget.
public bool IsAmber => DailyRatio >= AmberThreshold || HourlyRatio >= AmberThreshold;
public bool DailyReached => UsedToday >= LimitToday;
public bool HourlyReached => LimitPerHour is { } limit && (UsedLastHour ?? 0) >= limit;
}