feat: backup schedule creation form

This commit is contained in:
Nicolas Meienberger
2025-10-28 22:34:56 +01:00
parent 37a22b260f
commit d1c1adaba7
14 changed files with 746 additions and 610 deletions

View File

@@ -28,6 +28,7 @@ import {
deleteBackupSchedule,
getBackupSchedule,
updateBackupSchedule,
getBackupScheduleForVolume,
runBackupNow,
} from "../sdk.gen";
import { queryOptions, type UseMutationOptions, type DefaultError } from "@tanstack/react-query";
@@ -73,6 +74,7 @@ import type {
GetBackupScheduleData,
UpdateBackupScheduleData,
UpdateBackupScheduleResponse,
GetBackupScheduleForVolumeData,
RunBackupNowData,
RunBackupNowResponse,
} from "../types.gen";
@@ -842,6 +844,27 @@ export const updateBackupScheduleMutation = (
return mutationOptions;
};
export const getBackupScheduleForVolumeQueryKey = (options: Options<GetBackupScheduleForVolumeData>) =>
createQueryKey("getBackupScheduleForVolume", options);
/**
* Get a backup schedule for a specific volume
*/
export const getBackupScheduleForVolumeOptions = (options: Options<GetBackupScheduleForVolumeData>) => {
return queryOptions({
queryFn: async ({ queryKey, signal }) => {
const { data } = await getBackupScheduleForVolume({
...options,
...queryKey[0],
signal,
throwOnError: true,
});
return data;
},
queryKey: getBackupScheduleForVolumeQueryKey(options),
});
};
export const runBackupNowQueryKey = (options: Options<RunBackupNowData>) => createQueryKey("runBackupNow", options);
/**

View File

@@ -64,6 +64,8 @@ import type {
GetBackupScheduleResponses,
UpdateBackupScheduleData,
UpdateBackupScheduleResponses,
GetBackupScheduleForVolumeData,
GetBackupScheduleForVolumeResponses,
RunBackupNowData,
RunBackupNowResponses,
} from "./types.gen";
@@ -416,6 +418,18 @@ export const updateBackupSchedule = <ThrowOnError extends boolean = false>(
});
};
/**
* Get a backup schedule for a specific volume
*/
export const getBackupScheduleForVolume = <ThrowOnError extends boolean = false>(
options: Options<GetBackupScheduleForVolumeData, ThrowOnError>,
) => {
return (options.client ?? _heyApiClient).get<GetBackupScheduleForVolumeResponses, unknown, ThrowOnError>({
url: "/api/v1/backups/volume/{volumeId}",
...options,
});
};
/**
* Trigger a backup immediately for a schedule
*/

View File

