Skip to content

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

feat: add blob storage integration (#6143)

Steffen Schmitzeecb25309350
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index be20605635..d143193144 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -80,6 +80,12 @@ export const JobExecutionStatus = {
CANCELLED: "CANCELLED"
} as const;
export type JobExecutionStatus = (typeof JobExecutionStatus)[keyof typeof JobExecutionStatus];
+export const BlobStorageIntegrationType = {
+ S3: "S3",
+ S3_COMPATIBLE: "S3_COMPATIBLE",
+ AZURE_BLOB_STORAGE: "AZURE_BLOB_STORAGE"
+} as const;
+export type BlobStorageIntegrationType = (typeof BlobStorageIntegrationType)[keyof typeof BlobStorageIntegrationType];
export type Account = {
id: string;
user_id: string;
@@ -188,6 +194,23 @@ export type BillingMeterBackup = {
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
+export type BlobStorageIntegration = {
+ project_id: string;
+ type: BlobStorageIntegrationType;
+ bucket_name: string;
+ prefix: string;
+ access_key_id: string;
+ secret_access_key: string;
+ region: string;
+ endpoint: string | null;
+ force_path_style: boolean;
+ next_sync_at: Timestamp | null;
+ last_sync_at: Timestamp | null;
+ enabled: boolean;
+ export_frequency: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
export type Comment = {
id: string;
project_id: string;
@@ -572,6 +595,7 @@ export type DB = {
background_migrations: BackgroundMigration;
batch_exports: BatchExport;
billing_meter_backups: BillingMeterBackup;
+ blob_storage_integrations: BlobStorageIntegration;
comments: Comment;
cron_jobs: CronJobs;
dataset_items: DatasetItem;
diff --git a/packages/shared/prisma/migrations/20250324110557_add_blobstorage_integration_table/migration.sql b/packages/shared/prisma/migrations/20250324110557_add_blobstorage_integration_table/migration.sql
new file mode 100644
index 0000000000..ba0285f270
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250324110557_add_blobstorage_integration_table/migration.sql
@@ -0,0 +1,26 @@
+-- CreateEnum
+CREATE TYPE "BlobStorageIntegrationType" AS ENUM ('S3', 'S3_COMPATIBLE', 'AZURE_BLOB_STORAGE');
+
+-- CreateTable
+CREATE TABLE "blob_storage_integrations" (
+ "project_id" TEXT NOT NULL,
+ "type" "BlobStorageIntegrationType" NOT NULL,
+ "bucket_name" TEXT NOT NULL,
+ "prefix" TEXT NOT NULL,
+ "access_key_id" TEXT NOT NULL,
+ "secret_access_key" TEXT NOT NULL,
+ "region" TEXT NOT NULL,
+ "endpoint" TEXT,
+ "force_path_style" BOOLEAN NOT NULL,
+ "next_sync_at" TIMESTAMP(3),
+ "last_sync_at" TIMESTAMP(3),
+ "enabled" BOOLEAN NOT NULL,
+ "export_frequency" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "blob_storage_integrations_pkey" PRIMARY KEY ("project_id")
+);
+
+-- AddForeignKey
+ALTER TABLE "blob_storage_integrations" ADD CONSTRAINT "blob_storage_integrations_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index b64b9d0d78..f18907b79e 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -109,38 +109,39 @@ model Organization {
}
model Project {
- id String @id @default(cuid())
- orgId String @map("org_id")
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- deletedAt DateTime? @map("deleted_at")
- name String
- retentionDays Int? @map("retention_days")
- projectMembers ProjectMembership[]
- organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
- apiKeys ApiKey[]
- dataset Dataset[]
- invitations MembershipInvitation[]
- sessions TraceSession[]
- Prompt Prompt[]
- Model Model[]
- EvalTemplate EvalTemplate[]
- JobConfiguration JobConfiguration[]
- JobExecution JobExecution[]
- LlmApiKeys LlmApiKeys[]
- PosthogIntegration PosthogIntegration[]
- scoreConfig ScoreConfig[]
- BatchExport BatchExport[]
- comment Comment[]
- annotationQueue AnnotationQueue[]
- annotationQueueItem AnnotationQueueItem[]
- TraceMedia TraceMedia[]
- Media Media[]
- ObservationMedia ObservationMedia[]
- LegacyTrace LegacyPrismaTrace[]
- LegacyObservation LegacyPrismaObservation[]
- LegacyScore LegacyPrismaScore[]
- PromptDependency PromptDependency[]
+ id String @id @default(cuid())
+ orgId String @map("org_id")
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ deletedAt DateTime? @map("deleted_at")
+ name String
+ retentionDays Int? @map("retention_days")
+ projectMembers ProjectMembership[]
+ organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ apiKeys ApiKey[]
+ dataset Dataset[]
+ invitations MembershipInvitation[]
+ sessions TraceSession[]
+ Prompt Prompt[]
+ Model Model[]
+ EvalTemplate EvalTemplate[]
+ JobConfiguration JobConfiguration[]
+ JobExecution JobExecution[]
+ LlmApiKeys LlmApiKeys[]
+ PosthogIntegration PosthogIntegration[]
+ BlobStorageIntegration BlobStorageIntegration[]
+ scoreConfig ScoreConfig[]
+ BatchExport BatchExport[]
+ comment Comment[]
+ annotationQueue AnnotationQueue[]
+ annotationQueueItem AnnotationQueueItem[]
+ TraceMedia TraceMedia[]
+ Media Media[]
+ ObservationMedia ObservationMedia[]
+ LegacyTrace LegacyPrismaTrace[]
+ LegacyObservation LegacyPrismaObservation[]
+ LegacyScore LegacyPrismaScore[]
+ PromptDependency PromptDependency[]
@@index([orgId])
@@map("projects")
@@ -860,7 +861,6 @@ model SsoConfig {
authConfig Json? @map("auth_config")
// e.g. { "clientId": "1234", "clientSecret": "5678" }, null if credentials from env should be used
// secrets like clientSecret are encrypted on the application level
-
@@map("sso_configs")
}
@@ -876,6 +876,40 @@ model PosthogIntegration {
@@map("posthog_integrations")
}
+model BlobStorageIntegration {
+ projectId String @id @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ // Blob Storage Config
+ type BlobStorageIntegrationType @map("type")
+ bucketName String @map("bucket_name")
+ prefix String @map("prefix")
+ accessKeyId String @map("access_key_id")
+ secretAccessKey String @map("secret_access_key")
+ region String @map("region")
+ endpoint String? @map("endpoint")
+ forcePathStyle Boolean @map("force_path_style")
+
+ // Integration Config
+ nextSyncAt DateTime? @map("next_sync_at")
+ lastSyncAt DateTime? @map("last_sync_at")
+ enabled Boolean
+ exportFrequency String @map("export_frequency")
+
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@map("blob_storage_integrations")
+}
+
+enum BlobStorageIntegrationType {
+ S3
+ S3_COMPATIBLE
+ AZURE_BLOB_STORAGE
+
+ @@map("BlobStorageIntegrationType")
+}
+
model BatchExport {
id String @id @default(cuid())
createdAt DateTime @default(now()) @map("created_at")
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index d2132509e7..5db3f13977 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -34,6 +34,8 @@ export * from "./redis/batchActionQueue";
export * from "./redis/ingestionQueue";
export * from "./redis/postHogIntegrationQueue";
export * from "./redis/postHogIntegrationProcessingQueue";
+export * from "./redis/blobStorageIntegrationQueue";
+export * from "./redis/blobStorageIntegrationProcessingQueue";
export * from "./redis/dataRetentionQueue";
export * from "./redis/dataRetentionProcessingQueue";
export * from "./redis/coreDataS3ExportQueue";
diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.ts
index 9f7b3fd95c..6454632903 100644
--- a/packages/shared/src/server/queues.ts
+++ b/packages/shared/src/server/queues.ts
@@ -56,6 +56,9 @@ export const EvalExecutionEvent = z.object({
export const PostHogIntegrationProcessingEventSchema = z.object({
projectId: z.string(),
});
+export const BlobStorageIntegrationProcessingEventSchema = z.object({
+ projectId: z.string(),
+});
export const ExperimentCreateEventSchema = z.object({
projectId: z.string(),
datasetId: z.string(),
@@ -146,6 +149,9 @@ export type DataRetentionProcessingEventType = z.infer<
export type BatchActionProcessingEventType = z.infer<
typeof BatchActionProcessingEventSchema
>;
+export type BlobStorageIntegrationProcessingEventType = z.infer<
+ typeof BlobStorageIntegrationProcessingEventSchema
+>;
export enum QueueName {
TraceUpsert = "trace-upsert", // Ingestion pipeline adds events on each Trace upsert
@@ -160,6 +166,8 @@ export enum QueueName {
ExperimentCreate = "experiment-create-queue",
PostHogIntegrationQueue = "posthog-integration-queue",
PostHogIntegrationProcessingQueue = "posthog-integration-processing-queue",
+ BlobStorageIntegrationQueue = "blobstorage-integration-queue",
+ BlobStorageIntegrationProcessingQueue = "blobstorage-integration-processing-queue",
CoreDataS3ExportQueue = "core-data-s3-export-queue",
MeteringDataPostgresExportQueue = "metering-data-postgres-export-queue",
DataRetentionQueue = "data-retention-queue",
@@ -182,6 +190,8 @@ export enum QueueJobs {
ExperimentCreateJob = "experiment-create-job",
PostHogIntegrationJob = "posthog-integration-job",
PostHogIntegrationProcessingJob = "posthog-integration-processing-job",
+ BlobStorageIntegrationJob = "blobstorage-integration-job",
+ BlobStorageIntegrationProcessingJob = "blobstorage-integration-processing-job",
CoreDataS3ExportJob = "core-data-s3-export-job",
MeteringDataPostgresExportJob = "metering-data-postgres-export-job",
DataRetentionJob = "data-retention-job",
@@ -276,4 +286,10 @@ export type TQueueJobTypes = {
payload: CreateEvalQueueEventType;
name: QueueJobs.CreateEvalJob;
};
+ [QueueName.BlobStorageIntegrationProcessingQueue]: {
+ timestamp: Date;
+ id: string;
+ payload: BlobStorageIntegrationProcessingEventType;
+ name: QueueJobs.BlobStorageIntegrationProcessingJob;
+ };
};
diff --git a/packages/shared/src/server/redis/blobStorageIntegrationProcessingQueue.ts b/packages/shared/src/server/redis/blobStorageIntegrationProcessingQueue.ts
new file mode 100644
index 0000000000..2b7a36ca2f
--- /dev/null
+++ b/packages/shared/src/server/redis/blobStorageIntegrationProcessingQueue.ts
@@ -0,0 +1,40 @@
+import { Queue } from "bullmq";
+import { QueueName } from "../queues";
+import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
+import { logger } from "../logger";
+
+export class BlobStorageIntegrationProcessingQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (BlobStorageIntegrationProcessingQueue.instance) {
+ return BlobStorageIntegrationProcessingQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ BlobStorageIntegrationProcessingQueue.instance = newRedis
+ ? new Queue(QueueName.BlobStorageIntegrationProcessingQueue, {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100_000,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ BlobStorageIntegrationProcessingQueue.instance?.on("error", (err) => {
+ logger.error("BlobStorageIntegrationProcessingQueue error", err);
+ });
+
+ return BlobStorageIntegrationProcessingQueue.instance;
+ }
+}
\ No newline at end of file
diff --git a/packages/shared/src/server/redis/blobStorageIntegrationQueue.ts b/packages/shared/src/server/redis/blobStorageIntegrationQueue.ts
new file mode 100644
index 0000000000..b46895cc42
--- /dev/null
+++ b/packages/shared/src/server/redis/blobStorageIntegrationQueue.ts
@@ -0,0 +1,55 @@
+import { Queue } from "bullmq";
+import { QueueName, QueueJobs } from "../queues";
+import { createNewRedisInstance, redisQueueRetryOptions } from "./redis";
+import { logger } from "../logger";
+
+export class BlobStorageIntegrationQueue {
+ private static instance: Queue | null = null;
+
+ public static getInstance(): Queue | null {
+ if (BlobStorageIntegrationQueue.instance) {
+ return BlobStorageIntegrationQueue.instance;
+ }
+
+ const newRedis = createNewRedisInstance({
+ enableOfflineQueue: false,
+ ...redisQueueRetryOptions,
+ });
+
+ BlobStorageIntegrationQueue.instance = newRedis
+ ? new Queue(QueueName.BlobStorageIntegrationQueue, {
+ connection: newRedis,
+ defaultJobOptions: {
+ removeOnComplete: true,
+ removeOnFail: 100,
+ attempts: 5,
+ backoff: {
+ type: "exponential",
+ delay: 5000,
+ },
+ },
+ })
+ : null;
+
+ BlobStorageIntegrationQueue.instance?.on("error", (err) => {
+ logger.error("BlobStorageIntegrationQueue error", err);
+ });
+
+ if (BlobStorageIntegrationQueue.instance) {
+ logger.debug("Scheduling jobs for BlobStorageIntegrationQueue");
+ BlobStorageIntegrationQueue.instance
+ .add(
+ QueueJobs.BlobStorageIntegrationJob,
+ {},
+ {
+ repeat: { pattern: "20 * * * *" }, // every hour at 20 minutes past
+ },
+ )
+ .catch((err) => {
+ logger.error("Error adding BlobStorageIntegrationJob schedule", err);
+ });
+ }
+
+ return BlobStorageIntegrationQueue.instance;
+ }
+}
diff --git a/packages/shared/src/server/redis/getQueue.ts b/packages/shared/src/server/redis/getQueue.ts
index 884fa7171a..582ead0aec 100644
--- a/packages/shared/src/server/redis/getQueue.ts
+++ b/packages/shared/src/server/redis/getQueue.ts
@@ -11,6 +11,8 @@ import { TraceDeleteQueue } from "./traceDelete";
import { ProjectDeleteQueue } from "./projectDelete";
import { PostHogIntegrationQueue } from "./postHogIntegrationQueue";
import { PostHogIntegrationProcessingQueue } from "./postHogIntegrationProcessingQueue";
+import { BlobStorageIntegrationQueue } from "./blobStorageIntegrationQueue";
+import { BlobStorageIntegrationProcessingQueue } from "./blobStorageIntegrationProcessingQueue";
import { CoreDataS3ExportQueue } from "./coreDataS3ExportQueue";
import { MeteringDataPostgresExportQueue } from "./meteringDataPostgresExportQueue";
import { DataRetentionQueue } from "./dataRetentionQueue";
@@ -43,6 +45,10 @@ export function getQueue(queueName: QueueName): Queue | null {
return PostHogIntegrationQueue.getInstance();
case QueueName.PostHogIntegrationProcessingQueue:
return PostHogIntegrationProcessingQueue.getInstance();
+ case QueueName.BlobStorageIntegrationQueue:
+ return BlobStorageIntegrationQueue.getInstance();
+ case QueueName.BlobStorageIntegrationProcessingQueue:
+ return BlobStorageIntegrationProcessingQueue.getInstance();
case QueueName.IngestionSecondaryQueue:
return SecondaryIngestionQueue.getInstance();
case QueueName.CoreDataS3ExportQueue:
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 4ac069dad4..61595bd487 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1324,6 +1324,59 @@ export const getTraceIdsForObservations = async (
}));
};
+export const getObservationsForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ const query = `
+ SELECT
+ id,
+ trace_id,
+ project_id,
+ environment,
+ type,
+ parent_observation_id,
+ start_time,
+ end_time,
+ name,
+ metadata,
+ level,
+ status_message,
+ version,
+ input,
+ output,
+ provided_model_name,
+ model_parameters,
+ usage_details,
+ cost_details,
+ completion_start_time,
+ prompt_name,
+ prompt_version
+ FROM observations FINAL
+ WHERE project_id = {projectId: String}
+ AND start_time >= {minTimestamp: DateTime64(3)}
+ AND start_time <= {maxTimestamp: DateTime64(3)}
+ `;
+
+ const records = queryClickhouseStream<Record<string, unknown>>({
+ query,
+ params: {
+ projectId,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ tags: {
+ feature: "blobstorage",
+ type: "observation",
+ kind: "analytic",
+ projectId,
+ },
+ });
+
+ return records;
+};
+
export const getGenerationsForPostHog = async function* (
projectId: string,
minTimestamp: Date,
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index ed71420570..4596fd4d6f 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -846,6 +846,49 @@ export const getDistinctScoreNames = async (
return rows.map((row) => row.name);
};
+export const getScoresForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ const query = `
+ SELECT
+ id,
+ timestamp,
+ project_id,
+ environment,
+ trace_id,
+ observation_id,
+ name,
+ value,
+ source,
+ comment,
+ data_type,
+ string_value
+ FROM scores FINAL
+ WHERE project_id = {projectId: String}
+ AND timestamp >= {minTimestamp: DateTime64(3)}
+ AND timestamp <= {maxTimestamp: DateTime64(3)}
+ `;
+
+ const records = queryClickhouseStream<Record<string, unknown>>({
+ query,
+ params: {
+ projectId,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ tags: {
+ feature: "blobstorage",
+ type: "score",
+ kind: "analytic",
+ projectId,
+ },
+ });
+
+ return records;
+};
+
export const getScoresForPostHog = async function* (
projectId: string,
minTimestamp: Date,
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index 1b90e8299f..63ee1ef5b5 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -810,6 +810,52 @@ export const getUserMetrics = async (
}));
};
+export const getTracesForBlobStorageExport = function (
+ projectId: string,
+ minTimestamp: Date,
+ maxTimestamp: Date,
+) {
+ const query = `
+ SELECT
+ id,
+ timestamp,
+ name,
+ environment,
+ project_id,
+ metadata,
+ user_id,
+ session_id,
+ release,
+ version,
+ public,
+ bookmarked,
+ tags,
+ input,
+ output
+ FROM traces FINAL
+ WHERE project_id = {projectId: String}
+ AND timestamp >= {minTimestamp: DateTime64(3)}
+ AND timestamp <= {maxTimestamp: DateTime64(3)}
+ `;
+
+ const records = queryClickhouseStream<Record<string, unknown>>({
+ query,
+ params: {
+ projectId,
+ minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
+ maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
+ },
+ tags: {
+ feature: "blobstorage",
+ type: "trace",
+ kind: "analytic",
+ projectId,
+ },
+ });
+
+ return records;
+};
+
export const getTracesForPostHog = async function* (
projectId: string,
minTimestamp: Date,
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.ts
index f55c1895b2..08cbb2dd92 100644
--- a/packages/shared/src/server/services/StorageService.ts
+++ b/packages/shared/src/server/services/StorageService.ts
@@ -69,8 +69,9 @@ export class StorageServiceFactory {
externalEndpoint?: string | undefined;
region: string | undefined;
forcePathStyle: boolean;
+ useAzureBlob?: boolean;
}): StorageService {
- if (env.LANGFUSE_USE_AZURE_BLOB === "true") {
+ if (params.useAzureBlob || env.LANGFUSE_USE_AZURE_BLOB === "true") {
return new AzureBlobStorageService(params);
}
return new S3StorageService(params);
@@ -133,10 +134,13 @@ class AzureBlobStorageService implements StorageService {
if (typeof data === "string") {
await blockBlobClient.upload(data, data.length);
} else if (data instanceof Readable) {
- let offset = 0;
const blockIds = [];
for await (const chunk of data) {
- const blockId = Buffer.from(`block-${offset}`).toString("base64");
+ // Azure requires block IDs to be base64 strings of the same length
+ // Use a fixed format with padded index to ensure consistent length
+ const blockIdStr: string = `block-${blockIds.length.toString().padStart(10, "0")}`;
+ const blockId = Buffer.from(blockIdStr).toString("base64");
+
const bufferChunk = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk);
@@ -147,11 +151,10 @@ class AzureBlobStorageService implements StorageService {
bufferChunk.length,
);
blockIds.push(blockId);
-
- offset += bufferChunk.length;
}
-
- await blockBlobClient.commitBlockList(blockIds);
+ if (blockIds.length > 0) {
+ await blockBlobClient.commitBlockList(blockIds);
+ }
} else {
throw new Error("Unsupported data type. Must be Readable or string.");
}
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 31da3540e3..77fcd1b083 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -26,6 +26,7 @@ export type AuditableResource =
| "apiKey"
| "evalTemplate"
| "job"
+ | "blobStorageIntegration"
| "posthogIntegration"
| "llmApiKey"
| "batchExport"
diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
new file mode 100644
index 0000000000..976c278283
--- /dev/null
+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts
@@ -0,0 +1,186 @@
+import { z } from "zod";
+
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { encrypt } from "@langfuse/shared/encryption";
+import { blobStorageIntegrationFormSchema } from "@/src/features/blobstorage-integration/types";
+import { TRPCError } from "@trpc/server";
+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
+import { logger } from "@langfuse/shared/src/server";
+import { type BlobStorageIntegration } from "@langfuse/shared";
+
+export const blobStorageIntegrationRouter = createTRPCRouter({
+ get: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoEntitlement({
+ entitlement: "integration-blobstorage",
+ sessionUser: ctx.session.user,
+ projectId: input.projectId,
+ });
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ try {
+ const config = await ctx.prisma.blobStorageIntegration.findFirst({
+ where: {
+ projectId: input.projectId,
+ },
+ omit: {
+ secretAccessKey: true,
+ },
+ });
+
+ if (!config) {
+ return null;
+ }
+
+ return config;
+ } catch (e) {
+ logger.error(`Failed to get blob storage integration`, e);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to get blob storage integration",
+ });
+ }
+ }),
+
+ update: protectedProjectProcedure
+ .input(blobStorageIntegrationFormSchema.extend({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "integration-blobstorage",
+ sessionUser: ctx.session.user,
+ projectId: input.projectId,
+ });
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ await auditLog({
+ session: ctx.session,
+ action: "update",
+ resourceType: "blobStorageIntegration",
+ resourceId: input.projectId,
+ });
+
+ // Extract data from input
+ const {
+ accessKeyId,
+ secretAccessKey,
+ type,
+ bucketName,
+ endpoint,
+ region,
+ prefix,
+ exportFrequency,
+ enabled,
+ forcePathStyle,
+ } = input;
+
+ const data: Partial<BlobStorageIntegration> = {
+ type,
+ bucketName,
+ endpoint: endpoint || null,
+ region,
+ prefix: prefix ?? "",
+ exportFrequency,
+ enabled,
+ accessKeyId,
+ forcePathStyle: forcePathStyle || false,
+ };
+
+ // Use a transaction to check if record exists, then create or update
+ return await ctx.prisma.$transaction(async (prisma) => {
+ // Check if a record exists for this project
+ const existingConfig = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: {
+ projectId: input.projectId,
+ },
+ },
+ );
+
+ if (existingConfig) {
+ // Record exists, perform update
+ if (secretAccessKey) {
+ data.secretAccessKey = encrypt(secretAccessKey);
+ }
+
+ return await prisma.blobStorageIntegration.update({
+ where: {
+ projectId: input.projectId,
+ },
+ data,
+ });
+ } else {
+ // Record doesn't exist, perform create
+ // For create, secretAccessKey is mandatory
+ if (!secretAccessKey) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Secret access key is required for new configuration",
+ });
+ }
+
+ return await prisma.blobStorageIntegration.create({
+ data: {
+ ...(data as BlobStorageIntegration),
+ projectId: input.projectId,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ },
+ });
+ }
+ });
+ } catch (e) {
+ logger.error(`Failed to update blob storage integration`, e);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to update blob storage integration",
+ });
+ }
+ }),
+ delete: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoEntitlement({
+ entitlement: "integration-blobstorage",
+ sessionUser: ctx.session.user,
+ projectId: input.projectId,
+ });
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ await auditLog({
+ session: ctx.session,
+ action: "delete",
+ resourceType: "blobStorageIntegration",
+ resourceId: input.projectId,
+ });
+
+ await ctx.prisma.blobStorageIntegration.delete({
+ where: {
+ projectId: input.projectId,
+ },
+ });
+ } catch (e) {
+ logger.error(`Failed to delete blob storage integration`, e);
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to delete blob storage integration",
+ });
+ }
+ }),
+});
diff --git a/web/src/features/blobstorage-integration/types.ts b/web/src/features/blobstorage-integration/types.ts
new file mode 100644
index 0000000000..a4ac28c375
--- /dev/null
+++ b/web/src/features/blobstorage-integration/types.ts
@@ -0,0 +1,28 @@
+import { z } from "zod";
+import { BlobStorageIntegrationType } from "@langfuse/shared";
+
+export const blobStorageIntegrationFormSchema = z.object({
+ type: z.nativeEnum(BlobStorageIntegrationType),
+ bucketName: z.string().min(1, { message: "Bucket name is required" }),
+ endpoint: z.string().url().optional().nullable(),
+ region: z.string().default("auto"),
+ accessKeyId: z.string().min(1, { message: "Access key ID is required" }),
+ secretAccessKey: z
+ .string()
+ .min(1, { message: "Secret access key is required" })
+ .nullable(), // Only required on create
+ prefix: z.string()
+ .refine(
+ (value) => !value || value === "" || value.endsWith("/"),
+ { message: "Prefix must end with a forward slash (/)" }
+ )
+ .optional()
+ .or(z.literal("")),
+ exportFrequency: z.enum(["hourly", "daily", "weekly"]),
+ enabled: z.boolean(),
+ forcePathStyle: z.boolean(),
+});
+
+export type BlobStorageIntegrationFormSchema = z.infer<
+ typeof blobStorageIntegrationFormSchema
+>;
diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.ts
index b3f012d903..9e76ddb198 100644
--- a/web/src/features/entitlements/constants/entitlements.ts
+++ b/web/src/features/entitlements/constants/entitlements.ts
@@ -9,6 +9,7 @@ const entitlements = [
"cloud-billing",
"cloud-multi-tenant-sso",
"integration-posthog",
+ "integration-blobstorage",
"annotation-queues",
"self-host-ui-customization",
"self-host-allowed-organization-creators",
@@ -65,7 +66,7 @@ export const entitlementAccess: Record<
},
},
"cloud:core": {
- entitlements: [...cloudAllPlansEntitlements],
+ entitlements: [...cloudAllPlansEntitlements, "integration-blobstorage"],
entitlementLimits: {
"organization-member-count": false,
"data-access-days": 90,
@@ -75,7 +76,7 @@ export const entitlementAccess: Record<
},
},
"cloud:pro": {
- entitlements: [...cloudAllPlansEntitlements],
+ entitlements: [...cloudAllPlansEntitlements, "integration-blobstorage"],
entitlementLimits: {
"annotation-queue-count": false,
"organization-member-count": false,
@@ -91,6 +92,7 @@ export const entitlementAccess: Record<
"audit-logs",
"data-retention",
"cloud-multi-tenant-sso",
+ "integration-blobstorage",
],
entitlementLimits: {
"annotation-queue-count": false,
@@ -107,6 +109,7 @@ export const entitlementAccess: Record<
"audit-logs",
"data-retention",
"cloud-multi-tenant-sso",
+ "integration-blobstorage",
],
entitlementLimits: {
"annotation-queue-count": false,
@@ -134,6 +137,7 @@ export const entitlementAccess: Record<
"playground",
"prompt-experiments",
"integration-posthog",
+ "integration-blobstorage",
],
entitlementLimits: {
"annotation-queue-count": false,
@@ -154,6 +158,7 @@ export const entitlementAccess: Record<
"self-host-allowed-organization-creators",
"self-host-ui-customization",
"integration-posthog",
+ "integration-blobstorage",
"audit-logs",
"data-retention",
],
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 9a4ef4fa49..239e0fc3bf 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -75,7 +75,7 @@ const events = {
"new_form_submit",
"update_form_submit",
],
- integrations: ["posthog_form_submitted"],
+ integrations: ["posthog_form_submitted", "blob_storage_form_submitted"],
sign_in: ["cloud_region_switch", "button_click"],
auth: ["reset_password_email_requested", "update_password_form_submit"],
playground: [
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index a64538e855..ed43804a1b 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -228,7 +228,10 @@ export default function SettingsPage() {
}
const Integrations = (props: { projectId: string }) => {
- const hasEntitlement = useHasEntitlement("integration-posthog");
+ const hasPosthogEntitlement = useHasEntitlement("integration-posthog");
+ const hasBlobStorageEntitlement = useHasEntitlement(
+ "integration-blobstorage",
+ );
const hasAccess = useHasProjectAccess({
projectId: props.projectId,
scope: "integrations:CRUD",
@@ -237,29 +240,61 @@ const Integrations = (props: { projectId: string }) => {
return (
<div>
<Header title="Integrations" />
- <Card className="p-3">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <PostHogLogo className="mb-4 w-40 text-foreground" />
- <p className="mb-4 text-sm text-primary">
- We have teamed up with PostHog (OSS product analytics) to make
- Langfuse Events/Metrics available in your Posthog Dashboards.
- </p>
- <div className="flex items-center gap-2">
- <ActionButton
- variant="secondary"
- hasAccess={hasAccess}
- hasEntitlement={hasEntitlement}
- href={`/project/${props.projectId}/settings/integrations/posthog`}
- >
- Configure
- </ActionButton>
- <Button asChild variant="ghost">
- <Link href="https://langfuse.com/docs/analytics/posthog">
- Integration Docs ↗
- </Link>
- </Button>
- </div>
- </Card>
+ <div className="space-y-6">
+ <Card className="p-3">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <PostHogLogo className="mb-4 w-40 text-foreground" />
+ <p className="mb-4 text-sm text-primary">
+ We have teamed up with PostHog (OSS product analytics) to make
+ Langfuse Events/Metrics available in your Posthog Dashboards.
+ </p>
+ <div className="flex items-center gap-2">
+ <ActionButton
+ variant="secondary"
+ hasAccess={hasAccess}
+ hasEntitlement={hasPosthogEntitlement}
+ href={`/project/${props.projectId}/settings/integrations/posthog`}
+ >
+ Configure
+ </ActionButton>
+ <Button asChild variant="ghost">
+ <Link
+ href="https://langfuse.com/docs/analytics/posthog"
+ target="_blank"
+ >
+ Integration Docs ↗
+ </Link>
+ </Button>
+ </div>
+ </Card>
+
+ <Card className="p-3">
+ <span className="font-semibold">Blob Storage (Beta)</span>
+ <p className="mb-4 text-sm text-primary">
+ Configure scheduled exports of your trace data to S3 compatible
+ storages or Azure Blob Storage. Set up a scheduled export to your
+ own storage for data analysis or backup purposes.
+ </p>
+ <div className="flex items-center gap-2">
+ <ActionButton
+ variant="secondary"
+ hasAccess={hasAccess}
+ hasEntitlement={hasBlobStorageEntitlement}
+ href={`/project/${props.projectId}/settings/integrations/blobstorage`}
+ >
+ Configure
+ </ActionButton>
+ <Button asChild variant="ghost">
+ <Link
+ href="https://langfuse.com/docs/query-traces#blob-storage"
+ target="_blank"
+ >
+ Integration Docs ↗
+ </Link>
+ </Button>
+ </div>
+ </Card>
+ </div>
</div>
);
};
diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
new file mode 100644
index 0000000000..84c128652b
--- /dev/null
+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx
@@ -0,0 +1,485 @@
+import Header from "@/src/components/layouts/header";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { Button } from "@/src/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import { PasswordInput } from "@/src/components/ui/password-input";
+import { Switch } from "@/src/components/ui/switch";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/src/components/ui/select";
+import { useHasEntitlement } from "@/src/features/entitlements/hooks";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import {
+ blobStorageIntegrationFormSchema,
+ type BlobStorageIntegrationFormSchema,
+} from "@/src/features/blobstorage-integration/types";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { api } from "@/src/utils/api";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Card } from "@tremor/react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import {
+ BlobStorageIntegrationType,
+ type BlobStorageIntegration,
+} from "@langfuse/shared";
+
+export default function BlobStorageIntegrationSettings() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string;
+ const entitled = useHasEntitlement("integration-blobstorage");
+ const hasAccess = useHasProjectAccess({
+ projectId,
+ scope: "integrations:CRUD",
+ });
+ const state = api.blobStorageIntegration.get.useQuery(
+ { projectId },
+ {
+ enabled: hasAccess && entitled,
+ },
+ );
+ if (!entitled) return null;
+
+ const status =
+ state.isInitialLoading || !hasAccess
+ ? undefined
+ : state.data?.enabled
+ ? "active"
+ : "inactive";
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Blob Storage Integration (Beta)",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ actionButtonsLeft: <>{status && <StatusBadge type={status} />}</>,
+ actionButtonsRight: (
+ <Button asChild variant="secondary">
+ <Link
+ href="https://langfuse.com/docs/query-traces#blob-storage"
+ target="_blank"
+ >
+ Integration Docs ↗
+ </Link>
+ </Button>
+ ),
+ }}
+ >
+ <p className="mb-4 text-sm text-primary">
+ Configure scheduled exports of your trace data to AWS S3, S3-compatible
+ storages, or Azure Blob Storage. Set up a daily, weekly, or monthly
+ export to your own storage for data analysis or backup purposes.
+ </p>
+ {!hasAccess && (
+ <p className="text-sm">
+ Your current role does not grant you access to these settings, please
+ reach out to your project admin or owner.
+ </p>
+ )}
+ {hasAccess && (
+ <>
+ <Header title="Configuration" />
+ <Card className="p-3">
+ <BlobStorageIntegrationSettingsForm
+ state={state.data || undefined}
+ projectId={projectId}
+ isLoading={state.isLoading}
+ />
+ </Card>
+ </>
+ )}
+ {state.data?.enabled && (
+ <>
+ <Header title="Status" className="mt-8" />
+ <p className="text-sm text-primary">
+ Data last exported:{" "}
+ {state.data?.lastSyncAt
+ ? new Date(state.data.lastSyncAt).toLocaleString()
+ : "Never (pending)"}
+ </p>
+ </>
+ )}
+ </ContainerPage>
+ );
+}
+
+const BlobStorageIntegrationSettingsForm = ({
+ state,
+ projectId,
+ isLoading,
+}: {
+ state?: Partial<BlobStorageIntegration>;
+ projectId: string;
+ isLoading: boolean;
+}) => {
+ const capture = usePostHogClientCapture();
+ const [integrationType, setIntegrationType] =
+ useState<BlobStorageIntegrationType>(BlobStorageIntegrationType.S3);
+
+ const blobStorageForm = useForm<BlobStorageIntegrationFormSchema>({
+ resolver: zodResolver(blobStorageIntegrationFormSchema),
+ defaultValues: {
+ type: state?.type || BlobStorageIntegrationType.S3,
+ bucketName: state?.bucketName || "",
+ endpoint: state?.endpoint || null,
+ region: state?.region || "",
+ accessKeyId: state?.accessKeyId || "",
+ secretAccessKey: state?.secretAccessKey || null,
+ prefix: state?.prefix || "",
+ exportFrequency: (state?.exportFrequency || "daily") as
+ | "daily"
+ | "weekly"
+ | "hourly",
+ enabled: state?.enabled || false,
+ forcePathStyle: state?.forcePathStyle || false,
+ },
+ disabled: isLoading,
+ });
+
+ useEffect(() => {
+ blobStorageForm.reset({
+ type: state?.type || BlobStorageIntegrationType.S3,
+ bucketName: state?.bucketName || "",
+ endpoint: state?.endpoint || null,
+ region: state?.region || "",
+ accessKeyId: state?.accessKeyId || "",
+ secretAccessKey: state?.secretAccessKey || null,
+ prefix: state?.prefix || "",
+ exportFrequency: (state?.exportFrequency || "daily") as
+ | "daily"
+ | "weekly"
+ | "hourly",
+ enabled: state?.enabled || false,
+ forcePathStyle: state?.forcePathStyle || false,
+ });
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [state]);
+
+ const utils = api.useUtils();
+ const mut = api.blobStorageIntegration.update.useMutation({
+ onSuccess: () => {
+ utils.blobStorageIntegration.invalidate();
+ },
+ });
+ const mutDelete = api.blobStorageIntegration.delete.useMutation({
+ onSuccess: () => {
+ utils.blobStorageIntegration.invalidate();
+ },
+ });
+
+ async function onSubmit(values: BlobStorageIntegrationFormSchema) {
+ capture("integrations:blob_storage_form_submitted");
+ mut.mutate({
+ projectId,
+ ...values,
+ });
+ }
+
+ const handleIntegrationTypeChange = (value: BlobStorageIntegrationType) => {
+ setIntegrationType(value);
+ blobStorageForm.setValue("type", value);
+ };
+
+ return (
+ <Form {...blobStorageForm}>
+ <form
+ className="space-y-3"
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
+ onSubmit={blobStorageForm.handleSubmit(onSubmit)}
+ >
+ <FormField
+ control={blobStorageForm.control}
+ name="type"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Storage Provider</FormLabel>
+ <FormControl>
+ <Select
+ defaultValue={field.value}
+ onValueChange={(value) =>
+ handleIntegrationTypeChange(
+ value as BlobStorageIntegrationType,
+ )
+ }
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select provider" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="S3">AWS S3</SelectItem>
+ <SelectItem value="S3_COMPATIBLE">
+ S3 Compatible Storage
+ </SelectItem>
+ <SelectItem value="AZURE_BLOB_STORAGE">
+ Azure Blob Storage
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormDescription>
+ Choose your cloud storage provider
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={blobStorageForm.control}
+ name="bucketName"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Container Name"
+ : "Bucket Name"}
+ </FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "The Azure storage container name"
+ : "The S3 bucket name"}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Endpoint URL field - Only shown for S3-compatible and Azure */}
+ {integrationType !== "S3" && (
+ <FormField
+ control={blobStorageForm.control}
+ name="endpoint"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Endpoint URL</FormLabel>
+ <FormControl>
+ <Input {...field} value={field.value || ""} />
+ </FormControl>
+ <FormDescription>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Azure Blob Storage endpoint URL (e.g., https://accountname.blob.core.windows.net)"
+ : "S3 compatible endpoint URL (e.g., https://play.min.io)"}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {/* Region field - Only shown for AWS S3 */}
+ {integrationType === "S3" && (
+ <FormField
+ control={blobStorageForm.control}
+ name="region"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Region</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>AWS region (e.g., us-east-1)</FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ {/* Force Path Style switch - Only shown for S3-compatible */}
+ {integrationType === "S3_COMPATIBLE" && (
+ <FormField
+ control={blobStorageForm.control}
+ name="forcePathStyle"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Force Path Style</FormLabel>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ className="ml-4 mt-1"
+ />
+ </FormControl>
+ <FormDescription>
+ Enable for MinIO and some other S3 compatible providers
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
+ <FormField
+ control={blobStorageForm.control}
+ name="accessKeyId"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Storage Account Name"
+ : integrationType === "S3"
+ ? "AWS Access Key ID"
+ : "Access Key ID"}
+ </FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Your Azure storage account name"
+ : integrationType === "S3"
+ ? "Your AWS IAM user access key ID"
+ : "Access key for your S3-compatible storage"}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={blobStorageForm.control}
+ name="secretAccessKey"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Storage Account Key"
+ : integrationType === "S3"
+ ? "AWS Secret Access Key"
+ : "Secret Access Key"}
+ </FormLabel>
+ <FormControl>
+ <PasswordInput
+ placeholder="********************"
+ {...field}
+ value={field.value || ""}
+ />
+ </FormControl>
+ <FormDescription>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? "Your Azure storage account access key"
+ : integrationType === "S3"
+ ? "Your AWS IAM user secret access key"
+ : "Secret key for your S3-compatible storage"}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={blobStorageForm.control}
+ name="prefix"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Export Prefix</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ {integrationType === "AZURE_BLOB_STORAGE"
+ ? 'Optional prefix path for exported files in your Azure container (e.g., "langfuse-exports/")'
+ : integrationType === "S3"
+ ? 'Optional prefix path for exported files in your S3 bucket (e.g., "langfuse-exports/")'
+ : 'Optional prefix path for exported files (e.g., "langfuse-exports/")'}
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={blobStorageForm.control}
+ name="exportFrequency"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Export Frequency</FormLabel>
+ <FormControl>
+ <Select
+ defaultValue={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select frequency" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="hourly">Hourly</SelectItem>
+ <SelectItem value="daily">Daily</SelectItem>
+ <SelectItem value="weekly">Weekly</SelectItem>
+ </SelectContent>
+ </Select>
+ </FormControl>
+ <FormDescription>
+ How often the data should be exported. Changes are taken into
+ consideration from the next run onwards.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={blobStorageForm.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Enabled</FormLabel>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ className="ml-4 mt-1"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ </form>
+ <div className="mt-8 flex gap-2">
+ <Button
+ loading={mut.isLoading}
+ onClick={blobStorageForm.handleSubmit(onSubmit)}
+ disabled={isLoading}
+ >
+ Save
+ </Button>
+ <Button
+ variant="ghost"
+ loading={mutDelete.isLoading}
+ disabled={isLoading || !!!state}
+ onClick={() => {
+ if (
+ confirm(
+ "Are you sure you want to reset the Blob Storage integration for this project?",
+ )
+ )
+ mutDelete.mutate({ projectId });
+ }}
+ >
+ Reset
+ </Button>
+ </div>
+ </Form>
+ );
+};
diff --git a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
index 64d2d84680..ba58c9cafb 100644
--- a/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
+++ b/web/src/pages/project/[projectId]/settings/integrations/posthog.tsx
@@ -163,7 +163,6 @@ const PostHogIntegrationSettings = ({
projectId,
...values,
});
- console.log(values);
}
return (
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index c049177b31..41525c376c 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -15,6 +15,7 @@ import { promptRouter } from "@/src/features/prompts/server/routers/promptRouter
import { modelRouter } from "@/src/server/api/routers/models";
import { evalRouter } from "@/src/ee/features/evals/server/router";
import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posthog-integration-router";
+import { blobStorageIntegrationRouter } from "@/src/features/blobstorage-integration/blobstorage-integration-router";
import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";
import { organizationsRouter } from "@/src/features/organizations/server/organizationRouter";
import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";
@@ -61,6 +62,7 @@ export const appRouter = createTRPCRouter({
evals: evalRouter,
experiments: experimentsRouter,
posthogIntegration: posthogIntegrationRouter,
+ blobStorageIntegration: blobStorageIntegrationRouter,
llmApiKey: llmApiKeyRouter,
public: publicRouter,
credentials: credentialsRouter,
diff --git a/worker/package.json b/worker/package.json
index 42116549c4..e2c3467631 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -13,7 +13,7 @@
"start": "dotenv -e ../.env -- node dist/index.js",
"build": "tsc",
"dev": "dotenv -e ../.env -- nodemon src/index.ts",
- "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 31",
+ "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 32",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"refill-ingestion-events": "dotenv -e ../.env -- tsx src/scripts/refill-ingestion-events.ts",
"refill-billing-event": "dotenv -e ../.env -- tsx src/scripts/refill-billing-event.ts"
diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
new file mode 100644
index 0000000000..8bb4484024
--- /dev/null
+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts
@@ -0,0 +1,303 @@
+import { expect, it, describe, beforeAll } from "vitest";
+import { env } from "../env";
+import { randomUUID } from "crypto";
+import {
+ createObservation,
+ createObservationsCh,
+ createOrgProjectAndApiKey,
+ createScore,
+ createScoresCh,
+ createTrace,
+ createTracesCh,
+ StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { Job } from "bullmq";
+import { handleBlobStorageIntegrationProjectJob } from "../ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob";
+import { BlobStorageIntegrationType } from "@langfuse/shared";
+import { encrypt } from "@langfuse/shared/encryption";
+
+describe("BlobStorageIntegrationProcessingJob", () => {
+ let storageService: StorageService;
+ const bucketName = env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET || "";
+ const accessKeyId = env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID || "";
+ const secretAccessKey = env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY || "";
+ const endpoint = env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT || undefined;
+ const region = env.LANGFUSE_S3_EVENT_UPLOAD_REGION || undefined;
+
+ beforeAll(async () => {
+ storageService = StorageServiceFactory.getInstance({
+ accessKeyId,
+ secretAccessKey,
+ bucketName,
+ endpoint,
+ region,
+ forcePathStyle: env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ });
+ });
+
+ it("should not process when blob storage integration is disabled", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Setup an integration but disabled
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: "",
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: false,
+ exportFrequency: "hourly",
+ },
+ });
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ expect(files.filter((f) => f.file.includes(projectId))).toHaveLength(0);
+ });
+
+ it("should export traces, generations, and scores to S3", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ const now = new Date();
+ const threeHourAgo = new Date(now.getTime() - 3 * 60 * 60 * 1000);
+
+ // Create integration
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: "",
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "hourly",
+ nextSyncAt: threeHourAgo,
+ lastSyncAt: threeHourAgo,
+ },
+ });
+
+ // Create test data
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const scoreId = randomUUID();
+
+ // Create trace, observation, and score in Clickhouse
+ await Promise.all([
+ createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 40 * 60 * 1000, // 40 min before now
+ name: "Test Trace",
+ }),
+ ]),
+ createObservationsCh([
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ start_time: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Observation",
+ }),
+ ]),
+ createScoresCh([
+ createScore({
+ id: scoreId,
+ trace_id: traceId,
+ project_id: projectId,
+ timestamp: now.getTime() - 35 * 60 * 1000, // 35 minutes before now
+ name: "Test Score",
+ value: 0.95,
+ }),
+ ]),
+ ]);
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
+
+ // Should have 3 files (traces, observations, scores)
+ expect(projectFiles).toHaveLength(3);
+
+ // Check file paths follow the expected pattern
+ const traceFile = projectFiles.find((f) => f.file.includes("/traces/"));
+ const observationFile = projectFiles.find((f) =>
+ f.file.includes("/observations/"),
+ );
+ const scoreFile = projectFiles.find((f) => f.file.includes("/scores/"));
+
+ expect(traceFile).toBeDefined();
+ expect(observationFile).toBeDefined();
+ expect(scoreFile).toBeDefined();
+
+ // Check file contents
+ if (traceFile) {
+ const content = await storageService.download(traceFile.file);
+ expect(content).toContain(traceId);
+ expect(content).toContain("Test Trace");
+ }
+
+ if (observationFile) {
+ const content = await storageService.download(observationFile.file);
+ expect(content).toContain(observationId);
+ expect(content).toContain("Test Observation");
+ }
+
+ if (scoreFile) {
+ const content = await storageService.download(scoreFile.file);
+ expect(content).toContain(scoreId);
+ expect(content).toContain("Test Score");
+ expect(content).toContain("0.95");
+ }
+
+ // Check integration lastSyncAt and nextSyncAt are updated
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique({
+ where: { projectId },
+ });
+
+ if (updatedIntegration?.lastSyncAt && updatedIntegration?.nextSyncAt) {
+ expect(updatedIntegration.lastSyncAt.getTime()).toBeGreaterThan(
+ threeHourAgo.getTime(),
+ );
+ expect(updatedIntegration.nextSyncAt.getTime()).toBeGreaterThan(
+ now.getTime(),
+ );
+ } else {
+ expect.fail("Integration should have lastSyncAt and nextSyncAt set");
+ }
+ });
+
+ it("should respect export frequency when setting nextSyncAt", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ // Setup for weekly export
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix: "",
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region,
+ endpoint: endpoint,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "weekly",
+ lastSyncAt: oneHourAgo,
+ },
+ });
+
+ // Create test data
+ const traceId = randomUUID();
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
+ }),
+ ]);
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const updatedIntegration = await prisma.blobStorageIntegration.findUnique({
+ where: { projectId },
+ });
+
+ // Should be set to 7 days in the future from maxTimestamp (now - 30min)
+ const expectedNextSync = new Date(
+ now.getTime() - 30 * 60 * 1000 + 7 * 24 * 60 * 60 * 1000,
+ );
+
+ if (updatedIntegration?.nextSyncAt) {
+ // Use a tolerance value in milliseconds instead of numeric precision
+ const tolerance = 1000; // 1 second tolerance
+ expect(
+ Math.abs(
+ updatedIntegration.nextSyncAt.getTime() - expectedNextSync.getTime(),
+ ),
+ ).toBeLessThan(tolerance);
+ } else {
+ expect.fail("Integration should have nextSyncAt set");
+ }
+ });
+
+ it("should use prefix in file path when specified", async () => {
+ // Setup
+ const { projectId } = await createOrgProjectAndApiKey();
+ const prefix = "test-prefix";
+ const now = new Date();
+ const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
+
+ await prisma.blobStorageIntegration.create({
+ data: {
+ projectId,
+ type: BlobStorageIntegrationType.S3,
+ bucketName,
+ prefix,
+ accessKeyId,
+ secretAccessKey: encrypt(secretAccessKey),
+ region: region ? region : "auto",
+ endpoint: endpoint ? endpoint : null,
+ forcePathStyle:
+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",
+ enabled: true,
+ exportFrequency: "daily",
+ lastSyncAt: oneHourAgo,
+ },
+ });
+
+ // Create test data
+ const traceId = randomUUID();
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: oneHourAgo.getTime() + 10 * 60 * 1000,
+ }),
+ ]);
+
+ // When
+ await handleBlobStorageIntegrationProjectJob({
+ data: { payload: { projectId } },
+ } as Job);
+
+ // Then
+ const files = await storageService.listFiles("");
+ const projectFiles = files.filter((f) => f.file.includes(projectId));
+
+ // All files should have the prefix
+ expect(projectFiles.every((f) => f.file.startsWith(prefix))).toBe(true);
+ });
+});
diff --git a/worker/src/app.ts b/worker/src/app.ts
index d69973fd37..d1d46518e4 100644
--- a/worker/src/app.ts
+++ b/worker/src/app.ts
@@ -27,6 +27,7 @@ import {
PostHogIntegrationQueue,
QueueName,
logger,
+ BlobStorageIntegrationQueue,
} from "@langfuse/shared/src/server";
import { env } from "./env";
import { ingestionQueueProcessorBuilder } from "./queues/ingestionQueue";
@@ -38,6 +39,10 @@ import {
postHogIntegrationProcessingProcessor,
postHogIntegrationProcessor,
} from "./queues/postHogIntegrationQueue";
+import {
+ blobStorageIntegrationProcessingProcessor,
+ blobStorageIntegrationProcessor,
+} from "./queues/blobStorageIntegrationQueue";
import { coreDataS3ExportProcessor } from "./queues/coreDataS3ExportQueue";
import { meteringDataPostgresExportProcessor } from "./ee/meteringDataPostgresExport/handleMeteringDataPostgresExportJob";
import {
@@ -263,6 +268,27 @@ if (env.QUEUE_CONSUMER_POSTHOG_INTEGRATION_QUEUE_IS_ENABLED === "true") {
);
}
+if (env.QUEUE_CONSUMER_BLOB_STORAGE_INTEGRATION_QUEUE_IS_ENABLED === "true") {
+ // Instantiate the queue to trigger scheduled jobs
+ BlobStorageIntegrationQueue.getInstance();
+
+ WorkerManager.register(
+ QueueName.BlobStorageIntegrationQueue,
+ blobStorageIntegrationProcessor,
+ {
+ concurrency: 1,
+ },
+ );
+
+ WorkerManager.register(
+ QueueName.BlobStorageIntegrationProcessingQueue,
+ blobStorageIntegrationProcessingProcessor,
+ {
+ concurrency: 1,
+ },
+ );
+}
+
if (env.QUEUE_CONSUMER_DATA_RETENTION_QUEUE_IS_ENABLED === "true") {
// Instantiate the queue to trigger scheduled jobs
DataRetentionQueue.getInstance();
diff --git a/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts
new file mode 100644
index 0000000000..249843521d
--- /dev/null
+++ b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob.ts
@@ -0,0 +1,207 @@
+import { pipeline } from "stream";
+import { Job } from "bullmq";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ QueueName,
+ TQueueJobTypes,
+ logger,
+ StorageService,
+ StorageServiceFactory,
+ streamTransformations,
+ getObservationsForBlobStorageExport,
+ getTracesForBlobStorageExport,
+ getScoresForBlobStorageExport,
+} from "@langfuse/shared/src/server";
+import { BlobStorageIntegrationType } from "@langfuse/shared";
+import { decrypt } from "@langfuse/shared/encryption";
+
+const processBlobStorageExport = async (config: {
+ projectId: string;
+ minTimestamp: Date;
+ maxTimestamp: Date;
+ bucketName: string;
+ endpoint: string | null;
+ region?: string;
+ accessKeyId: string;
+ secretAccessKey: string;
+ prefix?: string;
+ forcePathStyle?: boolean;
+ type: BlobStorageIntegrationType;
+ table: "traces" | "observations" | "scores";
+}) => {
+ logger.info(
+ `Processing ${config.table} export for project ${config.projectId}`,
+ );
+
+ // Initialize the storage service
+ const storageService: StorageService = StorageServiceFactory.getInstance({
+ accessKeyId: config.accessKeyId,
+ secretAccessKey: config.secretAccessKey,
+ bucketName: config.bucketName,
+ endpoint: config.endpoint ?? undefined,
+ region: config.region,
+ forcePathStyle: config.forcePathStyle ?? false,
+ useAzureBlob: config.type === BlobStorageIntegrationType.AZURE_BLOB_STORAGE,
+ });
+
+ try {
+ // Create the file path with prefix if available
+ const timestamp = config.maxTimestamp
+ .toISOString()
+ .replace(/:/g, "-")
+ .substring(0, 19);
+ const filePath = `${config.prefix ?? ""}${config.projectId}/${config.table}/${timestamp}.csv`;
+
+ // Fetch data based on table type
+ let dataStream: AsyncGenerator<Record<string, unknown>>;
+
+ switch (config.table) {
+ case "traces":
+ dataStream = getTracesForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+ break;
+ case "observations":
+ dataStream = getObservationsForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+ break;
+ case "scores":
+ dataStream = getScoresForBlobStorageExport(
+ config.projectId,
+ config.minTimestamp,
+ config.maxTimestamp,
+ );
+ break;
+ default:
+ throw new Error(`Unsupported table type: ${config.table}`);
+ }
+
+ const fileStream = pipeline(
+ dataStream,
+ streamTransformations["CSV"](),
+ (err) => {
+ if (err) {
+ logger.error(
+ "Getting data from DB for blob storage integration failed: ",
+ err,
+ );
+ }
+ },
+ );
+
+ // Upload the file to cloud storage
+ await storageService.uploadFile({
+ fileName: filePath,
+ fileType: "text/csv",
+ data: fileStream,
+ expiresInSeconds: 3600, // 1 hour expiry for the signed URL - is ignored
+ });
+
+ logger.info(
+ `Successfully exported ${config.table} records for project ${config.projectId}`,
+ );
+ } catch (error) {
+ logger.error(
+ `Error exporting ${config.table} for project ${config.projectId}`,
+ error,
+ );
+ throw error;
+ }
+};
+
+export const handleBlobStorageIntegrationProjectJob = async (
+ job: Job<TQueueJobTypes[QueueName.BlobStorageIntegrationProcessingQueue]>,
+) => {
+ const { projectId } = job.data.payload;
+
+ logger.info(`Processing blob storage integration for project ${projectId}`);
+
+ const blobStorageIntegration = await prisma.blobStorageIntegration.findUnique(
+ {
+ where: {
+ projectId,
+ },
+ },
+ );
+
+ if (!blobStorageIntegration) {
+ logger.warn(`Blob storage integration not found for project ${projectId}`);
+ return;
+ }
+ if (!blobStorageIntegration.enabled) {
+ logger.info(
+ `Blob storage integration is disabled for project ${projectId}`,
+ );
+ return;
+ }
+
+ // Sync between lastSyncAt and now - 30 minutes
+ const minTimestamp = blobStorageIntegration.lastSyncAt || new Date(0);
+ const maxTimestamp = new Date(new Date().getTime() - 30 * 60 * 1000);
+
+ try {
+ // Process the export based on the integration configuration
+ const executionConfig = {
+ projectId,
+ minTimestamp,
+ maxTimestamp,
+ bucketName: blobStorageIntegration.bucketName,
+ endpoint: blobStorageIntegration.endpoint,
+ region: blobStorageIntegration.region || undefined,
+ accessKeyId: blobStorageIntegration.accessKeyId,
+ secretAccessKey: decrypt(blobStorageIntegration.secretAccessKey),
+ prefix: blobStorageIntegration.prefix || undefined,
+ forcePathStyle: blobStorageIntegration.forcePathStyle || undefined,
+ type: blobStorageIntegration.type,
+ };
+
+ await Promise.all([
+ processBlobStorageExport({ ...executionConfig, table: "traces" }),
+ processBlobStorageExport({ ...executionConfig, table: "observations" }),
+ processBlobStorageExport({ ...executionConfig, table: "scores" }),
+ ]);
+
+ let nextSyncAt: Date;
+ switch (blobStorageIntegration.exportFrequency) {
+ case "hourly":
+ nextSyncAt = new Date(maxTimestamp.getTime() + 60 * 60 * 1000);
+ break;
+ case "daily":
+ nextSyncAt = new Date(maxTimestamp.getTime() + 24 * 60 * 60 * 1000);
+ break;
+ case "weekly":
+ nextSyncAt = new Date(maxTimestamp.getTime() + 7 * 24 * 60 * 60 * 1000);
+ break;
+ default:
+ throw new Error(
+ `Unsupported export frequency ${blobStorageIntegration.exportFrequency}`,
+ );
+ }
+
+ // Update integration after successful processing
+ await prisma.blobStorageIntegration.update({
+ where: {
+ projectId,
+ },
+ data: {
+ lastSyncAt: maxTimestamp,
+ nextSyncAt,
+ },
+ });
+
+ logger.info(
+ `Successfully processed blob storage integration for project ${projectId}`,
+ );
+ } catch (error) {
+ logger.error(
+ `Error processing blob storage integration for project ${projectId}`,
+ error,
+ );
+ throw error; // Rethrow to trigger retries
+ }
+};
diff --git a/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationSchedule.ts b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationSchedule.ts
new file mode 100644
index 0000000000..ac796ed179
--- /dev/null
+++ b/worker/src/ee/integrations/blobstorage/handleBlobStorageIntegrationSchedule.ts
@@ -0,0 +1,62 @@
+import { Job } from "bullmq";
+import { prisma } from "@langfuse/shared/src/db";
+import {
+ BlobStorageIntegrationProcessingQueue,
+ QueueJobs,
+ logger,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+export const handleBlobStorageIntegrationSchedule = async (job: Job) => {
+ const now = new Date();
+
+ const blobStorageIntegrationProjects =
+ await prisma.blobStorageIntegration.findMany({
+ select: {
+ lastSyncAt: true,
+ projectId: true,
+ },
+ where: {
+ enabled: true,
+ OR: [
+ // Never synced before
+ { lastSyncAt: null },
+ // Next sync is due
+ { nextSyncAt: { lte: now } },
+ ],
+ },
+ });
+
+ if (blobStorageIntegrationProjects.length === 0) {
+ logger.info("No blob storage integrations ready for sync");
+ return;
+ }
+
+ const blobStorageIntegrationProcessingQueue =
+ BlobStorageIntegrationProcessingQueue.getInstance();
+ if (!blobStorageIntegrationProcessingQueue) {
+ throw new Error("BlobStorageIntegrationProcessingQueue not initialized");
+ }
+
+ logger.info(
+ `Scheduling ${blobStorageIntegrationProjects.length} blob storage integrations for sync`,
+ );
+
+ await blobStorageIntegrationProcessingQueue.addBulk(
+ blobStorageIntegrationProjects.map((integration) => ({
+ name: QueueJobs.BlobStorageIntegrationProcessingJob,
+ data: {
+ id: randomUUID(),
+ name: QueueJobs.BlobStorageIntegrationProcessingJob,
+ timestamp: new Date(),
+ payload: {
+ projectId: integration.projectId,
+ },
+ },
+ opts: {
+ // Use projectId and last sync as jobId to prevent duplicate jobs.
+ jobId: `${integration.projectId}-${integration.lastSyncAt?.toISOString() ?? ""}`,
+ },
+ })),
+ );
+};
diff --git a/worker/src/env.ts b/worker/src/env.ts
index 3fbf1df449..06cbd4d8b2 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -180,6 +180,9 @@ const EnvSchema = z.object({
QUEUE_CONSUMER_POSTHOG_INTEGRATION_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
+ QUEUE_CONSUMER_BLOB_STORAGE_INTEGRATION_QUEUE_IS_ENABLED: z
+ .enum(["true", "false"])
+ .default("true"),
QUEUE_CONSUMER_INGESTION_SECONDARY_QUEUE_IS_ENABLED: z
.enum(["true", "false"])
.default("true"),
diff --git a/worker/src/queues/blobStorageIntegrationQueue.ts b/worker/src/queues/blobStorageIntegrationQueue.ts
new file mode 100644
index 0000000000..cc37d3f3ff
--- /dev/null
+++ b/worker/src/queues/blobStorageIntegrationQueue.ts
@@ -0,0 +1,32 @@
+import { Processor } from "bullmq";
+import { QueueJobs, logger } from "@langfuse/shared/src/server";
+import { handleBlobStorageIntegrationSchedule } from "../ee/integrations/blobstorage/handleBlobStorageIntegrationSchedule";
+import { handleBlobStorageIntegrationProjectJob } from "../ee/integrations/blobstorage/handleBlobStorageIntegrationProjectJob";
+
+export const blobStorageIntegrationProcessor: Processor = async (job) => {
+ if (job.name === QueueJobs.BlobStorageIntegrationJob) {
+ logger.info("Executing Blob Storage Integration Job");
+ try {
+ return await handleBlobStorageIntegrationSchedule(job);
+ } catch (error) {
+ logger.error("Error executing BlobStorageIntegrationJob", error);
+ throw error;
+ }
+ }
+};
+
+export const blobStorageIntegrationProcessingProcessor: Processor = async (
+ job,
+) => {
+ if (job.name === QueueJobs.BlobStorageIntegrationProcessingJob) {
+ try {
+ return await handleBlobStorageIntegrationProjectJob(job);
+ } catch (error) {
+ logger.error(
+ "Error executing BlobStorageIntegrationProcessingJob",
+ error,
+ );
+ throw error;
+ }
+ }
+};