using Febe.Core.Abstractions; using Febe.Core.Domain; using Febe.Core.Engine; using Febe.Core.Storage; namespace Febe.Tests.Engine.Support; /// /// Independent check of the budgets from action_log: at every action, the rolling hour and the local day so far /// must stay within the profile's full limits (reductions only make them lower). /// internal static class BudgetAudit { private static readonly TimeSpan Hour = TimeSpan.FromMinutes(60); public static async Task> OverrunsAsync(IFebeStorage storage, CautionProfile profile, TimeZoneInfo zone, DateTimeOffset from, DateTimeOffset to) { var actions = await storage.ActionLog.ListAsync(from, to); var problems = new List(); foreach (var kind in Enum.GetValues()) { var list = actions.Where(a => a.Category == kind).OrderBy(a => a.At).ThenBy(a => a.Id).ToList(); var first = 0; long hour = 0; long day = 0; DateOnly? current = null; foreach (var action in list) { hour += action.Amount; while (list[first].At <= action.At - Hour) { hour -= list[first].Amount; first++; } var today = LocalCalendar.Today(action.At, zone); if (today != current) { current = today; day = 0; } day += action.Amount; var over = kind == ActionKind.DataDownload ? day > profile.DataPerDayBytes : hour > profile.Budgets[kind].PerHour || day > profile.Budgets[kind].PerDay; if (over) { problems.Add($"{kind} at {action.At:O}: hour {hour}, day {day}"); } } } return problems; } /// Actions (data excluded) that fall outside the active window of their day. public static async Task> OutsideWindowAsync(IFebeStorage storage, DayPlanner planner, DateTimeOffset from, DateTimeOffset to) { var outside = new List(); foreach (var action in (await storage.ActionLog.ListAsync(from, to)).Where(a => a.Category != ActionKind.DataDownload)) { if (await planner.GetWindowAtAsync(action.At) is null) { outside.Add(action); } } return outside; } }