forked from jordanlambrecht/tracker-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup-scheduler.ts
More file actions
177 lines (156 loc) · 5.17 KB
/
backup-scheduler.ts
File metadata and controls
177 lines (156 loc) · 5.17 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
// src/lib/backup-scheduler.ts
//
// Functions: startBackupScheduler, stopBackupScheduler, runScheduledBackup
import { mkdir, writeFile } from "node:fs/promises"
import path from "node:path"
import cron, { type ScheduledTask } from "node-cron"
import {
encryptBackupPayload,
generateBackupPayload,
pruneOldBackups,
resolveBackupPassword,
} from "@/lib/backup"
import { db } from "@/lib/db"
import { appSettings, backupHistory } from "@/lib/db/schema"
import { log } from "@/lib/logger"
// Store on globalThis to survive HMR in development.
// Without this, each hot-reload orphans the old cron job while creating a new one.
const g = globalThis as typeof globalThis & {
__backupSchedulerTask?: ScheduledTask | null
__backupSchedulerKey?: Buffer | null
}
function getBackupTask(): ScheduledTask | null {
return g.__backupSchedulerTask ?? null
}
function setBackupTask(task: ScheduledTask | null) {
g.__backupSchedulerTask = task
}
function getBackupKey(): Buffer | null {
return g.__backupSchedulerKey ?? null
}
function setBackupKey(key: Buffer | null) {
g.__backupSchedulerKey = key
}
// Cron expressions for backup frequencies (run at 03:00)
function getCronExpression(frequency: string): string {
switch (frequency) {
case "daily":
return "0 3 * * *" // 03:00 every day
case "weekly":
return "0 3 * * 0" // 03:00 every Sunday
case "monthly":
return "0 3 1 * *" // 03:00 first of month
default:
log.warn(`Unknown backup frequency "${frequency}", defaulting to daily`)
return "0 3 * * *"
}
}
export async function runScheduledBackup(encryptionKey: Buffer): Promise<void> {
const [settings] = await db.select().from(appSettings).limit(1)
if (!settings) return
const storagePath = settings.backupStoragePath ?? "/data/backups"
const retentionCount = settings.backupRetentionCount
try {
const payload = await generateBackupPayload()
// Encrypt if enabled and a backup password is stored
let serialized: string
let ext: string
let encrypted = false
if (settings.backupEncryptionEnabled && settings.encryptedBackupPassword) {
try {
const backupPassword = resolveBackupPassword(
true,
settings.encryptedBackupPassword,
encryptionKey
)
if (!backupPassword) throw new Error("resolveBackupPassword returned null unexpectedly")
const envelope = await encryptBackupPayload(payload, backupPassword)
serialized = JSON.stringify(envelope)
ext = "ttbak"
encrypted = true
} catch {
log.error(
"Scheduled backup aborted: cannot decrypt stored backup password. " +
"Re-enter backup password in settings to resume encrypted backups."
)
await db.insert(backupHistory).values({
sizeBytes: 0,
encrypted: false,
frequency: settings.backupScheduleFrequency,
status: "failed",
storagePath: null,
})
return
}
} else {
serialized = JSON.stringify(payload)
ext = "json"
}
await mkdir(storagePath, { recursive: true })
const timestamp = new Date().toISOString().replace(/[:.]/g, "-")
const filename = `tracker-tracker-backup-${timestamp}.${ext}`
const filePath = path.join(storagePath, filename)
await writeFile(filePath, serialized, "utf8")
const sizeBytes = Buffer.byteLength(serialized, "utf8")
await db.insert(backupHistory).values({
sizeBytes,
encrypted,
frequency: settings.backupScheduleFrequency,
status: "completed",
storagePath: filePath,
})
log.info(`Scheduled backup saved: ${filePath} (${sizeBytes} bytes)`)
await pruneOldBackups(retentionCount, storagePath)
} catch (error) {
log.error(error, "Scheduled backup failed")
try {
await db.insert(backupHistory).values({
sizeBytes: 0,
encrypted: false,
frequency: settings.backupScheduleFrequency,
status: "failed",
storagePath: null,
notes: error instanceof Error ? error.message : "Unknown error",
})
} catch (historyError) {
log.error(historyError, "Failed to record backup failure")
}
}
}
export function startBackupScheduler(encryptionKey: Buffer): void {
if (getBackupTask()) return
db.select()
.from(appSettings)
.limit(1)
.then(([settings]) => {
if (!settings?.backupScheduleEnabled) return
setBackupKey(Buffer.from(encryptionKey))
const cronExpr = getCronExpression(settings.backupScheduleFrequency)
const task = cron.schedule(cronExpr, async () => {
const key = getBackupKey()
if (!key) return
try {
await runScheduledBackup(key)
} catch (error) {
log.error(error, "Backup scheduler error")
}
})
setBackupTask(task)
log.info(`Backup scheduler started (${settings.backupScheduleFrequency} at 03:00)`)
})
.catch((err) => {
log.error(err, "Failed to initialize backup scheduler")
})
}
export function stopBackupScheduler(): void {
const task = getBackupTask()
if (task) {
task.stop()
setBackupTask(null)
}
const key = getBackupKey()
if (key) {
key.fill(0)
setBackupKey(null)
}
}