67 lines
3.8 KiB
TypeScript
67 lines
3.8 KiB
TypeScript
import assert from "node:assert/strict"
|
|
import { execFile } from "node:child_process"
|
|
import { mkdir } from "node:fs/promises"
|
|
import { join } from "node:path"
|
|
import { setTimeout as delay } from "node:timers/promises"
|
|
import { fileURLToPath } from "node:url"
|
|
import { promisify } from "node:util"
|
|
import Database from "better-sqlite3"
|
|
import { pool } from "../db/index.js"
|
|
import { SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK, withSystemDatabaseOperationLock } from "../db/operation-lock.js"
|
|
import { mcpStateDirectory } from "../modules/mcp/security.js"
|
|
|
|
export async function verifySqliteImportCliAdmission() {
|
|
assert.equal(process.env.MMAPP_OWN_SQLITE_IMPORT_CLI_ONLY, "true")
|
|
const directory = mcpStateDirectory()
|
|
await mkdir(directory, { recursive: true })
|
|
const sqlitePath = join(directory, "owned-import.sqlite")
|
|
const sqlite = new Database(sqlitePath)
|
|
try {
|
|
sqlite.exec(`CREATE TABLE traffic_settings(id INT, enabled INT, interval_sec INT, retention_days INT, created_at TEXT, updated_at TEXT);
|
|
INSERT INTO traffic_settings VALUES(1,0,31,12,'2026-01-01','2026-01-01');`)
|
|
} finally { sqlite.close() }
|
|
|
|
const cli = fileURLToPath(new URL("../scripts/migrate-sqlite-to-pg.ts", import.meta.url))
|
|
const runImport = promisify(execFile)
|
|
const args = ["--import", "tsx", cli, `--sqlite=${sqlitePath}`]
|
|
await assert.rejects(runImport(process.execPath, [...args, "--dry-run"], {
|
|
timeout: 20000,
|
|
windowsHide: true,
|
|
env: { ...process.env, DATABASE_RUNTIME_REQUEST_FILE: join(directory, "unread-runtime-request.json") },
|
|
}), /Импорт SQLite требует отдельного процесса оператора PostgreSQL/)
|
|
|
|
const blocker = await pool.connect()
|
|
let child: Promise<{ stdout: string; stderr: string }> | undefined
|
|
try {
|
|
await blocker.query("BEGIN")
|
|
const { rows: [before] } = await blocker.query("SELECT interval_sec FROM traffic_settings WHERE id=1 FOR UPDATE")
|
|
assert(before && before.interval_sec !== 31)
|
|
child = runImport(process.execPath, args, { timeout: 20000, windowsHide: true })
|
|
void child.catch(() => {})
|
|
let copying = false
|
|
for (let i = 0; i < 240 && !copying; i++) {
|
|
const { rowCount } = await pool.query("SELECT 1 FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock' AND query LIKE 'INSERT INTO traffic_settings (%'")
|
|
copying = !!rowCount
|
|
if (!copying) await Promise.race([delay(15), child.then(() => assert.fail("CLI exited before the held SQLite import write"))])
|
|
}
|
|
assert(copying, "Expected the real SQLite importer to reach its held PostgreSQL write")
|
|
const { rows } = await pool.query(`SELECT objid::int AS key FROM pg_locks
|
|
WHERE locktype='advisory' AND classid=0 AND objsubid=1 AND mode='ExclusiveLock' AND granted
|
|
AND objid=ANY($1::oid[]) ORDER BY objid`, [[SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK]])
|
|
assert.deepEqual(rows.map(row => row.key), [SYSTEM_DATABASE_OPERATION_LOCK, SYSTEM_DATABASE_REQUEST_LOCK])
|
|
assert.deepEqual((await blocker.query("SELECT interval_sec FROM traffic_settings WHERE id=1")).rows, [before])
|
|
await blocker.query("ROLLBACK")
|
|
} finally {
|
|
try { await blocker.query("ROLLBACK") } finally { blocker.release() }
|
|
await child?.catch(() => {})
|
|
}
|
|
const output = await child
|
|
assert.match(output?.stdout ?? "", /"copied": 1/)
|
|
await withSystemDatabaseOperationLock(() => pool.connect(), async () => {
|
|
const { rows } = await pool.query("SELECT interval_sec,enabled FROM traffic_settings WHERE id=1")
|
|
assert.deepEqual(rows, [{ interval_sec: 31, enabled: false }])
|
|
assert.equal((await pool.query("SELECT 1 FROM data_migration WHERE id=1 AND sqlite_imported_at IS NOT NULL")).rowCount, 1)
|
|
})
|
|
console.log("SQLite CLI: request drain and DB operation lock retained through actual import; rows and import marker verified")
|
|
}
|