Skip to content

Commit

Permalink
feat: auto bak and ignore damaged db file
Browse files Browse the repository at this point in the history
  • Loading branch information
WhiteMinds committed Apr 9, 2024
1 parent c3169c8 commit 17e344f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
15 changes: 13 additions & 2 deletions packages/http-server/src/db/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
*/
import { Recorder, RecordHandle, SerializedRecorder } from '@autorecord/manager'
import path from 'path'
import fs from 'fs'
import { Low, JSONFile } from './lowdb'
import { paths } from '../env'
import { assert, asyncThrottle, ensureFileFolderExists } from '../utils'
import { RecorderExtra } from '../manager'
import { ServerOpts } from '../types'

export interface DatabaseSchema {
records: RecordModel[]
Expand All @@ -33,8 +35,17 @@ const dbPath = path.join(paths.data, 'data.json')
const adapter = new JSONFile<DatabaseSchema>(dbPath)
const db = new Low(adapter)

export async function initDB() {
await db.read()
export async function initDB(serverOpts: ServerOpts) {
try {
await db.read()
} catch (error) {
// 理论上这个文件的保存过程是原子化的不会损坏,但根据 https://github.com/WhiteMinds/LiveAutoRecord/issues/193 的反馈仍然出现了损坏的情况。
serverOpts.logger.error('Failed to read db:', error)
if (fs.existsSync(dbPath)) {
serverOpts.logger.debug('DB content', fs.readFileSync(dbPath, 'utf-8').toString())
fs.renameSync(dbPath, dbPath + '.bak')
}
}
if (db.data == null) {
db.data = { records: [], recorders: [], nextRecorderId: 1 }
}
Expand Down
2 changes: 1 addition & 1 deletion packages/http-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export async function startServer(opts: PickPartial<ServerOpts, 'getSettings' |
const { logger } = serverOpts

logger.info('initializing db')
await initDB()
await initDB(serverOpts)

logger.info('initializing recorder manager')
if (opts.ffmpegPath != null) {
Expand Down

0 comments on commit 17e344f

Please sign in to comment.