feat: implement rollback functionality with UI components and database schema updates

- Added ShowEnv and ShowRollbackSettings components for displaying and configuring rollback settings.
- Implemented ShowRollbacks component to list and manage rollbacks for applications.
- Created rollback database schema and updated application schema to include rollback settings.
- Added API routes for managing rollbacks, including fetching, creating, and deleting rollbacks.
- Integrated rollback functionality into the application deployment process.
This commit is contained in:
Mauricio Siu
2025-05-10 20:28:34 -06:00
parent aa475e6123
commit 2ad8bf355b
17 changed files with 12317 additions and 2 deletions

View File

@@ -0,0 +1,46 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Eye } from "lucide-react";
import { CodeEditor } from "@/components/shared/code-editor";
interface Props {
env: string | null;
}
export const ShowEnv = ({ env }: Props) => {
if (!env) return null;
return (
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="text-xs">
<Eye className="size-3.5 mr-1" />
View Env
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Environment Variables</DialogTitle>
<DialogDescription>
Environment variables for this rollback version
</DialogDescription>
</DialogHeader>
<div className="mt-4">
<CodeEditor
language="shell"
value={env}
className="h-[12rem] font-mono"
/>
</div>
</DialogContent>
</Dialog>
);
};

View File

@@ -0,0 +1,143 @@
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { api } from "@/utils/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";
const formSchema = z.object({
rollbackActive: z.boolean(),
limitRollback: z.number().min(1).max(50),
});
type FormValues = z.infer<typeof formSchema>;
interface Props {
applicationId: string;
children?: React.ReactNode;
}
export const ShowRollbackSettings = ({ applicationId, children }: Props) => {
const [isOpen, setIsOpen] = useState(false);
const { data: application, refetch } = api.application.one.useQuery(
{
applicationId,
},
{
enabled: !!applicationId,
},
);
const { mutateAsync: updateApplication, isLoading } =
api.application.update.useMutation();
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
rollbackActive: application?.rollbackActive ?? false,
limitRollback: application?.limitRollback ?? 5,
},
});
const onSubmit = async (data: FormValues) => {
await updateApplication({
applicationId,
rollbackActive: data.rollbackActive,
limitRollback: data.limitRollback,
})
.then(() => {
toast.success("Rollback settings updated");
setIsOpen(false);
refetch();
})
.catch(() => {
toast.error("Failed to update rollback settings");
});
};
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>{children}</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Rollback Settings</DialogTitle>
<DialogDescription>
Configure how rollbacks work for this application
</DialogDescription>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<FormField
control={form.control}
name="rollbackActive"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between rounded-lg border p-4">
<div className="space-y-0.5">
<FormLabel className="text-base">
Enable Rollbacks
</FormLabel>
<FormDescription>
Allow rolling back to previous deployments
</FormDescription>
</div>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
</FormItem>
)}
/>
<FormField
control={form.control}
name="limitRollback"
render={({ field }) => (
<FormItem>
<FormLabel>Maximum Rollbacks</FormLabel>
<FormControl>
<Input
type="number"
{...field}
onChange={(e) => field.onChange(Number(e.target.value))}
/>
</FormControl>
<FormDescription>
Number of rollback points to maintain (1-50)
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" isLoading={isLoading}>
Save Settings
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
);
};

View File

