Skip to content

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

feat: expose project retention via the projects API (#6456)

Steffen Schmitz7ad6749058ae
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.yml
index eb583f9c18..9489e55f3e 100644
--- a/fern/apis/server/definition/projects.yml
+++ b/fern/apis/server/definition/projects.yml
@@ -21,6 +21,25 @@ service:
body:
properties:
name: string
+ retention:
+ type: integer
+ docs: Number of days to retain data. Must be 0 or at least 7 days. Requires data-retention entitlement for non-zero values. Optional.
+ response: Project
+
+ update:
+ docs: Update a project by ID (requires organization-scoped API key).
+ method: PUT
+ path: /projects/{projectId}
+ path-parameters:
+ projectId: string
+ request:
+ name: UpdateProjectRequest
+ body:
+ properties:
+ name: string
+ retention:
+ type: integer
+ docs: Number of days to retain data. Must be 0 or at least 7 days. Requires data-retention entitlement for non-zero values. Optional.
response: Project
delete:
@@ -75,7 +94,10 @@ types:
properties:
id: string
name: string
-
+ retentionDays:
+ type: integer
+ docs: Number of days to retain data. Null or 0 means no retention. Omitted if no retention is configured.
+
ProjectDeletionResponse:
properties:
success: boolean
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 8d74105934..b660e7da42 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2256,9 +2256,79 @@ paths:
properties:
name:
type: string
+ retention:
+ type: integer
+ description: >-
+ Number of days to retain data. Must be 0 or at least 7 days.
+ Requires data-retention entitlement for non-zero values.
+ Optional.
required:
- name
+ - retention
/api/public/projects/{projectId}:
+ put:
+ description: Update a project by ID (requires organization-scoped API key).
+ operationId: projects_update
+ tags:
+ - Projects
+ parameters:
+ - name: projectId
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Project'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ name:
+ type: string
+ retention:
+ type: integer
+ description: >-
+ Number of days to retain data. Must be 0 or at least 7 days.
+ Requires data-retention entitlement for non-zero values.
+ Optional.
+ required:
+ - name
+ - retention
delete:
description: >-
Delete a project by ID (requires organization-scoped API key). Project
@@ -6212,9 +6282,15 @@ components:
type: string
name:
type: string
+ retentionDays:
+ type: integer
+ description: >-
+ Number of days to retain data. Null or 0 means no retention. Omitted
+ if no retention is configured.
required:
- id
- name
+ - retentionDays
ProjectDeletionResponse:
title: ProjectDeletionResponse
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 8ed64b4e90..0eb74cd4e2 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1723,7 +1723,47 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"name\": \"example\"\n}",
+ "raw": "{\n \"name\": \"example\",\n \"retention\": 0\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Update",
+ "request": {
+ "description": "Update a project by ID (requires organization-scoped API key).",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/projects/:projectId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "projects",
+ ":projectId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "projectId",
+ "value": "",
+ "description": null
+ }
+ ]
+ },
+ "header": [],
+ "method": "PUT",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"name\": \"example\",\n \"retention\": 0\n}",
"options": {
"raw": {
"language": "json"
diff --git a/web/src/__tests__/async/projects-api.servertest.ts b/web/src/__tests__/async/projects-api.servertest.ts
index 00699721d4..d4f7c27e8e 100644
--- a/web/src/__tests__/async/projects-api.servertest.ts
+++ b/web/src/__tests__/async/projects-api.servertest.ts
@@ -18,6 +18,7 @@ const ProjectResponseSchema = z.object({
z.object({
id: z.string(),
name: z.string(),
+ retentionDays: z.number().nullable().optional(),
}),
),
});
@@ -26,6 +27,14 @@ const ProjectResponseSchema = z.object({
const ProjectCreationResponseSchema = z.object({
id: z.string(),
name: z.string(),
+ retentionDays: z.number().nullable().optional(),
+});
+
+// Schema for project update response
+const ProjectUpdateResponseSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ retentionDays: z.number().nullable().optional(),
});
// Schema for project deletion response
@@ -191,6 +200,51 @@ describe("Projects API", () => {
expect(project?.name).toBe(uniqueProjectName);
});
+ it("should create a new project with retention days", async () => {
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ const response = await makeZodVerifiedAPICall(
+ ProjectCreationResponseSchema,
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ retention: 0, // Setting retention to 0 (no retention)
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 201, // Expected status code is 201 Created
+ );
+
+ expect(response.status).toBe(201);
+ expect(response.body).toMatchObject({
+ name: uniqueProjectName,
+ });
+
+ // Verify the project was created with the correct retention days
+ const project = await prisma.project.findUnique({
+ where: { id: response.body.id },
+ });
+ expect(project).not.toBeNull();
+ expect(project?.retentionDays).toBe(0);
+ });
+
+ it("should validate retention days", async () => {
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ // Test with invalid retention days (less than 7 and not 0)
+ const invalidResult = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ retention: 5, // Invalid: less than 7 and not 0
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(invalidResult.status).toBe(400);
+ expect(invalidResult.body.message).toContain("Invalid retention value");
+ });
+
it("should return 403 when using project API key instead of organization API key", async () => {
const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
@@ -276,6 +330,119 @@ describe("Projects API", () => {
});
});
+ describe("PUT /api/public/projects/[projectId]", () => {
+ let testProjectId: string;
+
+ beforeEach(async () => {
+ // Create a test project to update
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+ const project = await prisma.project.create({
+ data: {
+ name: uniqueProjectName,
+ orgId: "seed-org-id", // Same org ID used for the API key
+ },
+ });
+ testProjectId = project.id;
+ });
+
+ afterEach(async () => {
+ // Clean up test projects
+ await prisma.project.deleteMany({
+ where: {
+ id: testProjectId,
+ },
+ });
+ });
+
+ it("should update project retention days with valid organization API key", async () => {
+ const response = await makeZodVerifiedAPICall(
+ ProjectUpdateResponseSchema,
+ "PUT",
+ `/api/public/projects/${testProjectId}`,
+ {
+ name: "Updated Project Name",
+ retention: 7, // Valid retention value
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 200, // Expected status code is 200 OK
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.name).toBe("Updated Project Name");
+ expect(response.body.retentionDays).toBe(7);
+
+ // Verify the project was updated in the database
+ const project = await prisma.project.findUnique({
+ where: { id: testProjectId },
+ });
+ expect(project).not.toBeNull();
+ expect(project?.name).toBe("Updated Project Name");
+ expect(project?.retentionDays).toBe(7);
+ });
+
+ it("should validate retention days on update", async () => {
+ // Test with invalid retention days (less than 7 and not 0)
+ const invalidResult = await makeAPICall(
+ "PUT",
+ `/api/public/projects/${testProjectId}`,
+ {
+ name: "Updated Project Name",
+ retention: 5, // Invalid: less than 7 and not 0
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(invalidResult.status).toBe(400);
+ expect(invalidResult.body.message).toContain("Invalid retention value");
+ });
+
+ it("should allow setting retention to 0", async () => {
+ const response = await makeZodVerifiedAPICall(
+ ProjectUpdateResponseSchema,
+ "PUT",
+ `/api/public/projects/${testProjectId}`,
+ {
+ name: "Updated Project Name",
+ retention: 0, // Valid: 0 means no retention
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 200, // Expected status code is 200 OK
+ );
+
+ expect(response.status).toBe(200);
+ // Retentions with value 0 are not returned.
+ expect(response.body.retentionDays).toBeUndefined();
+ });
+
+ it("should return 403 when using project API key instead of organization API key", async () => {
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/projects/${testProjectId}`,
+ {
+ retention: 7,
+ },
+ createBasicAuthHeader(projectApiKey, projectSecretKey),
+ );
+ expect(result.status).toBe(403);
+ expect(result.body.message).toContain(
+ "Organization-scoped API key required",
+ );
+ });
+
+ it("should return 404 when project does not exist", async () => {
+ const nonExistentProjectId = randomUUID();
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/projects/${nonExistentProjectId}`,
+ {
+ retention: 7,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(result.status).toBe(404);
+ expect(result.body.message).toContain("Project not found");
+ });
+ });
+
describe("DELETE /api/public/projects/[projectId]", () => {
let testProjectId: string;
@@ -357,17 +524,6 @@ describe("Projects API", () => {
expect(result.status).toBe(404);
expect(result.body.message).toContain("Project not found");
});
-
- it("should return 405 for non-DELETE methods", async () => {
- const result = await makeAPICall(
- "GET",
- `/api/public/projects/${testProjectId}`,
- undefined,
- createBasicAuthHeader(orgApiKey, orgSecretKey),
- );
- expect(result.status).toBe(405);
- expect(result.body.message).toContain("Method not allowed");
- });
});
describe("GET /api/public/projects/[projectId]/apiKeys", () => {
@@ -626,16 +782,16 @@ describe("Projects API", () => {
expect(result.status).toBe(404);
expect(result.body.message).toContain("Project not found");
});
+ });
- it("should return 405 for non-DELETE methods", async () => {
- const result = await makeAPICall(
- "GET",
- `/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,
- undefined,
- createBasicAuthHeader(orgApiKey, orgSecretKey),
- );
- expect(result.status).toBe(405);
- expect(result.body.message).toContain("Method Not Allowed");
- });
+ it("should return 405 for unallowed methods", async () => {
+ const result = await makeAPICall(
+ "PATCH",
+ `/api/public/projects/${projectId}`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(result.status).toBe(405);
+ expect(result.body.message).toContain("Method not allowed");
});
});
diff --git a/web/src/pages/api/public/projects/[projectId]/index.ts b/web/src/pages/api/public/projects/[projectId]/index.ts
index 3510e5a0f8..b502df74ee 100644
--- a/web/src/pages/api/public/projects/[projectId]/index.ts
+++ b/web/src/pages/api/public/projects/[projectId]/index.ts
@@ -6,10 +6,13 @@ import {
redis,
QueueJobs,
ProjectDeleteQueue,
+ type ApiAccessScope,
} from "@langfuse/shared/src/server";
import { randomUUID } from "crypto";
-
+import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";
+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { type NextApiRequest, type NextApiResponse } from "next";
+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
export default async function handler(
req: NextApiRequest,
@@ -23,7 +26,7 @@ export default async function handler(
return res.status(400).json({ message: "Invalid project ID" });
}
- if (req.method !== "DELETE") {
+ if (req.method !== "DELETE" && req.method !== "PUT") {
logger.error(
`Method not allowed for ${req.method} on /api/public/projects/${projectId}`,
);
@@ -53,21 +56,109 @@ export default async function handler(
}
// END CHECK AUTH
+ // Check if project exists and belongs to the organization
+ const project = await prisma.project.findFirst({
+ where: {
+ id: projectId,
+ orgId: authCheck.scope.orgId,
+ },
+ });
+
+ if (!project) {
+ return res.status(404).json({
+ message: "Project not found or you don't have access to it",
+ });
+ }
+
+ // Route to the appropriate handler based on HTTP method
+ if (req.method === "PUT") {
+ return handlePut(req, res, projectId, authCheck.scope);
+ }
+
+ if (req.method === "DELETE") {
+ return handleDelete(req, res, projectId, authCheck.scope);
+ }
+}
+
+async function handlePut(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ projectId: string,
+ scope: ApiAccessScope,
+) {
try {
- // Check if project exists and belongs to the organization
- const project = await prisma.project.findFirst({
+ const { name, retention } = req.body;
+
+ // Validate project name
+ try {
+ projectNameSchema.parse({ name });
+ } catch (error) {
+ return res.status(400).json({
+ message: "Invalid project name. Should be between 3 and 60 characters.",
+ });
+ }
+
+ // Validate retention days using the schema
+ try {
+ projectRetentionSchema.parse({ retention });
+ } catch (error) {
+ return res.status(400).json({
+ message: "Invalid retention value. Must be 0 or at least 7 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.",
+ });
+ }
+ }
+
+ // Update the project with the new retention setting
+ const updatedProject = await prisma.project.update({
where: {
id: projectId,
- orgId: authCheck.scope.orgId,
+ orgId: scope.orgId,
+ },
+ data: {
+ name,
+ retentionDays: retention,
+ },
+ select: {
+ id: true,
+ name: true,
+ retentionDays: true,
},
});
- if (!project) {
- return res.status(404).json({
- message: "Project not found or you don't have access to it",
- });
- }
+ return res.status(200).json({
+ id: updatedProject.id,
+ name: updatedProject.name,
+ ...(updatedProject.retentionDays // Do not add if null or 0
+ ? { retentionDays: updatedProject.retentionDays }
+ : {}),
+ });
+ } catch (error) {
+ logger.error("Failed to update project", error);
+ return res.status(500).json({ message: "Internal server error" });
+ }
+}
+async function handleDelete(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ projectId: string,
+ scope: ApiAccessScope,
+) {
+ try {
// API keys need to be deleted from cache. Otherwise, they will still be valid.
await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(projectId);
@@ -83,7 +174,7 @@ export default async function handler(
await prisma.project.update({
where: {
id: projectId,
- orgId: authCheck.scope.orgId,
+ orgId: scope.orgId,
},
data: {
deletedAt: new Date(),
@@ -104,7 +195,7 @@ export default async function handler(
id: randomUUID(),
payload: {
projectId: projectId,
- orgId: authCheck.scope.orgId,
+ orgId: scope.orgId,
},
name: QueueJobs.ProjectDelete,
});
diff --git a/web/src/pages/api/public/projects/index.ts b/web/src/pages/api/public/projects/index.ts
index bd54616198..b60cac0b98 100644
--- a/web/src/pages/api/public/projects/index.ts
+++ b/web/src/pages/api/public/projects/index.ts
@@ -5,6 +5,8 @@ import { logger, redis } from "@langfuse/shared/src/server";
import { type NextApiRequest, type NextApiResponse } from "next";
import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
+import { projectRetentionSchema } from "@/src/features/auth/lib/projectRetentionSchema";
+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
export default async function handler(
req: NextApiRequest,
@@ -48,6 +50,7 @@ export default async function handler(
select: {
id: true,
name: true,
+ retentionDays: true,
},
where: {
id: authCheck.scope.projectId,
@@ -59,6 +62,9 @@ export default async function handler(
data: projects.map((project) => ({
id: project.id,
name: project.name,
+ ...(project.retentionDays // Do not add if null or 0
+ ? { retentionDays: project.retentionDays }
+ : {}),
})),
});
} catch (error) {
@@ -80,7 +86,7 @@ export default async function handler(
}
try {
- const { name } = req.body;
+ const { name, retention } = req.body;
// Validate project name
try {
@@ -88,10 +94,36 @@ export default async function handler(
} catch (error) {
return res.status(400).json({
message:
- "Invalid project name length. Should be between 3 and 60 characters.",
+ "Invalid project name. Should be between 3 and 60 characters.",
});
}
+ // Validate retention days if provided
+ if (retention !== undefined) {
+ try {
+ projectRetentionSchema.parse({ retention });
+ } catch (error) {
+ return res.status(400).json({
+ message: "Invalid retention value. Must be 0 or at least 7 days.",
+ });
+ }
+
+ // If retention is non-zero, check for data-retention entitlement
+ if (retention > 0) {
+ const hasDataRetentionEntitlement = hasEntitlementBasedOnPlan({
+ entitlement: "data-retention",
+ plan: authCheck.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: {
@@ -112,12 +144,16 @@ export default async function handler(
data: {
name,
orgId: authCheck.scope.orgId,
+ retentionDays: retention,
},
});
return res.status(201).json({
id: project.id,
name: project.name,
+ ...(project.retentionDays // Do not add if null or 0
+ ? { retentionDays: project.retentionDays }
+ : {}),
});
} catch (error) {
logger.error("Failed to create project", error);