add dashboard
This commit is contained in:
143
lib/scheduler.js
Normal file
143
lib/scheduler.js
Normal file
@@ -0,0 +1,143 @@
|
||||
// Automatic backup: runs the normal backup (check → copy, never deletes) of
|
||||
// all projects folders on a schedule chosen in the settings - at every start,
|
||||
// hourly, daily at a time, or weekly on a day at a time. Only while the
|
||||
// dashboard runs; a missed time (PC off, window closed) is made up at the next
|
||||
// start. An unreachable target (NAS off, USB disk missing) is tried again after
|
||||
// RETRY_MS. With target 'all' the targets are backed up one after another.
|
||||
const fs = require('fs')
|
||||
const path = require('path')
|
||||
const settings = require('./settings')
|
||||
const backup = require('./backup')
|
||||
|
||||
const FILE = path.join(settings.DATA_DIR, 'auto-backup.json')
|
||||
const TICK_MS = 30 * 1000
|
||||
const RETRY_MS = 30 * 60 * 1000
|
||||
const START_DELAY_MS = 2 * 60 * 1000 // "at every start": give the PC (and the NAS) a moment
|
||||
|
||||
// since: when the current schedule was switched on/changed - times before that
|
||||
// are not "missed" (switching on "daily 20:00" at 14:00 starts today at 20:00)
|
||||
let st = { lastRun: null, lastAttempt: null, lastResult: null, since: null, plan: null }
|
||||
try { st = { ...st, ...JSON.parse(fs.readFileSync(FILE, 'utf-8')) } } catch {}
|
||||
const bootAt = Date.now()
|
||||
let startDone = false
|
||||
let queue = [] // target ids still to do in this run
|
||||
let current = null // { id } of the running job
|
||||
let results = [] // per target of this run: { id, name, ok, error }
|
||||
let timer = null
|
||||
|
||||
function save() {
|
||||
try { fs.mkdirSync(path.dirname(FILE), { recursive: true }); fs.writeFileSync(FILE, JSON.stringify(st, null, 1)) } catch {}
|
||||
}
|
||||
const ms = (iso) => (iso ? new Date(iso).getTime() : 0)
|
||||
function cfg() {
|
||||
const c = settings.get().backup.auto ?? { interval: 'off' }
|
||||
const plan = c.interval === 'off' ? 'off' : `${c.interval}|${c.time}|${c.weekday}`
|
||||
if (plan !== st.plan) { st.plan = plan; st.since = new Date().toISOString(); save() }
|
||||
return c
|
||||
}
|
||||
// last time that counts as "done": the last run, or when the schedule was set
|
||||
const base = () => Math.max(ms(st.lastRun), ms(st.since))
|
||||
|
||||
// the latest scheduled moment at or before `now` (daily/weekly), else null
|
||||
function lastSlot(c, now) {
|
||||
const [h, m] = (c.time ?? '20:00').split(':').map(Number)
|
||||
const d = new Date(now)
|
||||
d.setHours(h, m, 0, 0)
|
||||
if (c.interval === 'daily') { if (d > now) d.setDate(d.getDate() - 1); return d }
|
||||
if (c.interval === 'weekly') {
|
||||
d.setDate(d.getDate() - ((d.getDay() - c.weekday + 7) % 7))
|
||||
if (d > now) d.setDate(d.getDate() - 7)
|
||||
return d
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function due(c, now = new Date()) {
|
||||
if (c.interval === 'off' || !settings.get().backup.targets.length) return false
|
||||
// failed last time: wait before trying again
|
||||
if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return false
|
||||
switch (c.interval) {
|
||||
case 'start': return !startDone && now - bootAt >= START_DELAY_MS
|
||||
case 'hourly': return now - base() >= 60 * 60 * 1000
|
||||
case 'daily':
|
||||
case 'weekly': return base() < lastSlot(c, now).getTime()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// when the next automatic backup will start (for the settings), or null
|
||||
function nextRun(c, now = new Date()) {
|
||||
if (c.interval === 'off' || !settings.get().backup.targets.length) return null
|
||||
if (current || queue.length) return now.toISOString()
|
||||
if (ms(st.lastAttempt) > ms(st.lastRun) && now - ms(st.lastAttempt) < RETRY_MS) return new Date(ms(st.lastAttempt) + RETRY_MS).toISOString()
|
||||
if (due(c, now)) return now.toISOString()
|
||||
switch (c.interval) {
|
||||
case 'start': return startDone ? null : new Date(bootAt + START_DELAY_MS).toISOString()
|
||||
case 'hourly': return new Date(base() + 60 * 60 * 1000).toISOString()
|
||||
case 'daily':
|
||||
case 'weekly': {
|
||||
const s = lastSlot(c, now)
|
||||
s.setDate(s.getDate() + (c.interval === 'daily' ? 1 : 7))
|
||||
return s.toISOString()
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// all registered projects folders that exist (not only the ones shown right now)
|
||||
const allRoots = () => settings.get().roots.map((r) => path.resolve(r.path)).filter((p) => fs.existsSync(p))
|
||||
|
||||
function startNext() {
|
||||
if (backup.busy() || !queue.length) return
|
||||
const id = queue[0]
|
||||
if (!backup.check(null, true, id, { roots: allRoots(), auto: true })) return
|
||||
queue.shift()
|
||||
current = { id }
|
||||
}
|
||||
|
||||
function finishRun() {
|
||||
const ok = results.length > 0 && results.every((r) => r.ok)
|
||||
st.lastResult = { at: new Date().toISOString(), ok, targets: results }
|
||||
if (ok) st.lastRun = st.lastResult.at
|
||||
save()
|
||||
results = []
|
||||
}
|
||||
|
||||
function tick() {
|
||||
try {
|
||||
if (current) {
|
||||
if (backup.busy()) return
|
||||
const s = backup.getState()
|
||||
const t = settings.get().backup.targets.find((x) => x.id === current.id)
|
||||
results.push({ id: current.id, name: t?.name ?? current.id, ok: s.phase === 'done', error: s.phase === 'done' ? null : s.phase === 'cancelled' ? 'abgebrochen' : s.error })
|
||||
current = null
|
||||
if (!queue.length) finishRun()
|
||||
}
|
||||
if (queue.length) return startNext()
|
||||
const c = cfg()
|
||||
// someone else's backup is running: the schedule waits for the next tick
|
||||
if (backup.busy() || !due(c)) return
|
||||
const targets = settings.get().backup.targets
|
||||
queue = c.target === 'all' ? targets.map((t) => t.id) : targets.filter((t) => t.id === c.target).map((t) => t.id)
|
||||
if (!queue.length) queue = targets.slice(0, 1).map((t) => t.id)
|
||||
if (c.interval === 'start') startDone = true
|
||||
st.lastAttempt = new Date().toISOString()
|
||||
save()
|
||||
startNext()
|
||||
} catch (e) {
|
||||
console.error('Auto-Backup:', e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function start() {
|
||||
if (timer) return
|
||||
timer = setInterval(tick, TICK_MS)
|
||||
setTimeout(tick, 5000)
|
||||
}
|
||||
|
||||
function status() {
|
||||
const c = cfg()
|
||||
return { ...c, next: nextRun(c), running: !!current || queue.length > 0, lastRun: st.lastRun, lastResult: st.lastResult }
|
||||
}
|
||||
|
||||
module.exports = { start, status, lastSlot, due }
|
||||
Reference in New Issue
Block a user