feat: update volume

This commit is contained in:
Nicolas Meienberger
2025-09-27 15:50:34 +02:00
parent aa32ea322d
commit 202759d9de
11 changed files with 216 additions and 220 deletions

View File

@@ -16,16 +16,17 @@ export const formSchema = type({
name: "2<=string<=32",
}).and(volumeConfigSchema);
type FormValues = typeof formSchema.inferIn;
export type FormValues = typeof formSchema.inferIn;
type Props = {
onSubmit: (values: FormValues) => void;
mode?: "create" | "update";
initialValues?: Partial<FormValues>;
formId?: string;
loading?: boolean;
};
export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, formId }: Props) => {
export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, formId, loading }: Props) => {
const form = useForm<FormValues>({
resolver: arktypeResolver(formSchema),
defaultValues: initialValues,
@@ -505,6 +506,11 @@ export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, for
)}
</div>
)}
{mode === "update" && (
<Button type="submit" className="w-full mt-4" loading={loading}>
Save Changes
</Button>
)}
</form>
</Form>
);

View File

@@ -1,59 +0,0 @@
import { useMutation } from "@tanstack/react-query";
import { useId } from "react";
import { toast } from "sonner";
import { updateVolumeMutation } from "~/api-client/@tanstack/react-query.gen";
import { parseError } from "~/lib/errors";
import type { Volume } from "../lib/types";
import { CreateVolumeForm } from "./create-volume-form";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
type Props = {
open: boolean;
setOpen: (open: boolean) => void;
initialValues?: Partial<Volume>;
};
export const EditVolumeDialog = ({ open, setOpen, initialValues }: Props) => {
const formId = useId();
const update = useMutation({
...updateVolumeMutation(),
onSuccess: () => {
toast.success("Volume updated successfully");
setOpen(false);
},
onError: (error) => {
toast.error("Failed to update volume", {
description: parseError(error)?.message,
});
},
});
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Create volume</DialogTitle>
<DialogDescription>Enter a name for the new volume</DialogDescription>
</DialogHeader>
<CreateVolumeForm
mode="update"
formId={formId}
initialValues={{ ...initialValues, ...initialValues?.config }}
onSubmit={(values) => {
update.mutate({ body: { config: values }, path: { name: values.name } });
}}
/>
<DialogFooter>
<Button type="button" variant="secondary" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button type="submit" form={formId} disabled={update.isPending}>
Update
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
};

View File

