OpenTalon / app · opentalon.ai / native / daily-backup.cjs
| 1 | const fs = require('node:fs') |
| 2 | const path = require('node:path') |
| 3 | const { randomUUID } = require('node:crypto') |
| 4 | |
| 5 | const day = (date) => |
| 6 | [date.getFullYear(), date.getMonth() + 1, date.getDate()] |
| 7 | .map((part, index) => String(part).padStart(index === 0 ? 4 : 2, '0')) |
| 8 | .join('-') |
| 9 | |
| 10 | class DailyBackup { |
| 11 | constructor(store, { now = () => new Date(), changed = () => {} } = {}) { |
| 12 | this.store = store |
| 13 | this.now = now |
| 14 | this.changed = changed |
| 15 | this.file = path.join(store.folder, 'daily-backup.json') |
| 16 | this.defaultFolder = path.join(store.folder, 'Backups', 'Daily') |
| 17 | try { |
| 18 | this.config = JSON.parse(fs.readFileSync(this.file, 'utf8')) |
| 19 | } catch (error) { |
| 20 | this.config = {} |
| 21 | if (error.code !== 'ENOENT') |
| 22 | this.configError = 'Could not read the daily backup settings. Review the folder and save your settings again.' |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | status() { |
| 27 | return { |
| 28 | enabled: this.config.enabled !== false, |
| 29 | folder: this.config.folder || this.defaultFolder, |
| 30 | usesDefaultFolder: !this.config.folder, |
| 31 | lastBackupAt: this.config.lastBackupAt || null, |
| 32 | lastError: this.configError || this.config.lastError || '', |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | persist() { |
| 37 | const temp = path.join(this.store.folder, `.daily-${randomUUID()}.tmp`) |
| 38 | try { |
| 39 | fs.writeFileSync(temp, JSON.stringify(this.config) + '\n', { mode: 0o600, flag: 'wx' }) |
| 40 | fs.renameSync(temp, this.file) |
| 41 | } finally { |
| 42 | if (fs.existsSync(temp)) fs.unlinkSync(temp) |
| 43 | } |
| 44 | this.changed() |
| 45 | } |
| 46 | |
| 47 | async configure(input) { |
| 48 | if (this.running) await this.running.catch(() => {}) |
| 49 | if ('enabled' in input) this.config.enabled = input.enabled === true |
| 50 | if ('folder' in input) { |
| 51 | if (input.folder !== null && |
| 52 | (!path.isAbsolute(input.folder) || !fs.statSync(input.folder).isDirectory())) |
| 53 | throw new Error('Choose an existing backup folder.') |
| 54 | this.config.folder = input.folder |
| 55 | this.config.lastBackupAt = null |
| 56 | } |
| 57 | this.configError = '' |
| 58 | this.config.lastError = '' |
| 59 | this.persist() |
| 60 | return this.status() |
| 61 | } |
| 62 | |
| 63 | run({ force = false } = {}) { |
| 64 | if (this.running) return force |
| 65 | ? this.running.catch(() => {}).then(() => this.run({ force: true })) |
| 66 | : this.running |
| 67 | this.running = this.backUp(force).finally(() => { this.running = null }) |
| 68 | return this.running |
| 69 | } |
| 70 | |
| 71 | async backUp(force) { |
| 72 | const settings = this.status() |
| 73 | if (!force && (!settings.enabled || this.configError)) return settings |
| 74 | const date = this.now() |
| 75 | const file = path.join(settings.folder, |
| 76 | force ? `OpenTalon-${day(date)}-${randomUUID().slice(0, 8)}.json` : `OpenTalon-${day(date)}.json`) |
| 77 | let staging |
| 78 | try { |
| 79 | if (settings.usesDefaultFolder) fs.mkdirSync(settings.folder, { recursive: true, mode: 0o700 }) |
| 80 | if (fs.existsSync(file)) return settings |
| 81 | // Stage under the destination so publishing stays on the same volume. The |
| 82 | // shared store writes a complete JSON export before a daily file is visible. |
| 83 | staging = fs.mkdtempSync(path.join(settings.folder, '.opentalon-backup-')) |
| 84 | const destination = path.join(staging, 'snapshot.json') |
| 85 | await this.store.dispatch('create_backup', { destination, format: 'json', requestKey: randomUUID() }) |
| 86 | try { |
| 87 | fs.linkSync(destination, file) |
| 88 | } catch (error) { |
| 89 | if (error.code === 'EEXIST') return settings |
| 90 | if (!['ENOTSUP', 'EOPNOTSUPP', 'EPERM'].includes(error.code)) throw error |
| 91 | // Some removable filesystems do not support hard links. |
| 92 | fs.copyFileSync(destination, file, fs.constants.COPYFILE_EXCL) |
| 93 | fs.chmodSync(file, 0o600) |
| 94 | } |
| 95 | this.config.lastBackupAt = date.toISOString() |
| 96 | this.config.lastError = '' |
| 97 | this.persist() |
| 98 | } catch (error) { |
| 99 | const message = ['ENOENT', 'ENOTDIR'].includes(error.code) |
| 100 | ? 'The backup folder is unavailable. Reconnect its drive or choose another folder.' |
| 101 | : 'Could not save the backup. Check the folder’s permissions and available space.' |
| 102 | if (this.config.lastError !== message) { |
| 103 | this.config.lastError = message |
| 104 | this.persist() |
| 105 | } |
| 106 | if (force) throw new Error(message) |
| 107 | } finally { |
| 108 | if (staging) fs.rmSync(staging, { recursive: true, force: true }) |
| 109 | } |
| 110 | return this.status() |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | module.exports = { DailyBackup } |