Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(ai-gateway): turn the gateway off when its ingestion project is d… (#19556)

Tobias Wochingerf30088aacff0
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.yml
index 89e548841b..657c302f31 100644
--- a/fern/apis/server/definition/projects.yml
+++ b/fern/apis/server/definition/projects.yml
@@ -53,7 +53,7 @@ service:
response: Project
delete:
- docs: Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously.
+ docs: Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously. Deleting the AI Gateway ingestion project turns off the AI Gateway for the organization until another ingestion project is selected.
method: DELETE
path: /projects/{projectId}
path-parameters:
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 95ee7ef6fb..fd3f0aa27d 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -4580,7 +4580,9 @@ paths:
delete:
description: >-
Delete a project by ID (requires organization-scoped API key). Project
- deletion is processed asynchronously.
+ deletion is processed asynchronously. Deleting the AI Gateway ingestion
+ project turns off the AI Gateway for the organization until another
+ ingestion project is selected.
operationId: projects_delete
tags:
- Projects
diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
index e5d52d7f78..d0ac687b67 100644
--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts
@@ -4,6 +4,7 @@ import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
import type { Session } from "next-auth";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as SharedServer from "@langfuse/shared/src/server";
+import type * as BillingServer from "@/src/ee/features/billing/server";
import { z } from "zod/v4";
const { addNotificationJobs, getNotificationJob } = vi.hoisted(() => ({
@@ -30,6 +31,17 @@ vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
};
});
+// organizations.delete cancels Stripe on Cloud, which the test env cannot reach.
+const { isCloudBillingEnabled } = vi.hoisted(() => ({
+ isCloudBillingEnabled: vi.fn<() => boolean>(),
+}));
+
+vi.mock("@/src/ee/features/billing/server", async (importOriginal) => {
+ const actual = await importOriginal<typeof BillingServer>();
+ isCloudBillingEnabled.mockImplementation(actual.isCloudBillingEnabled);
+ return { ...actual, isCloudBillingEnabled };
+});
+
function queuedNotifications(): SharedServer.NotificationEventType[] {
return addNotificationJobs.mock.calls.flatMap(([jobs]) =>
jobs.map((job) => job.data.payload),
@@ -220,6 +232,7 @@ async function prepare(role: Role = Role.OWNER) {
async function createCallerForOrganizationRole(
setup: Awaited<ReturnType<typeof prepare>>,
role: Role,
+ projectRole: Role = role,
) {
const suffix = randomUUID();
const user = await prisma.user.create({
@@ -246,7 +259,7 @@ async function createCallerForOrganizationRole(
role,
projects: organization.projects.map((project) => ({
...project,
- role,
+ role: projectRole,
})),
}
: organization,
@@ -782,9 +795,6 @@ describe("AI gateway control plane", () => {
await expect(
caller.projects.deletionProtection({ projectId: project.id }),
).resolves.toEqual({ isGatewayIngestionProject: true });
- await expect(
- caller.projects.delete({ projectId: project.id }),
- ).rejects.toThrow("Select another ingestion project before deleting it");
} finally {
Object.assign(env, {
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: originalCloudRegion,
@@ -2363,23 +2373,53 @@ describe("AI gateway control plane", () => {
}
});
- it("blocks deletion of the default ingestion project", async () => {
- const { caller, org, project } = await prepare();
+ it("turns the gateway off when its ingestion project is deleted, so the organization can be deleted", async () => {
+ const setup = await prepare();
+ const { caller, org, project } = setup;
await caller.aiGateway.updateConfig({
orgId: org.id,
defaultIngestionProjectId: project.id,
ingestionMode: "USAGE",
});
+ const projectOwnerWithoutGatewayManage =
+ await createCallerForOrganizationRole(setup, Role.MEMBER, Role.OWNER);
+ await expect(
+ projectOwnerWithoutGatewayManage.projects.delete({
+ projectId: project.id,
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
await expect(
caller.projects.deletionProtection({ projectId: project.id }),
).resolves.toEqual({ isGatewayIngestionProject: true });
await expect(
caller.projects.delete({ projectId: project.id }),
- ).rejects.toThrow("Select another ingestion project");
+ ).resolves.toBe(true);
await expect(
- prisma.project.findUnique({ where: { id: project.id } }),
- ).resolves.toMatchObject({ deletedAt: null });
+ caller.aiGateway.getSetupStatus({ orgId: org.id }),
+ ).resolves.toEqual({ isConfigured: false });
+ await expect(
+ prisma.gatewayConfig.findUnique({ where: { organizationId: org.id } }),
+ ).resolves.toMatchObject({ defaultIngestionProjectId: null });
+ // The org audit log only lists entries without a project.
+ await expect(
+ prisma.auditLog.findFirst({
+ where: {
+ orgId: org.id,
+ resourceType: "gatewayConfig",
+ action: "update",
+ },
+ select: { projectId: true },
+ orderBy: { createdAt: "desc" },
+ }),
+ ).resolves.toEqual({ projectId: null });
+
+ // The project delete worker hard-deletes soft-deleted projects.
+ await prisma.project.delete({ where: { id: project.id } });
+ isCloudBillingEnabled.mockReturnValueOnce(false);
+ await expect(caller.organizations.delete({ orgId: org.id })).resolves.toBe(
+ true,
+ );
});
it("allows deleting the linked ingestion project while ingestion is NONE on self-hosted", async () => {
diff --git a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
index 0f9d757be0..e3ade7410a 100644
--- a/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
+++ b/web/src/__tests__/server/apiKeyCacheInvalidation.servertest.ts
@@ -1,4 +1,3 @@
-import { getGatewayIngestionProjectDeletionMessage } from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
import { testFeatureFlags } from "@/src/__tests__/fixtures/feature-flags";
import { LLMAdapter, type Plan, Role } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
@@ -374,67 +373,6 @@ describe("API-key cache invalidation on project/org lifecycle", () => {
expect(await survivingKeys(keys)).toEqual([]);
});
- it("admin project deletion keeps the ingestion project and its keys", async () => {
- const orgId = await createOrg();
- const projectId = await createProject(orgId);
- const keys = await seedOrgScopedKey(orgId);
- await prisma.gatewayConfig.create({
- data: { organizationId: orgId, defaultIngestionProjectId: projectId },
- });
-
- const res = makeRes();
- await handleDeleteProject({} as any, res, projectId, {
- orgId,
- apiKeyId: "ADMIN_KEY",
- } as any);
-
- expect(res.statusCode).toBe(409);
- expect(res.body).toEqual({
- message: getGatewayIngestionProjectDeletionMessage(),
- });
- expect(await survivingKeys(keys)).toEqual(keys);
- await expect(
- prisma.project.findUnique({ where: { id: projectId } }),
- ).resolves.toMatchObject({ deletedAt: null });
- });
-
- it("admin project deletion keeps a Cloud project whose stored ingestion mode is NONE", async () => {
- const orgId = await createOrg();
- const projectId = await createProject(orgId);
- const keys = await seedOrgScopedKey(orgId);
- // A legacy Cloud row can still store NONE. It runs as USAGE, so deletion stays blocked.
- const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- Object.assign(env, { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: "EU" });
- try {
- await prisma.gatewayConfig.create({
- data: {
- organizationId: orgId,
- defaultIngestionProjectId: projectId,
- ingestionMode: "NONE",
- },
- });
-
- const res = makeRes();
- await handleDeleteProject({} as any, res, projectId, {
- orgId,
- apiKeyId: "ADMIN_KEY",
- } as any);
-
- expect(res.statusCode).toBe(409);
- expect(res.body).toEqual({
- message: getGatewayIngestionProjectDeletionMessage(),
- });
- expect(await survivingKeys(keys)).toEqual(keys);
- await expect(
- prisma.project.findUnique({ where: { id: projectId } }),
- ).resolves.toMatchObject({ deletedAt: null });
- } finally {
- Object.assign(env, {
- NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: originalCloudRegion,
- });
- }
- });
-
it("admin project soft deletion preserves user permissions and evicts cached keys", async () => {
const orgId = await createOrg();
const projectId = await createProject(orgId);
diff --git a/web/src/__tests__/server/projects-api.servertest.ts b/web/src/__tests__/server/projects-api.servertest.ts
index 931ce397f4..b371cdc299 100644
--- a/web/src/__tests__/server/projects-api.servertest.ts
+++ b/web/src/__tests__/server/projects-api.servertest.ts
@@ -6,6 +6,7 @@ import { z } from "zod";
import {
createApiKey,
createBasicAuthHeader,
+ createOrgProjectAndApiKey,
invalidateCachedOrgApiKeys,
} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
@@ -831,6 +832,39 @@ describe("Projects API", () => {
expect(project?.deletedAt).not.toBeNull();
});
+ it("turns the gateway off when deleting its ingestion project", async () => {
+ const { orgId, projectId: ingestionProjectId } =
+ await createOrgProjectAndApiKey({ plan: "Enterprise" });
+ const orgKey = await createApiKey(prisma, {
+ tenant: OrganizationId(orgId),
+ scope: OrganizationId(orgId),
+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),
+ createdBy: "system",
+ });
+ await prisma.gatewayConfig.create({
+ data: {
+ organizationId: orgId,
+ defaultIngestionProjectId: ingestionProjectId,
+ ingestionMode: "USAGE",
+ },
+ });
+
+ const result = await makeAPICall<{ success: boolean }>(
+ "DELETE",
+ `/api/public/projects/${ingestionProjectId}`,
+ undefined,
+ createBasicAuthHeader(orgKey.publicKey, orgKey.secretKey),
+ );
+
+ expect(result.status).toBe(202);
+ await expect(
+ prisma.gatewayConfig.findUnique({ where: { organizationId: orgId } }),
+ ).resolves.toMatchObject({ defaultIngestionProjectId: null });
+ await expect(
+ prisma.project.findUnique({ where: { id: ingestionProjectId } }),
+ ).resolves.toMatchObject({ deletedAt: expect.any(Date) });
+ });
+
it("should return 403 when using project API key instead of organization API key", async () => {
const result = await makeAPICall<{ message: string }>(
"DELETE",
diff --git a/web/src/ee/features/admin-api/server/projects/projectById/index.ts b/web/src/ee/features/admin-api/server/projects/projectById/index.ts
index 1308372f77..e80d06083b 100644
--- a/web/src/ee/features/admin-api/server/projects/projectById/index.ts
+++ b/web/src/ee/features/admin-api/server/projects/projectById/index.ts
@@ -1,23 +1,21 @@
-import {
- getCapturingGatewayIngestionModes,
- getGatewayIngestionProjectDeletionMessage,
-} from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
+import { ForbiddenError } from "@langfuse/shared";
+import { type AuthorizationContext } from "@/src/features/auth/policy/types";
+import { ProjectService } from "@/src/features/projects/server";
import { type NextApiRequest, type NextApiResponse } from "next";
import { prisma } from "@langfuse/shared/src/db";
import {
logger,
redis,
- QueueJobs,
- ProjectDeleteQueue,
type ApiAccessScope,
} from "@langfuse/shared/src/server";
-import { randomUUID } from "crypto";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";
-import { ApiAuthService } from "@/src/features/public-api/server";
-import { auditLog } from "@/src/features/audit-logs/server";
-import { emitChbProjectEvent } from "@/src/ee/features/billing/server";
+import {
+ ApiAuthService,
+ shadowAuthorize,
+ writeProjectError,
+} from "@/src/features/public-api/server";
export async function handleUpdateProject(
req: NextApiRequest,
@@ -122,88 +120,20 @@ export async function handleDeleteProject(
res: NextApiResponse,
projectId: string,
scope: ApiAccessScope,
+ ctx?: AuthorizationContext,
) {
try {
- const gatewayConfig = await prisma.gatewayConfig.findFirst({
- where: {
- organizationId: scope.orgId,
- defaultIngestionProjectId: projectId,
- // With ingestion NONE the project is only remembered, not written to.
- ingestionMode: { in: getCapturingGatewayIngestionModes() },
- },
- select: { organizationId: true },
+ const gatewayManageDecision = shadowAuthorize({
+ ctx,
+ action: "gateway:manage",
+ resource: { orgId: scope.orgId },
+ legacyDecision: { success: true, scope },
});
- if (gatewayConfig) {
- return res.status(409).json({
- message: getGatewayIngestionProjectDeletionMessage(),
- });
- }
-
- // API keys need to be deleted from cache. Otherwise, they will still be valid.
- await new ApiAuthService(prisma, redis).invalidateCachedProjectApiKeys(
+ await new ProjectService(prisma, new ApiAuthService(prisma, redis)).delete({
+ organizationId: scope.orgId,
projectId,
- );
-
- // Delete API keys from DB
- await prisma.apiKey.deleteMany({
- where: {
- projectId: projectId,
- scope: "PROJECT",
- },
- });
-
- // Mark project as deleted
- const project = await prisma.project.update({
- where: {
- id: projectId,
- orgId: scope.orgId,
- },
- data: {
- deletedAt: new Date(),
- },
- });
-
- // Create audit log entry
- await auditLog({
- apiKeyId: scope.apiKeyId,
- orgId: scope.orgId,
- projectId,
- resourceType: "project",
- resourceId: projectId,
- before: project,
- action: "delete",
- });
-
- // Refresh org-scoped keys' baked projectIds now that a project is gone.
- await new ApiAuthService(prisma, redis).invalidateCachedOrgApiKeys(
- scope.orgId,
- );
-
- // Soft-delete is the billing-relevant moment: the customer stops being
- // billable now, not when the async hard-delete worker finishes.
- emitChbProjectEvent({
- type: "LANGFUSE_PROJECT_DELETED",
- orgId: scope.orgId,
- projectId,
- });
-
- // Queue project deletion job
- const projectDeleteQueue = ProjectDeleteQueue.getInstance();
- if (!projectDeleteQueue) {
- logger.error("ProjectDeleteQueue is not available");
- return res.status(500).json({
- message: "Internal server error",
- });
- }
-
- await projectDeleteQueue.add(QueueJobs.ProjectDelete, {
- timestamp: new Date(),
- id: randomUUID(),
- payload: {
- projectId: projectId,
- orgId: scope.orgId,
- },
- name: QueueJobs.ProjectDelete,
+ actor: { apiKeyId: scope.apiKeyId, orgId: scope.orgId, projectId },
+ canManageGateway: gatewayManageDecision.success,
});
return res.status(202).json({
@@ -212,6 +142,9 @@ export async function handleDeleteProject(
"Project deletion has been initiated and is being processed asynchronously",
});
} catch (error) {
+ if (error instanceof ForbiddenError) {
+ return writeProjectError(res, error);
+ }
logger.error("Failed to delete project", error);
return res.status(500).json({ message: "Internal server error" });
}
diff --git a/web/src/features/ai-gateway/fns/gatewayIngestionModePolicy.ts b/web/src/features/ai-gateway/fns/gatewayIngestionModePolicy.ts
index 7eca928cba..b1c0553719 100644
--- a/web/src/features/ai-gateway/fns/gatewayIngestionModePolicy.ts
+++ b/web/src/features/ai-gateway/fns/gatewayIngestionModePolicy.ts
@@ -29,9 +29,3 @@ export function getCapturingGatewayIngestionModes() {
(mode) => getEffectiveGatewayIngestionMode(mode) !== "NONE",
);
}
-
-export function getGatewayIngestionProjectDeletionMessage() {
- return isGatewayIngestionModeAvailable("NONE")
- ? "This project is used as the AI Gateway ingestion project. Select another ingestion project or set the ingestion mode to None before deleting it."
- : "This project is used as the AI Gateway ingestion project. Select another ingestion project before deleting it.";
-}
diff --git a/web/src/features/ai-gateway/server/config/gatewayConfigRepository.ts b/web/src/features/ai-gateway/server/config/gatewayConfigRepository.ts
index 8cae1e656f..00cd8edffc 100644
--- a/web/src/features/ai-gateway/server/config/gatewayConfigRepository.ts
+++ b/web/src/features/ai-gateway/server/config/gatewayConfigRepository.ts
@@ -1,7 +1,22 @@
-import type { PrismaClient } from "@langfuse/shared/src/db";
+import type { Prisma, PrismaClient } from "@langfuse/shared/src/db";
+import { getCapturingGatewayIngestionModes } from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
+
+function writingToProject(params: {
+ organizationId: string;
+ projectId: string;
+}) {
+ return {
+ organizationId: params.organizationId,
+ defaultIngestionProjectId: params.projectId,
+ // With ingestion NONE the project is only remembered, not written to.
+ ingestionMode: { in: getCapturingGatewayIngestionModes() },
+ };
+}
export class GatewayConfigRepository {
- constructor(private readonly prisma: PrismaClient) {}
+ constructor(
+ private readonly prisma: PrismaClient | Prisma.TransactionClient,
+ ) {}
getConfig(organizationId: string) {
return this.prisma.gatewayConfig.findUnique({
@@ -27,4 +42,25 @@ export class GatewayConfigRepository {
select: { id: true },
});
}
+
+ getConfigWritingToProject(params: {
+ organizationId: string;
+ projectId: string;
+ }) {
+ return this.prisma.gatewayConfig.findFirst({
+ where: writingToProject(params),
+ });
+ }
+
+ /** Conditional so a concurrently selected replacement project is not cleared. */
+ async clearIngestionProject(params: {
+ organizationId: string;
+ projectId: string;
+ }) {
+ const { count } = await this.prisma.gatewayConfig.updateMany({
+ where: writingToProject(params),
+ data: { defaultIngestionProjectId: null },
+ });
+ return count > 0;
+ }
}
diff --git a/web/src/features/ai-gateway/server/config/gatewayConfigService.ts b/web/src/features/ai-gateway/server/config/gatewayConfigService.ts
index 2fb60dd865..137f85846d 100644
--- a/web/src/features/ai-gateway/server/config/gatewayConfigService.ts
+++ b/web/src/features/ai-gateway/server/config/gatewayConfigService.ts
@@ -1,9 +1,10 @@
import { InvalidRequestError } from "@langfuse/shared";
import type {
GatewayIngestionMode,
+ Prisma,
PrismaClient,
} from "@langfuse/shared/src/db";
-import { auditLog } from "@/src/features/audit-logs/server";
+import { auditLog, type AuditLogActor } from "@/src/features/audit-logs/server";
import type { OrgAuthedContext } from "@/src/server/api/trpc";
import { invalidateGatewayResolveCacheForOrganization } from "@/src/features/ai-gateway/server/resolve/gatewayResolveCache";
import { isGatewayIngestionConfigured } from "@/src/features/ai-gateway/fns/isGatewayIngestionConfigured";
@@ -13,13 +14,67 @@ import {
} from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
import { GatewayConfigRepository } from "./gatewayConfigRepository";
+/** The gateway config is org-level; the org audit log only lists entries without a project. */
+function withoutProjectContext(actor: AuditLogActor): AuditLogActor {
+ if ("session" in actor) {
+ return {
+ session: {
+ ...actor.session,
+ projectId: undefined,
+ projectRole: undefined,
+ },
+ };
+ }
+ return { ...actor, projectId: undefined };
+}
+
export class GatewayConfigService {
private readonly repository: GatewayConfigRepository;
- constructor(private readonly prisma: PrismaClient) {
+ constructor(
+ private readonly prisma: PrismaClient | Prisma.TransactionClient,
+ ) {
this.repository = new GatewayConfigRepository(prisma);
}
+ /** isIngestionProject reports whether the gateway writes its traces into the project. */
+ async isIngestionProject(params: {
+ organizationId: string;
+ projectId: string;
+ }) {
+ return (await this.repository.getConfigWritingToProject(params)) !== null;
+ }
+
+ /**
+ * clearIngestionProject unlinks a project from the gateway, which turns the
+ * gateway off until another ingestion project is selected. It returns
+ * whether it cleared the link. Run it inside the deleting transaction, then
+ * invalidate the gateway resolve cache once that transaction commits.
+ */
+ async clearIngestionProject(params: {
+ organizationId: string;
+ projectId: string;
+ actor: AuditLogActor;
+ }): Promise<boolean> {
+ const before = await this.repository.getConfigWritingToProject(params);
+ if (!before) return false;
+ if (!(await this.repository.clearIngestionProject(params))) return false;
+
+ const after = await this.repository.getConfig(params.organizationId);
+ await auditLog(
+ {
+ ...withoutProjectContext(params.actor),
+ resourceType: "gatewayConfig",
+ resourceId: params.organizationId,
+ action: "update",
+ before,
+ after,
+ },
+ this.prisma,
+ );
+ return true;
+ }
+
async getConfig(organizationId: string) {
const config = await this.repository.getConfig(organizationId);
return (
diff --git a/web/src/features/ai-gateway/server/index.ts b/web/src/features/ai-gateway/server/index.ts
index f26431ac5b..cee897d29f 100644
--- a/web/src/features/ai-gateway/server/index.ts
+++ b/web/src/features/ai-gateway/server/index.ts
@@ -3,7 +3,11 @@ export {
withGatewayModelsSignatureVerification,
withGatewayResolveSignatureVerification,
} from "./auth";
+export { GatewayConfigService } from "./config/gatewayConfigService";
export { gatewayModelsApiHandler } from "./provider/models/gatewayModelsApiHandler";
export { gatewayResolveApiHandler } from "./resolve/gatewayResolveApiHandler";
-export { invalidateGatewayResolveCacheForApiKey } from "./resolve/gatewayResolveCache";
+export {
+ invalidateGatewayResolveCacheForApiKey,
+ invalidateGatewayResolveCacheForOrganization,
+} from "./resolve/gatewayResolveCache";
export { aiGatewayRouter } from "./router";
diff --git a/web/src/features/projects/components/DeleteProjectDialogController/DeleteProjectDialogController.tsx b/web/src/features/projects/components/DeleteProjectDialogController/DeleteProjectDialogController.tsx
index ea24240c38..0a885efce0 100644
--- a/web/src/features/projects/components/DeleteProjectDialogController/DeleteProjectDialogController.tsx
+++ b/web/src/features/projects/components/DeleteProjectDialogController/DeleteProjectDialogController.tsx
@@ -1,14 +1,14 @@
-import { getGatewayIngestionProjectDeletionMessage } from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
-import { ExternalLink } from "@langfuse/icons";
import { type ReactNode } from "react";
-import { useRouter } from "next/router";
import { Dialog } from "@/src/components/design-system/Dialog/Dialog";
import { DialogController } from "@/src/components/design-system/DialogController/DialogController";
import { env } from "@/src/env.mjs";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { useQueryProject } from "@/src/features/projects/hooks";
-import { useHasProjectAccess } from "@/src/features/rbac";
+import {
+ useHasOrganizationAccess,
+ useHasProjectAccess,
+} from "@/src/features/rbac";
import { api, reportNonTrpcError } from "@/src/utils/api";
import { DeleteProjectDialog } from "@/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog";
@@ -22,7 +22,6 @@ type DeleteProjectDialogControllerProps = {
export function DeleteProjectDialogController({
children,
}: DeleteProjectDialogControllerProps) {
- const router = useRouter();
const capture = usePostHogClientCapture();
const { project, organization } = useQueryProject();
const confirmMessage = `${organization?.name}/${project?.name}`
@@ -32,6 +31,10 @@ export function DeleteProjectDialogController({
projectId: project?.id,
scope: "project:delete",
});
+ const canManageGateway = useHasOrganizationAccess({
+ organizationId: organization?.id,
+ scope: "gateway:manage",
+ });
const deletionProtection = api.projects.deletionProtection.useQuery(
{ projectId: project?.id ?? "" },
{ enabled: Boolean(project?.id) && hasAccess },
@@ -55,24 +58,13 @@ export function DeleteProjectDialogController({
return (
<DialogController
renderDialog={() => {
- if (
- deletionProtection.data?.isGatewayIngestionProject &&
- organization
- ) {
+ const isGatewayIngestionProject =
+ deletionProtection.data?.isGatewayIngestionProject === true;
+ if (isGatewayIngestionProject && !canManageGateway) {
return (
<Dialog
title="Project cannot be deleted"
- text={getGatewayIngestionProjectDeletionMessage()}
- actions={[
- {
- label: "Open AI Gateway settings",
- icon: ExternalLink,
- onClick: () =>
- router.push(
- `/organization/${organization.id}/settings/ai-gateway`,
- ),
- },
- ]}
+ text="This project receives the organization's AI Gateway traces. Only members who can manage the AI Gateway can delete it."
/>
);
}
@@ -82,6 +74,9 @@ export function DeleteProjectDialogController({
confirmMessage={confirmMessage}
isPending={deleteProject.isPending}
onSubmit={handleDelete}
+ gatewayOrganizationName={
+ isGatewayIngestionProject ? organization?.name : undefined
+ }
/>
);
}}
diff --git a/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.stories.tsx b/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.stories.tsx
index 0df21d664a..867ae2e23f 100644
--- a/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.stories.tsx
+++ b/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.stories.tsx
@@ -31,6 +31,16 @@ export const Default = meta.story({
render: renderDialog,
});
+export const GatewayIngestionProject = meta.story({
+ args: {
+ confirmMessage: "acme/gateway-traces",
+ isPending: false,
+ onSubmit: fn(),
+ gatewayOrganizationName: "Acme",
+ },
+ render: renderDialog,
+});
+
export const ConfirmsDeletion = meta.story({
name: "(Test) Confirms deletion",
args: {
diff --git a/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.tsx b/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.tsx
index 16e8caff5a..4f0cc4c437 100644
--- a/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.tsx
+++ b/web/src/features/projects/components/DeleteProjectDialogController/components/DeleteProjectDialog/DeleteProjectDialog.tsx
@@ -1,8 +1,10 @@
import { zodResolver } from "@hookform/resolvers/zod";
+import { AlertTriangle } from "@langfuse/icons";
import { useId } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
+import { Alert } from "@/src/components/design-system/Alert/Alert";
import { Dialog } from "@/src/components/design-system/Dialog/Dialog";
import {
Form,
@@ -21,6 +23,8 @@ export type DeleteProjectDialogProps = {
confirmMessage: string;
isPending: boolean;
onSubmit: () => void;
+ /** Set when the project receives this organization's AI Gateway traces. */
+ gatewayOrganizationName?: string;
};
export function DeleteProjectDialog(props: DeleteProjectDialogProps) {
@@ -54,6 +58,14 @@ export function DeleteProjectDialog(props: DeleteProjectDialogProps) {
<Form {...form}>
<form id={formId} onSubmit={form.handleSubmit(props.onSubmit)}>
<Dialog.Body>
+ {props.gatewayOrganizationName ? (
+ <Alert variant="warning" icon={AlertTriangle}>
+ <Alert.Title>This turns off the AI Gateway</Alert.Title>
+ <Alert.Description>
+ {`This project receives the AI Gateway traces of ${props.gatewayOrganizationName}. Deleting it turns off the AI Gateway for the organization until you select a new ingestion project.`}
+ </Alert.Description>
+ </Alert>
+ ) : null}
<p>
Deletion takes time and scales with project size. For very large
projects, it can take multiple days. If deletion is slower than
diff --git a/web/src/features/projects/server/index.ts b/web/src/features/projects/server/index.ts
index ada68cf8e6..11e9281b06 100644
--- a/web/src/features/projects/server/index.ts
+++ b/web/src/features/projects/server/index.ts
@@ -1 +1,2 @@
export { projectsRouter } from "@/src/features/projects/server/projectsRouter";
+export { ProjectService } from "@/src/features/projects/server/projectService";
diff --git a/web/src/features/projects/server/projectService.ts b/web/src/features/projects/server/projectService.ts
new file mode 100644
index 0000000000..77f99309d8
--- /dev/null
+++ b/web/src/features/projects/server/projectService.ts
@@ -0,0 +1,98 @@
+import { randomUUID } from "crypto";
+import { ForbiddenError, InternalServerError } from "@langfuse/shared";
+import type { PrismaClient } from "@langfuse/shared/src/db";
+import { ProjectDeleteQueue, QueueJobs } from "@langfuse/shared/src/server";
+import {
+ GatewayConfigService,
+ invalidateGatewayResolveCacheForOrganization,
+} from "@/src/features/ai-gateway/server";
+import { auditLog, type AuditLogActor } from "@/src/features/audit-logs/server";
+import type { ApiAuthService } from "@/src/features/public-api/server";
+import { emitChbProjectEvent } from "@/src/ee/features/billing/server";
+
+type DeleteProjectParams = {
+ organizationId: string;
+ projectId: string;
+ actor: AuditLogActor;
+ /** Whether the actor holds `gateway:manage`, required to delete the gateway's ingestion project. */
+ canManageGateway: boolean;
+};
+
+export class ProjectService {
+ constructor(
+ private readonly prisma: PrismaClient,
+ private readonly apiAuthService: ApiAuthService,
+ ) {}
+
+ /**
+ * delete soft-deletes a project and queues its hard delete. If the project
+ * is the AI Gateway's ingestion project, it also turns the gateway off.
+ * Callers must check `project:delete`.
+ */
+ async delete(params: DeleteProjectParams) {
+ // API keys need to be deleted from cache. Otherwise, they will still be valid.
+ await this.apiAuthService.invalidateCachedProjectApiKeys(params.projectId);
+ const project = await this.softDeleteAndUnlinkGateway(params);
+ await auditLog({
+ ...params.actor,
+ resourceType: "project",
+ resourceId: params.projectId,
+ before: project,
+ action: "delete",
+ });
+ // Refresh org-scoped keys' baked projectIds now that a project is gone.
+ await this.apiAuthService.invalidateCachedOrgApiKeys(params.organizationId);
+ // Soft-delete is the billing-relevant moment: the customer stops being
+ // billable now, not when the async hard-delete worker finishes.
+ emitChbProjectEvent({
+ type: "LANGFUSE_PROJECT_DELETED",
+ orgId: params.organizationId,
+ projectId: params.projectId,
+ });
+ await this.queueHardDelete(params);
+ }
+
+ private async softDeleteAndUnlinkGateway(params: DeleteProjectParams) {
+ const { project, clearedGateway } = await this.prisma.$transaction(
+ async (tx) => {
+ const clearedGateway = await new GatewayConfigService(
+ tx,
+ ).clearIngestionProject(params);
+ // Decided on the cleared row, so a project selected as the ingestion
+ // project while this delete runs still requires the permission.
+ if (clearedGateway && !params.canManageGateway) {
+ throw new ForbiddenError(
+ "Deleting the AI Gateway ingestion project requires the gateway:manage permission.",
+ );
+ }
+ await tx.apiKey.deleteMany({
+ where: { projectId: params.projectId, scope: "PROJECT" },
+ });
+ const project = await tx.project.update({
+ where: { id: params.projectId, orgId: params.organizationId },
+ data: { deletedAt: new Date() },
+ });
+ return { project, clearedGateway };
+ },
+ );
+ if (clearedGateway) {
+ await invalidateGatewayResolveCacheForOrganization(params.organizationId);
+ }
+ return project;
+ }
+
+ private async queueHardDelete(params: DeleteProjectParams) {
+ const projectDeleteQueue = ProjectDeleteQueue.getInstance();
+ if (!projectDeleteQueue) {
+ throw new InternalServerError(
+ "ProjectDeleteQueue is not available. Please try again later.",
+ );
+ }
+ await projectDeleteQueue.add(QueueJobs.ProjectDelete, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ payload: { projectId: params.projectId, orgId: params.organizationId },
+ name: QueueJobs.ProjectDelete,
+ });
+ }
+}
diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.ts
index c2126e7816..024f9a1c80 100644
--- a/web/src/features/projects/server/projectsRouter.ts
+++ b/web/src/features/projects/server/projectsRouter.ts
@@ -1,7 +1,5 @@
-import {
- getCapturingGatewayIngestionModes,
- getGatewayIngestionProjectDeletionMessage,
-} from "@/src/features/ai-gateway/fns/gatewayIngestionModePolicy";
+import { GatewayConfigService } from "@/src/features/ai-gateway/server";
+import { ProjectService } from "@/src/features/projects/server/projectService";
import {
createTRPCRouter,
protectedOrganizationProcedure,
@@ -9,6 +7,7 @@ import {
} from "@/src/server/api/trpc";
import * as z from "zod";
import {
+ hasOrganizationAccess,
throwIfNoOrganizationAccess,
throwIfNoProjectAccess,
} from "@/src/features/rbac";
@@ -18,18 +17,14 @@ import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
import { auditLog } from "@/src/features/audit-logs/server";
import { ApiAuthService } from "@/src/features/public-api/server";
import {
- QueueJobs,
redis,
- ProjectDeleteQueue,
DefaultEvalModelService,
getEnvironmentsForProject,
invalidateCachedOrgApiKeys,
} from "@langfuse/shared/src/server";
import { transferRoleAssignments } from "@langfuse/shared/rbac/server";
import { reconcileTopicsConnectionsForProject } from "@langfuse/shared/topics/server";
-import { randomUUID } from "crypto";
-import { LangfuseConflictError, StringNoHTMLNonEmpty } from "@langfuse/shared";
-import type { PrismaClient } from "@langfuse/shared/src/db";
+import { StringNoHTMLNonEmpty } from "@langfuse/shared";
import { buildAdminOrgContext } from "@/src/features/organizations/server";
import { emitChbProjectEvent } from "@/src/ee/features/billing/server";
@@ -196,8 +191,9 @@ export const projectsRouter = createTRPCRouter({
scope: "project:delete",
});
return {
- isGatewayIngestionProject: await isGatewayIngestionProject({
- prisma: ctx.prisma,
+ isGatewayIngestionProject: await new GatewayConfigService(
+ ctx.prisma,
+ ).isIngestionProject({
organizationId: ctx.session.orgId,
projectId: input.projectId,
}),
@@ -216,72 +212,18 @@ export const projectsRouter = createTRPCRouter({
projectId: ctx.session.projectId,
scope: "project:delete",
});
- await throwIfGatewayIngestionProject({
- prisma: ctx.prisma,
- organizationId: ctx.session.orgId,
- projectId: input.projectId,
- });
-
- // API keys need to be deleted from cache. Otherwise, they will still be valid.
- await new ApiAuthService(
+ await new ProjectService(
ctx.prisma,
- redis,
- ).invalidateCachedProjectApiKeys(input.projectId);
-
- // Delete API keys from DB
- await ctx.prisma.apiKey.deleteMany({
- where: {
- projectId: input.projectId,
- scope: "PROJECT",
- },
- });
-
- const project = await ctx.prisma.project.update({
- where: {
- id: input.projectId,
- orgId: ctx.session.orgId,
- },
- data: {
- deletedAt: new Date(),
- },
- });
-
- await auditLog({
- session: ctx.session,
- resourceType: "project",
- resourceId: input.projectId,
- before: project,
- action: "delete",
- });
-
- // Refresh org-scoped keys' baked projectIds now that a project is gone.
- await invalidateCachedOrgApiKeys(ctx.session.orgId);
-
- // Soft-delete is the billing-relevant moment: the customer stops being
- // billable now, not when the async hard-delete worker finishes.
- emitChbProjectEvent({
- type: "LANGFUSE_PROJECT_DELETED",
- orgId: ctx.session.orgId,
+ new ApiAuthService(ctx.prisma, redis),
+ ).delete({
+ organizationId: ctx.session.orgId,
projectId: input.projectId,
- });
-
- const projectDeleteQueue = ProjectDeleteQueue.getInstance();
- if (!projectDeleteQueue) {
- throw new TRPCError({
- code: "INTERNAL_SERVER_ERROR",
- message:
- "ProjectDeleteQueue is not available. Please try again later.",
- });
- }
-
- await projectDeleteQueue.add(QueueJobs.ProjectDelete, {
- timestamp: new Date(),
- id: randomUUID(),
- payload: {
- projectId: input.projectId,
- orgId: ctx.session.orgId,
- },
- name: QueueJobs.ProjectDelete,
+ actor: { session: ctx.session },
+ canManageGateway: hasOrganizationAccess({
+ session: ctx.session,
+ organizationId: ctx.session.orgId,
+ scope: "gateway:manage",
+ }),
});
return true;
@@ -409,32 +351,3 @@ export const projectsRouter = createTRPCRouter({
return { project, organization };
}),
});
-
-async function isGatewayIngestionProject(params: {
- prisma: PrismaClient;
- organizationId: string;
- projectId: string;
-}) {
- const config = await params.prisma.gatewayConfig.findFirst({
- where: {
- organizationId: params.organizationId,
- defaultIngestionProjectId: params.projectId,
- // With ingestion NONE the project is only remembered, not written to.
- ingestionMode: { in: getCapturingGatewayIngestionModes() },
- },
- select: { organizationId: true },
- });
- return config !== null;
-}
-
-async function throwIfGatewayIngestionProject(params: {
- prisma: PrismaClient;
- organizationId: string;
- projectId: string;
-}) {
- if (await isGatewayIngestionProject(params)) {
- throw new LangfuseConflictError(
- getGatewayIngestionProjectDeletionMessage(),
- );
- }
-}
diff --git a/web/src/pages/api/public/projects/[projectId]/index.ts b/web/src/pages/api/public/projects/[projectId]/index.ts
index 81f00f93b4..2e22b1b3da 100644
--- a/web/src/pages/api/public/projects/[projectId]/index.ts
+++ b/web/src/pages/api/public/projects/[projectId]/index.ts
@@ -74,6 +74,12 @@ export default async function handler(
}
if (req.method === "DELETE") {
- return handleDeleteProject(req, res, projectId, authCheck.scope);
+ return handleDeleteProject(
+ req,
+ res,
+ projectId,
+ authCheck.scope,
+ authCheck.ctx,
+ );
}
}