Files
MikrotikManager/components/mcp/database-restore.tsx
T

103 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client"
import { useEffect, useRef, useState } from "react"
import { mcpPageQuerySchema } from "@mmapp/contracts/mcp"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { getClaims, hasPermission } from "@/lib/auth"
import { maxMcpRestoreArchiveBytes, type McpApi } from "@/shared/api/mcp"
export function DatabaseRestore({ api }: { api: McpApi }) {
const [connections, setConnections] = useState<{ id: string; name: string }[]>([])
const [connectionId, setConnectionId] = useState("")
const [file, setFile] = useState<File | null>(null)
const [archive, setArchive] = useState<Awaited<ReturnType<McpApi["uploadRestoreArchive"]>> | null>(null)
const [operationId, setOperationId] = useState("")
const [result, setResult] = useState<unknown>(null)
const [busy, setBusy] = useState(false)
const [error, setError] = useState("")
const [clock, setClock] = useState(0)
const activeRequest = useRef<AbortController | null>(null)
const deadline = archive ? Date.parse(archive.expiresAt) : null
const expired = deadline !== null && deadline <= clock
const validFile = !!file && file.size > 0 && file.size <= maxMcpRestoreArchiveBytes
const receiptId = operationId.trim()
const validReceiptId = mcpPageQuerySchema.shape.operationId.safeParse(receiptId).success
useEffect(() => {
const abort = new AbortController()
void api.connections(abort.signal).then(data => {
if (abort.signal.aborted) return
const viewer = getClaims()?.sub
setConnections(data.connections.filter(item => item.ownerId === viewer && item.generationValid && item.policy.status === "active" && item.policy.scope.allowGlobal &&
item.policy.scope.operationIds.includes("database.restore") && hasPermission(item.policy.permissions, "mm:settings:admin")))
}, failure => { if (!abort.signal.aborted) setError(String(failure)) })
return () => { abort.abort(); activeRequest.current?.abort() }
}, [api])
useEffect(() => {
if (deadline === null) return
let timer: ReturnType<typeof setTimeout>
const update = () => {
clearTimeout(timer)
const now = Date.now()
setClock(now)
if (now < deadline) timer = setTimeout(update, Math.min(deadline - now, 2_147_483_647))
}
update()
document.addEventListener("visibilitychange", update)
return () => { clearTimeout(timer); document.removeEventListener("visibilitychange", update) }
}, [deadline])
const clearResult = () => { setResult(null); setError("") }
const run = async (work: (signal: AbortSignal) => Promise<unknown>) => {
if (activeRequest.current) return
const request = new AbortController()
activeRequest.current = request
setBusy(true); clearResult()
try {
const response = await work(request.signal)
if (!request.signal.aborted) setResult(response)
} catch (failure) {
if (!request.signal.aborted) setError(failure instanceof Error ? failure.message : String(failure))
} finally {
activeRequest.current = null
if (!request.signal.aborted) setBusy(false)
}
}
const upload = () => {
if (!file || !validFile) return
void run(async signal => {
setArchive(null)
const data = await api.uploadRestoreArchive(file, signal)
if (data.sizeBytes !== file.size) throw new Error("Размер загруженного архива не совпадает с выбранным файлом.")
if (!signal.aborted) setArchive(data)
return data
})
}
const prepare = () => {
if (!archive || !connectionId) return
const now = Date.now()
if (Date.parse(archive.expiresAt) <= now) { setClock(now); return }
void run(signal => api.restorePlan(connectionId, archive.archiveRef, archive.sha256, signal))
}
return <section className="flex flex-col gap-3 rounded-xl border p-4" aria-labelledby="mcp-database-restore-title">
<h2 id="mcp-database-restore-title" className="font-semibold">Восстановление БД через MCP</h2>
<p className="text-sm text-muted-foreground">Архив PostgreSQL загружает администратор. Модель получает ссылку и SHA-256. Выполнение требует отдельного подтверждения в планах. После восстановления прежний MCP-доступ отзывается, а результат хранится во внешней квитанции.</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<label className="flex flex-col gap-1 text-sm">Подключение для восстановления
<select className="h-9 rounded-md border bg-background px-3" value={connectionId} disabled={busy} onChange={event => { setConnectionId(event.target.value); clearResult() }}><option value="">Выберите свой глобальный допуск</option>{connections.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select>
</label>
<label className="flex flex-col gap-1 text-sm">Архив PostgreSQL, до 64 МиБ
<Input type="file" accept=".dump,.backup" disabled={busy} onChange={event => { setFile(event.target.files?.[0] ?? null); setArchive(null); clearResult() }} />
</label>
{file && !validFile && <p className="text-sm text-destructive">Выберите непустой архив размером до 64 МиБ.</p>}
<div className="flex flex-wrap gap-2">
<Button variant="outline" disabled={busy || !validFile} onClick={upload}>Загрузить архив</Button>
<Button disabled={busy || !archive || expired || !connectionId} onClick={prepare}>Подготовить план восстановления БД</Button>
</div>
{archive && <p className="break-all text-xs text-muted-foreground">SHA-256: {archive.sha256} · Допуск до {new Date(archive.expiresAt).toLocaleString()}</p>}
{expired && <p role="status" className="text-sm text-muted-foreground">Срок архива истёк. Загрузите архив снова для нового плана.</p>}
<label className="flex flex-col gap-1 text-sm">ID операции восстановления БД<Input value={operationId} disabled={busy} aria-invalid={!!receiptId && !validReceiptId} onChange={event => { setOperationId(event.target.value); clearResult() }} /></label>
<Button className="self-start" variant="outline" disabled={busy || !validReceiptId} onClick={() => { void run(signal => api.restoreReceipt(receiptId, signal)) }}>Прочитать внешнюю квитанцию</Button>
{result !== null && <pre role="status" className="max-h-60 overflow-auto whitespace-pre-wrap break-all text-xs">{JSON.stringify(result, null, 2)}</pre>}
</section>
}