File size: 1,934 Bytes
4f2665c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
 * Quota warning state store.
 * Tracks accounts approaching or exceeding quota limits.
 */

export interface QuotaWarning {
  accountId: string;
  email: string | null;
  window: "primary" | "secondary";
  level: "warning" | "critical";
  usedPercent: number;
  resetAt: number | null;
}

const _warnings = new Map<string, QuotaWarning[]>();
let _lastUpdated: string | null = null;

/**
 * Evaluate quota thresholds and return warnings for a single account.
 * Thresholds are sorted ascending; highest matched threshold determines level.
 */
export function evaluateThresholds(
  accountId: string,
  email: string | null,
  usedPercent: number | null,
  resetAt: number | null,
  window: "primary" | "secondary",
  thresholds: number[],
): QuotaWarning | null {
  if (usedPercent == null) return null;
  // Sort ascending
  const sorted = [...thresholds].sort((a, b) => a - b);
  // Find highest matched threshold
  let matchedIdx = -1;
  for (let i = sorted.length - 1; i >= 0; i--) {
    if (usedPercent >= sorted[i]) {
      matchedIdx = i;
      break;
    }
  }
  if (matchedIdx < 0) return null;

  // Highest threshold = critical, others = warning
  const level: "warning" | "critical" =
    matchedIdx === sorted.length - 1 ? "critical" : "warning";

  return { accountId, email, window, level, usedPercent, resetAt };
}

export function updateWarnings(accountId: string, warnings: QuotaWarning[]): void {
  if (warnings.length === 0) {
    _warnings.delete(accountId);
  } else {
    _warnings.set(accountId, warnings);
  }
  _lastUpdated = new Date().toISOString();
}

export function clearWarnings(accountId: string): void {
  _warnings.delete(accountId);
}

export function getActiveWarnings(): QuotaWarning[] {
  const all: QuotaWarning[] = [];
  for (const list of _warnings.values()) {
    all.push(...list);
  }
  return all;
}

export function getWarningsLastUpdated(): string | null {
  return _lastUpdated;
}