@@ -0,0 +1,225 @@
import { api } from "@/utils/api";
import {
Loader2,
RefreshCcw,
Settings,
ArrowDownToLine,
CalendarClock,
Box,
Trash2,
} from "lucide-react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ShowRollbackSettings } from "./show-rollback-settings";
import { ShowEnv } from "./show-env";
import { format } from "date-fns";
import { DialogAction } from "@/components/shared/dialog-action";
import { toast } from "sonner";
interface Props {
applicationId: string;
}
export const ShowRollbacks = ({ applicationId }: Props) => {
const { data: application } = api.application.one.useQuery(
{
applicationId,
},
{
enabled: !!applicationId,
},
);
const { data, isLoading, refetch } = api.rollback.all.useQuery(
{
applicationId,
},
{
enabled: !!applicationId,
},
);
const { mutateAsync: rollbackVersion, isLoading: isRollingBack } =
api.rollback.rollback.useMutation();
const { mutateAsync: deleteRollback, isLoading: isDeleting } =
api.rollback.delete.useMutation();
if (!application?.rollbackActive) {
return (
<Card className="border px-6 shadow-none bg-transparent h-full min-h-[50vh]">
<CardHeader className="px-0">
<div className="flex justify-between items-center">
<div className="flex flex-col gap-2">
<CardTitle className="text-xl font-bold flex items-center gap-2">
Rollbacks
</CardTitle>
<CardDescription>
Rollback to a previous deployment.
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="py-0">
<div className="flex flex-col gap-2 items-center justify-center py-12 rounded-lg">
<Settings className="size-8 mb-4 text-muted-foreground" />
<p className="text-lg font-medium text-muted-foreground">
Rollbacks Not Enabled
</p>
<p className="text-sm text-muted-foreground mt-1 text-center max-w-md">
Enable rollbacks to keep track of previous deployments and roll
back when needed.
</p>
<ShowRollbackSettings applicationId={applicationId}>
<Button variant="outline" className="mt-4">
Configure Rollbacks
</Button>
</ShowRollbackSettings>
</div>
</CardContent>
</Card>
);
}
return (
<Card className="border px-6 shadow-none bg-transparent h-full min-h-[50vh]">
<CardHeader className="px-0">
<div className="flex justify-between items-center">
<div className="flex flex-col gap-2">
<CardTitle className="text-xl font-bold flex items-center gap-2">
Rollbacks
</CardTitle>
<CardDescription>
Rollback to a previous deployment.
</CardDescription>
</div>
<ShowRollbackSettings applicationId={applicationId}>
<Button variant="outline" className="mt-4">
Configure Rollbacks
</Button>
</ShowRollbackSettings>
</div>
</CardHeader>
<CardContent className="px-0 py-0">
{isLoading ? (
<div className="flex gap-4 w-full items-center justify-center text-center mx-auto min-h-[45vh]">
<Loader2 className="size-4 text-muted-foreground/70 transition-colors animate-spin self-center" />
<span className="text-sm text-muted-foreground/70">
Loading rollbacks...
</span>
</div>
) : data && data.length > 0 ? (
<div className="grid xl:grid-cols-2 gap-4 grid-cols-1 h-full">
{data.map((rollback) => {
return (
<div
key={rollback.rollbackId}
className="flex flex-col rounded-lg border text-card-foreground shadow-sm"
>
<div className="p-6 flex flex-col gap-4">
<div className="flex items-start justify-between">
<div className="flex items-start gap-4">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10">
<ArrowDownToLine className="size-5 text-primary" />
</div>
<div className="space-y-1">
<h3 className="font-medium leading-none flex items-center gap-2">
Version {rollback.version}
</h3>
<div className="flex items-center gap-4 text-sm text-muted-foreground">
<div className="flex items-center gap-1">
<CalendarClock className="size-3.5" />
<span>
{format(
new Date(rollback.createdAt),
"MMM dd, yyyy HH:mm",
)}
</span>
</div>
{rollback.image && (
<div className="flex items-center gap-1">
<Box className="size-3.5" />
<code className="text-xs bg-muted px-1 py-0.5 rounded">
{rollback.image}
</code>
</div>
)}
</div>
</div>
</div>
<div className="flex flex-col items-center gap-2">
<Button
variant="outline"
size="sm"
className="text-xs"
isLoading={isRollingBack}
onClick={async () => {
await rollbackVersion({
rollbackId: rollback.rollbackId,
})
.then(() => {
refetch();
toast.success("Rollback successful");
})
.catch(() => {
toast.error("Error rolling back");
});
}}
>
Rollback to this version
</Button>
<ShowEnv env={rollback.env} />
<DialogAction
title="Delete Rollback"
description="Are you sure you want to delete this rollback?"
type="destructive"
onClick={async () => {
await deleteRollback({
rollbackId: rollback.rollbackId,
})
.then(() => {
refetch();
toast.success("Rollback deleted successfully");
})
.catch(() => {
toast.error("Error deleting rollback");
});
}}
>
<Button
variant="ghost"
size="icon"
className="group hover:bg-red-500/10 "
isLoading={isDeleting}
>
<Trash2 className="size-4 text-primary group-hover:text-red-500" />
</Button>
</DialogAction>
</div>
</div>
</div>
</div>
);
})}
</div>
) : (
<div className="flex flex-col gap-2 items-center justify-center py-12 rounded-lg min-h-[30vh]">
<RefreshCcw className="size-8 mb-4 text-muted-foreground" />
<p className="text-lg font-medium text-muted-foreground">
No rollbacks
</p>
<p className="text-sm text-muted-foreground mt-1">
No rollbacks found for this application.
</p>
</div>
)}
</CardContent>
</Card>
);
};

View File

