-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdashboard.ts
More file actions
383 lines (342 loc) · 11.9 KB
/
dashboard.ts
File metadata and controls
383 lines (342 loc) · 11.9 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// src/lib/dashboard.ts
//
// Functions: computeAggregateStats, computeAlerts, detectRankChanges, fetchDismissedKeys,
// postDismissAlert, deleteAllDismissed, computeSystemAlerts
import { findRegistryEntry } from "@/data/tracker-registry"
import { formatDateTime, formatRatio, formatTimeAgo } from "@/lib/formatters"
import { isRedacted } from "@/lib/privacy"
import {
checkAnniversaryMilestone,
checkRatioBelowMinimum,
checkTrackerError,
checkZeroSeeding,
} from "@/lib/tracker-events"
import type { Snapshot, TrackerSummary } from "@/types/api"
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface AggregateStats {
totalUploaded: string
totalDownloaded: string
totalBuffer: string
avgRatio: number | null
totalSeeding: number
totalLeeching: number
}
export const VALID_ALERT_TYPES = new Set([
"error",
"poll-paused",
"ratio-danger",
"stale-data",
"rank-change",
"zero-seeding",
"warned",
"anniversary",
"update-available",
"backup-failed",
"client-error",
"retention-unconfigured",
] as const)
export type AlertType = typeof VALID_ALERT_TYPES extends Set<infer T> ? T : never
export interface DashboardAlert {
key: string
type: AlertType
trackerId: number | null
trackerName: string
trackerColor: string
message: string
timestamp?: string
dismissible: boolean
}
// ---------------------------------------------------------------------------
// computeAggregateStats
// ---------------------------------------------------------------------------
export function computeAggregateStats(trackers: TrackerSummary[]): AggregateStats {
let totalUploaded = BigInt(0)
let totalDownloaded = BigInt(0)
let totalSeeding = 0
let totalLeeching = 0
for (const tracker of trackers) {
if (!tracker.latestStats) continue
const { uploadedBytes, downloadedBytes, seedingCount, leechingCount } = tracker.latestStats
totalUploaded += uploadedBytes ? BigInt(uploadedBytes) : BigInt(0)
totalDownloaded += downloadedBytes ? BigInt(downloadedBytes) : BigInt(0)
totalSeeding += seedingCount ?? 0
totalLeeching += leechingCount ?? 0
}
const totalBuffer = totalUploaded - totalDownloaded
const avgRatio =
totalDownloaded > 0n ? Number((totalUploaded * 1_000_000n) / totalDownloaded) / 1_000_000 : null
return {
totalUploaded: totalUploaded.toString(),
totalDownloaded: totalDownloaded.toString(),
totalBuffer: totalBuffer.toString(),
avgRatio,
totalSeeding,
totalLeeching,
}
}
// ---------------------------------------------------------------------------
// computeAlerts
// ---------------------------------------------------------------------------
export function computeAlerts(trackers: TrackerSummary[]): DashboardAlert[] {
const alerts: DashboardAlert[] = []
for (const tracker of trackers) {
// --- Poll paused (suppresses error alert when paused) ---
const { paused, pausedByUser, hasError } = checkTrackerError(
tracker.lastError,
tracker.pausedAt,
tracker.userPausedAt
)
if (paused && !pausedByUser) {
alerts.push({
key: `poll-paused-${tracker.id}`,
type: "poll-paused",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: "Polling paused after repeated failures — check API key and resume",
timestamp: tracker.pausedAt ?? undefined,
dismissible: false,
})
} else if (hasError) {
const snippet = tracker.lastError?.slice(0, 20).replace(/\s+/g, "_")
alerts.push({
key: `error-${tracker.id}-${snippet}`,
type: "error",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: `Last poll failed: ${tracker.lastError}`,
timestamp: tracker.lastPolledAt ?? undefined,
dismissible: true,
})
}
// --- Ratio danger ---
const registryEntry = findRegistryEntry(tracker.baseUrl)
const minimumRatio = registryEntry?.rules?.minimumRatio
if (checkRatioBelowMinimum(tracker.latestStats?.ratio, minimumRatio)) {
alerts.push({
key: `ratio-danger-${tracker.id}`,
type: "ratio-danger",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: `Ratio ${formatRatio(tracker.latestStats?.ratio)} is below the minimum of ${minimumRatio}`,
timestamp: tracker.lastPolledAt ?? undefined,
dismissible: true,
})
}
// --- Stale data (skip if paused — staleness is expected) ---
if (!tracker.pausedAt && !tracker.userPausedAt && tracker.lastPolledAt) {
const lastPolled = new Date(tracker.lastPolledAt)
const thresholdMs = 2 * 60 * 60 * 1000 // 2 hours
const ageMs = Date.now() - lastPolled.getTime()
if (ageMs > thresholdMs) {
alerts.push({
key: `stale-data-${tracker.id}`,
type: "stale-data",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: `Last polled ${formatTimeAgo(tracker.lastPolledAt)}`,
timestamp: tracker.lastPolledAt,
dismissible: true,
})
}
}
// --- Zero seeding ---
if (checkZeroSeeding(tracker.latestStats?.seedingCount, tracker.isActive)) {
alerts.push({
key: `zero-seeding-${tracker.id}`,
type: "zero-seeding",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: "Seeding 0 torrents — no active seeds",
timestamp: tracker.lastPolledAt ?? undefined,
dismissible: true,
})
}
// --- Warned by tracker ---
if (tracker.latestStats?.warned === true) {
alerts.push({
key: `warned-${tracker.id}`,
type: "warned",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: "You have an active warning on this tracker",
timestamp: tracker.lastPolledAt ?? undefined,
dismissible: true,
})
}
// --- Anniversary ---
const milestone = checkAnniversaryMilestone(tracker.joinedAt)
if (milestone) {
alerts.push({
key: `anniversary-${tracker.id}-${milestone.label}`,
type: "anniversary",
trackerId: tracker.id,
trackerName: tracker.name,
trackerColor: tracker.color,
message: milestone.label,
dismissible: true,
})
}
}
return alerts
}
// ---------------------------------------------------------------------------
// detectRankChanges
// ---------------------------------------------------------------------------
/**
* Detects rank/group changes from snapshot history.
* Only surfaces changes from the last `freshnessDays` days.
* Returns alerts that can be merged with other dashboard alerts.
*/
export function detectRankChanges(
trackers: TrackerSummary[],
snapshotMap: Map<number, Snapshot[]>,
freshnessDays = 7
): DashboardAlert[] {
const alerts: DashboardAlert[] = []
const cutoff = Date.now() - freshnessDays * 24 * 60 * 60 * 1000
for (const t of trackers) {
const snapshots = snapshotMap.get(t.id)
if (!snapshots || snapshots.length < 2) continue
// INVARIANT: snapshots arrive sorted ascending by polledAt from the API
// Walk backwards to find the most recent rank change
for (let i = snapshots.length - 1; i > 0; i--) {
const current = snapshots[i]
const previous = snapshots[i - 1]
// Skip if no group data or redacted (privacy mode)
if (!current.group || !previous.group) continue
if (isRedacted(current.group) || isRedacted(previous.group)) continue
// Skip if same group
if (current.group === previous.group) continue
// Found a rank change. check freshness
const changeTime = new Date(current.polledAt).getTime()
if (changeTime < cutoff) break // Older than freshness window, stop looking
alerts.push({
key: `rank-change-${t.id}-${current.group}`,
type: "rank-change" as AlertType,
trackerId: t.id,
trackerName: t.name,
trackerColor: t.color,
message: `Rank changed: ${previous.group} → ${current.group}`,
timestamp: current.polledAt,
dismissible: true,
})
break // Only report the most recent change per tracker
}
}
return alerts
}
// ---------------------------------------------------------------------------
// Dismissal helpers
// ---------------------------------------------------------------------------
export async function fetchDismissedKeys(): Promise<Set<string>> {
try {
const res = await fetch("/api/alerts/dismissed", {
signal: AbortSignal.timeout(5000),
})
if (!res.ok) return new Set()
const data = (await res.json()) as { keys: string[] }
return new Set(data.keys)
} catch {
// security-audit-ignore: best-effort. dismissed keys default to empty on failure
return new Set()
}
}
export async function postDismissAlert(key: string, type: string): Promise<boolean> {
try {
const res = await fetch("/api/alerts/dismissed", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ key, type }),
signal: AbortSignal.timeout(5000),
})
return res.ok
} catch {
return false
}
}
export async function deleteAllDismissed(): Promise<boolean> {
try {
const res = await fetch("/api/alerts/dismissed", {
method: "DELETE",
signal: AbortSignal.timeout(5000),
})
return res.ok
} catch {
return false
}
}
// ---------------------------------------------------------------------------
// computeSystemAlerts
// ---------------------------------------------------------------------------
export interface SystemAlertData {
latestVersion?: string
currentVersion: string
failedBackups: { createdAt: string }[]
clients: { id: number; name: string; enabled: boolean; lastError: string | null }[]
snapshotRetentionDays: number | null
}
export function computeSystemAlerts(data: SystemAlertData): DashboardAlert[] {
const alerts: DashboardAlert[] = []
// Update available
if (data.latestVersion && data.latestVersion !== data.currentVersion) {
alerts.push({
key: `update-available-${data.latestVersion}`,
type: "update-available",
trackerId: null,
trackerName: "System",
trackerColor: "var(--color-accent)",
message: `Version ${data.latestVersion} is available (current: ${data.currentVersion})`,
dismissible: true,
})
}
// Failed backups (most recent only)
if (data.failedBackups.length > 0) {
const latest = data.failedBackups[0]
alerts.push({
key: `backup-failed-${latest.createdAt}`,
type: "backup-failed",
trackerId: null,
trackerName: "Backups",
trackerColor: "var(--color-danger)",
message: `Scheduled backup failed at ${formatDateTime(latest.createdAt)}`,
timestamp: latest.createdAt,
dismissible: true,
})
}
// DL Client errors (non-dismissible)
for (const client of data.clients) {
if (client.enabled && client.lastError) {
alerts.push({
key: `client-error-${client.id}`,
type: "client-error",
trackerId: null,
trackerName: client.name,
trackerColor: "var(--color-danger)",
message: client.lastError,
dismissible: false,
})
}
}
// Snapshot retention unconfigured
if (data.snapshotRetentionDays === null) {
alerts.push({
key: "retention-unconfigured",
type: "retention-unconfigured",
trackerId: null,
trackerName: "System",
trackerColor: "var(--color-warn)",
message:
"Snapshot retention is not configured — database and backups will grow indefinitely. Configure in Settings > Security.",
dismissible: true,
})
}
return alerts
}