mirror of
https://github.com/nicotsx/ironmount.git
synced 2025-12-10 12:10:51 +01:00
refactor: improve error handling with global router catchall
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { exec, execFile as execFileCb } from "node:child_process";
|
||||
import { execFile as execFileCb } from "node:child_process";
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as npath from "node:path";
|
||||
@@ -9,6 +9,7 @@ import { promisify } from "node:util";
|
||||
import { withTimeout } from "../../../utils/timeout";
|
||||
import { OPERATION_TIMEOUT } from "../../../core/constants";
|
||||
import { toMessage } from "../../../utils/errors";
|
||||
import { getMountForPath } from "../../../utils/mountinfo";
|
||||
|
||||
const execFile = promisify(execFileCb);
|
||||
|
||||
@@ -110,6 +111,12 @@ const checkHealth = async (path: string) => {
|
||||
logger.debug(`Checking health of NFS volume at ${path}...`);
|
||||
await fs.access(path);
|
||||
|
||||
const mount = await getMountForPath(path);
|
||||
|
||||
if (!mount || !mount.fstype.startsWith("nfs")) {
|
||||
throw new Error(`Path ${path} is not mounted as NFS.`);
|
||||
}
|
||||
|
||||
const testFilePath = npath.join(path, `.healthcheck-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
|
||||
|
||||
await fs.writeFile(testFilePath, "healthcheck");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq, or } from "drizzle-orm";
|
||||
import { and, eq, or } from "drizzle-orm";
|
||||
import { db } from "../../db/db";
|
||||
import { logger } from "../../utils/logger";
|
||||
import { volumesTable } from "../../db/schema";
|
||||
@@ -7,7 +7,10 @@ import { volumeService } from "../volumes/volume.service";
|
||||
|
||||
export const startup = async () => {
|
||||
const volumes = await db.query.volumesTable.findMany({
|
||||
where: or(eq(volumesTable.status, "mounted"), eq(volumesTable.autoRemount, 1)),
|
||||
where: or(
|
||||
eq(volumesTable.status, "mounted"),
|
||||
and(eq(volumesTable.autoRemount, 1), eq(volumesTable.status, "error")),
|
||||
),
|
||||
});
|
||||
|
||||
for (const volume of volumes) {
|
||||
@@ -21,7 +24,7 @@ export const startup = async () => {
|
||||
logger.info("Running health check for all volumes...");
|
||||
|
||||
const volumes = await db.query.volumesTable.findMany({
|
||||
where: or(eq(volumesTable.status, "mounted")),
|
||||
where: or(eq(volumesTable.status, "mounted"), eq(volumesTable.status, "error")),
|
||||
});
|
||||
|
||||
for (const volume of volumes) {
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Hono } from "hono";
|
||||
import { validator } from "hono-openapi/arktype";
|
||||
import { handleServiceError } from "../../utils/errors";
|
||||
import {
|
||||
createVolumeBody,
|
||||
createVolumeDto,
|
||||
@@ -37,12 +36,7 @@ export const volumeController = new Hono()
|
||||
const body = c.req.valid("json");
|
||||
const res = await volumeService.createVolume(body.name, body.config);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume created", volume: res.volume });
|
||||
return c.json({ message: "Volume created", volume: res.volume }, 201);
|
||||
})
|
||||
.post("/test-connection", testConnectionDto, validator("json", testConnectionBody), async (c) => {
|
||||
const body = c.req.valid("json");
|
||||
@@ -52,24 +46,14 @@ export const volumeController = new Hono()
|
||||
})
|
||||
.delete("/:name", deleteVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.deleteVolume(name);
|
||||
await volumeService.deleteVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
return c.json({ message: "Volume deleted" });
|
||||
return c.json({ message: "Volume deleted" }, 200);
|
||||
})
|
||||
.get("/:name", getVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.getVolume(name);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
const response = {
|
||||
...res.volume,
|
||||
createdAt: res.volume.createdAt.getTime(),
|
||||
@@ -84,11 +68,6 @@ export const volumeController = new Hono()
|
||||
const body = c.req.valid("json");
|
||||
const res = await volumeService.updateVolume(name, body.config);
|
||||
|
||||
if (res.error) {
|
||||
const { message, status } = handleServiceError(res.error);
|
||||
return c.json(message, status);
|
||||
}
|
||||
|
||||
const response = {
|
||||
message: "Volume updated",
|
||||
volume: {
|
||||
@@ -105,23 +84,13 @@ export const volumeController = new Hono()
|
||||
})
|
||||
.post("/:name/mount", mountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.mountVolume(name);
|
||||
const { error, status } = 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);
|
||||
return c.json({ error, status }, error ? 500 : 200);
|
||||
})
|
||||
.post("/:name/unmount", unmountVolumeDto, async (c) => {
|
||||
const { name } = c.req.param();
|
||||
const res = await volumeService.unmountVolume(name);
|
||||
const { error, status } = 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);
|
||||
return c.json({ error, status }, error ? 500 : 200);
|
||||
});
|
||||
|
||||
@@ -8,11 +8,12 @@ const volumeSchema = type({
|
||||
path: "string",
|
||||
type: type.enumerated("nfs", "smb", "directory"),
|
||||
status: type.enumerated("mounted", "unmounted", "error", "unknown"),
|
||||
lastError: "string|null",
|
||||
lastError: "string | null",
|
||||
createdAt: "number",
|
||||
updatedAt: "number",
|
||||
lastHealthCheck: "number",
|
||||
config: volumeConfigSchema,
|
||||
autoRemount: "0 | 1",
|
||||
});
|
||||
|
||||
export type VolumeDto = typeof volumeSchema.infer;
|
||||
@@ -55,7 +56,6 @@ export const createVolumeResponse = type({
|
||||
volume: type({
|
||||
name: "string",
|
||||
path: "string",
|
||||
createdAt: "number",
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -195,7 +195,8 @@ export const testConnectionDto = describeRoute({
|
||||
* Mount volume
|
||||
*/
|
||||
export const mountVolumeResponse = type({
|
||||
message: "string",
|
||||
error: "string?",
|
||||
status: type.enumerated("mounted", "unmounted", "error"),
|
||||
});
|
||||
|
||||
export const mountVolumeDto = describeRoute({
|
||||
@@ -222,7 +223,8 @@ export const mountVolumeDto = describeRoute({
|
||||
* Unmount volume
|
||||
*/
|
||||
export const unmountVolumeResponse = type({
|
||||
message: "string",
|
||||
error: "string?",
|
||||
status: type.enumerated("mounted", "unmounted", "error"),
|
||||
});
|
||||
|
||||
export const unmountVolumeDto = describeRoute({
|
||||
|
||||
@@ -9,7 +9,6 @@ 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";
|
||||
import { toMessage } from "../../utils/errors";
|
||||
|
||||
const listVolumes = async () => {
|
||||
@@ -26,7 +25,7 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return { error: new ConflictError("Volume already exists") };
|
||||
throw new ConflictError("Volume already exists");
|
||||
}
|
||||
|
||||
const volumePathHost = path.join(config.volumeRootHost);
|
||||
@@ -45,82 +44,54 @@ const createVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
};
|
||||
|
||||
const deleteVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
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.delete(volumesTable).where(eq(volumesTable.name, name));
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to delete volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
await backend.unmount();
|
||||
await db.delete(volumesTable).where(eq(volumesTable.name, name));
|
||||
};
|
||||
|
||||
const mountVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
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.mount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "mounted", lastHealthCheck: new Date(), lastError: null })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to mount volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { error, status } = await backend.mount();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status, lastError: error, lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, name));
|
||||
|
||||
return { error, status };
|
||||
};
|
||||
|
||||
const unmountVolume = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
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,
|
||||
}),
|
||||
};
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { status, error } = await backend.unmount();
|
||||
|
||||
await db.update(volumesTable).set({ status }).where(eq(volumesTable.name, name));
|
||||
|
||||
return { error, status };
|
||||
};
|
||||
|
||||
const getVolume = async (name: string) => {
|
||||
@@ -129,121 +100,88 @@ const getVolume = async (name: string) => {
|
||||
});
|
||||
|
||||
if (!volume) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
return { volume };
|
||||
};
|
||||
|
||||
const updateVolume = async (name: string, backendConfig: BackendConfig) => {
|
||||
try {
|
||||
const existing = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
const existing = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
return { error: new NotFoundError("Volume not found") };
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(volumesTable)
|
||||
.set({
|
||||
config: backendConfig,
|
||||
type: backendConfig.backend,
|
||||
updatedAt: new Date(),
|
||||
status: "unmounted",
|
||||
})
|
||||
.where(eq(volumesTable.name, name))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
return { error: new InternalServerError("Failed to update volume") };
|
||||
}
|
||||
|
||||
return { volume: updated };
|
||||
} catch (error) {
|
||||
return {
|
||||
error: new InternalServerError("Failed to update volume", {
|
||||
cause: error,
|
||||
}),
|
||||
};
|
||||
if (!existing) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(volumesTable)
|
||||
.set({
|
||||
config: backendConfig,
|
||||
type: backendConfig.backend,
|
||||
updatedAt: new Date(),
|
||||
status: "unmounted",
|
||||
})
|
||||
.where(eq(volumesTable.name, name))
|
||||
.returning();
|
||||
|
||||
if (!updated) {
|
||||
throw new InternalServerError("Failed to update volume");
|
||||
}
|
||||
|
||||
return { volume: updated };
|
||||
};
|
||||
|
||||
const testConnection = async (backendConfig: BackendConfig) => {
|
||||
let tempDir: string | null = null;
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ironmount-test-"));
|
||||
|
||||
try {
|
||||
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ironmount-test-"));
|
||||
const mockVolume = {
|
||||
id: 0,
|
||||
name: "test-connection",
|
||||
path: tempDir,
|
||||
config: backendConfig,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastHealthCheck: new Date(),
|
||||
type: backendConfig.backend,
|
||||
status: "unmounted" as const,
|
||||
lastError: null,
|
||||
autoRemount: 0 as const,
|
||||
};
|
||||
|
||||
const mockVolume = {
|
||||
id: 0,
|
||||
name: "test-connection",
|
||||
path: tempDir,
|
||||
config: backendConfig,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
lastHealthCheck: new Date(),
|
||||
type: backendConfig.backend,
|
||||
status: "unmounted" as const,
|
||||
lastError: null,
|
||||
autoRemount: 0,
|
||||
};
|
||||
const backend = createVolumeBackend(mockVolume);
|
||||
const { error } = await backend.mount();
|
||||
|
||||
const backend = createVolumeBackend(mockVolume);
|
||||
await backend.unmount();
|
||||
|
||||
await backend.mount();
|
||||
await backend.unmount();
|
||||
await fs.access(tempDir);
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: "Connection successful",
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
message: toMessage(error),
|
||||
};
|
||||
} finally {
|
||||
if (tempDir) {
|
||||
try {
|
||||
await fs.access(tempDir);
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
} catch (cleanupError) {
|
||||
logger.warn("Failed to cleanup temp directory:", cleanupError);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: !error,
|
||||
message: error ? toMessage(error) : "Connection successful",
|
||||
};
|
||||
};
|
||||
|
||||
const checkHealth = async (name: string) => {
|
||||
try {
|
||||
const volume = await db.query.volumesTable.findFirst({
|
||||
where: eq(volumesTable.name, name),
|
||||
});
|
||||
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);
|
||||
const { error } = await backend.checkHealth();
|
||||
|
||||
if (error) {
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ status: "error", lastError: error, lastHealthCheck: new Date() })
|
||||
.where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { error };
|
||||
}
|
||||
|
||||
await db.update(volumesTable).set({ lastHealthCheck: new Date() }).where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { status: 200 };
|
||||
} catch (err) {
|
||||
return { error: new InternalServerError("Health check failed", { cause: err }) };
|
||||
if (!volume) {
|
||||
throw new NotFoundError("Volume not found");
|
||||
}
|
||||
|
||||
const backend = createVolumeBackend(volume);
|
||||
const { error, status } = await backend.checkHealth();
|
||||
|
||||
await db
|
||||
.update(volumesTable)
|
||||
.set({ lastHealthCheck: new Date(), status, lastError: error })
|
||||
.where(eq(volumesTable.name, volume.name));
|
||||
|
||||
return { status, error };
|
||||
};
|
||||
|
||||
export const volumeService = {
|
||||
|
||||
Reference in New Issue
Block a user