@@ -0,0 +1,13 @@
CREATE TABLE "rollback" (
"rollbackId" text PRIMARY KEY NOT NULL,
"env" text,
"applicationId" text NOT NULL,
"id" serial NOT NULL,
"image" text,
"enabled" boolean DEFAULT true NOT NULL,
"createdAt" text NOT NULL
);
--> statement-breakpoint
ALTER TABLE "application" ADD COLUMN "rollbackActive" boolean DEFAULT false;--> statement-breakpoint
ALTER TABLE "application" ADD COLUMN "limitRollback" integer DEFAULT 5;--> statement-breakpoint
ALTER TABLE "rollback" ADD CONSTRAINT "rollback_applicationId_application_applicationId_fk" FOREIGN KEY ("applicationId") REFERENCES "public"."application"("applicationId") ON DELETE cascade ON UPDATE no action;

View File

@@ -0,0 +1 @@
ALTER TABLE "rollback" RENAME COLUMN "id" TO "version";

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -645,6 +645,20 @@
"when": 1746518402168,
"tag": "0091_spotty_kulan_gath",
"breakpoints": true
},
{
"idx": 92,
"version": "7",
"when": 1746915683635,
"tag": "0092_violet_daredevil",
"breakpoints": true
},
{
"idx": 93,
"version": "7",
"when": 1746916912063,
"tag": "0093_milky_cerebro",
"breakpoints": true
}
]
}

View File

@@ -12,6 +12,7 @@ import { ShowEnvironment } from "@/components/dashboard/application/environment/
import { ShowGeneralApplication } from "@/components/dashboard/application/general/show";
import { ShowDockerLogs } from "@/components/dashboard/application/logs/show";
import { ShowPreviewDeployments } from "@/components/dashboard/application/preview-deployments/show-preview-deployments";
import { ShowRollbacks } from "@/components/dashboard/application/rollbacks/show-rollbacks";
import { ShowSchedules } from "@/components/dashboard/application/schedules/show-schedules";
import { UpdateApplication } from "@/components/dashboard/application/update-application";
import { DeleteService } from "@/components/dashboard/compose/delete-service";
@@ -234,6 +235,7 @@ const Service = (
Preview Deployments
</TabsTrigger>
<TabsTrigger value="schedules">Schedules</TabsTrigger>
<TabsTrigger value="rollbacks">Rollbacks</TabsTrigger>
<TabsTrigger value="deployments">Deployments</TabsTrigger>
<TabsTrigger value="logs">Logs</TabsTrigger>
{((data?.serverId && isCloud) || !data?.server) && (
@@ -310,6 +312,11 @@ const Service = (
/>
</div>
</TabsContent>
<TabsContent value="rollbacks">
<div className="flex flex-col gap-4 pt-2.5">
<ShowRollbacks applicationId={applicationId} />
</div>
</TabsContent>
<TabsContent value="schedules">
<div className="flex flex-col gap-4 pt-2.5">
<ShowSchedules

View File

@@ -36,6 +36,7 @@ import { stripeRouter } from "./routers/stripe";
import { swarmRouter } from "./routers/swarm";
import { userRouter } from "./routers/user";
import { scheduleRouter } from "./routers/schedule";
import { rollbackRouter } from "./routers/rollbacks";
/**
* This is the primary router for your server.
*
@@ -80,6 +81,7 @@ export const appRouter = createTRPCRouter({
ai: aiRouter,
organization: organizationRouter,
schedule: scheduleRouter,
rollback: rollbackRouter,
});
// export type definition of API

View File

@@ -0,0 +1,60 @@
import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc";
import { apiFindOneRollback, rollbacks } from "@/server/db/schema";
import { removeRollbackById, rollback } from "@dokploy/server";
import { TRPCError } from "@trpc/server";
import { eq, desc } from "drizzle-orm";
import { db } from "@/server/db";
import { z } from "zod";
export const rollbackRouter = createTRPCRouter({
delete: protectedProcedure
.input(apiFindOneRollback)
.mutation(async ({ input }) => {
try {
return removeRollbackById(input.rollbackId);
} catch (error) {
const message =
error instanceof Error
? error.message
: "Error input: Deleting rollback";
throw new TRPCError({
code: "BAD_REQUEST",
message,
});
}
}),
all: protectedProcedure
.input(
z.object({
applicationId: z.string(),
}),
)
.query(async ({ input }) => {
try {
return await db.query.rollbacks.findMany({
where: eq(rollbacks.applicationId, input.applicationId),
orderBy: desc(rollbacks.createdAt),
});
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error input: Fetching rollbacks",
cause: error,
});
}
}),
rollback: protectedProcedure
.input(apiFindOneRollback)
.mutation(async ({ input }) => {
try {
return await rollback(input.rollbackId);
} catch (error) {
console.error(error);
throw new TRPCError({
code: "BAD_REQUEST",
message: "Error input: Rolling back",
cause: error,
});
}
}),
});