mirror of
https://github.com/nicotsx/ironmount.git
synced 2025-12-10 12:10:51 +01:00
feat: mount / unmount
This commit is contained in:
@@ -8,6 +8,8 @@ import {
|
||||
deleteVolume,
|
||||
getVolume,
|
||||
updateVolume,
|
||||
mountVolume,
|
||||
unmountVolume,
|
||||
} from "../sdk.gen";
|
||||
import { queryOptions, type UseMutationOptions, type DefaultError } from "@tanstack/react-query";
|
||||
import type {
|
||||
@@ -21,6 +23,10 @@ import type {
|
||||
GetVolumeData,
|
||||
UpdateVolumeData,
|
||||
UpdateVolumeResponse,
|
||||
MountVolumeData,
|
||||
MountVolumeResponse,
|
||||
UnmountVolumeData,
|
||||
UnmountVolumeResponse,
|
||||
} from "../types.gen";
|
||||
import { client as _heyApiClient } from "../client.gen";
|
||||
|
||||
@@ -219,3 +225,81 @@ export const updateVolumeMutation = (
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const mountVolumeQueryKey = (options: Options<MountVolumeData>) => createQueryKey("mountVolume", options);
|
||||
|
||||
/**
|
||||
* Mount a volume
|
||||
*/
|
||||
export const mountVolumeOptions = (options: Options<MountVolumeData>) => {
|
||||
return queryOptions({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await mountVolume({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: mountVolumeQueryKey(options),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Mount a volume
|
||||
*/
|
||||
export const mountVolumeMutation = (
|
||||
options?: Partial<Options<MountVolumeData>>,
|
||||
): UseMutationOptions<MountVolumeResponse, DefaultError, Options<MountVolumeData>> => {
|
||||
const mutationOptions: UseMutationOptions<MountVolumeResponse, DefaultError, Options<MountVolumeData>> = {
|
||||
mutationFn: async (localOptions) => {
|
||||
const { data } = await mountVolume({
|
||||
...options,
|
||||
...localOptions,
|
||||
throwOnError: true,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const unmountVolumeQueryKey = (options: Options<UnmountVolumeData>) => createQueryKey("unmountVolume", options);
|
||||
|
||||
/**
|
||||
* Unmount a volume
|
||||
*/
|
||||
export const unmountVolumeOptions = (options: Options<UnmountVolumeData>) => {
|
||||
return queryOptions({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await unmountVolume({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: unmountVolumeQueryKey(options),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Unmount a volume
|
||||
*/
|
||||
export const unmountVolumeMutation = (
|
||||
options?: Partial<Options<UnmountVolumeData>>,
|
||||
): UseMutationOptions<UnmountVolumeResponse, DefaultError, Options<UnmountVolumeData>> => {
|
||||
const mutationOptions: UseMutationOptions<UnmountVolumeResponse, DefaultError, Options<UnmountVolumeData>> = {
|
||||
mutationFn: async (localOptions) => {
|
||||
const { data } = await unmountVolume({
|
||||
...options,
|
||||
...localOptions,
|
||||
throwOnError: true,
|
||||
});
|
||||
return data;
|
||||
},
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
@@ -16,6 +16,12 @@ import type {
|
||||
UpdateVolumeData,
|
||||
UpdateVolumeResponses,
|
||||
UpdateVolumeErrors,
|
||||
MountVolumeData,
|
||||
MountVolumeResponses,
|
||||
MountVolumeErrors,
|
||||
UnmountVolumeData,
|
||||
UnmountVolumeResponses,
|
||||
UnmountVolumeErrors,
|
||||
} from "./types.gen";
|
||||
import { client as _heyApiClient } from "./client.gen";
|
||||
|
||||
@@ -115,3 +121,25 @@ export const updateVolume = <ThrowOnError extends boolean = false>(
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Mount a volume
|
||||
*/
|
||||
export const mountVolume = <ThrowOnError extends boolean = false>(options: Options<MountVolumeData, ThrowOnError>) => {
|
||||
return (options.client ?? _heyApiClient).post<MountVolumeResponses, MountVolumeErrors, ThrowOnError>({
|
||||
url: "/api/v1/volumes/{name}/mount",
|
||||
...options,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Unmount a volume
|
||||
*/
|
||||
export const unmountVolume = <ThrowOnError extends boolean = false>(
|
||||
options: Options<UnmountVolumeData, ThrowOnError>,
|
||||
) => {
|
||||
return (options.client ?? _heyApiClient).post<UnmountVolumeResponses, UnmountVolumeErrors, ThrowOnError>({
|
||||
url: "/api/v1/volumes/{name}/unmount",
|
||||
...options,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -245,6 +245,60 @@ export type UpdateVolumeResponses = {
|
||||
|
||||
export type UpdateVolumeResponse = UpdateVolumeResponses[keyof UpdateVolumeResponses];
|
||||
|
||||
export type MountVolumeData = {
|
||||
body?: never;
|
||||
path: {
|
||||
name: string;
|
||||
};
|
||||
query?: never;
|
||||
url: "/api/v1/volumes/{name}/mount";
|
||||
};
|
||||
|
||||
export type MountVolumeErrors = {
|
||||
/**
|
||||
* Volume not found
|
||||
*/
|
||||
404: unknown;
|
||||
};
|
||||
|
||||
export type MountVolumeResponses = {
|
||||
/**
|
||||
* Volume mounted successfully
|
||||
*/
|
||||
200: {
|
||||
message: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type MountVolumeResponse = MountVolumeResponses[keyof MountVolumeResponses];
|
||||
|
||||
export type UnmountVolumeData = {
|
||||
body?: never;
|
||||
path: {
|
||||
name: string;
|
||||
};
|
||||
query?: never;
|
||||
url: "/api/v1/volumes/{name}/unmount";
|
||||
};
|
||||
|
||||
export type UnmountVolumeErrors = {
|
||||
/**
|
||||
* Volume not found
|
||||
*/
|
||||
404: unknown;
|
||||
};
|
||||
|
||||
export type UnmountVolumeResponses = {
|
||||
/**
|
||||
* Volume unmounted successfully
|
||||
*/
|
||||
200: {
|
||||
message: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type UnmountVolumeResponse = UnmountVolumeResponses[keyof UnmountVolumeResponses];
|
||||
|
||||
export type ClientOptions = {
|
||||
baseUrl: "http://localhost:3000" | (string & {});
|
||||
};
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
|
||||
@theme {
|
||||
--font-sans:
|
||||
"Google Sans Code", ui-sans-serif, system-ui, sans-serif,
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
"Google Sans Code", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol",
|
||||
"Noto Color Emoji";
|
||||
}
|
||||
|
||||
html,
|
||||
|
||||
@@ -8,6 +8,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
position="top-center"
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
|
||||
@@ -3,5 +3,9 @@ export const parseError = (error?: unknown) => {
|
||||
return { message: error.message as string };
|
||||
}
|
||||
|
||||
if (typeof error === "string") {
|
||||
return { message: error };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,12 @@ import { WifiIcon } from "lucide-react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import { getVolume } from "~/api-client";
|
||||
import { deleteVolumeMutation, getVolumeOptions } from "~/api-client/@tanstack/react-query.gen";
|
||||
import {
|
||||
deleteVolumeMutation,
|
||||
getVolumeOptions,
|
||||
mountVolumeMutation,
|
||||
unmountVolumeMutation,
|
||||
} from "~/api-client/@tanstack/react-query.gen";
|
||||
import { CreateVolumeForm } from "~/components/create-volume-form";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Card } from "~/components/ui/card";
|
||||
@@ -11,6 +16,7 @@ import { VolumeIcon } from "~/components/volume-icon";
|
||||
import { parseError } from "~/lib/errors";
|
||||
import { HealthchecksCard } from "~/modules/details/components/healthchecks-card";
|
||||
import type { Route } from "./+types/details";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const clientLoader = async ({ params }: Route.ClientLoaderArgs) => {
|
||||
const volume = await getVolume({ path: { name: params.name ?? "" } });
|
||||
@@ -39,6 +45,30 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
||||
},
|
||||
});
|
||||
|
||||
const mountVol = useMutation({
|
||||
...mountVolumeMutation(),
|
||||
onSuccess: () => {
|
||||
toast.success("Volume mounted successfully");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to mount volume", {
|
||||
description: parseError(error)?.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const unmountVol = useMutation({
|
||||
...unmountVolumeMutation(),
|
||||
onSuccess: () => {
|
||||
toast.success("Volume unmounted successfully");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error("Failed to unmount volume", {
|
||||
description: parseError(error)?.message,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleDeleteConfirm = (name: string) => {
|
||||
if (confirm(`Are you sure you want to delete the volume "${name}"? This action cannot be undone.`)) {
|
||||
deleteVol.mutate({ path: { name } });
|
||||
@@ -67,7 +97,22 @@ export default function DetailsPage({ loaderData }: Route.ComponentProps) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<Button>Mount</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => mountVol.mutate({ path: { name } })}
|
||||
disabled={mountVol.isPending}
|
||||
className={cn({ hidden: data.status === "mounted" })}
|
||||
>
|
||||
Mount
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => unmountVol.mutate({ path: { name } })}
|
||||
disabled={unmountVol.isPending}
|
||||
className={cn({ hidden: data.status !== "mounted" })}
|
||||
>
|
||||
Unmount
|
||||
</Button>
|
||||
<Button variant="destructive" onClick={() => handleDeleteConfirm(name)} disabled={deleteVol.isPending}>
|
||||
Delete
|
||||
</Button>
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"hono": "^4.9.2",
|
||||
"hono-openapi": "^0.4.8",
|
||||
"http-errors-enhanced": "^3.0.2",
|
||||
"slugify": "^1.6.6"
|
||||
"slugify": "^1.6.6",
|
||||
"winston": "^3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.2.20",
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import { Scalar } from "@scalar/hono-api-reference";
|
||||
import { Hono } from "hono";
|
||||
import { logger } from "hono/logger";
|
||||
import { logger as honoLogger } from "hono/logger";
|
||||
import { openAPISpecs } from "hono-openapi";
|
||||
import { runDbMigrations } from "./db/db";
|
||||
import { driverController } from "./modules/driver/driver.controller";
|
||||
import { volumeController } from "./modules/volumes/volume.controller";
|
||||
import { logger } from "./utils/logger";
|
||||
|
||||
export const generalDescriptor = (app: Hono) =>
|
||||
openAPISpecs(app, {
|
||||
@@ -25,9 +26,9 @@ export const scalarDescriptor = Scalar({
|
||||
url: "/api/v1/openapi.json",
|
||||
});
|
||||
|
||||
const driver = new Hono().use(logger()).route("/", driverController);
|
||||
const driver = new Hono().use(honoLogger()).route("/", driverController);
|
||||
const app = new Hono()
|
||||
.use(logger())
|
||||
.use(honoLogger())
|
||||
.get("healthcheck", (c) => c.json({ status: "ok" }))
|
||||
.basePath("/api/v1")
|
||||
.route("/volumes", volumeController);
|
||||
@@ -56,7 +57,7 @@ const socketPath = "/run/docker/plugins/ironmount.sock";
|
||||
fetch: app.fetch,
|
||||
});
|
||||
|
||||
console.log(`Server is running at http://localhost:8080 and unix socket at ${socketPath}`);
|
||||
logger.info(`Server is running at http://localhost:8080 and unix socket at ${socketPath}`);
|
||||
})();
|
||||
|
||||
export type AppType = typeof app;
|
||||
|
||||
@@ -2,14 +2,15 @@ import * as fs from "node:fs/promises";
|
||||
import * as npath from "node:path";
|
||||
import { BACKEND_STATUS, type BackendConfig } from "@ironmount/schemas";
|
||||
import type { VolumeBackend } from "../backend";
|
||||
import { logger } from "../../../utils/logger";
|
||||
|
||||
const mount = async (_config: BackendConfig, path: string) => {
|
||||
console.log("Mounting directory volume...");
|
||||
logger.info("Mounting directory volume...");
|
||||
await fs.mkdir(path, { recursive: true });
|
||||
};
|
||||
|
||||
const unmount = async () => {
|
||||
console.log("Cannot unmount directory volume.");
|
||||
logger.info("Cannot unmount directory volume.");
|
||||
};
|
||||
|
||||
const checkHealth = async (path: string) => {
|
||||
@@ -23,7 +24,7 @@ const checkHealth = async (path: string) => {
|
||||
|
||||
return { status: BACKEND_STATUS.mounted };
|
||||
} catch (error) {
|
||||
console.error("Directory health check failed:", error);
|
||||
logger.error("Directory health check failed:", error);
|
||||
return { status: BACKEND_STATUS.error, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import * as os from "node:os";
|
||||
import * as npath from "node:path";
|
||||
import { BACKEND_STATUS, type BackendConfig } from "@ironmount/schemas";
|
||||
import type { VolumeBackend } from "../backend";
|
||||
import { logger } from "../../../utils/logger";
|
||||
|
||||
const mount = async (config: BackendConfig, path: string) => {
|
||||
if (config.backend !== "nfs") {
|
||||
@@ -11,7 +12,7 @@ const mount = async (config: BackendConfig, path: string) => {
|
||||
}
|
||||
|
||||
if (os.platform() !== "linux") {
|
||||
console.error("NFS mounting is only supported on Linux hosts.");
|
||||
logger.error("NFS mounting is only supported on Linux hosts.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,14 +28,14 @@ const mount = async (config: BackendConfig, path: string) => {
|
||||
}, 5000);
|
||||
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
console.log("Mount command executed:", { cmd, error, stdout, stderr });
|
||||
logger.info("Mount command executed:", { cmd, error, stdout, stderr });
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (error) {
|
||||
console.error(`Error mounting NFS volume: ${stderr}`);
|
||||
logger.error(`Error mounting NFS volume: ${stderr}`);
|
||||
return reject(new Error(`Failed to mount NFS volume: ${stderr}`));
|
||||
}
|
||||
console.log(`NFS volume mounted successfully: ${stdout}`);
|
||||
logger.info(`NFS volume mounted successfully: ${stdout}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
@@ -42,7 +43,14 @@ const mount = async (config: BackendConfig, path: string) => {
|
||||
|
||||
const unmount = async (path: string) => {
|
||||
if (os.platform() !== "linux") {
|
||||
console.error("NFS unmounting is only supported on Linux hosts.");
|
||||
logger.error("NFS unmounting is only supported on Linux hosts.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.access(path);
|
||||
} catch {
|
||||
logger.warn(`Path ${path} does not exist. Skipping unmount.`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -54,14 +62,14 @@ const unmount = async (path: string) => {
|
||||
}, 5000);
|
||||
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
console.log("Unmount command executed:", { cmd, error, stdout, stderr });
|
||||
logger.info("Unmount command executed:", { cmd, error, stdout, stderr });
|
||||
clearTimeout(timeout);
|
||||
|
||||
if (error) {
|
||||
console.error(`Error unmounting NFS volume: ${stderr}`);
|
||||
logger.error(`Error unmounting NFS volume: ${stderr}`);
|
||||
return reject(new Error(`Failed to unmount NFS volume: ${stderr}`));
|
||||
}
|
||||
console.log(`NFS volume unmounted successfully: ${stdout}`);
|
||||
logger.info(`NFS volume unmounted successfully: ${stdout}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
@@ -78,7 +86,7 @@ const checkHealth = async (path: string) => {
|
||||
|
||||
return { status: BACKEND_STATUS.mounted };
|
||||
} catch (error) {
|
||||
console.error("NFS volume health check failed:", error);
|
||||
logger.error("NFS volume health check failed:", error);
|
||||
return { status: BACKEND_STATUS.error, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -13,8 +13,11 @@ import {
|
||||
updateVolumeBody,
|
||||
updateVolumeDto,
|
||||
type VolumeDto,
|
||||
mountVolumeDto,
|
||||
unmountVolumeDto,
|
||||
} from "./volume.dto";
|
||||
import { volumeService } from "./volume.service";
|
||||
import { logger } from "../../utils/logger";
|
||||
|
||||
export const volumeController = new Hono()
|
||||
.get("/", listVolumesDto, async (c) => {
|
||||
@@ -100,4 +103,26 @@ export const volumeController = new Hono()
|
||||
};
|
||||
|
||||
return c.json(response, 200);
|
||||
})
|
||||
.post("/:name/mount", mountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.mountVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume mounted successfully" }, 200);
|
||||
})
|
||||
.post("/:name/unmount", unmountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.unmountVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume unmounted successfully" }, 200);
|
||||
});
|
||||
|
||||
@@ -190,3 +190,57 @@ export const testConnectionDto = describeRoute({
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Mount volume
|
||||
*/
|
||||
export const mountVolumeResponse = type({
|
||||
message: "string",
|
||||
});
|
||||
|
||||
export const mountVolumeDto = describeRoute({
|
||||
description: "Mount a volume",
|
||||
operationId: "mountVolume",
|
||||
validateResponse: true,
|
||||
tags: ["Volumes"],
|
||||
responses: {
|
||||
200: {
|
||||
description: "Volume mounted successfully",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(mountVolumeResponse),
|
||||
},
|
||||
},
|
||||
},
|
||||
404: {
|
||||
description: "Volume not found",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
/**
|
||||
* Unmount volume
|
||||
*/
|
||||
export const unmountVolumeResponse = type({
|
||||
message: "string",
|
||||
});
|
||||
|
||||
export const unmountVolumeDto = describeRoute({
|
||||
description: "Unmount a volume",
|
||||
operationId: "unmountVolume",
|
||||
validateResponse: true,
|
||||
tags: ["Volumes"],
|
||||
responses: {
|
||||
200: {
|
||||
description: "Volume unmounted successfully",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: resolver(unmountVolumeResponse),
|
||||
},
|
||||
},
|
||||
},
|
||||
404: {
|
||||
description: "Volume not found",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { config } from "../../core/config";
|
||||
import { db } from "../../db/db";
|
||||
import { volumesTable } from "../../db/schema";
|
||||
import { createVolumeBackend } from "../backends/backend";
|
||||
import { logger } from "../../utils/logger";
|
||||
|
||||
const listVolumes = async () => {
|
||||
const volumes = await db.query.volumesTable.findMany({});
|
||||
@@ -76,7 +77,18 @@ const mountVolume = async (name: string) => {
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount().catch((_) => {
|
||||
// Ignore unmount errors
|
||||
});
|
||||
|
||||
await backend.mount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "mounted", lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to mount volume", {
|
||||
@@ -86,6 +98,34 @@ const mountVolume = async (name: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const unmountVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "unmounted", lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to unmount volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const getVolume = async (name: string) => {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
@@ -202,7 +242,7 @@ const testConnection = async (backendConfig: BackendConfig) => {
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
} catch (cleanupError) {
|
||||
// Ignore cleanup errors if directory doesn't exist or can't be removed
|
||||
console.warn("Failed to cleanup temp directory:", cleanupError);
|
||||
logger.warn("Failed to cleanup temp directory:", cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,4 +258,5 @@ export const volumeService = {
|
||||
testConnection,
|
||||
updateVolumeStatus,
|
||||
getVolumeStatus,
|
||||
unmountVolume,
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ConflictError, NotFoundError } from "http-errors-enhanced";
|
||||
import { logger } from "./logger";
|
||||
|
||||
export const handleServiceError = (error: unknown) => {
|
||||
if (error instanceof ConflictError) {
|
||||
@@ -9,6 +10,6 @@ export const handleServiceError = (error: unknown) => {
|
||||
return { message: error.message, status: 404 as const };
|
||||
}
|
||||
|
||||
console.error("Unhandled service error:", error);
|
||||
logger.error("Unhandled service error:", error);
|
||||
return { message: "Internal Server Error", status: 500 as const };
|
||||
};
|
||||
|
||||
34
apps/server/src/utils/logger.ts
Normal file
34
apps/server/src/utils/logger.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { createLogger, format, transports } from "winston";
|
||||
|
||||
const { printf, combine, colorize } = format;
|
||||
|
||||
const printConsole = printf((info) => `${info.level} > ${info.message}`);
|
||||
const consoleFormat = combine(colorize(), printConsole);
|
||||
|
||||
const winstonLogger = createLogger({
|
||||
level: "info",
|
||||
format: format.json(),
|
||||
transports: [new transports.Console({ level: "info", format: consoleFormat })],
|
||||
});
|
||||
|
||||
const log = (level: "info" | "warn" | "error", messages: unknown[]) => {
|
||||
const stringMessages = messages.flatMap((m) => {
|
||||
if (m instanceof Error) {
|
||||
return [m.message, m.stack];
|
||||
}
|
||||
|
||||
if (typeof m === "object") {
|
||||
return JSON.stringify(m, null, 2);
|
||||
}
|
||||
|
||||
return m;
|
||||
});
|
||||
|
||||
winstonLogger.log(level, stringMessages.join(" | "));
|
||||
};
|
||||
|
||||
export const logger = {
|
||||
info: (...messages: unknown[]) => log("info", messages),
|
||||
warn: (...messages: unknown[]) => log("warn", messages),
|
||||
error: (...messages: unknown[]) => log("error", messages),
|
||||
};
|
||||
Reference in New Issue
Block a user