PostgreSQL backup tool with Point-In-Time-Recovery and restore verification
TypeScript backupbackupsdatabasedatabase-backupdevopsdockergolangkubernetesmariadbmongodbmysqlpgpostgrespostgresqls3self-hostedsystem-administrationtoolsweb-ui
import { Alert, App, Button, Skeleton } from 'antd';
import { type ReactNode, memo, useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
type WalStreamLive,
WalStreamStatisticsPeriod,
physicalBackupsApi,
physicalWalStreamStatisticsApi,
} from '../../../../../entity/backups/physical';
import type { Database } from '../../../../../entity/databases';
import { translateApiError } from '../../../../../shared/i18n';
import { getFullBackupAction } from '../lib/fullBackupAction';
import { FullBackupRequestController } from '../lib/fullBackupRequestController';
import { getKeepingUpSentences } from '../lib/keepingUpSentences';
import { applyLiveValues } from '../lib/liveOverlay';
import { getMonitoringFigures } from '../lib/monitoringFigures';
import { getStageTones } from '../lib/pathStages';
import { getTipTexts } from '../lib/reasonTexts';
import { getVerdictBanner } from '../lib/verdictBanner';
import { WalStreamLiveController } from '../lib/walStreamLiveController';
import {
type PageVisibility,
type RefreshTimer,
WalStreamRefreshController,
} from '../lib/walStreamRefreshController';
import type { WalStreamRefreshState } from '../model/WalStreamRefreshState';
import { MonitoringFiguresComponent } from './MonitoringFiguresComponent';
import { RestoreTimelineComponent } from './RestoreTimelineComponent';
import { TechnicalDetailsComponent } from './TechnicalDetailsComponent';
import { useCurrentTime } from './useCurrentTime';
import { usePrefersReducedMotion } from './usePrefersReducedMotion';
import { VerdictBannerComponent } from './VerdictBannerComponent';
import { WalStreamKeepingUpChartComponent } from './WalStreamChartsComponent';
interface Props {
database: Database;
isCanManageDBs: boolean;
isDirectlyUnderTab: boolean;
onOpenConfig: () => void;
}
// eslint-disable-next-line i18next/no-literal-string -- DOM event name
const VISIBILITY_CHANGE_EVENT = 'visibilitychange';
const browserPageVisibility: PageVisibility = {
isVisible: () => document.visibilityState !== 'hidden',
subscribe: (onVisibilityChange) => {
document.addEventListener(VISIBILITY_CHANGE_EVENT, onVisibilityChange);
return () => document.removeEventListener(VISIBILITY_CHANGE_EVENT, onVisibilityChange);
},
};
const browserRefreshTimer: RefreshTimer = {
setInterval: (callback, intervalMs) => window.setInterval(callback, intervalMs),
clearInterval: (handle) => window.clearInterval(handle as number),
};
// Longer than any chart's entry animation, so the animation of a new period finishes before
// later refreshes stop animating.
const CHART_ENTRY_ANIMATION_MS = 1500;
// The charts re-render only when a refresh brings a new series, not on every tick of the clock.
const MemoizedWalStreamKeepingUpChartComponent = memo(WalStreamKeepingUpChartComponent);
const MonitoringContainerComponent = ({
isDirectlyUnderTab,
children,
}: {
isDirectlyUnderTab: boolean;
children: ReactNode;
}) => (
// The width stops where a line of text and a chart still read at a glance; past it the tab only
// grows empty space.
<div
className={`w-full max-w-6xl bg-white p-3 shadow md:p-5 dark:bg-gray-800 ${isDirectlyUnderTab ? 'rounded-tr-md rounded-br-md rounded-bl-md' : 'rounded-md'}`}
>
{children}
</div>
);
const MonitoringSkeletonComponent = () => (
<div className="space-y-4">
<div className="h-24 rounded-lg border border-gray-200 p-4 dark:border-gray-700">
<Skeleton active title paragraph={{ rows: 1 }} />
</div>
<div className="h-36 rounded-lg border border-gray-200 p-4 dark:border-gray-700">
<Skeleton active paragraph={{ rows: 3 }} />
</div>
<div className="h-[760px] rounded-lg border border-gray-200 p-4 dark:border-gray-700">
<Skeleton active paragraph={{ rows: 12 }} />
</div>
</div>
);
export const WalStreamMonitoringComponent = ({
database,
isCanManageDBs,
isDirectlyUnderTab,
onOpenConfig,
}: Props) => {
const { t } = useTranslation();
const { message } = App.useApp();
const [period, setPeriod] = useState(WalStreamStatisticsPeriod.HOUR);
const [refreshState, setRefreshState] = useState<WalStreamRefreshState | null>(null);
const [lastAnimatedPeriod, setLastAnimatedPeriod] = useState<WalStreamStatisticsPeriod | null>(
null,
);
const [isRequestingFullBackup, setIsRequestingFullBackup] = useState(false);
const [live, setLive] = useState<WalStreamLive | null>(null);
const controllerRef = useRef<WalStreamRefreshController | null>(null);
const fullBackupRequestControllerRef = useRef<FullBackupRequestController | null>(null);
const retryFirstLoad = () => {
controllerRef.current?.retry();
};
const startFullBackup = () => {
void fullBackupRequestControllerRef.current?.requestFullBackup();
};
const now = useCurrentTime();
const isReducedMotion = usePrefersReducedMotion();
const changePeriod = useCallback((newPeriod: WalStreamStatisticsPeriod) => {
setPeriod(newPeriod);
controllerRef.current?.setPeriod(newPeriod);
}, []);
useEffect(() => {
const controller = new WalStreamRefreshController(
{
fetchStatistics: (requestedPeriod) =>
physicalWalStreamStatisticsApi.getWalStreamStatistics(database.id, requestedPeriod),
timer: browserRefreshTimer,
pageVisibility: browserPageVisibility,
getNow: () => new Date(),
},
period,
setRefreshState,
);
controllerRef.current = controller;
controller.start();
return () => controller.stop();
}, [database.id]);
useEffect(() => {
setLive(null);
const liveController = new WalStreamLiveController(
{
fetchLive: () => physicalWalStreamStatisticsApi.getWalStreamLive(database.id),
timer: browserRefreshTimer,
pageVisibility: browserPageVisibility,
},
setLive,
);
liveController.start();
return () => liveController.stop();
}, [database.id]);
useEffect(() => {
fullBackupRequestControllerRef.current = new FullBackupRequestController(
{
requestFullBackup: () => physicalBackupsApi.triggerPhysicalBackup(database.id, 'full'),
refreshNow: () => controllerRef.current?.retry(),
reportRequested: () =>
message.success(t('backups.physical.monitoring.banner.fullBackupRequested')),
reportError: (e) => message.error(translateApiError(e, t)),
},
setIsRequestingFullBackup,
);
}, [database.id, message, t]);
useEffect(() => {
fullBackupRequestControllerRef.current?.handleRefreshLanded();
}, [refreshState]);
const shownSeriesPeriod = refreshState?.statistics?.series.period ?? null;
useEffect(() => {
if (shownSeriesPeriod === null || shownSeriesPeriod === lastAnimatedPeriod) {
return;
}
const timeout = setTimeout(
() => setLastAnimatedPeriod(shownSeriesPeriod),
CHART_ENTRY_ANIMATION_MS,
);
return () => clearTimeout(timeout);
}, [shownSeriesPeriod, lastAnimatedPeriod]);
const statistics = refreshState?.statistics
? applyLiveValues(refreshState.statistics, live)
: null;
if (!statistics || !refreshState?.lastSuccessfulRefreshAt) {
return (
<MonitoringContainerComponent isDirectlyUnderTab={isDirectlyUnderTab}>
{refreshState?.firstLoadError ? (
<Alert
type="error"
showIcon
message={translateApiError(refreshState.firstLoadError, t)}
action={
<Button size="small" onClick={retryFirstLoad}>
{t('common.actions.retry')}
</Button>
}
/>
) : (
<MonitoringSkeletonComponent />
)}
</MonitoringContainerComponent>
);
}
const banner = getVerdictBanner({
statistics,
lastSuccessfulRefreshAt: refreshState.lastSuccessfulRefreshAt,
now,
});
const figures = getMonitoringFigures(statistics);
const isChartAnimationActive =
!isReducedMotion && statistics.series.period !== lastAnimatedPeriod;
return (
<MonitoringContainerComponent isDirectlyUnderTab={isDirectlyUnderTab}>
<VerdictBannerComponent
banner={banner}
fullBackupAction={getFullBackupAction({
level: statistics.health.level,
isStateConfirmed: banner.isStateConfirmed,
reasons: statistics.health.reasons,
latestRestorableAt: statistics.latestRestorableAt,
isFullBackupPending: statistics.health.isFullBackupPending,
isCanManageDBs,
isRequestingFullBackup,
})}
sampledAt={statistics.current?.sampledAt ?? null}
now={now}
isReducedMotion={isReducedMotion}
onStartFullBackup={startFullBackup}
onOpenConfig={onOpenConfig}
/>
{refreshState.isLastRefreshFailed && (
<Alert
className="mt-3"
type="warning"
showIcon
message={t('backups.physical.monitoring.banner.refreshFailed')}
/>
)}
{figures && (
<MonitoringFiguresComponent
figures={figures}
keepingUpSentences={getKeepingUpSentences(statistics.keepingUp)}
isReducedMotion={isReducedMotion}
/>
)}
<RestoreTimelineComponent ranges={statistics.restorableRanges} now={now} />
<MemoizedWalStreamKeepingUpChartComponent
series={statistics.series}
period={period}
onPeriodChange={changePeriod}
isAnimationActive={isChartAnimationActive}
/>
<TechnicalDetailsComponent
statistics={statistics}
stageTones={getStageTones(statistics.health.level, statistics.health.reasons)}
tips={getTipTexts(statistics.health.notices)}
isReducedMotion={isReducedMotion}
isChartAnimationActive={isChartAnimationActive}
/>
</MonitoringContainerComponent>
);
};