Files
MikrotikManager/backend/src/db/bootstrap.ts
T

96 lines
5.5 KiB
TypeScript

import { assertRuntimeDatabaseActivationCurrent, pool, readRuntimeDatabaseWriterHead } from "./index.js"
import { applySqlMigrations, assertSqlMigrationsApplied } from "./migrate.js"
import { withSystemDatabaseOperationLock } from "./operation-lock.js"
import { dropExpiredPartitions, ensurePartitionsAround } from "./partitions.js"
import { importSqliteToPostgres, shouldImportSqlite, sqliteFileLooksPresent } from "./sqlite-import.js"
import { env } from "../config.js"
import { mcpStateDirectory } from "../modules/mcp/security.js"
import { assertDatabaseMaintenanceStartup, assertDatabaseRestoreJournalCurrent } from "../services/database-maintenance-startup.js"
import { reconcileDatabaseRestoreAudits } from "../services/database-restore-audit.js"
import { assertDatabaseRestoreQuarantineOpen, databaseRestoreQuarantineEnabled } from "./database-restore-quarantine.js"
import { DatabaseRestoreCheckpointRefused, readDatabaseRestoreCheckpoint, restoreJournalHeadsEqual, restoreWriterHeadIsCurrent } from "../services/database-restore-checkpoint.js"
const ETL_LOCK = 8723101
export async function initDatabase(mode: "startup" | "operator-partitions" = "startup"): Promise<void> {
const schemaSha256 = process.env.DATABASE_RUNTIME_SCHEMA_SHA256
const sourceConfigured = process.env.DATABASE_RUNTIME_REQUEST_FILE !== undefined
if ((process.env.DATABASE_RUNTIME_WRITER_APPROVAL_FILE !== undefined || process.env.DATABASE_RUNTIME_WRITER_APPROVAL_SHA256 !== undefined) &&
(!schemaSha256 || !databaseRestoreQuarantineEnabled() || !process.env.DATABASE_RESTORE_CHECKPOINT_FILE)) {
throw new Error("Защищённый профиль записи требует утверждённую схему и контрольную точку восстановления PostgreSQL")
}
if (mode === "operator-partitions" && sourceConfigured) {
throw new Error("Обслуживание партиций требует отдельного процесса оператора PostgreSQL")
}
if (schemaSha256 !== undefined && !sourceConfigured) throw new Error("Проверка схемы требует утверждённого источника PostgreSQL")
const stateDirectory = mcpStateDirectory()
await assertDatabaseMaintenanceStartup(stateDirectory, env.DATABASE_URL)
await withSystemDatabaseOperationLock(() => pool.connect(), async (client, discard) => {
// A restore may have recorded an uncertain outcome while startup waited for the lock.
await assertDatabaseMaintenanceStartup(stateDirectory, env.DATABASE_URL)
const checkpoint = await readDatabaseRestoreCheckpoint(stateDirectory, env.DATABASE_URL)
if (checkpoint && (!databaseRestoreQuarantineEnabled() || checkpoint.status !== "sealed")) throw new DatabaseRestoreCheckpointRefused()
if (databaseRestoreQuarantineEnabled()) {
await assertDatabaseRestoreQuarantineOpen(client)
const head = await assertDatabaseRestoreJournalCurrent(client, stateDirectory)
if (checkpoint && (!restoreJournalHeadsEqual(checkpoint.head, head) ||
!restoreWriterHeadIsCurrent(checkpoint.writerHead, await readRuntimeDatabaseWriterHead(client)))) {
throw new DatabaseRestoreCheckpointRefused()
}
}
if (mode === "operator-partitions") {
await assertSqlMigrationsApplied(client)
const around = new Date()
await dropExpiredPartitions(pool, around)
await ensurePartitionsAround(pool, around)
return
}
if (sourceConfigured) {
assertRuntimeDatabaseActivationCurrent()
if (schemaSha256 !== undefined) {
const { captureRuntimeDatabaseSchema } = await import("./database-runtime-schema.js")
await captureRuntimeDatabaseSchema(client, discard, schemaSha256)
assertRuntimeDatabaseActivationCurrent()
} else await assertSqlMigrationsApplied(client)
if (await shouldImportSqlite(pool, env.DATABASE_PATH)) {
throw new Error("Перед запуском приложения оператор должен завершить импорт SQLite")
}
await ensurePartitionsAround(pool)
await reconcileDatabaseRestoreAudits(pool, stateDirectory)
assertRuntimeDatabaseActivationCurrent()
return
}
await applySqlMigrations(pool)
await ensurePartitionsAround(pool)
try {
await client.query("SELECT pg_advisory_lock($1)", [ETL_LOCK])
if (await shouldImportSqlite(pool, env.DATABASE_PATH)) {
console.log(`SQLite → PostgreSQL: импорт ${env.DATABASE_PATH}`)
const report = await importSqliteToPostgres(pool, env.DATABASE_PATH, { strict: true })
console.log(
`SQLite → PostgreSQL: готово за ${report.durationMs}ms, таблиц ${Object.keys(report.tables).length}`,
)
} else {
const marker = await pool.query<{ sqlite_imported_at: string | null }>(
`SELECT sqlite_imported_at FROM data_migration WHERE id = 1`,
)
if (!marker.rows[0]?.sqlite_imported_at && !sqliteFileLooksPresent(env.DATABASE_PATH)) {
console.warn(
`SQLite → PostgreSQL: файл ${env.DATABASE_PATH} не найден, база после wipe остаётся пустой (defaults settings)`,
)
}
}
} finally {
try {
const result = await client.query("SELECT pg_advisory_unlock($1) AS released", [ETL_LOCK])
if (result.rows[0]?.released !== true) discard()
} catch {
discard()
}
}
await dropExpiredPartitions(pool)
await ensurePartitionsAround(pool)
await reconcileDatabaseRestoreAudits(pool, stateDirectory)
})
}