|
1 | 1 | import fs from 'node:fs'; |
2 | 2 | import path from 'node:path'; |
3 | 3 | import Database from 'better-sqlite3'; |
4 | | -import { debug } from './logger.js'; |
| 4 | +import { debug, warn } from './logger.js'; |
5 | 5 |
|
6 | 6 | // ─── Schema Migrations ───────────────────────────────────────────────── |
7 | 7 | export const MIGRATIONS = [ |
@@ -134,11 +134,59 @@ export function setBuildMeta(db, entries) { |
134 | 134 | export function openDb(dbPath) { |
135 | 135 | const dir = path.dirname(dbPath); |
136 | 136 | if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true }); |
| 137 | + acquireAdvisoryLock(dbPath); |
137 | 138 | const db = new Database(dbPath); |
138 | 139 | db.pragma('journal_mode = WAL'); |
| 140 | + db.pragma('busy_timeout = 5000'); |
| 141 | + db.__lockPath = `${dbPath}.lock`; |
139 | 142 | return db; |
140 | 143 | } |
141 | 144 |
|
| 145 | +export function closeDb(db) { |
| 146 | + db.close(); |
| 147 | + if (db.__lockPath) releaseAdvisoryLock(db.__lockPath); |
| 148 | +} |
| 149 | + |
| 150 | +function isProcessAlive(pid) { |
| 151 | + try { |
| 152 | + process.kill(pid, 0); |
| 153 | + return true; |
| 154 | + } catch { |
| 155 | + return false; |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +function acquireAdvisoryLock(dbPath) { |
| 160 | + const lockPath = `${dbPath}.lock`; |
| 161 | + try { |
| 162 | + if (fs.existsSync(lockPath)) { |
| 163 | + const content = fs.readFileSync(lockPath, 'utf-8').trim(); |
| 164 | + const pid = Number(content); |
| 165 | + if (pid && pid !== process.pid && isProcessAlive(pid)) { |
| 166 | + warn(`Another process (PID ${pid}) may be using this database. Proceeding with caution.`); |
| 167 | + } |
| 168 | + } |
| 169 | + } catch { |
| 170 | + /* ignore read errors */ |
| 171 | + } |
| 172 | + try { |
| 173 | + fs.writeFileSync(lockPath, String(process.pid), 'utf-8'); |
| 174 | + } catch { |
| 175 | + /* best-effort */ |
| 176 | + } |
| 177 | +} |
| 178 | + |
| 179 | +function releaseAdvisoryLock(lockPath) { |
| 180 | + try { |
| 181 | + const content = fs.readFileSync(lockPath, 'utf-8').trim(); |
| 182 | + if (Number(content) === process.pid) { |
| 183 | + fs.unlinkSync(lockPath); |
| 184 | + } |
| 185 | + } catch { |
| 186 | + /* ignore */ |
| 187 | + } |
| 188 | +} |
| 189 | + |
142 | 190 | export function initSchema(db) { |
143 | 191 | db.exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL DEFAULT 0)`); |
144 | 192 |
|
|
0 commit comments