@@ -1,155 +1,110 @@
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
import type * as React from "react";
import { buttonVariants } from "~/components/ui/button";
import { cn } from "~/lib/utils";
import { cn } from "~/lib/utils"
import { buttonVariants } from "~/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className,
)}
{...props}
/>
);
}
function AlertDialogContent({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className,
)}
{...props}
/>
</AlertDialogPortal>
);
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
);
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
{...props}
/>
);
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
)
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn("text-lg font-semibold", className)}
{...props}
/>
);
}
function AlertDialogDescription({
className,
...props
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
);
}
function AlertDialogAction({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
function AlertDialogAction({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />;
}
function AlertDialogCancel({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
function AlertDialogCancel({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return <AlertDialogPrimitive.Cancel className={cn(buttonVariants({ variant: "outline" }), className)} {...props} />;
}
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
}
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -54,7 +54,7 @@ export const HealthchecksCard = ({ volume }: Props) => {
</CardHeader>
<CardContent>
<div className="flex flex-col flex-1 justify-start">
{volume.lastError && <span className="text-sm text-red-500 ">{volume.lastError}</span>}
{volume.lastError && <span className="text-sm text-red-500 break-words">{volume.lastError}</span>}
{volume.status === "mounted" && <span className="text-md text-emerald-500">Healthy</span>}
{volume.status !== "unmounted" && (
<span className="text-xs text-muted-foreground mb-4">Checked {timeAgo || "never"}</span>

View File

@@ -1,4 +1,18 @@
import { CreateVolumeForm } from "~/components/create-volume-form";
import { useMutation } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { updateVolumeMutation } from "~/api-client/@tanstack/react-query.gen";
import { CreateVolumeForm, type FormValues } from "~/components/create-volume-form";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "~/components/ui/alert-dialog";
import { Card } from "~/components/ui/card";
import type { StatFs, Volume } from "~/lib/types";
import { HealthchecksCard } from "../components/healthchecks-card";
@@ -10,19 +24,73 @@ type Props = {
};
export const VolumeInfoTabContent = ({ volume, statfs }: Props) => {
const updateMutation = useMutation({
...updateVolumeMutation(),
onSuccess: (_) => {
toast.success("Volume updated successfully");
setOpen(false);
setPendingValues(null);
},
onError: (error) => {
toast.error("Failed to update volume", { description: error.message });
setOpen(false);
setPendingValues(null);
},
});
const [open, setOpen] = useState(false);
const [pendingValues, setPendingValues] = useState<FormValues | null>(null);
const handleSubmit = (values: FormValues) => {
console.log({ values });
setPendingValues(values);
setOpen(true);
};
const confirmUpdate = () => {
if (pendingValues) {
updateMutation.mutate({
path: { name: volume.name },
body: { config: pendingValues },
});
}
};
return (
<div className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]">
<Card className="p-6">
<CreateVolumeForm initialValues={{ ...volume, ...volume.config }} onSubmit={console.log} />
</Card>
<div className="flex flex-col gap-4">
<div className="self-start w-full">
<HealthchecksCard volume={volume} />
</div>
<div className="flex-1 w-full">
<StorageChart statfs={statfs} />
<>
<div className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]">
<Card className="p-6">
<CreateVolumeForm
initialValues={{ ...volume, ...volume.config }}
onSubmit={handleSubmit}
mode="update"
loading={updateMutation.isPending}
/>
</Card>
<div className="flex flex-col gap-4">
<div className="self-start w-full">
<HealthchecksCard volume={volume} />
</div>
<div className="flex-1 w-full">
<StorageChart statfs={statfs} />
</div>
</div>
</div>
</div>
<AlertDialog open={open} onOpenChange={setOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Update Volume Configuration</AlertDialogTitle>
<AlertDialogDescription>
Editing the volume will remount it with the new config immediately. This may temporarily disrupt access to
the volume. Continue?
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={confirmUpdate}>Update</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
};

View File

@@ -29,6 +29,10 @@ const queryClient = new QueryClient({
onSuccess: () => {
queryClient.invalidateQueries();
},
onError: (error) => {
console.error("Mutation error:", error);
queryClient.invalidateQueries();
},
}),
});

View File

@@ -2,10 +2,9 @@ import { useQuery } from "@tanstack/react-query";
import { Copy, RotateCcw } from "lucide-react";
import { useState } from "react";
import { useNavigate } from "react-router";
import { type ListVolumesResponse, listVolumes } from "~/api-client";
import { listVolumes } from "~/api-client";
import { listVolumesOptions } from "~/api-client/@tanstack/react-query.gen";
import { CreateVolumeDialog } from "~/components/create-volume-dialog";
import { EditVolumeDialog } from "~/components/edit-volume-dialog";
import { StatusDot } from "~/components/status-dot";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
@@ -31,7 +30,6 @@ export const clientLoader = async () => {
};
export default function Home({ loaderData }: Route.ComponentProps) {
const [volumeToEdit, setVolumeToEdit] = useState<ListVolumesResponse["volumes"][number]>();
const [createVolumeOpen, setCreateVolumeOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState("");
@@ -139,11 +137,6 @@ export default function Home({ loaderData }: Route.ComponentProps) {
))}
</TableBody>
</Table>
<EditVolumeDialog
open={Boolean(volumeToEdit)}
setOpen={() => setVolumeToEdit(undefined)}
initialValues={volumeToEdit}
/>
</>
);
}

View File

@@ -32,10 +32,10 @@ export const scalarDescriptor = Scalar({
const driver = new Hono().use(honoLogger()).route("/", driverController);
const app = new Hono()
.use(honoLogger())
.get("/healthcheck", (c) => c.json({ status: "ok" }))
.route("/api/v1/volumes", volumeController)
.get("/assets/*", serveStatic({ root: "./assets/frontend" }))
.get("*", serveStatic({ path: "./assets/frontend/index.html" }));
.get("*", serveStatic({ root: "./assets/frontend" }))
.get("healthcheck", (c) => c.json({ status: "ok" }))
.basePath("/api/v1")
.route("/volumes", volumeController);
app.get("/openapi.json", generalDescriptor(app));
app.get("/docs", scalarDescriptor);

View File

@@ -1,5 +1,5 @@
import { Hono } from "hono";
import { VOLUME_MOUNT_BASE } from "~/core/constants";
import { VOLUME_MOUNT_BASE } from "../../core/constants";
import { volumeService } from "../volumes/volume.service";
export const driverController = new Hono()

View File

@@ -33,7 +33,7 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
const volumePathHost = path.join(VOLUME_MOUNT_BASE);
const val = await db
const [created] = await db
.insert(volumesTable)
.values({
name: slug,
@@ -43,7 +43,19 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
})
.returning();
return { volume: val[0], status: 201 };
if (!created) {
throw new InternalServerError("Failed to create volume");
}
const backend = createVolumeBackend(created);
const { error, status } = await backend.mount();
await db
.update(volumesTable)
.set({ status, lastError: error ?? null, lastHealthCheck: new Date() })
.where(eq(volumesTable.name, slug));
return { volume: created, status: 201 };
};
const deleteVolume = async (name: string) => {
@@ -123,6 +135,15 @@ const updateVolume = async (name: string, volumeData: UpdateVolumeBody) => {
throw new NotFoundError("Volume not found");
}
const configChanged =
JSON.stringify(existing.config) !== JSON.stringify(volumeData.config) && volumeData.config !== undefined;
if (configChanged) {
console.log("Unmounting existing volume before applying new config");
const backend = createVolumeBackend(existing);
await backend.unmount();
}
const [updated] = await db
.update(volumesTable)
.set({
@@ -138,6 +159,15 @@ const updateVolume = async (name: string, volumeData: UpdateVolumeBody) => {
throw new InternalServerError("Failed to update volume");
}
if (configChanged) {
const backend = createVolumeBackend(updated);
const { error, status } = await backend.mount();
await db
.update(volumesTable)
.set({ status, lastError: error ?? null, lastHealthCheck: new Date() })
.where(eq(volumesTable.name, name));
}
return { volume: updated };
};

View File

@@ -18,12 +18,11 @@ services:
- /var/run/docker.sock:/var/run/docker.sock
- /run/docker/plugins:/run/docker/plugins
- /var/lib/docker/volumes/:/var/lib/docker/volumes:rshared
- ironmount_data:/data
- ./apps/client/app:/app/apps/client/app
- ./apps/server/src:/app/apps/server/src
- ironmount_data:/data
ironmount-prod:
build:
context: .