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", name: "2<=string<=32",
}).and(volumeConfigSchema); }).and(volumeConfigSchema);
type FormValues = typeof formSchema.inferIn; export type FormValues = typeof formSchema.inferIn;
type Props = { type Props = {
onSubmit: (values: FormValues) => void; onSubmit: (values: FormValues) => void;
mode?: "create" | "update"; mode?: "create" | "update";
initialValues?: Partial<FormValues>; initialValues?: Partial<FormValues>;
formId?: string; 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>({ const form = useForm<FormValues>({
resolver: arktypeResolver(formSchema), resolver: arktypeResolver(formSchema),
defaultValues: initialValues, defaultValues: initialValues,
@@ -505,6 +506,11 @@ export const CreateVolumeForm = ({ onSubmit, mode = "create", initialValues, for
)} )}
</div> </div>
)} )}
{mode === "update" && (
<Button type="submit" className="w-full mt-4" loading={loading}>
Save Changes
</Button>
)}
</form> </form>
</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" function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
import { buttonVariants } from "~/components/ui/button" 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({ function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
...props return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
} }
function AlertDialogPortal({ function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
...props return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
} }
function AlertDialogOverlay({ function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
className, return (
...props <AlertDialogPrimitive.Overlay
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) { data-slot="alert-dialog-overlay"
return ( className={cn(
<AlertDialogPrimitive.Overlay "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",
data-slot="alert-dialog-overlay" className,
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", {...props}
className />
)} );
{...props}
/>
)
} }
function AlertDialogContent({ function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
className, return (
...props <AlertDialogPortal>
}: React.ComponentProps<typeof AlertDialogPrimitive.Content>) { <AlertDialogOverlay />
return ( <AlertDialogPrimitive.Content
<AlertDialogPortal> data-slot="alert-dialog-content"
<AlertDialogOverlay /> className={cn(
<AlertDialogPrimitive.Content "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",
data-slot="alert-dialog-content" className,
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", {...props}
className />
)} </AlertDialogPortal>
{...props} );
/>
</AlertDialogPortal>
)
} }
function AlertDialogHeader({ function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
className, return (
...props <div
}: React.ComponentProps<"div">) { data-slot="alert-dialog-header"
return ( className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
<div {...props}
data-slot="alert-dialog-header" />
className={cn("flex flex-col gap-2 text-center sm:text-left", className)} );
{...props}
/>
)
} }
function AlertDialogFooter({ function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
className, return (
...props <div
}: React.ComponentProps<"div">) { data-slot="alert-dialog-footer"
return ( className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end", className)}
<div {...props}
data-slot="alert-dialog-footer" />
className={cn( );
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
} }
function AlertDialogTitle({ function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
className, return (
...props <AlertDialogPrimitive.Title
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) { data-slot="alert-dialog-title"
return ( className={cn("text-lg font-semibold", className)}
<AlertDialogPrimitive.Title {...props}
data-slot="alert-dialog-title" />
className={cn("text-lg font-semibold", className)} );
{...props}
/>
)
} }
function AlertDialogDescription({ function AlertDialogDescription({
className, className,
...props ...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) { }: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return ( return (
<AlertDialogPrimitive.Description <AlertDialogPrimitive.Description
data-slot="alert-dialog-description" data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)} className={cn("text-muted-foreground text-sm", className)}
{...props} {...props}
/> />
) );
} }
function AlertDialogAction({ function AlertDialogAction({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
className, return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />;
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
return (
<AlertDialogPrimitive.Action
className={cn(buttonVariants(), className)}
{...props}
/>
)
} }
function AlertDialogCancel({ function AlertDialogCancel({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
className, return <AlertDialogPrimitive.Cancel className={cn(buttonVariants({ variant: "outline" }), className)} {...props} />;
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
return (
<AlertDialogPrimitive.Cancel
className={cn(buttonVariants({ variant: "outline" }), className)}
{...props}
/>
)
} }
export { export {
AlertDialog, AlertDialog,
AlertDialogPortal, AlertDialogPortal,
AlertDialogOverlay, AlertDialogOverlay,
AlertDialogTrigger, AlertDialogTrigger,
AlertDialogContent, AlertDialogContent,
AlertDialogHeader, AlertDialogHeader,
AlertDialogFooter, AlertDialogFooter,
AlertDialogTitle, AlertDialogTitle,
AlertDialogDescription, AlertDialogDescription,
AlertDialogAction, AlertDialogAction,
AlertDialogCancel, AlertDialogCancel,
} };

View File

@@ -54,7 +54,7 @@ export const HealthchecksCard = ({ volume }: Props) => {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="flex flex-col flex-1 justify-start"> <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 === "mounted" && <span className="text-md text-emerald-500">Healthy</span>}
{volume.status !== "unmounted" && ( {volume.status !== "unmounted" && (
<span className="text-xs text-muted-foreground mb-4">Checked {timeAgo || "never"}</span> <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 { Card } from "~/components/ui/card";
import type { StatFs, Volume } from "~/lib/types"; import type { StatFs, Volume } from "~/lib/types";
import { HealthchecksCard } from "../components/healthchecks-card"; import { HealthchecksCard } from "../components/healthchecks-card";
@@ -10,19 +24,73 @@ type Props = {
}; };
export const VolumeInfoTabContent = ({ volume, statfs }: 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 ( return (
<div className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]"> <>
<Card className="p-6"> <div className="grid gap-4 xl:grid-cols-[minmax(0,_2.3fr)_minmax(320px,_1fr)]">
<CreateVolumeForm initialValues={{ ...volume, ...volume.config }} onSubmit={console.log} /> <Card className="p-6">
</Card> <CreateVolumeForm
<div className="flex flex-col gap-4"> initialValues={{ ...volume, ...volume.config }}
<div className="self-start w-full"> onSubmit={handleSubmit}
<HealthchecksCard volume={volume} /> mode="update"
</div> loading={updateMutation.isPending}
<div className="flex-1 w-full"> />
<StorageChart statfs={statfs} /> </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> </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: () => { onSuccess: () => {
queryClient.invalidateQueries(); 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 { Copy, RotateCcw } from "lucide-react";
import { useState } from "react"; import { useState } from "react";
import { useNavigate } from "react-router"; 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 { listVolumesOptions } from "~/api-client/@tanstack/react-query.gen";
import { CreateVolumeDialog } from "~/components/create-volume-dialog"; import { CreateVolumeDialog } from "~/components/create-volume-dialog";
import { EditVolumeDialog } from "~/components/edit-volume-dialog";
import { StatusDot } from "~/components/status-dot"; import { StatusDot } from "~/components/status-dot";
import { Button } from "~/components/ui/button"; import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input"; import { Input } from "~/components/ui/input";
@@ -31,7 +30,6 @@ export const clientLoader = async () => {
}; };
export default function Home({ loaderData }: Route.ComponentProps) { export default function Home({ loaderData }: Route.ComponentProps) {
const [volumeToEdit, setVolumeToEdit] = useState<ListVolumesResponse["volumes"][number]>();
const [createVolumeOpen, setCreateVolumeOpen] = useState(false); const [createVolumeOpen, setCreateVolumeOpen] = useState(false);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [statusFilter, setStatusFilter] = useState(""); const [statusFilter, setStatusFilter] = useState("");
@@ -139,11 +137,6 @@ export default function Home({ loaderData }: Route.ComponentProps) {
))} ))}
</TableBody> </TableBody>
</Table> </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 driver = new Hono().use(honoLogger()).route("/", driverController);
const app = new Hono() const app = new Hono()
.use(honoLogger()) .use(honoLogger())
.get("/healthcheck", (c) => c.json({ status: "ok" })) .get("*", serveStatic({ root: "./assets/frontend" }))
.route("/api/v1/volumes", volumeController) .get("healthcheck", (c) => c.json({ status: "ok" }))
.get("/assets/*", serveStatic({ root: "./assets/frontend" })) .basePath("/api/v1")
.get("*", serveStatic({ path: "./assets/frontend/index.html" })); .route("/volumes", volumeController);
app.get("/openapi.json", generalDescriptor(app)); app.get("/openapi.json", generalDescriptor(app));
app.get("/docs", scalarDescriptor); app.get("/docs", scalarDescriptor);

View File

@@ -1,5 +1,5 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { VOLUME_MOUNT_BASE } from "~/core/constants"; import { VOLUME_MOUNT_BASE } from "../../core/constants";
import { volumeService } from "../volumes/volume.service"; import { volumeService } from "../volumes/volume.service";
export const driverController = new Hono() 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 volumePathHost = path.join(VOLUME_MOUNT_BASE);
const val = await db const [created] = await db
.insert(volumesTable) .insert(volumesTable)
.values({ .values({
name: slug, name: slug,
@@ -43,7 +43,19 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
}) })
.returning(); .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) => { const deleteVolume = async (name: string) => {
@@ -123,6 +135,15 @@ const updateVolume = async (name: string, volumeData: UpdateVolumeBody) => {
throw new NotFoundError("Volume not found"); 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 const [updated] = await db
.update(volumesTable) .update(volumesTable)
.set({ .set({
@@ -138,6 +159,15 @@ const updateVolume = async (name: string, volumeData: UpdateVolumeBody) => {
throw new InternalServerError("Failed to update volume"); 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 }; return { volume: updated };
}; };

View File

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