forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker-scheduler.ts
More file actions
731 lines (672 loc) · 25.3 KB
/
Copy pathtracker-scheduler.ts
File metadata and controls
731 lines (672 loc) · 25.3 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// src/lib/tracker-scheduler.ts
//
// Functions: pollTracker, pollAllTrackers, pruneOldSnapshots, pruneOldCheckpoints,
// startScheduler, stopScheduler, ensureSchedulerRunning, fetchTrackerStats, POLL_FAILURE_THRESHOLD
// Constants: POLL_TRACKER_COLUMNS
import type { Agent as HttpAgent } from "node:http"
import { and, desc, eq, isNotNull, lt, notInArray, sql } from "drizzle-orm"
import cron, { type ScheduledTask } from "node-cron"
import { findRegistryEntry } from "@/data/tracker-registry"
import { buildFetchOptions, getAdapter } from "@/lib/adapters"
import type {
AvistazPlatformMeta,
DigitalCorePlatformMeta,
MamPlatformMeta,
} from "@/lib/adapters/types"
import { pruneDismissedAlerts } from "@/lib/alert-pruning"
import { decrypt } from "@/lib/crypto"
import { db } from "@/lib/db"
import type { NotificationTargetRow, TrackerRow } from "@/lib/db/schema"
import {
appSettings,
notificationTargets,
torrentDailyCheckpoints,
trackerDailyCheckpoints,
trackerSnapshots,
trackers,
} from "@/lib/db/schema"
import { errMsg, sanitizeNetworkError } from "@/lib/error-utils"
import { localDateStr } from "@/lib/formatters"
import { POLL_INTERVAL_DEFAULT } from "@/lib/limits"
import { log } from "@/lib/logger"
import { dispatchNotifications } from "@/lib/notifications/dispatch"
import { maskUsername } from "@/lib/privacy"
import { recordDatabaseSize } from "@/lib/server-data"
import { getPauseState } from "@/lib/tracker-status"
import { buildProxyAgentFromSettings } from "@/lib/tunnel"
// Store on globalThis to survive HMR in development.
// Without this, each hot-reload orphans the old cron job (it keeps firing)
// while creating a new one which causes duplicate polls that hammer tracker APIs.
const g = globalThis as typeof globalThis & {
__schedulerTask?: ScheduledTask | null
__schedulerKey?: Buffer | null
__pollInFlight?: boolean
}
function getSchedulerTask(): ScheduledTask | null {
return g.__schedulerTask ?? null
}
function setSchedulerTask(task: ScheduledTask | null) {
g.__schedulerTask = task
}
function getSchedulerKey(): Buffer | null {
return g.__schedulerKey ?? null
}
function setSchedulerKey(key: Buffer | null) {
g.__schedulerKey = key
}
function getPollInFlight(): boolean {
return g.__pollInFlight ?? false
}
function setPollInFlight(v: boolean) {
g.__pollInFlight = v
}
/** Columns needed for poll cycle. Excludes avatarData (~5MB), avatarMimeType, avatarCachedAt, color, qbtTag, etc. */
const POLL_TRACKER_COLUMNS = {
id: trackers.id,
name: trackers.name,
isActive: trackers.isActive,
encryptedApiToken: trackers.encryptedApiToken,
platformType: trackers.platformType,
baseUrl: trackers.baseUrl,
apiPath: trackers.apiPath,
useProxy: trackers.useProxy,
remoteUserId: trackers.remoteUserId,
platformMeta: trackers.platformMeta,
joinedAt: trackers.joinedAt,
lastPolledAt: trackers.lastPolledAt,
lastError: trackers.lastError,
lastErrorAt: trackers.lastErrorAt,
consecutiveFailures: trackers.consecutiveFailures,
pausedAt: trackers.pausedAt,
userPausedAt: trackers.userPausedAt,
updatedAt: trackers.updatedAt,
} as const
export const POLL_FAILURE_THRESHOLD = 4
/**
* Tolerance window for the overdue check. Trackers that would become overdue
* within this window are included in the current batch instead of waiting for
* the next cron cycle. Prevents permanent drift caused by manual polls or
* missed batches from keeping a tracker in its own solo cycle forever.
*/
const BATCH_TOLERANCE_MS = 60_000
/**
* Fetch fresh stats from a tracker's API without writing a snapshot.
* Used by the (currently unreleased) transit papers report route to get live data for the report.
* Also updates tracker metadata side effects (remoteUserId, joinedAt, lastAccessAt, platformMeta, avatarUrl).
*/
export async function fetchTrackerStats(
trackerId: number,
encryptionKey: Buffer,
proxyAgent?: HttpAgent
) {
const [tracker] = await db
.select(POLL_TRACKER_COLUMNS)
.from(trackers)
.where(eq(trackers.id, trackerId))
.limit(1)
if (!tracker?.isActive) throw new Error("Tracker not found or inactive")
let apiToken: string
try {
apiToken = decrypt(tracker.encryptedApiToken, encryptionKey)
} catch (err) {
const cause = errMsg(err)
throw new Error(`API key is missing or invalid for tracker "${tracker.name}": ${cause}`)
}
const adapter = getAdapter(tracker.platformType)
if (tracker.useProxy && !proxyAgent) {
throw new Error("Proxy required but not available, refusing to leak IP via direct connection")
}
const fetchOptions = buildFetchOptions(tracker.baseUrl, {
proxyAgent: tracker.useProxy ? proxyAgent : undefined,
remoteUserId: tracker.remoteUserId ?? undefined,
})
const stats = await adapter.fetchStats(tracker.baseUrl, apiToken, tracker.apiPath, fetchOptions)
// Write metadata side effects
const metaUpdates: Partial<TrackerRow> = {}
if (stats.remoteUserId && stats.remoteUserId !== tracker.remoteUserId) {
metaUpdates.remoteUserId = stats.remoteUserId
}
if (stats.joinedDate && !tracker.joinedAt) {
const parsed = new Date(stats.joinedDate)
if (!Number.isNaN(parsed.getTime())) metaUpdates.joinedAt = localDateStr(parsed)
}
if (stats.lastAccessDate) {
const parsed = new Date(stats.lastAccessDate)
if (!Number.isNaN(parsed.getTime())) metaUpdates.lastAccessAt = localDateStr(parsed)
}
if (stats.platformMeta) metaUpdates.platformMeta = JSON.stringify(stats.platformMeta)
if (stats.avatarUrl) metaUpdates.avatarRemoteUrl = stats.avatarUrl
if (Object.keys(metaUpdates).length > 0) {
await db.update(trackers).set(metaUpdates).where(eq(trackers.id, tracker.id))
}
// Merge metadata in-memory instead of re-fetching
return { stats, tracker: { ...tracker, ...metaUpdates } }
}
export async function pollTracker(
trackerId: number,
encryptionKey: Buffer,
privacyMode: boolean,
proxyAgent?: HttpAgent,
batchTimestamp?: Date,
enabledTargets?: NotificationTargetRow[],
isManual = false
): Promise<void> {
const [tracker] = await db
.select(POLL_TRACKER_COLUMNS)
.from(trackers)
.where(eq(trackers.id, trackerId))
.limit(1)
if (!tracker?.isActive) return
const timestamp = batchTimestamp ?? new Date()
try {
let apiToken: string
try {
apiToken = decrypt(tracker.encryptedApiToken, encryptionKey)
} catch (err) {
const cause = errMsg(err)
throw new Error(`API key is missing or invalid for tracker "${tracker.name}": ${cause}`)
}
const adapter = getAdapter(tracker.platformType)
if (tracker.useProxy && !proxyAgent) {
throw new Error("Proxy required but not available, refusing to leak IP via direct connection")
}
const fetchOptions = buildFetchOptions(tracker.baseUrl, {
proxyAgent: tracker.useProxy ? proxyAgent : undefined,
remoteUserId: tracker.remoteUserId ?? undefined,
})
const stats = await adapter.fetchStats(tracker.baseUrl, apiToken, tracker.apiPath, fetchOptions)
// Snapshot the previous platformMeta BEFORE writing the current poll's metadata to DB.
// dispatchNotifications uses this for change detection (i.e. canDownload transition).
let previousPlatformMeta: Record<string, unknown> | null = null
if (
(tracker.platformType === "avistaz" || tracker.platformType === "digitalcore") &&
tracker.platformMeta
) {
try {
previousPlatformMeta = JSON.parse(tracker.platformMeta) as Record<string, unknown>
} catch (err) {
log.warn(
{ trackerId: tracker.id, error: err instanceof Error ? err.message : "unknown" },
"failed to parse previous platformMeta"
)
}
}
// Cache metadata from poll (remoteUserId saves an API call, joinedDate/platformMeta enrich the UI)
const metaUpdates: Record<string, unknown> = {}
if (stats.remoteUserId && stats.remoteUserId !== tracker.remoteUserId) {
metaUpdates.remoteUserId = stats.remoteUserId
}
if (stats.joinedDate && !tracker.joinedAt) {
const parsed = new Date(stats.joinedDate)
if (!Number.isNaN(parsed.getTime())) {
metaUpdates.joinedAt = localDateStr(parsed)
}
}
if (stats.lastAccessDate) {
const parsed = new Date(stats.lastAccessDate)
if (!Number.isNaN(parsed.getTime())) {
metaUpdates.lastAccessAt = localDateStr(parsed)
}
}
if (stats.platformMeta) {
metaUpdates.platformMeta = JSON.stringify(stats.platformMeta)
}
if (stats.avatarUrl) {
metaUpdates.avatarRemoteUrl = stats.avatarUrl
}
if (Object.keys(metaUpdates).length > 0) {
await db.update(trackers).set(metaUpdates).where(eq(trackers.id, tracker.id))
}
// Fetch previous snapshot before inserting the new one (used for change detection in notifications)
const [previousSnapshot] = await db
.select({
ratio: trackerSnapshots.ratio,
hitAndRuns: trackerSnapshots.hitAndRuns,
bufferBytes: trackerSnapshots.bufferBytes,
warned: trackerSnapshots.warned,
group: trackerSnapshots.group,
seedingCount: trackerSnapshots.seedingCount,
seedbonus: trackerSnapshots.seedbonus,
})
.from(trackerSnapshots)
.where(eq(trackerSnapshots.trackerId, tracker.id))
.orderBy(desc(trackerSnapshots.polledAt))
.limit(1)
await db.insert(trackerSnapshots).values({
trackerId: tracker.id,
polledAt: timestamp,
uploadedBytes: stats.uploadedBytes,
downloadedBytes: stats.downloadedBytes,
ratio: stats.ratio,
bufferBytes: stats.bufferBytes,
seedingCount: stats.seedingCount,
leechingCount: stats.leechingCount,
seedbonus: stats.seedbonus,
hitAndRuns: stats.hitAndRuns,
requiredRatio: stats.requiredRatio,
warned: stats.warned,
freeleechTokens: stats.freeleechTokens,
shareScore: stats.shareScore ?? null,
username: privacyMode ? maskUsername(stats.username) : stats.username,
group: privacyMode ? maskUsername(stats.group) : stats.group,
isManual,
})
try {
// Upsert daily checkpoint for "Today At A Glance" comparisons
const checkpointDate = localDateStr(timestamp)
await db
.insert(trackerDailyCheckpoints)
.values({
trackerId: tracker.id,
checkpointDate,
uploadedBytesEnd: stats.uploadedBytes !== null ? BigInt(stats.uploadedBytes) : 0n,
downloadedBytesEnd: stats.downloadedBytes !== null ? BigInt(stats.downloadedBytes) : 0n,
bufferBytesEnd: stats.bufferBytes !== null ? BigInt(stats.bufferBytes) : null,
ratioEnd: stats.ratio,
seedbonusEnd: stats.seedbonus,
snapshotCount: 1,
})
.onConflictDoUpdate({
target: [trackerDailyCheckpoints.trackerId, trackerDailyCheckpoints.checkpointDate],
set: {
uploadedBytesEnd: stats.uploadedBytes !== null ? BigInt(stats.uploadedBytes) : 0n,
downloadedBytesEnd: stats.downloadedBytes !== null ? BigInt(stats.downloadedBytes) : 0n,
bufferBytesEnd: stats.bufferBytes !== null ? BigInt(stats.bufferBytes) : null,
ratioEnd: stats.ratio,
seedbonusEnd: stats.seedbonus,
snapshotCount: sql`${trackerDailyCheckpoints.snapshotCount} + 1`,
},
})
} catch (checkpointErr) {
log.warn(
`Daily checkpoint upsert failed for tracker ${tracker.id}: ${checkpointErr instanceof Error ? checkpointErr.message : "Unknown"}`
)
}
try {
const mamMeta =
tracker.platformType === "mam"
? (stats.platformMeta as MamPlatformMeta | undefined)
: undefined
const avistazMeta =
tracker.platformType === "avistaz"
? (stats.platformMeta as AvistazPlatformMeta | undefined)
: undefined
const dcMeta =
tracker.platformType === "digitalcore"
? (stats.platformMeta as DigitalCorePlatformMeta | undefined)
: undefined
await dispatchNotifications(
{
trackerId: tracker.id,
trackerName: tracker.name,
storeUsernames: privacyMode === false,
currentRatio: stats.ratio,
previousRatio: previousSnapshot?.ratio ?? null,
currentHnrs: stats.hitAndRuns,
previousHnrs: previousSnapshot?.hitAndRuns ?? null,
currentBufferBytes: stats.bufferBytes,
previousBufferBytes: previousSnapshot?.bufferBytes ?? null,
trackerDown: false,
trackerError: null,
currentWarned: stats.warned ?? null,
previousWarned: previousSnapshot?.warned ?? null,
currentSeedingCount: stats.seedingCount ?? null,
currentGroup: stats.group ?? null,
previousGroup: previousSnapshot?.group ?? null,
trackerIsActive: tracker.isActive,
trackerPausedAt: null,
trackerJoinedAt: tracker.joinedAt ?? null,
minimumRatio: findRegistryEntry(tracker.baseUrl)?.rules?.minimumRatio,
platformContext:
tracker.platformType === "mam"
? {
currentSeedbonus: stats.seedbonus ?? null,
previousSeedbonus: previousSnapshot?.seedbonus ?? null,
vipUntil: mamMeta?.vipUntil ?? null,
unsatisfiedCount: mamMeta?.unsatisfiedCount ?? null,
unsatisfiedLimit: mamMeta?.unsatisfiedLimit ?? null,
inactiveHnrCount: stats.hitAndRuns ?? null,
previousInactiveHnrCount: previousSnapshot?.hitAndRuns ?? null,
canDownload: null,
previousCanDownload: null,
}
: tracker.platformType === "avistaz"
? {
currentSeedbonus: stats.seedbonus ?? null,
previousSeedbonus: previousSnapshot?.seedbonus ?? null,
vipUntil: avistazMeta?.vipExpiry ?? null,
unsatisfiedCount: null,
unsatisfiedLimit: null,
inactiveHnrCount: null,
previousInactiveHnrCount: null,
canDownload: avistazMeta?.canDownload ?? null,
previousCanDownload:
(previousPlatformMeta?.canDownload as boolean | null) ?? null,
}
: tracker.platformType === "digitalcore"
? {
currentSeedbonus: stats.seedbonus ?? null,
previousSeedbonus: previousSnapshot?.seedbonus ?? null,
vipUntil: null,
unsatisfiedCount: null,
unsatisfiedLimit: null,
inactiveHnrCount: null,
previousInactiveHnrCount: null,
canDownload:
dcMeta?.downloadBan === true
? false
: dcMeta?.downloadBan === false
? true
: null,
previousCanDownload:
previousPlatformMeta?.downloadBan === true
? false
: previousPlatformMeta?.downloadBan === false
? true
: null,
}
: undefined,
},
encryptionKey,
enabledTargets
)
} catch (err) {
log.error(
`Notification dispatch failed for ${tracker.name}: ${err instanceof Error ? err.message : "Unknown"}`
)
}
const wasPaused = !!tracker.pausedAt
const hadFailures = tracker.consecutiveFailures > 0
await db
.update(trackers)
.set({
lastPolledAt: timestamp,
lastError: null,
lastErrorAt: null,
consecutiveFailures: 0,
pausedAt: null,
updatedAt: timestamp,
})
.where(eq(trackers.id, tracker.id))
if (wasPaused || hadFailures) {
log.info(
{
trackerId: tracker.id,
trackerName: tracker.name,
previousFailures: tracker.consecutiveFailures,
wasPaused,
source: isManual ? "manual" : "scheduled",
},
"circuit breaker reset by successful poll"
)
}
} catch (error) {
const raw = error instanceof Error ? error.message : "Unknown error"
const message = sanitizeNetworkError(raw, "Poll failed")
log.error(
{
trackerId,
trackerName: tracker?.name,
source: isManual ? "manual" : "scheduled",
previousFailures: tracker?.consecutiveFailures ?? "unknown",
},
`Poll failed for tracker ${trackerId}: ${message}`
)
try {
const now = new Date()
const [updated] = await db
.update(trackers)
.set({
lastError: message,
lastErrorAt: now,
consecutiveFailures: sql`${trackers.consecutiveFailures} + 1`,
pausedAt: sql`CASE WHEN ${trackers.consecutiveFailures} + 1 >= ${POLL_FAILURE_THRESHOLD} THEN ${now.toISOString()}::timestamp ELSE ${trackers.pausedAt} END`,
updatedAt: now,
})
.where(eq(trackers.id, trackerId))
.returning({
consecutiveFailures: trackers.consecutiveFailures,
pausedAt: trackers.pausedAt,
})
if (updated?.pausedAt) {
log.warn(
{
trackerId,
trackerName: tracker?.name,
consecutiveFailures: updated.consecutiveFailures,
threshold: POLL_FAILURE_THRESHOLD,
lastError: message,
},
`Tracker ${trackerId} auto-paused after ${updated.consecutiveFailures} consecutive failures`
)
} else if (updated) {
log.info(
{
trackerId,
consecutiveFailures: updated.consecutiveFailures,
threshold: POLL_FAILURE_THRESHOLD,
},
`Poll failure ${updated.consecutiveFailures}/${POLL_FAILURE_THRESHOLD} for tracker ${trackerId}`
)
}
} catch (dbError) {
log.error(dbError, `Failed to record poll failure for tracker ${trackerId}`)
}
try {
await dispatchNotifications(
{
trackerId: tracker?.id ?? trackerId,
trackerName: tracker?.name ?? String(trackerId),
storeUsernames: false,
currentRatio: null,
previousRatio: null,
currentHnrs: null,
previousHnrs: null,
currentBufferBytes: null,
previousBufferBytes: null,
trackerDown: true,
trackerError: message,
currentWarned: null,
previousWarned: null,
currentSeedingCount: null,
currentGroup: null,
previousGroup: null,
trackerIsActive: tracker?.isActive ?? true,
trackerPausedAt: tracker?.pausedAt?.toISOString() ?? null,
trackerJoinedAt: tracker?.joinedAt ?? null,
minimumRatio: undefined,
platformContext: undefined,
},
encryptionKey,
enabledTargets
)
} catch (err) {
log.warn(
{
trackerId: tracker?.id ?? trackerId,
error: errMsg(err),
},
"Error-path notification dispatch failed"
)
}
}
}
export async function pruneOldSnapshots(retentionDays: number): Promise<number> {
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000)
const deleted = await db
.delete(trackerSnapshots)
.where(
and(
lt(trackerSnapshots.polledAt, cutoff),
notInArray(
trackerSnapshots.trackerId,
db.select({ id: trackers.id }).from(trackers).where(isNotNull(trackers.userPausedAt))
)
)
)
.returning({ id: trackerSnapshots.id })
return deleted.length
}
export async function pruneOldCheckpoints(retentionDays: number): Promise<number> {
const cutoffDate = localDateStr(Date.now() - retentionDays * 24 * 60 * 60 * 1000)
const [deletedTracker, deletedTorrent] = await Promise.all([
db
.delete(trackerDailyCheckpoints)
.where(lt(trackerDailyCheckpoints.checkpointDate, cutoffDate))
.returning({ id: trackerDailyCheckpoints.id }),
db
.delete(torrentDailyCheckpoints)
.where(lt(torrentDailyCheckpoints.checkpointDate, cutoffDate))
.returning({ id: torrentDailyCheckpoints.id }),
])
return deletedTracker.length + deletedTorrent.length
}
export async function pollAllTrackers(encryptionKey: Buffer): Promise<void> {
// Query settings first; global interval is needed for overdue filtering
const [settings] = await db
.select({
storeUsernames: appSettings.storeUsernames,
snapshotRetentionDays: appSettings.snapshotRetentionDays,
trackerPollIntervalMinutes: appSettings.trackerPollIntervalMinutes,
proxyEnabled: appSettings.proxyEnabled,
proxyType: appSettings.proxyType,
proxyHost: appSettings.proxyHost,
proxyPort: appSettings.proxyPort,
proxyUsername: appSettings.proxyUsername,
encryptedProxyPassword: appSettings.encryptedProxyPassword,
})
.from(appSettings)
.limit(1)
const globalIntervalMs =
(settings?.trackerPollIntervalMinutes ?? POLL_INTERVAL_DEFAULT) * 60 * 1000
const allTrackers = await db
.select(POLL_TRACKER_COLUMNS)
.from(trackers)
.where(eq(trackers.isActive, true))
const now = Date.now()
const overdue = allTrackers.filter((tracker) => {
const pause = getPauseState(tracker)
if (pause.isPaused) {
log.debug(
{
tracker: tracker.name,
reason: pause.reason,
consecutiveFailures: tracker.consecutiveFailures,
pausedAt: tracker.pausedAt?.toISOString() ?? null,
userPausedAt: tracker.userPausedAt?.toISOString() ?? null,
},
"skipping paused tracker"
)
return false
}
const lastPoll = tracker.lastPolledAt?.getTime() ?? 0
return now - lastPoll >= globalIntervalMs - BATCH_TOLERANCE_MS
})
if (overdue.length === 0) return
const privacyMode = settings ? !settings.storeUsernames : false
// Build proxy agent once for all trackers that need it
const proxyAgent = settings ? buildProxyAgentFromSettings(settings, encryptionKey) : undefined
// Fetch notification targets once for the entire poll cycle (avoids N identical queries)
let enabledNotificationTargets: NotificationTargetRow[] = []
try {
enabledNotificationTargets = await db
.select()
.from(notificationTargets)
.where(eq(notificationTargets.enabled, true))
} catch (err) {
log.error(
`pollAllTrackers: failed to fetch notification targets: ${err instanceof Error ? err.message : "Unknown"}`
)
}
// Capture a single timestamp for the whole batch so all snapshots in one
// cycle share the same polledAt value, simplifying time-series queries
const batchTimestamp = new Date()
// Poll all overdue trackers in parallel so one slow tracker won't block the rest
await Promise.allSettled(
overdue.map((tracker) =>
pollTracker(
tracker.id,
encryptionKey,
privacyMode,
proxyAgent,
batchTimestamp,
enabledNotificationTargets
)
)
)
// Prune old snapshots if retention is configured in app settings
if (settings?.snapshotRetentionDays && settings.snapshotRetentionDays > 0) {
try {
const pruned = await pruneOldSnapshots(settings.snapshotRetentionDays)
if (pruned > 0) {
log.info(`Pruned ${pruned} snapshots older than ${settings.snapshotRetentionDays} days`)
}
} catch (error) {
log.error(error, "Snapshot pruning failed")
}
try {
const prunedCheckpoints = await pruneOldCheckpoints(settings.snapshotRetentionDays)
if (prunedCheckpoints > 0) {
log.info(
`Pruned ${prunedCheckpoints} checkpoint rows older than ${settings.snapshotRetentionDays} days`
)
}
} catch (error) {
log.error(error, "Checkpoint pruning failed")
}
}
// Record daily database size for storage chart
try {
await recordDatabaseSize()
} catch (error) {
log.error(error, "Database size recording failed")
}
// Prune expired dismissed alerts (stale-data and zero-seeding types expire after 24h)
try {
await pruneDismissedAlerts()
} catch (error) {
log.error(error, "Dismissed alerts pruning failed")
}
}
export function startTrackerPolling(encryptionKey: Buffer): void {
if (getSchedulerTask()) return
setSchedulerKey(encryptionKey)
// Poll immediately on start, don't wait for first 5-minute tick
pollAllTrackers(encryptionKey).catch((error) => {
log.error(error, "Initial poll error")
})
// Then check every 5 minutes for overdue trackers
const task = cron.schedule("*/5 * * * *", async () => {
if (getPollInFlight()) return
setPollInFlight(true)
try {
await pollAllTrackers(encryptionKey)
} catch (error) {
log.error(error, "Scheduler error")
} finally {
setPollInFlight(false)
}
})
setSchedulerTask(task)
log.info("Tracker polling started (checking every 5 minutes)")
}
export function stopTrackerPolling(): void {
const task = getSchedulerTask()
if (task) {
task.stop()
setSchedulerTask(null)
}
// Zero-fill the encryption key buffer to prevent it from lingering in memory
const key = getSchedulerKey()
if (key) {
key.fill(0)
setSchedulerKey(null)
}
}
export function isTrackerPollingRunning(): boolean {
return getSchedulerTask() !== null
}
/** Exposed for testing. Returns the raw schedulerKey buffer reference. */
export function _getSchedulerKeyForTest(): Buffer | null {
return getSchedulerKey()
}