Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions app/api/analysis/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
requireAuthUser,
unauthorizedResponse,
} from "@/lib/auth-helpers";
import { mapCreateAnalysisError } from "@/lib/create-analysis-errors";
import { getMembership } from "@/lib/org/access";
import { createLogger } from "@/lib/logger";
import type { ApiResponse } from "@/types";
Expand Down Expand Up @@ -138,14 +139,18 @@ export async function POST(
},
});
} catch (error) {
log.error("Failed to create analysis session", { error: String(error) });
const mapped = mapCreateAnalysisError(error);
log.error("Failed to create analysis session", {
error: String(error),
code: mapped.code,
});
return NextResponse.json(
{
success: false as const,
error: "Failed to create analysis session.",
code: "INTERNAL_ERROR",
error: mapped.message,
code: mapped.code,
},
{ status: 500 }
{ status: mapped.status }
);
}
}
8 changes: 8 additions & 0 deletions lib/auth-helpers.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
import { auth } from "@/auth";
import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import type { ApiResponse } from "@/types";

export async function requireAuthUser() {
const session = await auth();
const userId = session?.user?.id;
if (!userId) return null;

const user = await prisma.user.findUnique({
where: { id: userId },
select: { id: true },
});
if (!user) return null;

return { session, userId };
}

Expand Down
30 changes: 30 additions & 0 deletions lib/create-analysis-errors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, it, expect } from "vitest";
import { Prisma } from "@prisma/client";
import { mapCreateAnalysisError } from "./create-analysis-errors";

describe("mapCreateAnalysisError", () => {
it("maps database connection failures to DB_UNAVAILABLE", () => {
const error = new Prisma.PrismaClientInitializationError(
"tenant/user postgres.eccziupihegciupibxis not found",
"5.0.0"
);

const mapped = mapCreateAnalysisError(error);

expect(mapped.code).toBe("DB_UNAVAILABLE");
expect(mapped.status).toBe(503);
expect(mapped.message).toMatch(/Database unavailable|Service temporarily unavailable/);
});

it("maps foreign key violations to UNAUTHORIZED", () => {
const error = new Prisma.PrismaClientKnownRequestError(
"Foreign key constraint failed",
{ code: "P2003", clientVersion: "5.0.0" }
);

const mapped = mapCreateAnalysisError(error);

expect(mapped.code).toBe("UNAUTHORIZED");
expect(mapped.status).toBe(401);
});
});
52 changes: 52 additions & 0 deletions lib/create-analysis-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Prisma } from "@prisma/client";

function isDatabaseUnavailable(error: unknown): boolean {
if (error instanceof Prisma.PrismaClientInitializationError) return true;
const message = String(error);
return (
message.includes("ENOTFOUND") ||
message.includes("Can't reach database server") ||
message.includes("tenant/user") ||
message.includes("P1001")
);
}

export function mapCreateAnalysisError(error: unknown): {
message: string;
status: number;
code: string;
} {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === "P2003") {
return {
message: "Session expired. Please sign in again.",
status: 401,
code: "UNAUTHORIZED",
};
}
if (error.code === "P2002") {
return {
message: "Could not allocate a unique share link. Please retry.",
status: 409,
code: "CONFLICT",
};
}
}

if (isDatabaseUnavailable(error)) {
return {
message:
process.env.NODE_ENV === "development"
? "Database unavailable. Check DATABASE_URL / DIRECT_URL in .env.local and that your Supabase project is active."
: "Service temporarily unavailable. Try again shortly.",
status: 503,
code: "DB_UNAVAILABLE",
};
}

return {
message: "Failed to create analysis session.",
status: 500,
code: "INTERNAL_ERROR",
};
}
Loading