@@ -174,6 +174,7 @@ export type ListVolumesResponses = {
username?: string;
};
createdAt: number;
id: number;
lastError: string | null;
lastHealthCheck: number;
name: string;
@@ -370,6 +371,7 @@ export type GetVolumeResponses = {
username?: string;
};
createdAt: number;
id: number;
lastError: string | null;
lastHealthCheck: number;
name: string;
@@ -470,6 +472,7 @@ export type UpdateVolumeResponses = {
username?: string;
};
createdAt: number;
id: number;
lastError: string | null;
lastHealthCheck: number;
name: string;
@@ -820,15 +823,14 @@ export type ListBackupSchedulesResponses = {
createdAt: number;
cronExpression: string;
enabled: boolean;
excludePatterns: Array<string>;
excludePatterns: Array<string> | null;
id: number;
includePatterns: Array<string>;
includePatterns: Array<string> | null;
lastBackupAt: number | null;
lastBackupError: string | null;
lastBackupStatus: "error" | "success" | null;
nextBackupAt: number | null;
repositoryId: string;
repositoryName: string;
retentionPolicy: {
keepDaily?: number;
keepHourly?: number;
@@ -840,7 +842,6 @@ export type ListBackupSchedulesResponses = {
} | null;
updatedAt: number;
volumeId: number;
volumeName: string;
}>;
};
};
@@ -881,15 +882,14 @@ export type CreateBackupScheduleResponses = {
createdAt: number;
cronExpression: string;
enabled: boolean;
excludePatterns: Array<string>;
excludePatterns: Array<string> | null;
id: number;
includePatterns: Array<string>;
includePatterns: Array<string> | null;
lastBackupAt: number | null;
lastBackupError: string | null;
lastBackupStatus: "error" | "success" | null;
nextBackupAt: number | null;
repositoryId: string;
repositoryName: string;
retentionPolicy: {
keepDaily?: number;
keepHourly?: number;
@@ -901,7 +901,6 @@ export type CreateBackupScheduleResponses = {
} | null;
updatedAt: number;
volumeId: number;
volumeName: string;
};
};
};
@@ -946,15 +945,14 @@ export type GetBackupScheduleResponses = {
createdAt: number;
cronExpression: string;
enabled: boolean;
excludePatterns: Array<string>;
excludePatterns: Array<string> | null;
id: number;
includePatterns: Array<string>;
includePatterns: Array<string> | null;
lastBackupAt: number | null;
lastBackupError: string | null;
lastBackupStatus: "error" | "success" | null;
nextBackupAt: number | null;
repositoryId: string;
repositoryName: string;
retentionPolicy: {
keepDaily?: number;
keepHourly?: number;
@@ -966,7 +964,6 @@ export type GetBackupScheduleResponses = {
} | null;
updatedAt: number;
volumeId: number;
volumeName: string;
};
};
};
@@ -1008,15 +1005,14 @@ export type UpdateBackupScheduleResponses = {
createdAt: number;
cronExpression: string;
enabled: boolean;
excludePatterns: Array<string>;
excludePatterns: Array<string> | null;
id: number;
includePatterns: Array<string>;
includePatterns: Array<string> | null;
lastBackupAt: number | null;
lastBackupError: string | null;
lastBackupStatus: "error" | "success" | null;
nextBackupAt: number | null;
repositoryId: string;
repositoryName: string;
retentionPolicy: {
keepDaily?: number;
keepHourly?: number;
@@ -1028,13 +1024,54 @@ export type UpdateBackupScheduleResponses = {
} | null;
updatedAt: number;
volumeId: number;
volumeName: string;
};
};
};
export type UpdateBackupScheduleResponse = UpdateBackupScheduleResponses[keyof UpdateBackupScheduleResponses];
export type GetBackupScheduleForVolumeData = {
body?: never;
path: {
volumeId: string;
};
query?: never;
url: "/api/v1/backups/volume/{volumeId}";
};
export type GetBackupScheduleForVolumeResponses = {
/**
* Backup schedule details for the volume
*/
200: {
createdAt: number;
cronExpression: string;
enabled: boolean;
excludePatterns: Array<string> | null;
id: number;
includePatterns: Array<string> | null;
lastBackupAt: number | null;
lastBackupError: string | null;
lastBackupStatus: "error" | "success" | null;
nextBackupAt: number | null;
repositoryId: string;
retentionPolicy: {
keepDaily?: number;
keepHourly?: number;
keepLast?: number;
keepMonthly?: number;
keepWeekly?: number;
keepWithinDuration?: string;
keepYearly?: number;
} | null;
updatedAt: number;
volumeId: number;
} | null;
};
export type GetBackupScheduleForVolumeResponse =
GetBackupScheduleForVolumeResponses[keyof GetBackupScheduleForVolumeResponses];
export type RunBackupNowData = {
body?: never;
path: {

View File

@@ -16,12 +16,12 @@ export const formSchema = type({
}).and(repositoryConfigSchema);
const cleanSchema = type.pipe((d) => formSchema(deepClean(d)));
export type FormValues = typeof formSchema.inferIn;
export type RepositoryFormValues = typeof formSchema.inferIn;
type Props = {
onSubmit: (values: FormValues) => void;
onSubmit: (values: RepositoryFormValues) => void;
mode?: "create" | "update";
initialValues?: Partial<FormValues>;
initialValues?: Partial<RepositoryFormValues>;
formId?: string;
loading?: boolean;
className?: string;
@@ -40,7 +40,7 @@ export const CreateRepositoryForm = ({
loading,
className,
}: Props) => {
const form = useForm<FormValues>({
const form = useForm<RepositoryFormValues>({
resolver: arktypeResolver(cleanSchema as unknown as typeof formSchema),
defaultValues: initialValues,
resetOptions: {

View File

@@ -1,4 +1,4 @@
import type { GetMeResponse, GetRepositoryResponse, GetVolumeResponse } from "~/api-client";
import type { GetBackupScheduleResponse, GetMeResponse, GetRepositoryResponse, GetVolumeResponse } from "~/api-client";
export type Volume = GetVolumeResponse["volume"];
export type StatFs = GetVolumeResponse["statfs"];
@@ -7,3 +7,5 @@ export type VolumeStatus = Volume["status"];
export type User = GetMeResponse["user"];
export type Repository = GetRepositoryResponse["repository"];
export type BackupSchedule = GetBackupScheduleResponse["schedule"];

View File

@@ -0,0 +1,351 @@
import { arktypeResolver } from "@hookform/resolvers/arktype";
import { useQuery } from "@tanstack/react-query";
import { type } from "arktype";
import { useForm } from "react-hook-form";
import { listRepositoriesOptions } from "~/api-client/@tanstack/react-query.gen";
import { RepositoryIcon } from "~/components/repository-icon";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
import { Input } from "~/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select";
import type { BackupSchedule, Volume } from "~/lib/types";
import { deepClean } from "~/utils/object";
const formSchema = type({
repositoryId: "string",
excludePatterns: "string[]?",
includePatterns: "string[]?",
frequency: "string",
dailyTime: "string?",
weeklyDay: "string?",
keepLast: "number?",
keepHourly: "number?",
keepDaily: "number?",
keepWeekly: "number?",
keepMonthly: "number?",
keepYearly: "number?",
});
const cleanSchema = type.pipe((d) => formSchema(deepClean(d)));
export const weeklyDays = [
{ label: "Monday", value: "1" },
{ label: "Tuesday", value: "2" },
{ label: "Wednesday", value: "3" },
{ label: "Thursday", value: "4" },
{ label: "Friday", value: "5" },
{ label: "Saturday", value: "6" },
{ label: "Sunday", value: "0" },
];
export type BackupScheduleFormValues = typeof formSchema.infer;
type Props = {
volume: Volume;
initialValues?: BackupSchedule;
onSubmit: (data: BackupScheduleFormValues) => void;
loading?: boolean;
summaryContent?: React.ReactNode;
};
const backupScheduleToFormValues = (schedule?: BackupSchedule): BackupScheduleFormValues | undefined => {
if (!schedule) {
return undefined;
}
const parts = schedule.cronExpression.split(" ");
const [minutePart, hourPart, , , dayOfWeekPart] = parts;
const isHourly = hourPart === "*";
const isDaily = !isHourly && dayOfWeekPart === "*";
const frequency = isHourly ? "hourly" : isDaily ? "daily" : "weekly";
const dailyTime = isHourly ? undefined : `${hourPart.padStart(2, "0")}:${minutePart.padStart(2, "0")}`;
const weeklyDay = frequency === "weekly" ? dayOfWeekPart : undefined;
return {
repositoryId: schedule.repositoryId,
frequency,
dailyTime,
weeklyDay,
...schedule.retentionPolicy,
};
};
export const CreateScheduleForm = ({ initialValues, onSubmit, volume, loading, summaryContent }: Props) => {
console.log("Initial Values:", initialValues);
const form = useForm<BackupScheduleFormValues>({
resolver: arktypeResolver(cleanSchema as unknown as typeof formSchema),
defaultValues: backupScheduleToFormValues(initialValues),
});
const { data: repositoriesData } = useQuery({
...listRepositoriesOptions(),
});
const frequency = form.watch("frequency");
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]"
>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle>Backup automation</CardTitle>
<CardDescription className="mt-1">
Schedule automated backups of <strong>{volume.name}</strong> to a secure repository.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-6 md:grid-cols-2">
<FormField
control={form.control}
name="repositoryId"
render={({ field }) => (
<FormItem className="md:col-span-2">
<FormLabel>Backup repository</FormLabel>
<FormControl>
<Select {...field} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select a repository" />
</SelectTrigger>
<SelectContent>
{repositoriesData?.repositories.map((repo) => (
<SelectItem key={repo.id} value={repo.id}>
<span className="flex items-center gap-2">
<RepositoryIcon backend={repo.type} />
{repo.name}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormDescription>
Choose where encrypted backups for <strong>{volume.name}</strong> will be stored.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="frequency"
render={({ field }) => (
<FormItem>
<FormLabel>Backup frequency</FormLabel>
<FormControl>
<Select {...field} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select frequency" />
</SelectTrigger>
<SelectContent>
<SelectItem value="hourly">Hourly</SelectItem>
<SelectItem value="daily">Daily</SelectItem>
<SelectItem value="weekly">Weekly</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormDescription>Define how often snapshots should be taken.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{frequency !== "hourly" && (
<FormField
control={form.control}
name="dailyTime"
render={({ field }) => (
<FormItem>
<FormLabel>Execution time</FormLabel>
<FormControl>
<Input type="time" {...field} />
</FormControl>
<FormDescription>Time of day when the backup will run.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
{frequency === "weekly" && (
<FormField
control={form.control}
name="weeklyDay"
render={({ field }) => (
<FormItem className="md:col-span-2">
<FormLabel>Execution day</FormLabel>
<FormControl>
<Select {...field} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue placeholder="Select a day" />
</SelectTrigger>
<SelectContent>
{weeklyDays.map((day) => (
<SelectItem key={day.value} value={day.value}>
{day.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormDescription>Choose which day of the week to run the backup.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Retention policy</CardTitle>
<CardDescription>Define how many snapshots to keep. Leave empty to keep all.</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 md:grid-cols-2">
<FormField
control={form.control}
name="keepLast"
render={({ field }) => (
<FormItem>
<FormLabel>Keep last N snapshots</FormLabel>
<FormControl>
<Input
{...field}
type="number"
min={0}
placeholder="Optional"
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the N most recent snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="keepHourly"
render={({ field }) => (
<FormItem>
<FormLabel>Keep hourly</FormLabel>
<FormControl>
<Input
type="number"
min={0}
placeholder="Optional"
{...field}
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the last N hourly snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="keepDaily"
render={({ field }) => (
<FormItem>
<FormLabel>Keep daily</FormLabel>
<FormControl>
<Input
type="number"
min={0}
placeholder="e.g., 7"
{...field}
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the last N daily snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="keepWeekly"
render={({ field }) => (
<FormItem>
<FormLabel>Keep weekly</FormLabel>
<FormControl>
<Input
type="number"
min={0}
placeholder="e.g., 4"
{...field}
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the last N weekly snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="keepMonthly"
render={({ field }) => (
<FormItem>
<FormLabel>Keep monthly</FormLabel>
<FormControl>
<Input
type="number"
min={0}
placeholder="e.g., 6"
{...field}
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the last N monthly snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="keepYearly"
render={({ field }) => (
<FormItem>
<FormLabel>Keep yearly</FormLabel>
<FormControl>
<Input
type="number"
min={0}
placeholder="Optional"
{...field}
onChange={(v) => field.onChange(Number(v.target.value))}
/>
</FormControl>
<FormDescription>Keep the last N yearly snapshots.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
<CardFooter className="border-t pt-6">
<Button type="submit" className="ml-auto" variant="default" loading={loading}>
{initialValues ? "Update schedule" : "Create schedule"}
</Button>
</CardFooter>
</Card>
</div>
{summaryContent && <div className="h-full">{summaryContent}</div>}
</form>
</Form>
);
};

View File

@@ -1,607 +1,277 @@
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { OnOff } from "~/components/onoff";
import { useMemo, useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Link } from "react-router";
import { toast } from "sonner";
import { Database, Plus } from "lucide-react";
import { Button } from "~/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from "~/components/ui/form";
import { Input } from "~/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select";
import { Switch } from "~/components/ui/switch";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
import { OnOff } from "~/components/onoff";
import type { Volume } from "~/lib/types";
type BackupDestination = "s3" | "sftp" | "filesystem";
type BackupFrequency = "hourly" | "daily" | "weekly";
type BackupEncryption = "none" | "aes256" | "gpg";
type BackupFormValues = {
isEnabled: boolean;
destination: BackupDestination;
frequency: BackupFrequency;
dailyTime: string;
weeklyDay: string;
retentionCopies: string;
retentionDays: string;
notifyOnFailure: boolean;
notificationWebhook: string;
encryption: BackupEncryption;
encryptionPassword: string;
s3Bucket: string;
s3Region: string;
s3PathPrefix: string;
sftpHost: string;
sftpPort: string;
sftpUsername: string;
sftpPath: string;
filesystemPath: string;
};
import {
listRepositoriesOptions,
createBackupScheduleMutation,
updateBackupScheduleMutation,
getBackupScheduleForVolumeOptions,
} from "~/api-client/@tanstack/react-query.gen";
import { parseError } from "~/lib/errors";
import { CreateScheduleForm, type BackupScheduleFormValues } from "../components/create-schedule-form";
type Props = {
volume: Volume;
};
const weeklyDays = [
{ label: "Monday", value: "monday" },
{ label: "Tuesday", value: "tuesday" },
{ label: "Wednesday", value: "wednesday" },
{ label: "Thursday", value: "thursday" },
{ label: "Friday", value: "friday" },
{ label: "Saturday", value: "saturday" },
{ label: "Sunday", value: "sunday" },
];
const getCronExpression = (frequency: string, dailyTime?: string, weeklyDay?: string): string => {
if (frequency === "hourly") {
return "0 * * * *";
}
if (!dailyTime) {
dailyTime = "02:00";
}
const [hours, minutes] = dailyTime.split(":");
if (frequency === "daily") {
return `${minutes} ${hours} * * *`;
}
return `${minutes} ${hours} * * ${weeklyDay ?? "0"}`;
};
export const VolumeBackupsTabContent = ({ volume }: Props) => {
const form = useForm<BackupFormValues>({
defaultValues: {
isEnabled: true,
destination: "s3",
frequency: "daily",
dailyTime: "02:00",
weeklyDay: "sunday",
retentionCopies: "7",
retentionDays: "30",
notifyOnFailure: true,
notificationWebhook: "",
encryption: "aes256",
encryptionPassword: "",
s3Bucket: "",
s3Region: "us-east-1",
s3PathPrefix: `${volume.name}/backups`,
sftpHost: "",
sftpPort: "22",
sftpUsername: "",
sftpPath: `/backups/${volume.name}`,
filesystemPath: `/var/backups/${volume.name}`,
},
const queryClient = useQueryClient();
const { data: repositoriesData, isLoading: loadingRepositories } = useQuery({
...listRepositoriesOptions(),
});
const destination = form.watch("destination");
const frequency = form.watch("frequency");
const encryption = form.watch("encryption");
const notifyOnFailure = form.watch("notifyOnFailure");
const values = form.watch();
const { data: existingSchedule, isLoading: loadingSchedules } = useQuery({
...getBackupScheduleForVolumeOptions({ path: { volumeId: volume.id.toString() } }),
});
const [isEnabled, setIsEnabled] = useState(existingSchedule?.enabled ?? true);
const repositories = repositoriesData?.repositories || [];
const selectedRepository = repositories.find((r) => r.id === (existingSchedule?.repositoryId ?? ""));
const summary = useMemo(() => {
const scheduleLabel =
frequency === "hourly"
? "Every hour"
: frequency === "daily"
? `Every day at ${values.dailyTime}`
: `Every ${values.weeklyDay.charAt(0).toUpperCase()}${values.weeklyDay.slice(1)} at ${values.dailyTime}`;
const scheduleLabel = existingSchedule ? existingSchedule.cronExpression : "Every day at 02:00";
const destinationLabel = (() => {
if (destination === "s3") {
return `Amazon S3 → ${values.s3Bucket || "<bucket>"} (${values.s3Region})`;
}
if (destination === "sftp") {
return `SFTP → ${values.sftpUsername || "user"}@${values.sftpHost || "server"}:${values.sftpPath}`;
}
return `Filesystem → ${values.filesystemPath}`;
})();
const retentionParts: string[] = [];
if (existingSchedule?.retentionPolicy) {
const rp = existingSchedule.retentionPolicy;
if (rp.keepLast) retentionParts.push(`${rp.keepLast} last`);
if (rp.keepHourly) retentionParts.push(`${rp.keepHourly} hourly`);
if (rp.keepDaily) retentionParts.push(`${rp.keepDaily} daily`);
if (rp.keepWeekly) retentionParts.push(`${rp.keepWeekly} weekly`);
if (rp.keepMonthly) retentionParts.push(`${rp.keepMonthly} monthly`);
if (rp.keepYearly) retentionParts.push(`${rp.keepYearly} yearly`);
}
return {
vol: volume.name,
scheduleLabel,
destinationLabel,
encryptionLabel: encryption === "none" ? "Disabled" : encryption.toUpperCase(),
retentionLabel: `${values.retentionCopies} copies \u2022 ${values.retentionDays} days`,
notificationsLabel: notifyOnFailure
? values.notificationWebhook
? `Webhook to ${values.notificationWebhook}`
: "Webhook pending configuration"
: "Disabled",
repositoryLabel: selectedRepository?.name || "No repository selected",
retentionLabel: retentionParts.length > 0 ? retentionParts.join(" • ") : "No retention policy",
};
}, [
destination,
encryption,
frequency,
notifyOnFailure,
values.dailyTime,
values.filesystemPath,
values.notificationWebhook,
values.retentionCopies,
values.retentionDays,
values.s3Bucket,
values.s3Region,
values.sftpHost,
values.sftpPath,
values.sftpUsername,
values.weeklyDay,
volume.name,
]);
}, [existingSchedule, selectedRepository, volume.name]);
const handleSubmit = (formValues: BackupFormValues) => {
console.info("Backup configuration", formValues);
const createSchedule = useMutation({
...createBackupScheduleMutation(),
onSuccess: () => {
toast.success("Backup schedule created successfully");
queryClient.invalidateQueries({ queryKey: ["listBackupSchedules"] });
},
onError: (error) => {
toast.error("Failed to create backup schedule", {
description: parseError(error)?.message,
});
},
});
const updateSchedule = useMutation({
...updateBackupScheduleMutation(),
onSuccess: () => {
toast.success("Backup schedule updated successfully");
queryClient.invalidateQueries({ queryKey: ["listBackupSchedules"] });
},
onError: (error) => {
toast.error("Failed to update backup schedule", {
description: parseError(error)?.message,
});
},
});
const handleSubmit = (formValues: BackupScheduleFormValues) => {
const cronExpression = getCronExpression(formValues.frequency, formValues.dailyTime, formValues.weeklyDay);
const retentionPolicy: Record<string, number> = {};
if (formValues.keepLast) retentionPolicy.keepLast = formValues.keepLast;
if (formValues.keepHourly) retentionPolicy.keepHourly = formValues.keepHourly;
if (formValues.keepDaily) retentionPolicy.keepDaily = formValues.keepDaily;
if (formValues.keepWeekly) retentionPolicy.keepWeekly = formValues.keepWeekly;
if (formValues.keepMonthly) retentionPolicy.keepMonthly = formValues.keepMonthly;
if (formValues.keepYearly) retentionPolicy.keepYearly = formValues.keepYearly;
if (existingSchedule) {
updateSchedule.mutate({
path: { scheduleId: existingSchedule.id.toString() },
body: {
repositoryId: formValues.repositoryId,
enabled: isEnabled,
cronExpression,
retentionPolicy: Object.keys(retentionPolicy).length > 0 ? retentionPolicy : undefined,
},
});
} else {
createSchedule.mutate({
body: {
volumeId: volume.id,
repositoryId: formValues.repositoryId,
enabled: true,
cronExpression,
retentionPolicy: Object.keys(retentionPolicy).length > 0 ? retentionPolicy : undefined,
},
});
}
};
if (loadingRepositories || loadingSchedules) {
return (
<Card>
<CardContent className="py-12 text-center">
<p className="text-muted-foreground">Loading...</p>
</CardContent>
</Card>
);
}
if (repositories.length === 0) {
return (
<Card>
<CardContent className="py-16">
<div className="flex flex-col items-center justify-center text-center">
<div className="relative mb-6">
<div className="absolute inset-0 animate-pulse">
<div className="w-24 h-24 rounded-full bg-primary/10 blur-2xl" />
</div>
<div className="relative flex items-center justify-center w-24 h-24 rounded-full bg-gradient-to-br from-primary/20 to-primary/5 border-2 border-primary/20">
<Database className="w-12 h-12 text-primary/70" strokeWidth={1.5} />
</div>
</div>
<h3 className="text-xl font-semibold mb-2">No repositories available</h3>
<p className="text-muted-foreground text-sm mb-6 max-w-md">
To schedule automated backups, you need to create a repository first. Repositories are secure storage
locations where your backups will be stored.
</p>
<Button asChild>
<Link to="/repositories">
<Plus className="h-4 w-4 mr-2" />
Create a repository
</Link>
</Button>
</div>
</CardContent>
</Card>
);
}
const handleToggleEnabled = (enabled: boolean) => {
if (!existingSchedule) return;
setIsEnabled(enabled);
updateSchedule.mutate({
path: { scheduleId: existingSchedule.id.toString() },
body: {
repositoryId: existingSchedule.repositoryId,
enabled,
cronExpression: existingSchedule.cronExpression,
retentionPolicy: existingSchedule.retentionPolicy || undefined,
},
});
};
return (
<div className="relative">
<div className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]">
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)} className="grid gap-4">
<Card>
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle>Backup automation</CardTitle>
<CardDescription className="mt-1">
Enable scheduled snapshots and off-site replication for this volume.
</CardDescription>
</div>
<FormField
control={form.control}
name="isEnabled"
render={({ field }) => (
<FormItem className="flex flex-col items-center space-y-2">
<FormControl>
<OnOff
isOn={field.value}
toggle={field.onChange}
enabledLabel="Enabled"
disabledLabel="Paused"
/>
</FormControl>
</FormItem>
)}
/>
</CardHeader>
<CardContent className="grid gap-6 md:grid-cols-2">
<FormField
control={form.control}
name="destination"
render={({ field }) => (
<FormItem>
<FormLabel>Destination provider</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
<SelectValue placeholder="Select a destination" />
</SelectTrigger>
<SelectContent>
<SelectItem value="s3">Amazon S3</SelectItem>
<SelectItem value="sftp">SFTP server</SelectItem>
<SelectItem value="filesystem">Local filesystem</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormDescription>
Choose where backups for <strong>{volume.name}</strong> will be stored.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="frequency"
render={({ field }) => (
<FormItem>
<FormLabel>Backup frequency</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
<SelectValue placeholder="Select frequency" />
</SelectTrigger>
<SelectContent>
<SelectItem value="hourly">Hourly</SelectItem>
<SelectItem value="daily">Daily</SelectItem>
<SelectItem value="weekly">Weekly</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormDescription>Define how often snapshots should be taken.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{frequency !== "hourly" && (
<FormField
control={form.control}
name="dailyTime"
render={({ field }) => (
<FormItem>
<FormLabel>Execution time</FormLabel>
<FormControl>
<Input type="time" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>Time of day when the backup will run.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
{frequency === "weekly" && (
<FormField
control={form.control}
name="weeklyDay"
render={({ field }) => (
<FormItem>
<FormLabel>Execution day</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
<SelectValue placeholder="Select a day" />
</SelectTrigger>
<SelectContent>
{weeklyDays.map((day) => (
<SelectItem key={day.value} value={day.value}>
{day.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormControl>
<FormDescription>Choose which day of the week to run the backup.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
<FormField
control={form.control}
name="retentionCopies"
render={({ field }) => (
<FormItem>
<FormLabel>Max copies to retain</FormLabel>
<FormControl>
<Input
type="number"
min={1}
value={field.value}
onChange={(event) => field.onChange(event.target.value)}
/>
</FormControl>
<FormDescription>Oldest backups will be pruned after this many copies.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="retentionDays"
render={({ field }) => (
<FormItem>
<FormLabel>Retention window (days)</FormLabel>
<FormControl>
<Input
type="number"
min={1}
value={field.value}
onChange={(event) => field.onChange(event.target.value)}
/>
</FormControl>
<FormDescription>Backups older than this window will be removed.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
{destination === "s3" && (
<Card>
<CardHeader>
<CardTitle>Amazon S3 bucket</CardTitle>
<CardDescription>
Define the bucket and path where compressed archives will be uploaded.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 md:grid-cols-2">
<FormField
control={form.control}
name="s3Bucket"
render={({ field }) => (
<FormItem>
<FormLabel>Bucket name</FormLabel>
<FormControl>
<Input placeholder="ironmount-backups" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>
Ensure the bucket has versioning and lifecycle rules as needed.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="s3Region"
render={({ field }) => (
<FormItem>
<FormLabel>Region</FormLabel>
<FormControl>
<Input placeholder="us-east-1" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>AWS region where the bucket resides.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="s3PathPrefix"
render={({ field }) => (
<FormItem className="md:col-span-2">
<FormLabel>Object prefix</FormLabel>
<FormControl>
<Input placeholder="volume-name/backups" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>
Backups will be stored under this key prefix inside the bucket.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
)}
{destination === "sftp" && (
<Card>
<CardHeader>
<CardTitle>SFTP target</CardTitle>
<CardDescription>
Connect to a remote host that will receive encrypted backup archives.
</CardDescription>
</CardHeader>
<CardContent className="grid gap-4 md:grid-cols-2">
<FormField
control={form.control}
name="sftpHost"
render={({ field }) => (
<FormItem>
<FormLabel>Hostname</FormLabel>
<FormControl>
<Input placeholder="backup.example.com" value={field.value} onChange={field.onChange} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="sftpPort"
render={({ field }) => (
<FormItem>
<FormLabel>Port</FormLabel>
<FormControl>
<Input type="number" min={1} value={field.value} onChange={field.onChange} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="sftpUsername"
render={({ field }) => (
<FormItem>
<FormLabel>Username</FormLabel>
<FormControl>
<Input placeholder="backup" value={field.value} onChange={field.onChange} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="sftpPath"
render={({ field }) => (
<FormItem>
<FormLabel>Destination path</FormLabel>
<FormControl>
<Input placeholder="/var/backups/ironmount" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>Ensure the directory exists and has write permissions.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
)}
{destination === "filesystem" && (
<Card>
<CardHeader>
<CardTitle>Filesystem target</CardTitle>
<CardDescription>Persist archives to a directory on the host running Ironmount.</CardDescription>
</CardHeader>
<CardContent className="grid gap-4">
<FormField
control={form.control}
name="filesystemPath"
render={({ field }) => (
<FormItem>
<FormLabel>Backup directory</FormLabel>
<FormControl>
<Input placeholder="/var/backups/volume-name" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>The directory must be mounted with sufficient capacity.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle>Encryption & notifications</CardTitle>
<CardDescription>Secure backups and stay informed when something goes wrong.</CardDescription>
</CardHeader>
<CardContent className="grid gap-6 md:grid-cols-2">
<FormField
control={form.control}
name="encryption"
render={({ field }) => (
<FormItem>
<FormLabel>Encryption</FormLabel>
<FormControl>
<Select onValueChange={field.onChange} value={field.value}>
<SelectTrigger>
<SelectValue placeholder="Select encryption" />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Disabled</SelectItem>
<SelectItem value="aes256">AES-256 (managed key)</SelectItem>
<SelectItem value="gpg">GPG (bring your own)</SelectItem>
</SelectContent>
</Select>
</FormControl>
<FormDescription>Protect backups at rest with optional encryption.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{encryption !== "none" && (
<FormField
control={form.control}
name="encryptionPassword"
render={({ field }) => (
<FormItem>
<FormLabel>Encryption secret</FormLabel>
<FormControl>
<Input type="password" placeholder="••••••••" value={field.value} onChange={field.onChange} />
</FormControl>
<FormDescription>
Store this password securely. It will be required to restore backups.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
<FormField
control={form.control}
name="notifyOnFailure"
render={({ field }) => (
<FormItem className="flex flex-col space-y-2">
<FormLabel>Failure alerts</FormLabel>
<div className="flex items-center justify-between rounded-lg border px-3 py-2">
<div className="space-y-1">
<p className="text-sm font-medium">Webhook notifications</p>
<p className="text-xs text-muted-foreground">Send an HTTP POST when a backup fails.</p>
</div>
<FormControl>
<Switch checked={field.value} onCheckedChange={field.onChange} />
</FormControl>
</div>
<FormMessage />
</FormItem>
)}
/>
{notifyOnFailure && (
<FormField
control={form.control}
name="notificationWebhook"
render={({ field }) => (
<FormItem className="md:col-span-2">
<FormLabel>Webhook URL</FormLabel>
<FormControl>
<Input
placeholder="https://hooks.example.com/ironmount"
value={field.value}
onChange={field.onChange}
/>
</FormControl>
<FormDescription>Ironmount will POST a JSON payload with failure details.</FormDescription>
<FormMessage />
</FormItem>
)}
/>
)}
</CardContent>
<CardFooter className="border-t pt-6">
<Button type="submit" className="ml-auto" variant="default">
Save draft configuration
</Button>
</CardFooter>
</Card>
</form>
</Form>
<Card className="h-full">
<CardHeader>
<CardTitle>Runbook summary</CardTitle>
<CardDescription>Validate the automation before enabling it in production.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4 text-sm">
<div>
<p className="text-xs uppercase text-muted-foreground">Volume</p>
<p className="font-medium">{summary.vol}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Schedule</p>
<p className="font-medium">{summary.scheduleLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Destination</p>
<p className="font-medium">{summary.destinationLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Retention</p>
<p className="font-medium">{summary.retentionLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Encryption</p>
<p className="font-medium">{summary.encryptionLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Notifications</p>
<p className="font-medium">{summary.notificationsLabel}</p>
</div>
</CardContent>
</Card>
</div>
<div className="pointer-events-auto absolute inset-0 z-20 flex cursor-not-allowed select-none flex-col items-center justify-center gap-6 bg-gradient-to-br from-background/95 via-background/80 to-background/40 px-6 text-center backdrop-blur-x">
<div className="inline-flex items-center gap-2 rounded-full border border-muted-foreground/30 bg-muted/40 px-4 py-1.5 text-xs font-semibold uppercase tracking-[0.35em] text-muted-foreground">
<span className="tracking-[0.2em]">Preview</span>
</div>
<div className="max-w-md space-y-3 text-balance">
<h3 className="text-2xl font-semibold">Automated backups are coming soon</h3>
<p className="text-sm text-muted-foreground">
We&apos;re working hard to bring robust backup and snapshot capabilities to Ironmount.
</p>
</div>
<div className="rounded-xl border border-dashed border-muted-foreground/30 bg-background/70 px-4 py-2 text-xs text-muted-foreground">
Coming soon stay tuned!
</div>
</div>
</div>
<CreateScheduleForm
volume={volume}
initialValues={existingSchedule ?? undefined}
onSubmit={handleSubmit}
summaryContent={
existingSchedule ? (
<Card className="h-full">
<CardHeader className="flex flex-row items-center justify-between gap-4">
<div>
<CardTitle>Schedule summary</CardTitle>
<CardDescription>Review the backup configuration.</CardDescription>
</div>
<OnOff isOn={isEnabled} toggle={handleToggleEnabled} enabledLabel="Enabled" disabledLabel="Paused" />
</CardHeader>
<CardContent className="flex flex-col gap-4 text-sm">
<div>
<p className="text-xs uppercase text-muted-foreground">Volume</p>
<p className="font-medium">{summary.vol}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Schedule</p>
<p className="font-medium">{summary.scheduleLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Repository</p>
<p className="font-medium">{summary.repositoryLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Retention</p>
<p className="font-medium">{summary.retentionLabel}</p>
</div>
{existingSchedule && (
<>
<div>
<p className="text-xs uppercase text-muted-foreground">Last backup</p>
<p className="font-medium">
{existingSchedule.lastBackupAt
? new Date(existingSchedule.lastBackupAt).toLocaleString()
: "Never"}
</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Status</p>
<p className="font-medium">
{existingSchedule.lastBackupStatus === "success" && "✓ Success"}
{existingSchedule.lastBackupStatus === "error" && "✗ Error"}
{!existingSchedule.lastBackupStatus && "—"}
</p>
</div>
</>
)}
</CardContent>
</Card>
) : (
<Card className="h-full">
<CardHeader>
<CardTitle>Schedule summary</CardTitle>
<CardDescription>Review the backup configuration before saving.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4 text-sm">
<div>
<p className="text-xs uppercase text-muted-foreground">Volume</p>
<p className="font-medium">{summary.vol}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Schedule</p>
<p className="font-medium">{summary.scheduleLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Repository</p>
<p className="font-medium">{summary.repositoryLabel}</p>
</div>
<div>
<p className="text-xs uppercase text-muted-foreground">Retention</p>
<p className="font-medium">{summary.retentionLabel}</p>
</div>
</CardContent>
</Card>
)
}
/>
);
};

View File

@@ -1,12 +1,12 @@
export function deepClean<T>(obj: T): T {
if (Array.isArray(obj)) {
return obj.map(deepClean).filter((v) => v !== undefined && v !== null) as T;
return obj.map(deepClean).filter((v) => v !== undefined && v !== null && v !== "") as T;
}
if (obj && typeof obj === "object") {
return Object.entries(obj).reduce((acc, [key, value]) => {
const cleaned = deepClean(value);
if (cleaned !== undefined) acc[key as keyof T] = cleaned;
if (cleaned !== undefined && cleaned !== "") acc[key as keyof T] = cleaned;
return acc;
}, {} as T);
}

View File

@@ -29,6 +29,7 @@
"arktype": "^2.1.23",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cron-parser": "^5.4.0",
"date-fns": "^4.1.0",
"dither-plugin": "^1.1.1",
"isbot": "^5.1.31",

View File

@@ -5,6 +5,7 @@ import {
createBackupScheduleDto,
deleteBackupScheduleDto,
getBackupScheduleDto,
getBackupScheduleForVolumeDto,
listBackupSchedulesDto,
runBackupNowDto,
updateBackupScheduleBody,
@@ -25,6 +26,12 @@ export const backupScheduleController = new Hono()
return c.json({ schedule }, 200);
})
.get("/volume/:volumeId", getBackupScheduleForVolumeDto, async (c) => {
const volumeId = c.req.param("volumeId");
const schedule = await backupsService.getScheduleForVolume(Number(volumeId));
return c.json(schedule, 200);
})
.post("/", createBackupScheduleDto, validator("json", createBackupScheduleBody), async (c) => {
const body = c.req.valid("json");

View File

@@ -16,14 +16,12 @@ export type RetentionPolicy = typeof retentionPolicySchema.infer;
const backupScheduleSchema = type({
id: "number",
volumeId: "number",
volumeName: "string",
repositoryId: "string",
repositoryName: "string",
enabled: "boolean",
cronExpression: "string",
retentionPolicy: retentionPolicySchema.or("null"),
excludePatterns: "string[]",
includePatterns: "string[]",
excludePatterns: "string[] | null",
includePatterns: "string[] | null",
lastBackupAt: "number | null",
lastBackupStatus: "'success' | 'error' | null",
lastBackupError: "string | null",
@@ -66,7 +64,7 @@ export const getBackupScheduleResponse = type({
schedule: backupScheduleSchema,
});
export type GetBackupScheduleResponseDto = typeof getBackupScheduleResponse.infer;
export type GetBackupScheduleDto = typeof getBackupScheduleResponse.infer;
export const getBackupScheduleDto = describeRoute({
description: "Get a backup schedule by ID",
@@ -84,6 +82,26 @@ export const getBackupScheduleDto = describeRoute({
},
});
export const getBackupScheduleForVolumeResponse = backupScheduleSchema.or("null");
export type GetBackupScheduleForVolumeResponseDto = typeof getBackupScheduleForVolumeResponse.infer;
export const getBackupScheduleForVolumeDto = describeRoute({
description: "Get a backup schedule for a specific volume",
tags: ["Backups"],
operationId: "getBackupScheduleForVolume",
responses: {
200: {
description: "Backup schedule details for the volume",
content: {
"application/json": {
schema: resolver(getBackupScheduleForVolumeResponse),
},
},
},
},
});
/**
* Create a new backup schedule
*/
@@ -105,6 +123,8 @@ export const createBackupScheduleResponse = type({
schedule: backupScheduleSchema,
});
export type CreateBackupScheduleDto = typeof createBackupScheduleResponse.infer;
export const createBackupScheduleDto = describeRoute({
description: "Create a new backup schedule for a volume",
operationId: "createBackupSchedule",

View File

@@ -247,6 +247,14 @@ const getSchedulesToExecute = async () => {
return schedulesToRun;
};
const getScheduleForVolume = async (volumeId: number) => {
const schedule = await db.query.backupSchedulesTable.findFirst({
where: eq(backupSchedulesTable.volumeId, volumeId),
});
return schedule ?? null;
};
export const backupsService = {
listSchedules,
getSchedule,
@@ -255,4 +263,5 @@ export const backupsService = {
deleteSchedule,
executeBackup,
getSchedulesToExecute,
getScheduleForVolume,
};

View File

@@ -3,6 +3,7 @@ import { type } from "arktype";
import { describeRoute, resolver } from "hono-openapi";
const volumeSchema = type({
id: "number",
name: "string",
path: "string",
type: type.valueOf(BACKEND_TYPES),

View File

@@ -31,6 +31,7 @@
"arktype": "^2.1.23",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cron-parser": "^5.4.0",
"date-fns": "^4.1.0",
"dither-plugin": "^1.1.1",
"isbot": "^5.1.31",