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,
});
}
}),
});

View File

@ -27,7 +27,7 @@ import { server } from "./server";
import { applicationStatus, certificateType, triggerType } from "./shared";
import { sshKeys } from "./ssh-key";
import { generateAppName } from "./utils";
import { rollbacks } from "./rollbacks";
export const sourceType = pgEnum("sourceType", [
"docker",
"git",
@ -132,6 +132,8 @@ export const applications = pgTable("application", {
isPreviewDeploymentsActive: boolean("isPreviewDeploymentsActive").default(
false,
),
rollbackActive: boolean("rollbackActive").default(false),
limitRollback: integer("limitRollback").default(5),
buildArgs: text("buildArgs"),
memoryReservation: text("memoryReservation"),
memoryLimit: text("memoryLimit"),
@ -274,6 +276,7 @@ export const applicationsRelations = relations(
references: [server.serverId],
}),
previewDeployments: many(previewDeployments),
rollbacks: many(rollbacks),
}),
);

View File

@ -32,3 +32,4 @@ export * from "./preview-deployments";
export * from "./ai";
export * from "./account";
export * from "./schedule";
export * from "./rollbacks";

View File

@ -0,0 +1,45 @@
import { relations } from "drizzle-orm";
import { pgTable, serial, text } from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
import { applications } from "./application";
export const rollbacks = pgTable("rollback", {
rollbackId: text("rollbackId")
.notNull()
.primaryKey()
.$defaultFn(() => nanoid()),
env: text("env"),
applicationId: text("applicationId")
.notNull()
.references(() => applications.applicationId, {
onDelete: "cascade",
}),
version: serial(),
image: text("image"),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
});
export type Rollback = typeof rollbacks.$inferSelect;
export const rollbacksRelations = relations(rollbacks, ({ one }) => ({
application: one(applications, {
fields: [rollbacks.applicationId],
references: [applications.applicationId],
}),
}));
export const createRollbackSchema = createInsertSchema(rollbacks).extend({
appName: z.string().min(1),
});
export const updateRollbackSchema = createRollbackSchema.extend({
rollbackId: z.string().min(1),
});
export const apiFindOneRollback = z.object({
rollbackId: z.string().min(1),
});

View File

@ -32,6 +32,7 @@ export * from "./services/gitea";
export * from "./services/server";
export * from "./services/schedule";
export * from "./services/application";
export * from "./services/rollbacks";
export * from "./utils/databases/rebuild";
export * from "./setup/config-paths";
export * from "./setup/postgres-setup";

View File

@ -41,7 +41,10 @@ import {
import { createTraefikConfig } from "@dokploy/server/utils/traefik/application";
import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm";
import { encodeBase64 } from "../utils/docker/utils";
import {
encodeBase64,
prepareEnvironmentVariables,
} from "../utils/docker/utils";
import { getDokployUrl } from "./admin";
import {
createDeployment,
@ -60,6 +63,7 @@ import {
updatePreviewDeployment,
} from "./preview-deployment";
import { validUniqueServerAppName } from "./project";
import { createRollback } from "./rollbacks";
export type Application = typeof applications.$inferSelect;
export const createApplication = async (
@ -214,6 +218,21 @@ export const deployApplication = async ({
await updateDeploymentStatus(deployment.deploymentId, "done");
await updateApplicationStatus(applicationId, "done");
if (application.rollbackActive) {
const resolveEnvs = prepareEnvironmentVariables(
application.env,
application.project.env,
);
console.log(resolveEnvs);
await createRollback({
appName: application.appName,
env: resolveEnvs.join("\n"),
applicationId: applicationId,
});
}
await sendBuildSuccessNotifications({
projectName: application.project.name,
applicationName: application.name,

View File

@ -0,0 +1,145 @@
import { eq } from "drizzle-orm";
import { db } from "../db";
import { type createRollbackSchema, rollbacks } from "../db/schema";
import type { z } from "zod";
import { findApplicationById } from "./application";
import { getRemoteDocker } from "../utils/servers/remote-docker";
import type { ApplicationNested } from "../utils/builders";
import { execAsync, execAsyncRemote } from "../utils/process/execAsync";
import type { CreateServiceOptions } from "dockerode";
export const createRollback = async (
input: z.infer<typeof createRollbackSchema>,
) => {
await db.transaction(async (tx) => {
const rollback = await tx
.insert(rollbacks)
.values(input)
.returning()
.then((res) => res[0]);
if (!rollback) {
throw new Error("Failed to create rollback");
}
const tagImage = `${input.appName}:v${rollback.version}`;
await tx
.update(rollbacks)
.set({
image: tagImage,
})
.where(eq(rollbacks.rollbackId, rollback.rollbackId));
const application = await findApplicationById(input.applicationId);
await createRollbackImage(application, tagImage);
return rollback;
});
};
const findRollbackById = async (rollbackId: string) => {
const result = await db.query.rollbacks.findFirst({
where: eq(rollbacks.rollbackId, rollbackId),
});
if (!result) {
throw new Error("Rollback not found");
}
return result;
};
const createRollbackImage = async (
application: ApplicationNested,
tagImage: string,
) => {
const docker = await getRemoteDocker(application.serverId);
const result = docker.getImage(`${application.appName}:latest`);
const version = tagImage.split(":")[1];
await result.tag({
repo: tagImage,
tag: version,
});
};
const deleteRollbackImage = async (image: string, serverId?: string | null) => {
const command = `docker image rm ${image} --force`;
if (serverId) {
await execAsyncRemote(command, serverId);
} else {
await execAsync(command);
}
};
export const removeRollbackById = async (rollbackId: string) => {
const result = await db
.delete(rollbacks)
.where(eq(rollbacks.rollbackId, rollbackId))
.returning()
.then((res) => res[0]);
if (result?.image) {
try {
const application = await findApplicationById(result.applicationId);
await deleteRollbackImage(result.image, application.serverId);
} catch (error) {
console.error(error);
}
}
return result;
};
export const rollback = async (rollbackId: string) => {
const result = await findRollbackById(rollbackId);
const application = await findApplicationById(result.applicationId);
await rollbackApplication(
application.appName,
result.image || "",
result.env || "",
application.serverId,
);
};
const rollbackApplication = async (
appName: string,
image: string,
env: string,
serverId?: string | null,
) => {
const docker = await getRemoteDocker(serverId);
const settings: CreateServiceOptions = {
Name: appName,
TaskTemplate: {
ContainerSpec: {
Image: image,
Env: env.split("\n"),
},
},
};
try {
const service = docker.getService(appName);
const inspect = await service.inspect();
await service.update({
version: Number.parseInt(inspect.Version.Index),
...settings,
TaskTemplate: {
...settings.TaskTemplate,
ForceUpdate: inspect.Spec.TaskTemplate.ForceUpdate + 1,
},
});
} catch (_error: unknown) {
await docker.createService(settings);
}
};