Skip to content

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

3.7 KB
Raw Blame
import { type NextApiRequest, type NextApiResponse } from "next";
import { prisma } from "@langfuse/shared/src/db";
import {
  logger,
  type ApiAccessScope,
  invalidateCachedOrgApiKeys,
} from "@langfuse/shared/src/server";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { emitChbProjectEvent } from "@/src/ee/features/billing/server/chb/chbProjectEvents";

export async function handleCreateProject(
  req: NextApiRequest,
  res: NextApiResponse,
  scope: ApiAccessScope,
) {
  try {
    const { name, retention, metadata } = req.body;

    // Validate project name
    try {
      projectNameSchema.parse({ name });
    } catch {
      return res.status(400).json({
        message: "Invalid project name. Should be between 3 and 60 characters.",
      });
    }

    let parsedMetadata = metadata;
    if (metadata !== undefined && typeof metadata !== "object") {
      try {
        parsedMetadata = JSON.parse(metadata);
      } catch (error) {
        return res.status(400).json({
          message: `Invalid metadata. Should be a valid JSON object: ${error}`,
        });
      }
    }
    if (
      parsedMetadata !== undefined &&
      (typeof parsedMetadata !== "object" ||
        parsedMetadata === null ||
        Array.isArray(parsedMetadata))
    ) {
      return res.status(400).json({
        message: "Invalid metadata. Should be a valid JSON object.",
      });
    }

    // Validate retention days if provided
    if (retention !== undefined) {
      try {
        projectRetentionSchema.parse({ retention });
      } catch {
        return res.status(400).json({
          message: "Invalid retention value. Must be 0 or at least 3 days.",
        });
      }

      // If retention is non-zero, check for data-retention entitlement
      if (retention > 0) {
        const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({
          entitlement: "data-retention",
          plan: scope.plan,
        });

        if (!hasDataRetentionEntitlement) {
          return res.status(403).json({
            message:
              "The data-retention entitlement is required to set a non-zero retention period.",
          });
        }
      }
    }

    // Check if project with this name already exists in the organization
    const existingProject = await prisma.project.findFirst({
      where: {
        name,
        orgId: scope.orgId,
        deletedAt: null,
      },
    });

    if (existingProject) {
      return res.status(409).json({
        message: "A project with this name already exists in your organization",
      });
    }

    // Create the project
    const project = await prisma.project.create({
      data: {
        name,
        orgId: scope.orgId,
        retentionDays: retention,
        metadata: parsedMetadata,
      },
    });

    // Refresh org-scoped keys' baked projectIds now that a project exists.
    await invalidateCachedOrgApiKeys(scope.orgId);

    // Best-effort CHB metering signal; no-op unless the org is CHB-billed
    emitChbProjectEvent({
      type: "LANGFUSE_PROJECT_CREATED",
      orgId: scope.orgId,
      projectId: project.id,
    });

    return res.status(201).json({
      id: project.id,
      name: project.name,
      metadata: project.metadata ?? {},
      ...(project.retentionDays // Do not add if null or 0
        ? { retentionDays: project.retentionDays }
        : {}),
    });
  } catch (error) {
    logger.error("Failed to create project", error);
    return res.status(500).json({ message: "Internal server error" });
  }
}