diff --git a/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformBackupsPage.tsx b/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformBackupsPage.tsx index abe54bfb64638..8c53afc117f04 100644 --- a/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformBackupsPage.tsx +++ b/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformBackupsPage.tsx @@ -3,11 +3,14 @@ import { PageHeader, PageHeaderDescription, PageHeaderMeta, + PageHeaderNavigationTabs, PageHeaderSummary, PageHeaderTitle, } from 'ui-patterns/PageHeader' +import DatabaseBackupsNav from '../DatabaseBackupsNav' import { PlatformBackups } from './PlatformBackups' +import { PlatformPitr } from './PlatformPitr' import { DatabaseLayout } from '@/components/layouts/DatabaseLayout/DatabaseLayout' import { DefaultLayout } from '@/components/layouts/DefaultLayout' import type { NextPageWithLayout } from '@/types' @@ -24,6 +27,9 @@ export const PlatformBackupsPage: NextPageWithLayout = () => ( + + + @@ -36,3 +42,27 @@ PlatformBackupsPage.getLayout = (page) => ( {page} ) + +/** Self-hosted Database › Backups › Point in time: the platform's PITR (kubero-server #2407). */ +export const PlatformPitrPage: NextPageWithLayout = () => ( + <> + + + + Database Backups + + Restore the project to any second inside the retention window + + + + + + + + + + + +) + +PlatformPitrPage.getLayout = PlatformBackupsPage.getLayout diff --git a/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformPitr.tsx b/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformPitr.tsx new file mode 100644 index 0000000000000..cfdfe2602e685 --- /dev/null +++ b/apps/studio/components/interfaces/Database/Backups/SelfHosted/PlatformPitr.tsx @@ -0,0 +1,298 @@ +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import dayjs from 'dayjs' +import { Loader2Icon } from 'lucide-react' +import { useState } from 'react' +import { toast } from 'sonner' +import { Badge, Button, Card, CardContent, Switch } from 'ui' +import { Admonition } from 'ui-patterns/Admonition' +import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal' +import { + PageSection, + PageSectionContent, + PageSectionMeta, + PageSectionSummary, + PageSectionTitle, +} from 'ui-patterns/PageSection' +import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader' + +import { PITRForm } from '../PITR/PITRForm' +import { + clearPendingPitr, + currentRestore, + pitrWindowUnix, + readPendingPitr, + restoreLabel, + savePendingPitr, + type PendingPitr, + type PitrStatus, +} from './pitr-state' +import { BASE_PATH } from '@/lib/constants' + +const API = `${BASE_PATH}/api/self-hosted/backups/pitr` + +async function call(method: string, body?: unknown): Promise { + const res = await fetch(API, { + method, + headers: body === undefined ? undefined : { 'content-type': 'application/json' }, + body: body === undefined ? undefined : JSON.stringify(body), + }).catch(() => undefined) + if (!res?.ok) { + const message = await res + ?.json() + .then((j: { error?: { message?: string } }) => j?.error?.message) + .catch(() => undefined) + throw new Error(message ?? 'The platform did not answer') + } + return (await res.json()) as T +} + +const fmt = (v?: string | null) => (v ? dayjs(v).format('DD MMM YYYY, HH:mm:ss') : '—') + +/** + * Database › Backups › Point in time, on the platform (kubero-server #2407): turn PITR on + * with a retention (7, 14 or 28 days, capped by the plan), see the window you can restore + * to, and restore the project to a second inside it. Like the Supabase platform the + * project's database is replaced: the platform recovers it into a new database from the + * WAL archive, then moves every service onto it (Studio restarts). The previous database + * is kept until it is deleted on the dashboard. + */ +export const PlatformPitr = () => { + const queryClient = useQueryClient() + const [pending, setPending] = useState(() => readPendingPitr()) + const [retention, setRetention] = useState() + const [picking, setPicking] = useState(false) + const [confirm, setConfirm] = useState<{ unix: number; label: string; utc: string }>() + + const status = useQuery({ + queryKey: ['self-hosted', 'platform-pitr'], + queryFn: () => call('GET'), + // During the cutover Studio itself restarts: keep asking until it answers again. + retry: pending ? true : 3, + refetchInterval: (q) => { + const r = currentRestore(q.state.data)?.restore + const inFlight = !!r && r.cutover !== 'done' && r.cutover !== 'failed' + return pending || inFlight ? 5000 : 30000 + }, + }) + const st = status.data + const running = currentRestore(st) + const windowUnix = st ? pitrWindowUnix(st) : null + const retentionValue = retention ?? st?.retentionDays ?? st?.retentionChoices[0] ?? 7 + + const save = useMutation({ + mutationFn: (body: { enabled: boolean; retentionDays?: number }) => + call('PUT', body), + onSuccess: (next, body) => { + queryClient.setQueryData(['self-hosted', 'platform-pitr'], next) + toast.success( + body.enabled + ? 'Point-in-time recovery is on; the first base backup is running' + : 'Point-in-time recovery is off; the archive is kept for its retention' + ) + }, + onError: (e: Error) => toast.error(e.message), + }) + const restore = useMutation({ + mutationFn: (targetTime: string) => call<{ message: string }>('POST', { targetTime }), + onSuccess: (result, targetTime) => { + const p = { targetTime, startedAt: new Date().toISOString() } + savePendingPitr(p) + setPending(p) + setConfirm(undefined) + setPicking(false) + toast.success(result.message) + queryClient.invalidateQueries({ queryKey: ['self-hosted', 'platform-pitr'] }) + }, + onError: (e: Error) => toast.error(e.message), + }) + + if (status.isPending) return + if (status.isError && !pending) + return ( + + {status.error.message} + + ) + + const finished = running?.restore.cutover === 'done' || running?.restore.cutover === 'failed' + // A finished restore is shown to the browser that started it, until dismissed. + const showRestore = !!pending || (!!running && !finished) + + return ( +
+ {showRestore && ( + +

+ Restoring to {fmt(running?.restore.targetTime ?? pending?.targetTime)} UTC. + {running?.restore.error && {running.restore.error}} +

+ {!finished && ( +

+ This page updates by itself. +

+ )} + {finished && ( + + )} +
+ )} + + {st && ( + + + + Point-in-time recovery +

+ Every change is archived continuously, so the database can be restored to any second + inside the retention window. Off by default; the archive is billed as backup + storage. +

+
+
+ + + + {!st.available && !st.enabled && ( + + {st.unavailableReason} + + )} +
+
+

Enable point-in-time recovery

+

+ {st.enabled + ? `Keeping ${st.retentionDays ?? '?'} days of history` + : st.archiveKeptUntil + ? `Off. The archive is kept until ${fmt(st.archiveKeptUntil)}, then deleted.` + : 'Off'} +

+
+ + save.mutate( + on ? { enabled: true, retentionDays: retentionValue } : { enabled: false } + ) + } + /> +
+
+ Retention + {st.retentionChoices.map((d) => ( + + ))} +
+ {st.enabled && ( +
+
Earliest restore point
+
{fmt(st.firstRecoverableTime)}
+
Latest archived change
+
{fmt(st.lastRecoverableTime)}
+
Last base backup
+
{fmt(st.lastBaseBackupTime)}
+
WAL archiving
+
+ {st.walArchiving.healthy === false ? ( + Failing + ) : st.walArchiving.healthy ? ( + Healthy + ) : ( + Starting + )} +
+
+ )} +
+
+
+
+ )} + + {st?.enabled && ( + + + + Restore to a point in time +

+ Everything written after the chosen time is discarded. The project is down while its + services move to the restored database. +

+
+
+ + {!windowUnix ? ( + + The first base backup is still running; restores are possible once it finishes. + + ) : !picking ? ( + + ) : ( + + setConfirm({ + unix: p.recoveryTimeTargetUnix, + label: p.recoveryTimeString, + utc: p.recoveryTimeStringUtc, + }) + } + /> + )} + +
+ )} + + setConfirm(undefined)} + onConfirm={() => confirm && restore.mutate(new Date(confirm.unix * 1000).toISOString())} + > +

+ The database will be restored to {confirm?.label} ({confirm?.utc} UTC). + Every change after it is lost, including storage and auth changes. The project is + unavailable until its services have moved to the restored database; the previous database + is kept until you delete it on the dashboard. +

+
+
+ ) +} diff --git a/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.test.ts b/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.test.ts new file mode 100644 index 0000000000000..592af9396640d --- /dev/null +++ b/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' + +import { currentRestore, pitrWindowUnix, restoreLabel, type PitrStatus } from './pitr-state' + +const base: PitrStatus = { + instance: 'supabase-api-x-postgresql-ab12', + displayName: 'supabase-api-x-postgresql', + available: true, + unavailableReason: null, + enabled: true, + retentionDays: 7, + retentionChoices: [7, 14], + maxRetentionDays: 14, + walArchiving: { healthy: true, lastArchivedTime: null, lastFailedTime: null }, + firstRecoverableTime: '2026-11-15T10:00:00Z', + lastRecoverableTime: '2026-11-15T11:59:00Z', + lastBaseBackupTime: '2026-11-15T10:00:00Z', + archiveKeptUntil: null, + restores: [], + restoredFrom: null, +} +const restore = (over: Partial = {}) => ({ + instance: 'postgres-pitr-q7r2', + targetTime: '2026-11-15 11:30:00.000000+00', + requestedAt: '2026-11-15T12:00:00Z', + phase: 'Setting up primary', + ready: false, + cutover: 'requested', + error: null, + ...over, +}) + +describe('platform PITR state', () => { + it('offers first base backup .. now as the window, nothing before a base backup', () => { + const now = Date.parse('2026-11-15T12:00:00Z') + expect(pitrWindowUnix(base, now)).toEqual({ + earliest: Date.parse('2026-11-15T10:00:00Z') / 1000, + latest: now / 1000, + }) + expect(pitrWindowUnix({ ...base, firstRecoverableTime: null }, now)).toBeNull() + expect(pitrWindowUnix({ ...base, enabled: false }, now)).toBeNull() + }) + + it('follows a restore from the source and, after the cutover, from the restored database', () => { + expect(currentRestore(base)).toBeNull() + expect(currentRestore({ ...base, restores: [restore()] })).toEqual({ + restore: restore(), + onRestored: false, + }) + // A copy-only restore (no cutover) or a finished one is not "in flight" on the source. + expect(currentRestore({ ...base, restores: [restore({ cutover: null })] })).toBeNull() + expect(currentRestore({ ...base, restores: [restore({ cutover: 'done' })] })).toBeNull() + const done = restore({ cutover: 'done', ready: true }) + expect(currentRestore({ ...base, restoredFrom: done })).toEqual({ + restore: done, + onRestored: true, + }) + }) + + it('labels the steps', () => { + expect(restoreLabel(restore())).toBe('Recovering (Setting up primary)') + expect(restoreLabel(restore({ ready: true }))).toBe('Ready, switching over') + expect(restoreLabel(restore({ cutover: 'running' }))).toMatch(/Switching/) + expect(restoreLabel(restore({ cutover: 'done' }))).toBe('Restored') + expect(restoreLabel(restore({ cutover: 'failed' }))).toBe('Failed') + }) +}) diff --git a/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.ts b/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.ts new file mode 100644 index 0000000000000..32e71d3275a57 --- /dev/null +++ b/apps/studio/components/interfaces/Database/Backups/SelfHosted/pitr-state.ts @@ -0,0 +1,96 @@ +/** + * Point-in-time recovery state for self-hosted Studio (the platform's PITR, kubero-server + * #2407): what the page shows, from the platform's status, and the restore this browser + * started, kept across Studio restarting during the project cutover. + */ +type PitrRestore = { + instance: string + targetTime: string | null + requestedAt: string | null + phase: string | null + ready: boolean + cutover: string | null + error: string | null +} +export type PitrStatus = { + instance: string + displayName: string | null + available: boolean + unavailableReason: string | null + enabled: boolean + retentionDays: number | null + retentionChoices: number[] + maxRetentionDays: number | null + walArchiving: { + healthy: boolean | null + lastArchivedTime: string | null + lastFailedTime: string | null + } + firstRecoverableTime: string | null + lastRecoverableTime: string | null + lastBaseBackupTime: string | null + archiveKeptUntil: string | null + restores: PitrRestore[] + restoredFrom: PitrRestore | null +} + +/** The recoverable window as unix seconds, or null while there is none yet. */ +export function pitrWindowUnix( + status: Pick, + now = Date.now() +): { earliest: number; latest: number } | null { + if (!status.enabled || !status.firstRecoverableTime) return null + const earliest = Math.ceil(Date.parse(status.firstRecoverableTime) / 1000) + // A restore seals the current WAL first, so "now" is recoverable while archiving works. + const latest = Math.floor(now / 1000) + if (!Number.isFinite(earliest) || latest < earliest) return null + return { earliest, latest } +} + +/** The restore in flight (or just finished) for this database, if any. */ +export function currentRestore(status: PitrStatus | undefined): { + restore: PitrRestore + /** This database IS the restored one (Studio followed the cutover onto it). */ + onRestored: boolean +} | null { + if (!status) return null + if (status.restoredFrom && status.restoredFrom.cutover) + return { restore: status.restoredFrom, onRestored: true } + const r = status.restores.find((x) => x.cutover && x.cutover !== 'done') + return r ? { restore: r, onRestored: false } : null +} + +/** What a restore's state reads as. */ +export function restoreLabel(r: PitrRestore): string { + if (r.cutover === 'done') return 'Restored' + if (r.cutover === 'failed') return 'Failed' + if (r.cutover === 'running') return 'Switching the project to the restored database' + return r.ready ? 'Ready, switching over' : `Recovering (${r.phase ?? 'starting'})` +} + +const KEY = 'stackblaze:pitr-restore' + +export type PendingPitr = { targetTime: string; startedAt: string } + +export function savePendingPitr(p: PendingPitr) { + try { + localStorage.setItem(KEY, JSON.stringify(p)) + } catch { + /* private mode */ + } +} +export function readPendingPitr(): PendingPitr | undefined { + try { + const v = JSON.parse(localStorage.getItem(KEY) ?? 'null') + return v && typeof v.targetTime === 'string' ? v : undefined + } catch { + return undefined + } +} +export function clearPendingPitr() { + try { + localStorage.removeItem(KEY) + } catch { + /* private mode */ + } +} diff --git a/apps/studio/lib/api/self-hosted/platform-backups.ts b/apps/studio/lib/api/self-hosted/platform-backups.ts index 214042e948a1e..b9da6b90735d3 100644 --- a/apps/studio/lib/api/self-hosted/platform-backups.ts +++ b/apps/studio/lib/api/self-hosted/platform-backups.ts @@ -118,3 +118,58 @@ export const deleteBackup = (key: string) => export const getSchedule = () => call('GET', `${base()}/db-schedule`) export const setSchedule = (schedule: { cadences: DumpCadence[]; dbNames?: string[] | null }) => call('PUT', `${base()}/db-schedule`, schedule) + +/** A restore to a point in time: a NEW database recovered from the WAL archive. */ +type PlatformPitrRestore = { + instance: string + targetTime: string | null + requestedAt: string | null + phase: string | null + ready: boolean + /** requested → running → done | failed (Studio's project restore). */ + cutover: string | null + error: string | null +} +/** Point-in-time recovery of this deployment's database (kubero-server #2407). */ +type PlatformPitr = { + instance: string + displayName: string | null + available: boolean + unavailableReason: string | null + enabled: boolean + retentionDays: number | null + retentionChoices: number[] + maxRetentionDays: number | null + walArchiving: { + healthy: boolean | null + lastArchivedTime: string | null + lastFailedTime: string | null + } + firstRecoverableTime: string | null + lastRecoverableTime: string | null + lastBaseBackupTime: string | null + archiveKeptUntil: string | null + restores: PlatformPitrRestore[] + restoredFrom: PlatformPitrRestore | null +} +type PitrRestoreStarted = { + ok: boolean + source: string + instance: string + displayName: string + targetTime: string + cutover: boolean + message: string +} + +export const getPitr = () => call('GET', `${dbPath()}/pitr`) +/** The user's save: on with a retention (days, capped by the plan), or off. */ +export const setPitr = (body: { enabled: boolean; retentionDays?: number }) => + call('PUT', `${dbPath()}/pitr`, body) +/** + * Restore the project's database to `targetTime`, like the Supabase platform: the platform + * recovers it into a new database from the WAL archive, then moves every app of this deployment + * onto it (Studio restarts). The old database is kept until it is deleted on the dashboard. + */ +export const restorePitr = (targetTime: string) => + call('POST', `${dbPath()}/restore-pitr`, { targetTime, cutover: true }) diff --git a/apps/studio/pages/project/[ref]/database/backups/pitr.tsx b/apps/studio/pages/project/[ref]/database/backups/pitr.tsx index 2d447918ebc17..b5d4961a3feec 100644 --- a/apps/studio/pages/project/[ref]/database/backups/pitr.tsx +++ b/apps/studio/pages/project/[ref]/database/backups/pitr.tsx @@ -16,7 +16,7 @@ import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader' import DatabaseBackupsNav from '@/components/interfaces/Database/Backups/DatabaseBackupsNav' import { PITRNotice } from '@/components/interfaces/Database/Backups/PITR/PITRNotice' import { PITRSelection } from '@/components/interfaces/Database/Backups/PITR/PITRSelection' -import { SelfHostedBackupsRedirect } from '@/components/interfaces/Database/Backups/SelfHosted/SelfHostedBackupsRedirect' +import { PlatformPitrPage } from '@/components/interfaces/Database/Backups/SelfHosted/PlatformBackupsPage' import { DatabaseLayout } from '@/components/layouts/DatabaseLayout/DatabaseLayout' import { DefaultLayout } from '@/components/layouts/DefaultLayout' import { AlertError } from '@/components/ui/AlertError' @@ -165,5 +165,5 @@ const PITR = () => { ) } -// Self-hosted Studio has one backups page (the platform's dumps); send it there. -export default IS_PLATFORM ? DatabasePhysicalBackups : SelfHostedBackupsRedirect +// Self-hosted Studio: the platform's point-in-time recovery (kubero-server #2407). +export default IS_PLATFORM ? DatabasePhysicalBackups : PlatformPitrPage diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts index a15cf3cde1f49..3b52264aa0a55 100644 --- a/apps/studio/routeTree.gen.ts +++ b/apps/studio/routeTree.gen.ts @@ -134,6 +134,7 @@ import { Route as ApiSelfHostedBackupsIndexRouteImport } from './routes/api/self import { Route as ApiSelfHostedBackupsDeleteRouteImport } from './routes/api/self-hosted/backups/delete' import { Route as ApiSelfHostedBackupsRestoreRouteImport } from './routes/api/self-hosted/backups/restore' import { Route as ApiSelfHostedBackupsScheduleRouteImport } from './routes/api/self-hosted/backups/schedule' +import { Route as ApiSelfHostedBackupsPitrRouteImport } from './routes/api/self-hosted/backups/pitr' import { Route as ApiSelfHostedGithubInstallUrlRouteImport } from './routes/api/self-hosted/github/install-url' import { Route as ProjectRefAdvisorsHealthRouteImport } from './routes/project/$ref/advisors/health' import { Route as ProjectRefAdvisorsPerformanceRouteImport } from './routes/project/$ref/advisors/performance' @@ -1016,6 +1017,12 @@ const ApiSelfHostedBackupsScheduleRoute = path: '/api/self-hosted/backups/schedule', getParentRoute: () => rootRouteImport, } as any) +const ApiSelfHostedBackupsPitrRoute = + ApiSelfHostedBackupsPitrRouteImport.update({ + id: '/api/self-hosted/backups/pitr', + path: '/api/self-hosted/backups/pitr', + getParentRoute: () => rootRouteImport, + } as any) const ApiSelfHostedGithubInstallUrlRoute = ApiSelfHostedGithubInstallUrlRouteImport.update({ id: '/api/self-hosted/github/install-url', @@ -2509,6 +2516,7 @@ export interface FileRoutesByFullPath { '/api/self-hosted/backups/delete': typeof ApiSelfHostedBackupsDeleteRoute '/api/self-hosted/backups/restore': typeof ApiSelfHostedBackupsRestoreRoute '/api/self-hosted/backups/schedule': typeof ApiSelfHostedBackupsScheduleRoute + '/api/self-hosted/backups/pitr': typeof ApiSelfHostedBackupsPitrRoute '/api/self-hosted/github/install-url': typeof ApiSelfHostedGithubInstallUrlRoute '/project/$ref/advisors/health': typeof ProjectRefAdvisorsHealthRoute '/project/$ref/advisors/performance': typeof ProjectRefAdvisorsPerformanceRoute @@ -2858,6 +2866,7 @@ export interface FileRoutesByTo { '/api/self-hosted/backups/delete': typeof ApiSelfHostedBackupsDeleteRoute '/api/self-hosted/backups/restore': typeof ApiSelfHostedBackupsRestoreRoute '/api/self-hosted/backups/schedule': typeof ApiSelfHostedBackupsScheduleRoute + '/api/self-hosted/backups/pitr': typeof ApiSelfHostedBackupsPitrRoute '/api/self-hosted/github/install-url': typeof ApiSelfHostedGithubInstallUrlRoute '/project/$ref/advisors/health': typeof ProjectRefAdvisorsHealthRoute '/project/$ref/advisors/performance': typeof ProjectRefAdvisorsPerformanceRoute @@ -3218,6 +3227,7 @@ export interface FileRoutesById { '/api/self-hosted/backups/delete': typeof ApiSelfHostedBackupsDeleteRoute '/api/self-hosted/backups/restore': typeof ApiSelfHostedBackupsRestoreRoute '/api/self-hosted/backups/schedule': typeof ApiSelfHostedBackupsScheduleRoute + '/api/self-hosted/backups/pitr': typeof ApiSelfHostedBackupsPitrRoute '/api/self-hosted/github/install-url': typeof ApiSelfHostedGithubInstallUrlRoute '/project/$ref/advisors/health': typeof ProjectRefAdvisorsHealthRoute '/project/$ref/advisors/performance': typeof ProjectRefAdvisorsPerformanceRoute @@ -3581,6 +3591,7 @@ export interface FileRouteTypes { | '/api/self-hosted/backups/delete' | '/api/self-hosted/backups/restore' | '/api/self-hosted/backups/schedule' + | '/api/self-hosted/backups/pitr' | '/api/self-hosted/github/install-url' | '/project/$ref/advisors/health' | '/project/$ref/advisors/performance' @@ -3930,6 +3941,7 @@ export interface FileRouteTypes { | '/api/self-hosted/backups/delete' | '/api/self-hosted/backups/restore' | '/api/self-hosted/backups/schedule' + | '/api/self-hosted/backups/pitr' | '/api/self-hosted/github/install-url' | '/project/$ref/advisors/health' | '/project/$ref/advisors/performance' @@ -4289,6 +4301,7 @@ export interface FileRouteTypes { | '/api/self-hosted/backups/delete' | '/api/self-hosted/backups/restore' | '/api/self-hosted/backups/schedule' + | '/api/self-hosted/backups/pitr' | '/api/self-hosted/github/install-url' | '/project/$ref/advisors/health' | '/project/$ref/advisors/performance' @@ -4599,6 +4612,7 @@ export interface RootRouteChildren { ApiSelfHostedBackupsDeleteRoute: typeof ApiSelfHostedBackupsDeleteRoute ApiSelfHostedBackupsRestoreRoute: typeof ApiSelfHostedBackupsRestoreRoute ApiSelfHostedBackupsScheduleRoute: typeof ApiSelfHostedBackupsScheduleRoute + ApiSelfHostedBackupsPitrRoute: typeof ApiSelfHostedBackupsPitrRoute ApiSelfHostedGithubInstallUrlRoute: typeof ApiSelfHostedGithubInstallUrlRoute ApiPlatformOrganizationsIndexRoute: typeof ApiPlatformOrganizationsIndexRoute ApiPlatformProfileIndexRoute: typeof ApiPlatformProfileIndexRoute @@ -5566,6 +5580,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiSelfHostedBackupsScheduleRouteImport parentRoute: typeof rootRouteImport } + '/api/self-hosted/backups/pitr': { + id: '/api/self-hosted/backups/pitr' + path: '/api/self-hosted/backups/pitr' + fullPath: '/api/self-hosted/backups/pitr' + preLoaderRoute: typeof ApiSelfHostedBackupsPitrRouteImport + parentRoute: typeof rootRouteImport + } '/api/self-hosted/github/install-url': { id: '/api/self-hosted/github/install-url' path: '/api/self-hosted/github/install-url' @@ -8047,6 +8068,7 @@ const rootRouteChildren: RootRouteChildren = { ApiSelfHostedBackupsDeleteRoute: ApiSelfHostedBackupsDeleteRoute, ApiSelfHostedBackupsRestoreRoute: ApiSelfHostedBackupsRestoreRoute, ApiSelfHostedBackupsScheduleRoute: ApiSelfHostedBackupsScheduleRoute, + ApiSelfHostedBackupsPitrRoute: ApiSelfHostedBackupsPitrRoute, ApiSelfHostedGithubInstallUrlRoute: ApiSelfHostedGithubInstallUrlRoute, ApiPlatformOrganizationsIndexRoute: ApiPlatformOrganizationsIndexRoute, ApiPlatformProfileIndexRoute: ApiPlatformProfileIndexRoute, diff --git a/apps/studio/routes/api/self-hosted/backups/pitr.ts b/apps/studio/routes/api/self-hosted/backups/pitr.ts new file mode 100644 index 0000000000000..d1ea7d0442715 --- /dev/null +++ b/apps/studio/routes/api/self-hosted/backups/pitr.ts @@ -0,0 +1,58 @@ +import { createFileRoute } from '@tanstack/react-router' +import { type NextApiRequest, type NextApiResponse } from 'next' + +import { toWebHandler } from '@/compat/next/api' +import { apiWrapper } from '@/lib/api/apiWrapper' +import { getPitr, restorePitr, setPitr } from '@/lib/api/self-hosted/platform-backups' + +// Point-in-time recovery of this deployment's database (kubero-server #2407). +// GET: state + recoverable window. PUT { enabled, retentionDays }: the save. +// POST { targetTime }: restore the project to that time (202). +function nextHandler(req: NextApiRequest, res: NextApiResponse) { + return apiWrapper(req, res, handler) +} + +function fail(res: NextApiResponse, error: { status: number; message: string }) { + return res + .status(error.status >= 500 ? 502 : error.status) + .json({ error: { message: error.message } }) +} + +async function handler(req: NextApiRequest, res: NextApiResponse) { + if (req.method === 'GET') { + const result = await getPitr() + if (result.error) return fail(res, result.error) + return res.status(200).json(result.data) + } + if (req.method === 'PUT') { + const { enabled, retentionDays } = (req.body ?? {}) as { + enabled?: unknown + retentionDays?: unknown + } + if (typeof enabled !== 'boolean') + return res.status(400).json({ error: { message: 'enabled is required' } }) + if (retentionDays !== undefined && typeof retentionDays !== 'number') + return res.status(400).json({ error: { message: 'retentionDays must be a number' } }) + const result = await setPitr({ enabled, ...(retentionDays ? { retentionDays } : {}) }) + if (result.error) return fail(res, result.error) + return res.status(200).json(result.data) + } + if (req.method === 'POST') { + const { targetTime } = (req.body ?? {}) as { targetTime?: unknown } + if (typeof targetTime !== 'string' || Number.isNaN(Date.parse(targetTime))) + return res.status(400).json({ error: { message: 'targetTime must be an ISO timestamp' } }) + const result = await restorePitr(new Date(targetTime).toISOString()) + if (result.error) return fail(res, result.error) + return res.status(202).json(result.data) + } + res.setHeader('Allow', ['GET', 'PUT', 'POST']) + return res + .status(405) + .json({ data: null, error: { message: `Method ${req.method} Not Allowed` } }) +} + +const webHandler = toWebHandler(nextHandler) + +export const Route = createFileRoute('/api/self-hosted/backups/pitr')({ + server: { handlers: { GET: webHandler, PUT: webHandler, POST: webHandler } }, +})