import type { FastifyPluginAsync } from "fastify" import { appendEvent } from "../modules/events/service/events-service.js" import { exportSystemDatabaseBackup, exportSystemDatabaseBackupWithEvent, restoreSystemDatabaseBackup, } from "../services/system-database-backup.js" interface Dependencies { exportBackup: typeof exportSystemDatabaseBackup restoreBackup: typeof restoreSystemDatabaseBackup event: typeof appendEvent } const unavailableCodes = new Set([ "DATABASE_RESTORE_CHECKPOINT_REFUSED", "DATABASE_RESTORE_DATA_REFUSED", "DATABASE_RESTORE_QUARANTINE_UNAVAILABLE", "DATABASE_RUNTIME_SOURCE_REFUSED", ]) function databaseOperationFailure(error: unknown, fallbackStatus: 400 | 500) { const message = error instanceof Error ? error.message : String(error) if (error instanceof Error && "code" in error && typeof error.code === "string" && unavailableCodes.has(error.code)) { return { status: 503, body: { error: message, code: error.code } } } return { status: message.includes("уже выполняется") ? 409 : fallbackStatus, body: { error: message } } } export function createSystemDatabaseRoutes(deps: Dependencies): FastifyPluginAsync { return async (app) => { app.addContentTypeParser( "application/octet-stream", { parseAs: "buffer", bodyLimit: 512 * 1024 * 1024 }, (_req, body, done) => { done(null, body) }, ) app.get("/system/database/backup", async (_req, reply) => { try { const { filename, buffer, ...outcome } = await exportSystemDatabaseBackupWithEvent(undefined, { exportBackup: deps.exportBackup, event: deps.event }) reply.header("X-System-Database-Outcome", encodeURIComponent(JSON.stringify(outcome))) reply.header("Content-Type", "application/octet-stream") reply.header("Content-Disposition", `attachment; filename="${filename}"`) return reply.send(buffer) } catch (err) { const { status, body } = databaseOperationFailure(err, 500) return reply.status(status).send(body) } }) app.post("/system/database/restore", async (req, reply) => { const body = req.body if (!Buffer.isBuffer(body) || body.length === 0) { return reply.status(400).send({ error: "Ожидается тело запроса с файлом pg_dump (custom, PGDMP)" }) } try { const outcome = await deps.restoreBackup(body) const completionPending = Boolean(outcome.maintenanceError || outcome.migrationError) let eventError: string | undefined try { await deps.event({ level: "warning", eventType: "system.database.restore", sourceModule: "system", title: completionPending ? "Завершение восстановления базы требует проверки" : "Восстановлена база приложения", message: completionPending ? "Данные PostgreSQL заменены из дампа. Завершение обслуживания требует проверки." : "Данные PostgreSQL заменены из загруженного дампа", entityType: "system_database", entityId: "restore", payload: { sizeBytes: body.length, }, }) } catch { eventError = "Не удалось записать событие восстановления" } return reply.send({ ok: true, ...outcome, ...(eventError ? { eventError } : {}) }) } catch (err) { const { status, body } = databaseOperationFailure(err, 400) return reply.status(status).send(body) } }) } } export default createSystemDatabaseRoutes({ exportBackup: exportSystemDatabaseBackup, restoreBackup: restoreSystemDatabaseBackup, event: appendEvent })