File size: 7,868 Bytes
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Durable copy of the database in a private HF dataset.
 *
 * The Space has no persistent disk, so the whole SQLite file is gzipped,
 * encrypted (AES-256-GCM, key = sha256(SNAPSHOT_KEY)) and uploaded as
 * `db.v2.enc`. It carries the Telegram session and X cookies, which is why it
 * never leaves the machine unencrypted.
 *
 * When to save:
 *   - right after a push (so a restart can never push the same code again)
 *   - a few minutes after new posts / codes / settings
 *   - on shutdown (SIGTERM)
 * Pure bookkeeping (check times, read cursors) never triggers an upload.
 *
 * First boot of the new version imports the old `snapshot.json` (PGlite era)
 * once; the old file is left untouched.
 */
const crypto = require('node:crypto')
const fs = require('node:fs')
const zlib = require('node:zlib')
const db = require('./db')
const log = require('./log')

const DATASET = process.env.HF_DATA_REPO || 'Ethscriptions/cut-data'
const FILE = 'db.v2.enc'
const LEGACY_FILE = 'snapshot.json'
const MAGIC = Buffer.from('CUTDB2')
const MIN_GAP_MS = 4 * 60 * 1000
const URGENT_DELAY_MS = 2000
const SQUASH_EVERY_MS = 24 * 3600 * 1000

const state = { lastSave: null, lastError: null, saves: 0, bytes: 0, restoredFrom: null, dirty: false }

function token() {
  return process.env.HF_TOKEN || process.env.HF_HUB_TOKEN || ''
}

function key() {
  const secret = process.env.SNAPSHOT_KEY
  return secret ? crypto.createHash('sha256').update(secret).digest() : null
}

function enabled() {
  return Boolean(token() && key() && process.env.BACKUP !== '0')
}

function encrypt(plain, k) {
  const iv = crypto.randomBytes(12)
  const cipher = crypto.createCipheriv('aes-256-gcm', k, iv)
  const data = Buffer.concat([cipher.update(plain), cipher.final()])
  return Buffer.concat([MAGIC, iv, cipher.getAuthTag(), data])
}

function decrypt(blob, k) {
  if (!blob.subarray(0, MAGIC.length).equals(MAGIC)) throw new Error('not a v2 backup')
  const iv = blob.subarray(MAGIC.length, MAGIC.length + 12)
  const tag = blob.subarray(MAGIC.length + 12, MAGIC.length + 28)
  const decipher = crypto.createDecipheriv('aes-256-gcm', k, iv)
  decipher.setAuthTag(tag)
  return Buffer.concat([decipher.update(blob.subarray(MAGIC.length + 28)), decipher.final()])
}

function decryptLegacy(text, k) {
  const envelope = JSON.parse(text)
  if (envelope?.alg !== 'aes-256-gcm') return envelope // very old, unencrypted
  const decipher = crypto.createDecipheriv('aes-256-gcm', k, Buffer.from(envelope.iv, 'base64'))
  decipher.setAuthTag(Buffer.from(envelope.tag, 'base64'))
  const json = Buffer.concat([decipher.update(Buffer.from(envelope.data, 'base64')), decipher.final()])
  return JSON.parse(json.toString('utf8'))
}

/** null = the file does not exist; throws only after several network failures. */
async function download(path) {
  const { downloadFile } = require('@huggingface/hub')
  let lastErr = null
  for (let attempt = 0; attempt < 4; attempt += 1) {
    try {
      const blob = await downloadFile({ repo: { type: 'dataset', name: DATASET }, path, accessToken: token() })
      return blob ? Buffer.from(await blob.arrayBuffer()) : null
    } catch (err) {
      lastErr = err
      await new Promise((resolve) => setTimeout(resolve, 2000 * (attempt + 1)))
    }
  }
  throw lastErr
}

/**
 * Called once before the database is opened. Returns where the data came from.
 * A local file wins (dev restarts); on HF the disk is always empty at boot.
 */
