Центрирование заглушек в графиках/Frame; лимит тела backup 100 MiB; WAL checkpoint при экспорте и очистка -wal/-shm при импорте. Co-authored-by: Cursor <[email protected]>
This commit is contained in:
@@ -1,7 +1,13 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { desc } from 'drizzle-orm'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { getDb, getDbPath, reloadDatabaseFromBuffer, schema } from '@cfdm/db'
|
||||
import { existsSync } from 'node:fs'
|
||||
import {
|
||||
getDb,
|
||||
getDbPath,
|
||||
readDatabaseFileBuffer,
|
||||
reloadDatabaseFromBuffer,
|
||||
schema,
|
||||
} from '@cfdm/db'
|
||||
import { getSnapshot } from '@cfdm/db/repositories/snapshot'
|
||||
|
||||
import { importJsonSnapshot, type BackupPayload } from '../services/backup-import.js'
|
||||
@@ -9,10 +15,26 @@ import { restartScheduler } from '../services/scheduler.js'
|
||||
|
||||
const BACKUP_VERSION = 1
|
||||
|
||||
/** Лимит тела для импорта бэкапа (Fastify default = 1 MiB → 413). */
|
||||
function backupBodyLimitBytes(): number {
|
||||
const raw = process.env.BACKUP_BODY_LIMIT_BYTES
|
||||
if (raw) {
|
||||
const n = Number(raw)
|
||||
if (Number.isFinite(n) && n > 0) return Math.floor(n)
|
||||
}
|
||||
return 100 * 1024 * 1024 // 100 MiB
|
||||
}
|
||||
|
||||
export const backupRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer' }, (_req, body, done) => {
|
||||
done(null, body)
|
||||
})
|
||||
const bodyLimit = backupBodyLimitBytes()
|
||||
|
||||
app.addContentTypeParser(
|
||||
'application/octet-stream',
|
||||
{ parseAs: 'buffer', bodyLimit },
|
||||
(_req, body, done) => {
|
||||
done(null, body)
|
||||
},
|
||||
)
|
||||
|
||||
app.get('/api/backup/json', async (_req, reply) => {
|
||||
const syncLog = getDb()
|
||||
@@ -37,41 +59,49 @@ export const backupRoutes: FastifyPluginAsync = async (app) => {
|
||||
if (!existsSync(dbPath)) {
|
||||
return reply.code(404).send({ error: { code: 'NOT_FOUND', message: 'Файл базы не найден' } })
|
||||
}
|
||||
const buf = readFileSync(dbPath)
|
||||
const buf = readDatabaseFileBuffer()
|
||||
reply.header('Content-Type', 'application/octet-stream')
|
||||
reply.header('Content-Disposition', 'attachment; filename="vps-tracker.db"')
|
||||
return reply.send(buf)
|
||||
})
|
||||
|
||||
app.post('/api/backup/json', async (req, reply) => {
|
||||
const payload = req.body
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Неверное тело запроса' } })
|
||||
}
|
||||
try {
|
||||
importJsonSnapshot(payload as BackupPayload)
|
||||
restartScheduler()
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
req.log.error(err)
|
||||
const message = err instanceof Error ? err.message : 'Импорт не удался'
|
||||
return reply.code(500).send({ error: { code: 'INTERNAL_ERROR', message } })
|
||||
}
|
||||
})
|
||||
app.post(
|
||||
'/api/backup/json',
|
||||
{ bodyLimit },
|
||||
async (req, reply) => {
|
||||
const payload = req.body
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Неверное тело запроса' } })
|
||||
}
|
||||
try {
|
||||
importJsonSnapshot(payload as BackupPayload)
|
||||
restartScheduler()
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
req.log.error(err)
|
||||
const message = err instanceof Error ? err.message : 'Импорт не удался'
|
||||
return reply.code(500).send({ error: { code: 'INTERNAL_ERROR', message } })
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
app.post('/api/backup/database', async (req, reply) => {
|
||||
const buf = req.body as Buffer
|
||||
if (!Buffer.isBuffer(buf) || !buf.length) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Пустой файл' } })
|
||||
}
|
||||
try {
|
||||
reloadDatabaseFromBuffer(buf)
|
||||
restartScheduler()
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
req.log.error(err)
|
||||
const message = err instanceof Error ? err.message : 'Восстановление не удалось'
|
||||
return reply.code(500).send({ error: { code: 'INTERNAL_ERROR', message } })
|
||||
}
|
||||
})
|
||||
app.post(
|
||||
'/api/backup/database',
|
||||
{ bodyLimit },
|
||||
async (req, reply) => {
|
||||
const buf = req.body as Buffer
|
||||
if (!Buffer.isBuffer(buf) || !buf.length) {
|
||||
return reply.code(400).send({ error: { code: 'VALIDATION', message: 'Пустой файл' } })
|
||||
}
|
||||
try {
|
||||
reloadDatabaseFromBuffer(buf)
|
||||
restartScheduler()
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
req.log.error(err)
|
||||
const message = err instanceof Error ? err.message : 'Восстановление не удалось'
|
||||
return reply.code(500).send({ error: { code: 'INTERNAL_ERROR', message } })
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -370,7 +370,7 @@ export function DataGridCard<TData extends object>({
|
||||
{hasHeader ? (
|
||||
<DataGridSectionHeader title={title} description={description} actions={headerActions} />
|
||||
) : null}
|
||||
<FramePanel>
|
||||
<FramePanel className="flex min-h-72 w-full flex-col items-center justify-center">
|
||||
<EmptyState title={emptyTitle} description={emptyDescription} action={emptyAction} />
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
|
||||
@@ -51,7 +51,13 @@ import { aggregateBurnByProject } from '@/lib/project-analytics'
|
||||
import { EmptyState } from '@/components/empty-state'
|
||||
|
||||
function ChartEmpty({ message }: { message: string }) {
|
||||
return <EmptyState title={message} className="h-72 border-none" />
|
||||
return (
|
||||
<EmptyState
|
||||
title={message}
|
||||
className="min-h-72 w-full flex-1 py-0"
|
||||
stackedIcon
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const EXPENSE_CONFIG: ChartConfig = {
|
||||
@@ -103,7 +109,7 @@ export function MonthlyExpenseChart({
|
||||
<CardTitle>{title}</CardTitle>
|
||||
<CardDescription>{description ?? `Топ-10 по monthly rate, в ${baseCurrency}`}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{data.length === 0 ? (
|
||||
<ChartEmpty message="Нет данных для графика" />
|
||||
) : (
|
||||
@@ -167,7 +173,7 @@ export function PaymentsPieChart({
|
||||
<CardTitle>Платежи по типам</CardTitle>
|
||||
<CardDescription>Структура в {baseCurrency}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{data.length === 0 ? (
|
||||
<ChartEmpty message="Нет данных о платежах" />
|
||||
) : (
|
||||
@@ -264,7 +270,7 @@ function DashboardMonthlyBarChart({
|
||||
</div>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{!hasData ? (
|
||||
<ChartEmpty message="Нет данных за выбранный период" />
|
||||
) : (
|
||||
@@ -384,7 +390,7 @@ export function DashboardExpensesChart({
|
||||
</div>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{!hasData ? (
|
||||
<ChartEmpty message="Нет данных за выбранный период" />
|
||||
) : (
|
||||
@@ -440,7 +446,7 @@ export function MonthlyTrendChart({
|
||||
<CardTitle>Динамика платежей</CardTitle>
|
||||
<CardDescription>Последние 12 месяцев, {baseCurrency}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{data.length === 0 ? (
|
||||
<ChartEmpty message="Нет данных за выбранный период" />
|
||||
) : (
|
||||
@@ -460,7 +466,11 @@ export function MonthlyTrendChart({
|
||||
}
|
||||
|
||||
export function ChartsGrid({ children }: { children: ReactNode }) {
|
||||
return <div className="grid w-full gap-4 lg:grid-cols-2">{children}</div>
|
||||
return (
|
||||
<div className="grid w-full gap-4 lg:grid-cols-2 lg:items-stretch [&>*]:min-h-0 [&>*]:h-full">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function ProjectExpenseChart({
|
||||
@@ -506,7 +516,7 @@ export function ProjectExpenseChart({
|
||||
<CardTitle>Расходы по проектам (мес)</CardTitle>
|
||||
<CardDescription>Активные VPS, в {baseCurrency}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-72 flex-1 flex-col items-center justify-center">
|
||||
{data.length === 0 ? (
|
||||
<ChartEmpty message="Нет данных для графика" />
|
||||
) : (
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
/**
|
||||
* ReUI Empty + IconStack — adapted from empty-state-12.
|
||||
* Preview: https://reui.io/preview/base/empty-state-12
|
||||
* Docs: https://reui.io/blocks
|
||||
*/
|
||||
import { InboxIcon, type LucideIcon } from 'lucide-react'
|
||||
import { IconStack } from '@/components/reui/icon-stack'
|
||||
import {
|
||||
@@ -20,6 +25,11 @@ interface EmptyStateProps {
|
||||
className?: string
|
||||
/** Use IconStack media (empty-state-12). Default true. */
|
||||
stackedIcon?: boolean
|
||||
/**
|
||||
* Center in available width/height (empty-state-12).
|
||||
* Set false for tight panels/sheets where the parent already centers.
|
||||
*/
|
||||
centered?: boolean
|
||||
}
|
||||
|
||||
function isLucideIcon(icon: LucideIcon | ReactNode): icon is LucideIcon {
|
||||
@@ -33,7 +43,6 @@ function isLucideIcon(icon: LucideIcon | ReactNode): icon is LucideIcon {
|
||||
return false
|
||||
}
|
||||
|
||||
/** Empty state — ReUI empty-state-12. Preview: https://reui.io/preview/base/empty-state-12 */
|
||||
export function EmptyState({
|
||||
icon,
|
||||
title,
|
||||
@@ -41,18 +50,24 @@ export function EmptyState({
|
||||
action,
|
||||
className,
|
||||
stackedIcon = true,
|
||||
centered = true,
|
||||
}: EmptyStateProps) {
|
||||
const Icon = isLucideIcon(icon) ? icon : InboxIcon
|
||||
const customIcon = icon && !isLucideIcon(icon) ? icon : null
|
||||
|
||||
return (
|
||||
<Empty className={cn('max-w-md flex-none border-0 bg-transparent p-0', className)}>
|
||||
const body = (
|
||||
<Empty
|
||||
className={cn(
|
||||
'max-w-md flex-none border-0 bg-transparent p-0',
|
||||
!centered && className,
|
||||
)}
|
||||
>
|
||||
<EmptyHeader className="gap-5 text-center">
|
||||
<EmptyMedia className="mb-0">
|
||||
{customIcon ? (
|
||||
<div className="text-muted-foreground">{customIcon}</div>
|
||||
) : stackedIcon ? (
|
||||
<IconStack aria-hidden="true" className="h-14 w-12">
|
||||
<IconStack aria-hidden="true" className="h-14 w-12 shrink-0">
|
||||
<Icon strokeWidth={1.9} aria-hidden="true" className="size-5" />
|
||||
</IconStack>
|
||||
) : (
|
||||
@@ -72,7 +87,25 @@ export function EmptyState({
|
||||
) : null}
|
||||
</div>
|
||||
</EmptyHeader>
|
||||
{action ? <EmptyContent>{action}</EmptyContent> : null}
|
||||
{action ? (
|
||||
<EmptyContent className="mt-1 items-center justify-center">
|
||||
{action}
|
||||
</EmptyContent>
|
||||
) : null}
|
||||
</Empty>
|
||||
)
|
||||
|
||||
if (!centered) return body
|
||||
|
||||
// empty-state-12: center in available height (parent must be flex column / stretch)
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'flex w-full flex-1 items-center justify-center self-stretch py-14 sm:py-16',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{body}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -242,11 +242,15 @@ export function ResourcePage<T extends object>({
|
||||
|
||||
if (data.length === 0 && emptyState) {
|
||||
return (
|
||||
<EmptyState
|
||||
title={emptyState.title}
|
||||
description={emptyState.description}
|
||||
action={emptyState.action}
|
||||
/>
|
||||
<Frame dense spacing="sm" className="w-full">
|
||||
<FramePanel className="flex min-h-[min(28rem,55svh)] w-full flex-col items-center justify-center p-0">
|
||||
<EmptyState
|
||||
title={emptyState.title}
|
||||
description={emptyState.description}
|
||||
action={emptyState.action}
|
||||
/>
|
||||
</FramePanel>
|
||||
</Frame>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -268,6 +268,8 @@ export const api = {
|
||||
const headers = new Headers({ 'Content-Type': 'application/octet-stream' })
|
||||
const token = getToken()
|
||||
if (token) headers.set('Authorization', `Bearer ${token}`)
|
||||
const spaceId = getStoredSpaceId()
|
||||
if (spaceId) headers.set('X-Space-Id', spaceId)
|
||||
const res = await fetch(`${API_BASE}/api/backup/database`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
@@ -277,7 +279,25 @@ export const api = {
|
||||
if (res.status === 401) {
|
||||
await handoffOnUnauthorized()
|
||||
}
|
||||
throw new ApiError(res.statusText || 'Ошибка восстановления', res.status)
|
||||
let message = res.statusText || 'Ошибка восстановления'
|
||||
if (res.status === 413) {
|
||||
message =
|
||||
'Файл слишком большой для импорта (лимит тела запроса). Увеличьте BACKUP_BODY_LIMIT_BYTES на API или используйте копирование data/*.db на сервере.'
|
||||
} else {
|
||||
try {
|
||||
const data = (await res.json()) as {
|
||||
error?: string | { message?: string }
|
||||
message?: string
|
||||
}
|
||||
if (typeof data?.error === 'string') message = data.error
|
||||
else if (data?.error && typeof data.error === 'object' && data.error.message) {
|
||||
message = data.error.message
|
||||
} else if (typeof data?.message === 'string') message = data.message
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
throw new ApiError(message, res.status)
|
||||
}
|
||||
return res.json()
|
||||
},
|
||||
|
||||
@@ -97,14 +97,14 @@ function ResourcesPage() {
|
||||
]}
|
||||
/>
|
||||
|
||||
<Card>
|
||||
<Card className="flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>Ресурсы по хостерам</CardTitle>
|
||||
<CardDescription>Только активные VPS</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="flex min-h-80 flex-1 flex-col items-center justify-center">
|
||||
{chartData.length === 0 ? (
|
||||
<EmptyState title="Нет данных для графика" />
|
||||
<EmptyState title="Нет данных для графика" className="min-h-80 w-full flex-1 py-0" />
|
||||
) : (
|
||||
<ChartContainer config={RESOURCE_CONFIG} className="h-80 w-full" aria-label="Ресурсы по хостерам">
|
||||
<BarChart data={chartData} margin={{ top: 8, right: 8, bottom: 8, left: 8 }}>
|
||||
|
||||
Reference in New Issue
Block a user