221 lines
8.8 KiB
TypeScript
221 lines
8.8 KiB
TypeScript
import { databaseBackgroundWork } from "../services/database-background-work.js"
|
|
import { randomUUID } from "node:crypto"
|
|
import { z } from "zod"
|
|
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
|
|
import {
|
|
createBackupRequestSchema,
|
|
type BackupJobStatusResponse,
|
|
putBackupScheduleSettingsSchema,
|
|
putBackupStorageSettingsSchema,
|
|
} from "@mmapp/contracts/backups"
|
|
import { listServersRead } from "../modules/servers/service/servers-service.js"
|
|
import { appendEvent } from "../modules/events/service/events-service.js"
|
|
import { refreshScheduler } from "../services/scheduler.js"
|
|
import {
|
|
deleteBackupRecord,
|
|
getBackupById,
|
|
getBackupScheduleSettings,
|
|
getBackupStorageSettings,
|
|
listBackups,
|
|
readBackupContent,
|
|
restoreBackupToDevice,
|
|
runBackupForServer,
|
|
syncBackupsFromS3,
|
|
testBackupStorageConnection,
|
|
updateBackupScheduleSettings,
|
|
updateBackupStorageSettings,
|
|
} from "../services/backup-service.js"
|
|
|
|
import { BackupRestoreUnknownError } from "../services/backup-restore.js"
|
|
import { processBackupJob, recordBackupEvent } from "../services/backup-job-execution.js"
|
|
|
|
type BackupJob = BackupJobStatusResponse
|
|
|
|
const BackupIdParamSchema = z.object({
|
|
id: z.string().min(1),
|
|
})
|
|
const BackupJobIdParamSchema = z.object({
|
|
jobId: z.string().min(1),
|
|
})
|
|
|
|
export function createBackupsRoutes(deps: { listServers?: () => Promise<Array<{ id: string | number }>>; create?: typeof runBackupForServer; restore?: typeof restoreBackupToDevice; delete?: typeof deleteBackupRecord; appendEvent?: typeof appendEvent } = {}): FastifyPluginAsyncZod {
|
|
return async (app) => {
|
|
const backupJobs = new Map<string, BackupJob>()
|
|
const event = (input: Parameters<typeof appendEvent>[0]) => recordBackupEvent(input, deps.appendEvent ?? appendEvent, error => app.log.warn({ err: error }, "Не удалось записать событие резервных копий"))
|
|
app.get("/backups", async (_req, reply) => {
|
|
return reply.send(await listBackups())
|
|
})
|
|
|
|
app.get("/backups/schedule", async (_req, reply) => {
|
|
return reply.send(await getBackupScheduleSettings())
|
|
})
|
|
|
|
app.put("/backups/schedule", async (req, reply) => {
|
|
const parsed = putBackupScheduleSettingsSchema.safeParse(req.body ?? {})
|
|
if (!parsed.success) {
|
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
|
}
|
|
const result = await updateBackupScheduleSettings(parsed.data)
|
|
await refreshScheduler()
|
|
return reply.send(result)
|
|
})
|
|
|
|
app.get("/backups/storage", async (_req, reply) => {
|
|
return reply.send(await getBackupStorageSettings())
|
|
})
|
|
|
|
app.put("/backups/storage", async (req, reply) => {
|
|
const parsed = putBackupStorageSettingsSchema.safeParse(req.body ?? {})
|
|
if (!parsed.success) {
|
|
return reply.status(400).send({ error: "Некорректное тело запроса", details: parsed.error.flatten() })
|
|
}
|
|
return reply.send(await updateBackupStorageSettings(parsed.data))
|
|
})
|
|
|
|
app.post("/backups/storage/test", async (_req, reply) => {
|
|
try {
|
|
return reply.send(await testBackupStorageConnection())
|
|
} catch (err) {
|
|
return reply.status(400).send({
|
|
error: err instanceof Error ? err.message : "Ошибка проверки S3",
|
|
settings: await getBackupStorageSettings(),
|
|
})
|
|
}
|
|
})
|
|
|
|
app.post("/backups/storage/sync", async (_req, reply) => {
|
|
try {
|
|
return reply.send(await syncBackupsFromS3())
|
|
} catch (err) {
|
|
return reply.status(400).send({
|
|
error: err instanceof Error ? err.message : "Ошибка синхронизации S3",
|
|
})
|
|
}
|
|
})
|
|
|
|
app.post("/backups/create", { schema: { body: createBackupRequestSchema } }, async (req, reply) => {
|
|
const inputIds = req.body.serverIds.map((x) => String(x))
|
|
const notes = req.body.notes?.trim() || undefined
|
|
const previous = req.body.requestId ? backupJobs.get(req.body.requestId) : undefined
|
|
if (previous) {
|
|
if (JSON.stringify(previous.serverIds) !== JSON.stringify(inputIds) || previous.notes !== notes) return reply.status(409).send({ error: "Request ID уже относится к другой задаче" })
|
|
return reply.status(202).send({ jobId: previous.id, status: previous.status, total: previous.total, completed: previous.completed, serverIds: previous.serverIds })
|
|
}
|
|
const existingServers = new Set((await (deps.listServers ?? listServersRead)()).map((s) => String(s.id)))
|
|
const ids = [...new Set(inputIds)]
|
|
if (ids.some(id => !existingServers.has(id))) return reply.status(400).send({ error: "Выбранный сервер отсутствует в каталоге; обновите выбор" })
|
|
|
|
const jobId = req.body.requestId ?? randomUUID()
|
|
const job: BackupJob = {
|
|
id: jobId,
|
|
serverIds: ids,
|
|
notes,
|
|
status: "queued",
|
|
requestedAt: new Date().toISOString(),
|
|
total: ids.length,
|
|
completed: 0,
|
|
created: [],
|
|
failures: [],
|
|
}
|
|
const raced = backupJobs.get(jobId)
|
|
if (raced) {
|
|
if (JSON.stringify(raced.serverIds) !== JSON.stringify(ids) || raced.notes !== notes) return reply.status(409).send({ error: "Request ID уже относится к другой задаче" })
|
|
return reply.status(202).send({ jobId, status: raced.status, total: raced.total, completed: raced.completed, serverIds: raced.serverIds })
|
|
}
|
|
backupJobs.set(jobId, job)
|
|
void databaseBackgroundWork.track(event({
|
|
level: "info",
|
|
eventType: "backups.job.started",
|
|
sourceModule: "backups",
|
|
title: "Запущен бэкап",
|
|
message: `Серверов в очереди: ${ids.length}`,
|
|
entityType: "backup_job",
|
|
entityId: jobId,
|
|
payload: {
|
|
serverIds: ids,
|
|
notes: notes ?? null,
|
|
},
|
|
})).catch(() => {})
|
|
void databaseBackgroundWork.track(Promise.resolve().then(async () => {
|
|
await processBackupJob(job, ids, notes, { create: deps.create ?? runBackupForServer, event }).catch(async (err) => {
|
|
job.status = "failed"
|
|
job.finishedAt = new Date().toISOString()
|
|
const failure = {
|
|
serverId: "job",
|
|
error: err instanceof Error ? err.message : String(err),
|
|
}
|
|
job.failures.push(failure)
|
|
await event({
|
|
level: "critical",
|
|
eventType: "backups.job.failed",
|
|
sourceModule: "backups",
|
|
title: "Бэкап прерван",
|
|
message: failure.error,
|
|
entityType: "backup_job",
|
|
entityId: job.id,
|
|
payload: {
|
|
total: job.total,
|
|
completed: job.completed,
|
|
},
|
|
})
|
|
})
|
|
})).catch(() => {})
|
|
return reply.status(202).send({
|
|
jobId,
|
|
status: job.status,
|
|
total: job.total,
|
|
completed: job.completed,
|
|
serverIds: job.serverIds,
|
|
})
|
|
})
|
|
|
|
app.get("/backups/jobs/:jobId", { schema: { params: BackupJobIdParamSchema } }, async (req, reply) => {
|
|
const job = backupJobs.get(req.params.jobId)
|
|
if (!job) return reply.status(404).send({ error: "Job не найден" })
|
|
return reply.send(job)
|
|
})
|
|
|
|
app.get("/backups/:id/download", { schema: { params: BackupIdParamSchema } }, async (req, reply) => {
|
|
const hit = await getBackupById(req.params.id)
|
|
if (!hit) return reply.status(404).send({ error: "Бэкап не найден" })
|
|
try {
|
|
const content = await readBackupContent(hit)
|
|
reply.header("Content-Type", "text/plain; charset=utf-8")
|
|
reply.header("Content-Disposition", `attachment; filename="${hit.filename}"`)
|
|
return reply.send(content)
|
|
} catch {
|
|
return reply.status(404).send({ error: "Файл бэкапа не найден" })
|
|
}
|
|
})
|
|
|
|
app.post("/backups/:id/restore", { schema: { params: BackupIdParamSchema } }, async (req, reply) => {
|
|
try {
|
|
const result = await (deps.restore ?? restoreBackupToDevice)(req.params.id)
|
|
void databaseBackgroundWork.track(event({
|
|
level: "warning",
|
|
eventType: "backups.restore",
|
|
sourceModule: "backups",
|
|
title: "Восстановление бэкапа",
|
|
message: `${result.filename} → ${result.serverName}`,
|
|
entityType: "backup",
|
|
entityId: req.params.id,
|
|
})).catch(() => {})
|
|
return reply.send(result)
|
|
} catch (err) {
|
|
return reply.status(err instanceof BackupRestoreUnknownError ? 502 : 400).send({
|
|
outcome: err instanceof BackupRestoreUnknownError ? "unknown" : "not-applied",
|
|
error: err instanceof Error ? err.message : "Не удалось восстановить бэкап",
|
|
})
|
|
}
|
|
})
|
|
|
|
app.delete("/backups/:id", { schema: { params: BackupIdParamSchema } }, async (req, reply) => {
|
|
const hit = await (deps.delete ?? deleteBackupRecord)(req.params.id)
|
|
if (!hit) return reply.status(404).send({ error: "Бэкап не найден" })
|
|
return reply.status(204).send()
|
|
})
|
|
}
|
|
}
|
|
|
|
export default createBackupsRoutes()
|