async function restore() {
  if (fs.existsSync(db.DB_PATH)) {
    db.open()
    state.restoredFrom = 'local'
    return { from: 'local', ...db.counts() }
  }
  if (!token() || !key()) {
    db.open()
    state.restoredFrom = 'empty (no HF_TOKEN / SNAPSHOT_KEY)'
    return { from: 'empty', reason: 'no-credentials' }
  }
  try {
    const blob = await download(FILE)
    if (blob) {
      const raw = zlib.gunzipSync(decrypt(blob, key()))
      fs.mkdirSync(require('node:path').dirname(db.DB_PATH), { recursive: true })
      fs.writeFileSync(db.DB_PATH, raw)
      db.open()
      state.restoredFrom = 'backup'
      return { from: 'backup', bytes: blob.length, ...db.counts() }
    }
  } catch (err) {
    // A backup that exists but cannot be read must never be overwritten by an empty DB.
    log.error('backup', `读取备份失败:${err.message}`)
    state.lastError = `读取备份失败:${err.message}`
    state.blockSave = true
    db.open()
    state.restoredFrom = 'empty (backup unreadable)'
    return { from: 'empty', reason: 'backup-unreadable' }
  }
  db.open()
  try {
    const text = await download(LEGACY_FILE)
    if (text) {
      const payload = decryptLegacy(text.toString('utf8'), key())
      const result = require('./legacy').importLegacy(payload)
      state.restoredFrom = 'legacy'
      state.dirty = true
      return { from: 'legacy', ...result }
    }
  } catch (err) {
    log.error('backup', `导入旧版数据失败:${err.message}`)
    state.lastError = `导入旧版数据失败:${err.message}`
    state.blockSave = true
  }
  state.restoredFrom = 'empty'
  return { from: 'empty' }
}

let timer = null
let running = null
let lastSaveMs = 0

function schedule(urgent) {
  state.dirty = true
  if (!enabled() || state.blockSave) return
  const wait = urgent ? URGENT_DELAY_MS : Math.max(30000, lastSaveMs + MIN_GAP_MS - Date.now())
  if (timer) {
    // Pull an already scheduled save forward when something urgent happens.
    if (!urgent || timer.urgent) return
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    timer = null
    save('auto').catch(() => {})
  }, wait)
  timer.urgent = urgent
}

async function save(reason = 'manual') {
  if (!enabled()) return { saved: false, reason: 'disabled' }
  if (state.blockSave) return { saved: false, reason: 'blocked: backup unreadable, refusing to overwrite' }
  if (running) await running.catch(() => {})
  running = (async () => {
    state.dirty = false
    const plain = zlib.gzipSync(Buffer.from(db.serialize()), { level: 6 })
    const body = encrypt(plain, key())
    const { uploadFiles } = require('@huggingface/hub')
    await uploadFiles({
      repo: { type: 'dataset', name: DATASET },
      accessToken: token(),
      files: [{ path: FILE, content: new Blob([body]) }],
      commitTitle: `backup ${reason} ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`,
    })
    lastSaveMs = Date.now()
    state.lastSave = log.now()
    state.lastError = null
    state.saves += 1
    state.bytes = body.length
    return { saved: true, bytes: body.length }
  })()
  try {
    return await running
  } catch (err) {
    state.dirty = true
    state.lastError = String(err?.message || err).slice(0, 200)
    log.error('backup', `上传失败:${state.lastError}`)
    setTimeout(() => schedule(false), 60000)
    return { saved: false, reason: state.lastError }
  } finally {
    running = null
  }
}

/** HF keeps every version of the file; squash the history once a day to keep the dataset small. */
async function squash() {
  if (!enabled()) return
  try {
    const res = await fetch(`https://huggingface.co/api/datasets/${DATASET}/super-squash/main`, {
      method: 'POST',
      headers: { authorization: `Bearer ${token()}`, 'content-type': 'application/json' },
      body: JSON.stringify({ message: 'squash backups' }),
      signal: AbortSignal.timeout(60000),
    })
    if (!res.ok) log.warn('backup', `整理历史版本失败:HTTP ${res.status}`)
  } catch (err) {
    log.warn('backup', `整理历史版本失败:${err.message}`)
  }
}

function start() {
  db.onChange(schedule)
  if (state.dirty) schedule(false)
  setInterval(squash, SQUASH_EVERY_MS).unref?.()
}

function status() {
  return { enabled: enabled(), dataset: DATASET, ...state, blockSave: Boolean(state.blockSave) }
}

module.exports = { restore, save, start, status, encrypt, decrypt, decryptLegacy }