diff --git a/.gitignore b/.gitignore index db194efb..eb99498e 100644 --- a/.gitignore +++ b/.gitignore @@ -38,4 +38,6 @@ next-env.d.ts public/uploads/* !public/uploads/ +private/uploads/* + /.env diff --git a/app/(customer)/dashboard/agents/[agentId]/page.tsx b/app/(customer)/dashboard/agents/[agentId]/page.tsx index aa0dafac..c329454a 100644 --- a/app/(customer)/dashboard/agents/[agentId]/page.tsx +++ b/app/(customer)/dashboard/agents/[agentId]/page.tsx @@ -11,6 +11,7 @@ import {GearIcon} from "@radix-ui/react-icons"; import Link from "next/link"; import {AgentModalKey} from "@/components/wrappers/Agent/AgentModalKey/AgentModalKey"; import {KeyRound} from "lucide-react"; +import {BackupButton} from "@/components/wrappers/BackupButton/BackupButton"; export default async function RoutePage(props: PageParams<{ agentId: string }>) { @@ -76,7 +77,6 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>) const successRate = totalBackups > 0 ? (successfulBackups / totalBackups) * 100 : null - return (
@@ -93,7 +93,7 @@ export default async function RoutePage(props: PageParams<{ agentId: string }>) - +
diff --git a/app/api/agent/[agentId]/backup/helpers.ts b/app/api/agent/[agentId]/backup/helpers.ts new file mode 100644 index 00000000..139597f9 --- /dev/null +++ b/app/api/agent/[agentId]/backup/helpers.ts @@ -0,0 +1,2 @@ + + diff --git a/app/api/agent/[agentId]/backup/route.ts b/app/api/agent/[agentId]/backup/route.ts new file mode 100644 index 00000000..82a233ae --- /dev/null +++ b/app/api/agent/[agentId]/backup/route.ts @@ -0,0 +1,127 @@ +import {NextResponse} from "next/server"; +import {Body} from "../status/route"; +import {prisma} from "@/prisma"; +import {isUuidv4} from "@/utils/verify-uuid"; +import {uploadLocalPrivate} from "@/features/upload/private/upload.action"; +import {v4 as uuidv4} from "uuid"; + + +export async function POST( + request: Request, + {params}: { params: Promise<{ agentId: string }> } +) { + + try { + + const contentType = request.headers.get("Content-Type"); + + // Ensure `contentType` is not null before checking + if (!contentType || (!contentType.includes("multipart/form-data"))) { + return NextResponse.json( + { error: 'Unsupported or missing Content-Type' }, + { status: 400 } + ); + } + + const agentId = (await params).agentId + const formData = await request.formData(); + const generatedId = formData.get("generatedId") as string; + + + + if (!isUuidv4(generatedId)) { + return NextResponse.json( + {error: "generatedId is not a valid uuid"}, + {status: 500} + ); + } + + + const agent = await prisma.agent.findFirst({ + where: { + id: agentId + } + }) + if (!agent) { + return NextResponse.json({error: "Agent not found"}, {status: 404}) + } + + const database = await prisma.database.findFirst({ + where: { + generatedId: generatedId + } + }) + + if (!database) { + return NextResponse.json({error: "Database associated with generatedId provided not found"}, {status: 404}) + } + + const backup = await prisma.backup.findFirst({ + where: { + status : "ongoing", + databaseId: database.id + } + }) + if (!backup) { + return NextResponse.json({error: "Unable to fin the corresponding backup"}, {status: 404}) + } + + const status = formData.get("status") as string; + + if(status === "success"){ + + const file = formData.get("file") as File + const uuid = uuidv4() + const fileName = `${uuid}.dump` + const buffer = Buffer.from(await file.arrayBuffer()); + + const {success, message, filePath} = await uploadLocalPrivate(fileName, buffer) + + if (!success){ + return NextResponse.json( + {error: message}, + {status: 500} + ); + } + + await prisma.backup.update({ + where: { + id : backup.id, + }, + data: { + file: fileName, + status: "success" + } + }) + + const response = { + message: true, + details: "Backup successfully uploaded" + } + return Response.json(response) + + }else{ + await prisma.backup.update({ + where: { + id : backup.id, + }, + data: { + status: "failed" + } + }) + + const response = { + message: true, + details: "Backup successfully updated with status failed" + } + return Response.json(response) + } + + } catch (error) { + console.error('Error in POST handler:', error); + return NextResponse.json( + {error: 'Internal server error'}, + {status: 500} + ); + } +} \ No newline at end of file diff --git a/app/api/agent/[agentId]/status/helpers.ts b/app/api/agent/[agentId]/status/helpers.ts index 8b777b8f..3948aa9f 100644 --- a/app/api/agent/[agentId]/status/helpers.ts +++ b/app/api/agent/[agentId]/status/helpers.ts @@ -2,18 +2,10 @@ import {Agent, Database} from "@prisma/client"; import {prisma} from "@/prisma"; import {NextResponse} from "next/server"; import {Body} from "./route"; +import {isUuidv4} from "@/utils/verify-uuid"; -// Regular expression for UUIDv4 -const uuidv4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -// Type guard to check if a string is a valid UUIDv4 -function isUuidv4(value: string): value is string { - console.log(value) - console.log(uuidv4Regex.test(value)) - return uuidv4Regex.test(value); -} @@ -22,12 +14,12 @@ function isUuidv4(value: string): value is string { export async function handleDatabases(body: Body, agent: Agent, lastContact: Date) { const databasesResponse = []; - const formatDatabase = (database: Database) => ({ + const formatDatabase = (database: Database, backupAction: boolean) => ({ generatedId: database.generatedId, dbms: database.dbms, data: { backup: { - action: true, + action: backupAction, cron: "", }, restore: { @@ -44,6 +36,8 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat }, }); + let backupAction: boolean = false + if (!existingDatabase) { if (!isUuidv4(db.generatedId)) { return NextResponse.json( @@ -62,7 +56,7 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat }); if (databaseCreated) { - databasesResponse.push(formatDatabase(databaseCreated)); + databasesResponse.push(formatDatabase(databaseCreated, backupAction)); } } else { const databaseUpdated = await prisma.database.update({ @@ -73,7 +67,27 @@ export async function handleDatabases(body: Body, agent: Agent, lastContact: Dat lastContact: lastContact, }, }); - databasesResponse.push(formatDatabase(databaseUpdated)); + + const backup = await prisma.backup.findFirst({ + where: { + databaseId: databaseUpdated.id, + status: "waiting" + } + }) + + if(backup){ + backupAction = true + await prisma.backup.update({ + where:{ + id: backup.id + }, + data: { + status: "ongoing" + } + }) + } + + databasesResponse.push(formatDatabase(databaseUpdated, backupAction)); } } return databasesResponse; diff --git a/app/api/agent/[agentId]/status/route.ts b/app/api/agent/[agentId]/status/route.ts index e0be494a..e585a076 100644 --- a/app/api/agent/[agentId]/status/route.ts +++ b/app/api/agent/[agentId]/status/route.ts @@ -49,6 +49,7 @@ export async function POST( }, databases: databasesResponse } + console.log(response) return Response.json(response) } catch (error) { diff --git a/app/api/files/[fileName]/route.ts b/app/api/files/[fileName]/route.ts index f668c5cc..f58047e8 100644 --- a/app/api/files/[fileName]/route.ts +++ b/app/api/files/[fileName]/route.ts @@ -55,4 +55,6 @@ export async function GET( 'Content-Type': 'application/octet-stream', }, }); -} \ No newline at end of file +} + + diff --git a/middleware.ts b/middleware.ts index 824c6a65..f878a116 100644 --- a/middleware.ts +++ b/middleware.ts @@ -38,6 +38,7 @@ function checkRouteExists(pathname) { // /^\/api\/auth\/\w+$/, // Dynamic route with a number as a parameter (e.g., /api/dynamic/123) // /^\/api\/agent\/healthcheck\/\w+$/, // Dynamic route with an alphanumeric parameter (e.g., /api/user/username) /^\/api\/agent\/[^/]+\/status\/?$/, // Dynamic route for /api/agent/[id]/status + /^\/api\/agent\/[^/]+\/backup\/?$/, // Dynamic route for /api/agent/[id]/status /^\/api\/files\/[^/]+\/?$/, ]; return routePatterns.some(pattern => pattern.test(pathname)); diff --git a/prisma/migrations/20241129165221_2024_11_29/migration.sql b/prisma/migrations/20241129165221_2024_11_29/migration.sql new file mode 100644 index 00000000..3b9baaaa --- /dev/null +++ b/prisma/migrations/20241129165221_2024_11_29/migration.sql @@ -0,0 +1,9 @@ +/* + Warnings: + + - Added the required column `backupToRestore` to the `databases` table without a default value. This is not possible if the table is not empty. + +*/ +-- AlterTable +ALTER TABLE "databases" ADD COLUMN "backupToRestore" TEXT NOT NULL, +ADD COLUMN "isWaitingForBackup" BOOLEAN NOT NULL DEFAULT false; diff --git a/prisma/migrations/20241129173131_2024_11_29/migration.sql b/prisma/migrations/20241129173131_2024_11_29/migration.sql new file mode 100644 index 00000000..83eb3fae --- /dev/null +++ b/prisma/migrations/20241129173131_2024_11_29/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "databases" ALTER COLUMN "backupToRestore" DROP NOT NULL, +ALTER COLUMN "isWaitingForBackup" DROP NOT NULL; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 8056e261..3803aad2 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -97,13 +97,15 @@ enum Dbms { } model Database { - id String @id @default(cuid()) - name String - dbms Dbms - generatedId String @unique - description String? - backupPolicy String? @map("backup_policy") - createdAt DateTime @default(now()) @map("created_at") + id String @id @default(cuid()) + name String + dbms Dbms + generatedId String @unique + description String? + backupPolicy String? @map("backup_policy") + createdAt DateTime @default(now()) @map("created_at") + isWaitingForBackup Boolean? @default(false) + backupToRestore String? agentId String @map("agent_id") agent Agent @relation(fields: [agentId], references: [id], onDelete: Cascade) diff --git a/private/uploads/d4a7fa35-2506-4d01-a612-a8ef2e2cc1c5.dump b/private/uploads/d4a7fa35-2506-4d01-a612-a8ef2e2cc1c5.dump deleted file mode 100644 index 92756966..00000000 Binary files a/private/uploads/d4a7fa35-2506-4d01-a612-a8ef2e2cc1c5.dump and /dev/null differ diff --git a/src/components/wrappers/BackupButton/BackupButton.tsx b/src/components/wrappers/BackupButton/BackupButton.tsx new file mode 100644 index 00000000..ad41ae95 --- /dev/null +++ b/src/components/wrappers/BackupButton/BackupButton.tsx @@ -0,0 +1,29 @@ +"use client" +import {Button} from "@/components/ui/button"; +import {useMutation} from "@tanstack/react-query"; +import {backupButtonAction} from "@/components/wrappers/BackupButton/backup-button.action"; + +export type BackupButtonProps = { + // databaseId: string; +} + +export const BackupButton = () => { + + + const mutation = useMutation({ + mutationFn: async (databaseId: string) => { + const result = await backupButtonAction(databaseId) + console.log(result) + } + }) + + + return ( + + ) +} diff --git a/src/components/wrappers/BackupButton/backup-button.action.ts b/src/components/wrappers/BackupButton/backup-button.action.ts new file mode 100644 index 00000000..d35b174d --- /dev/null +++ b/src/components/wrappers/BackupButton/backup-button.action.ts @@ -0,0 +1,42 @@ +"use server" +import {userAction} from "@/safe-actions"; +import {z} from "zod"; +import {prisma} from "@/prisma"; +import {ServerActionResult} from "@/types/action-type"; +import {Backup} from "@prisma/client"; + + + +export const backupButtonAction = userAction + .schema(z.string()) + .action(async ({ parsedInput, ctx }): Promise> => { + try { + const backup = await prisma.backup.create({ + data: { + databaseId: parsedInput, + status: "waiting", + }, + }); + + return { + success: true, + value: backup, + actionSuccess: { + message: "Backup has been successfully created.", + messageParams: { databaseId: parsedInput }, + }, + }; + } catch (error) { + console.error("Error creating backup:", error); + + return { + success: false, + actionError: { + message: "Failed to create backup.", + status: 500, // Optional: Use a meaningful status code + cause: error instanceof Error ? error.message : "Unknown error", + messageParams: { databaseId: parsedInput }, + }, + }; + } + }); \ No newline at end of file diff --git a/src/features/upload/private/upload.action.ts b/src/features/upload/private/upload.action.ts index 9d37f8a0..b9b01128 100644 --- a/src/features/upload/private/upload.action.ts +++ b/src/features/upload/private/upload.action.ts @@ -6,22 +6,28 @@ import {getServerUrl} from "@/utils/get-server-url"; const privateLocalDir = "private/uploads/"; -async function uploadLocalPrivate(fileName: string, buffer: any) { +export async function uploadLocalPrivate(fileName: string, buffer: any) { try { await mkdir(path.join(process.cwd(), privateLocalDir), { recursive: true }); - return await writeFile( - path.join(process.cwd(), privateLocalDir + fileName), + + await writeFile( + path.join(process.cwd(), privateLocalDir, fileName), buffer - ) + ); + + return { + success: true, + message: "File uploaded successfully", + filePath: path.join(privateLocalDir, fileName), + }; } catch (error) { - console.log("Error occured ", error); - throw new Error('An error occured while importing private file'); + console.error("Error occurred:", error); + throw new Error("An error occurred while importing the private file"); } } - export async function getFileUrlPresignedLocal(fileName: string) { try { const filePath = path.join(privateLocalDir, fileName); diff --git a/src/safe-actions.ts b/src/safe-actions.ts index c9047df2..bf2f7eba 100644 --- a/src/safe-actions.ts +++ b/src/safe-actions.ts @@ -1,3 +1,4 @@ + import {createSafeActionClient} from "next-safe-action"; import {currentUser} from "@/auth/current-user"; diff --git a/src/types/action-type.ts b/src/types/action-type.ts new file mode 100644 index 00000000..570804c4 --- /dev/null +++ b/src/types/action-type.ts @@ -0,0 +1,6 @@ + +export type ServerActionResult = { success: true; value: T; actionSuccess?: ActionSuccessMessage } | { success: false; actionError: ActionErrorMessage }; + +export type ActionErrorMessage = { message?: string; status?: number; cause?: string; messageParams?: Record }; + +export type ActionSuccessMessage = { message?: string; messageParams?: Record }; \ No newline at end of file diff --git a/src/utils/verify-uuid.ts b/src/utils/verify-uuid.ts new file mode 100644 index 00000000..120e17a1 --- /dev/null +++ b/src/utils/verify-uuid.ts @@ -0,0 +1,6 @@ + +const uuidv4Regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function isUuidv4(value: string): value is string { + return uuidv4Regex.test(value); +} \ No newline at end of file