🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: allow validation and run now for blob storage integrations (#7064)
Steffen Schmitz55e0bdcac0a9
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.tsindex 8b53f55f47..d567390fc5 100644--- a/packages/shared/src/server/services/StorageService.ts+++ b/packages/shared/src/server/services/StorageService.ts@@ -460,7 +460,7 @@ class S3StorageService implements StorageService {return { signedUrl };} catch (err) {logger.error(`Failed to upload file to ${fileName}`, err);- throw new Error("Failed to upload to S3 or generate signed URL");+ throw new Error(`Failed to upload to S3 or generate signed URL: ${err}`);}}diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex 4ad0f61afb..67510cf56a 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -10,8 +10,18 @@ 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";+import {+ logger,+ BlobStorageIntegrationProcessingQueue,+ QueueJobs,+ StorageServiceFactory,+} from "@langfuse/shared/src/server";+import {+ type BlobStorageIntegration,+ BlobStorageIntegrationType,+} from "@langfuse/shared";+import { randomUUID } from "crypto";+import { decrypt } from "@langfuse/shared/encryption";export const blobStorageIntegrationRouter = createTRPCRouter({get: protectedProjectProcedure@@ -185,4 +195,203 @@ export const blobStorageIntegrationRouter = createTRPCRouter({});}}),++ runNow: 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",+ });++ // Check if integration exists and is enabled+ const integration = await ctx.prisma.blobStorageIntegration.findUnique({+ where: {+ projectId: input.projectId,+ },+ });++ if (!integration) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Blob storage integration not found for this project",+ });+ }++ if (!integration.enabled) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Blob storage integration is disabled",+ });+ }++ // Get the processing queue+ const blobStorageIntegrationProcessingQueue =+ BlobStorageIntegrationProcessingQueue.getInstance();+ if (!blobStorageIntegrationProcessingQueue) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "BlobStorageIntegrationProcessingQueue not initialized",+ });+ }++ // Create a unique job ID for manual runs to avoid conflicts+ const jobId = `${input.projectId}-manual-${new Date().toISOString()}`;++ // Enqueue the processing job+ await blobStorageIntegrationProcessingQueue.add(+ QueueJobs.BlobStorageIntegrationProcessingJob,+ {+ id: randomUUID(),+ name: QueueJobs.BlobStorageIntegrationProcessingJob,+ timestamp: new Date(),+ payload: {+ projectId: input.projectId,+ },+ },+ {+ jobId,+ },+ );++ logger.info(+ `Manual blob storage integration job queued for project ${input.projectId}`,+ );++ return { success: true, jobId };+ } catch (e) {+ logger.error(`Failed to trigger blob storage integration run`, e);+ if (e instanceof TRPCError) {+ throw e;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to trigger blob storage integration run",+ });+ }+ }),++ validate: 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: "create",+ resourceType: "blobStorageIntegration",+ resourceId: input.projectId,+ after: { action: "validation_test" },+ });++ // Get persisted configuration+ const integration = await ctx.prisma.blobStorageIntegration.findUnique({+ where: {+ projectId: input.projectId,+ },+ });++ if (!integration) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message:+ "Blob storage integration not found for this project. Please save your configuration first.",+ });+ }++ // Extract configuration from persisted data+ const {+ type,+ bucketName,+ endpoint,+ region,+ accessKeyId,+ secretAccessKey: encryptedSecretAccessKey,+ prefix,+ forcePathStyle,+ } = integration;++ const secretAccessKey = decrypt(encryptedSecretAccessKey);++ // Create storage service with provided configuration+ const storageService = StorageServiceFactory.getInstance({+ accessKeyId,+ secretAccessKey,+ bucketName,+ endpoint: endpoint || undefined,+ region: region || undefined,+ forcePathStyle: forcePathStyle || false,+ useAzureBlob: type === BlobStorageIntegrationType.AZURE_BLOB_STORAGE,+ useGoogleCloudStorage: false, // Not supported in blob storage integration+ googleCloudCredentials: undefined,+ awsSse: undefined,+ awsSseKmsKeyId: undefined,+ externalEndpoint: undefined,+ });++ // Create a test file+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-");+ const testFileName = `${prefix || ""}langfuse-validation-test-${timestamp}.txt`;+ const testContent = `Langfuse blob storage validation test+Project ID: ${input.projectId}+Timestamp: ${new Date().toISOString()}+Configuration: ${type} storage+This file can be safely deleted.`;++ // Upload the test file+ const result = await storageService.uploadFile({+ fileName: testFileName,+ fileType: "text/plain",+ data: testContent,+ expiresInSeconds: 3600, // 1 hour+ });++ logger.info(+ `Blob storage validation successful for project ${input.projectId}`,+ );++ return {+ success: true,+ message: "Validation successful! Test file uploaded.",+ testFileName,+ signedUrl: result.signedUrl,+ };+ } catch (e) {+ logger.error(+ `Blob storage validation failed for project ${input.projectId}`,+ e,+ );++ // Extract meaningful error message+ let errorMessage = "Unknown error occurred during validation";+ if (e instanceof Error) {+ errorMessage = e.message;+ }++ if (e instanceof TRPCError) {+ throw e;+ }++ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Validation failed: ${errorMessage}`,+ });+ }+ }),});diff --git a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsxindex ceab4e8f2e..a84ecf36ff 100644--- a/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx+++ b/web/src/pages/project/[projectId]/settings/integrations/blobstorage.tsx@@ -35,6 +35,8 @@ import Link from "next/link";import { useRouter } from "next/router";import { useEffect, useState } from "react";import { useForm } from "react-hook-form";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";+import { showErrorToast } from "@/src/features/notifications/showErrorToast";import {BlobStorageIntegrationType,BlobStorageIntegrationFileType,@@ -91,7 +93,10 @@ export default function BlobStorageIntegrationSettings() {<p className="mb-4 text-sm text-primary">Configure scheduled exports of your trace data to AWS S3, S3-compatiblestorages, or Azure Blob Storage. Set up a hourly, daily, or weekly- export to your own storage for data analysis or backup purposes.+ export to your own storage for data analysis or backup purposes. Use the+ "Validate" button to test your configuration by uploading a+ small test file, and the "Run Now" button to trigger an+ immediate export.</p>{!hasAccess && (<p className="text-sm">@@ -192,6 +197,22 @@ const BlobStorageIntegrationSettingsForm = ({utils.blobStorageIntegration.invalidate();},});+ const mutRunNow = api.blobStorageIntegration.runNow.useMutation({+ onSuccess: () => {+ utils.blobStorageIntegration.invalidate();+ },+ });+ const mutValidate = api.blobStorageIntegration.validate.useMutation({+ onSuccess: (data) => {+ showSuccessToast({+ title: data.message,+ description: `Test file: ${data.testFileName}`,+ });+ },+ onError: (error) => {+ showErrorToast("Validation failed", error.message);+ },+ });async function onSubmit(values: BlobStorageIntegrationFormSchema) {capture("integrations:blob_storage_form_submitted");@@ -495,6 +516,33 @@ const BlobStorageIntegrationSettingsForm = ({>Save</Button>+ <Button+ variant="secondary"+ loading={mutValidate.isLoading}+ disabled={isLoading || !state}+ title="Test your saved configuration by uploading a small test file to your storage"+ onClick={() => {+ mutValidate.mutate({ projectId });+ }}+ >+ Validate+ </Button>+ <Button+ variant="secondary"+ loading={mutRunNow.isLoading}+ disabled={isLoading || !state?.enabled}+ title="Trigger an immediate export of all data since the last sync"+ onClick={() => {+ if (+ confirm(+ "Are you sure you want to run the blob storage export now? This will export all data since the last sync.",+ )+ )+ mutRunNow.mutate({ projectId });+ }}+ >+ Run Now+ </Button><Buttonvariant="ghost"loading={mutDelete.isLoading}