🪢 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
fix(blob-export): reset lastSyncAt when export mode changes (#12640)
Valery Meleshkin2ba9027dfa49
diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex d648815950..264cba65ad 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -6,8 +6,8 @@ import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";-import { encrypt } from "@langfuse/shared/encryption";import { blobStorageIntegrationFormSchema } from "@/src/features/blobstorage-integration/types";+import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";import { TRPCError } from "@trpc/server";import {logger,@@ -18,11 +18,9 @@ import {import { randomUUID } from "crypto";import { decrypt } from "@langfuse/shared/encryption";import {- type BlobStorageIntegration,BlobStorageIntegrationType,- BlobStorageExportMode,+ InvalidRequestError,} from "@langfuse/shared";-import { env } from "@/src/env.mjs";export const blobStorageIntegrationRouter = createTRPCRouter({get: protectedProjectProcedure@@ -73,110 +71,38 @@ export const blobStorageIntegrationRouter = createTRPCRouter({resourceId: input.projectId,});- // Extract data from input- const {- accessKeyId,- secretAccessKey,- type,- bucketName,- endpoint,- region,- prefix,- exportFrequency,- enabled,- forcePathStyle,- fileType,- exportMode,- exportStartDate,- exportSource,- } = input;-- const isSelfHosted = !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;- const canUseHostCredentials =- isSelfHosted && type === BlobStorageIntegrationType.S3;- const isUsingHostCredentials =- canUseHostCredentials && (!accessKeyId || !secretAccessKey);-- if (!canUseHostCredentials && !accessKeyId) {- throw new TRPCError({- code: "BAD_REQUEST",- message: "Access Key ID and Secret Access Key are required",- });- }-- // Determine the export start date based on export mode- let finalExportStartDate: Date | null = null;- if (exportMode === BlobStorageExportMode.FROM_TODAY) {- finalExportStartDate = new Date();- } else if (exportMode === BlobStorageExportMode.FROM_CUSTOM_DATE) {- finalExportStartDate = exportStartDate || new Date();- }- // For FULL_HISTORY mode, exportStartDate remains null-- const data: Partial<BlobStorageIntegration> = {- type,- bucketName,- endpoint: endpoint || null,- region,- prefix: prefix ?? "",- exportFrequency,- enabled,- accessKeyId,- forcePathStyle: forcePathStyle || false,- fileType,- exportMode,- exportStartDate: finalExportStartDate,- exportSource,- };-- // 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) {- if (secretAccessKey) {- data.secretAccessKey = encrypt(secretAccessKey);- }-- return await prisma.blobStorageIntegration.update({- where: {- projectId: input.projectId,- },- data,- });- } else {- // Record doesn't exist, perform create- if (!isUsingHostCredentials && !secretAccessKey) {- throw new TRPCError({- code: "BAD_REQUEST",- message:- "Secret access key is required for new configuration when not using host credentials",- });- }-- return await prisma.blobStorageIntegration.create({- data: {- ...(data as BlobStorageIntegration),- projectId: input.projectId,- accessKeyId,- secretAccessKey: secretAccessKey- ? encrypt(secretAccessKey)- : undefined,- },- });- }+ const { projectId, ...rest } = input;++ return await upsertBlobStorageIntegration({+ prisma: ctx.prisma,+ projectId,+ data: {+ type: rest.type,+ bucketName: rest.bucketName,+ endpoint: rest.endpoint || null,+ region: rest.region,+ accessKeyId: rest.accessKeyId ?? null,+ secretAccessKey: rest.secretAccessKey ?? null,+ prefix: rest.prefix ?? "",+ exportFrequency: rest.exportFrequency,+ enabled: rest.enabled,+ forcePathStyle: rest.forcePathStyle,+ fileType: rest.fileType,+ exportMode: rest.exportMode,+ exportStartDate: rest.exportStartDate ?? null,+ exportSource: rest.exportSource,+ },});} catch (e) {if (e instanceof TRPCError) {throw e;}+ if (e instanceof InvalidRequestError) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: e.message,+ });+ }logger.error(`Failed to update blob storage integration`, e);throw new TRPCError({code: "INTERNAL_SERVER_ERROR",diff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsnew file mode 100644index 0000000000..2c66376a9e--- /dev/null+++ b/web/src/features/blobstorage-integration/service.ts@@ -0,0 +1,127 @@+import { type PrismaClient } from "@langfuse/shared/src/db";+import {+ BlobStorageExportMode,+ BlobStorageIntegrationType,+ InvalidRequestError,+ type BlobStorageIntegrationFileType,+ type AnalyticsIntegrationExportSource,+} from "@langfuse/shared";+import { encrypt } from "@langfuse/shared/encryption";+import { env } from "@/src/env.mjs";++type UpsertBlobStorageIntegrationInput = {+ type: BlobStorageIntegrationType;+ bucketName: string;+ endpoint: string | null;+ region: string;+ accessKeyId: string | null;+ secretAccessKey: string | null; // plain text — encrypted by this service+ prefix: string;+ exportFrequency: string;+ enabled: boolean;+ forcePathStyle: boolean;+ fileType: BlobStorageIntegrationFileType;+ exportMode: BlobStorageExportMode;+ exportStartDate: Date | null;+ exportSource?: AnalyticsIntegrationExportSource;+};++function resolveExportStartDate(params: {+ exportMode: BlobStorageExportMode;+ exportStartDate: Date | null;+}): Date | null {+ switch (params.exportMode) {+ case BlobStorageExportMode.FROM_TODAY:+ return new Date();+ case BlobStorageExportMode.FROM_CUSTOM_DATE:+ return params.exportStartDate || new Date();+ case BlobStorageExportMode.FULL_HISTORY:+ return null;+ default: {+ const _exhaustive: never = params.exportMode;+ void _exhaustive;+ return null;+ }+ }+}++export async function upsertBlobStorageIntegration(params: {+ prisma: PrismaClient;+ projectId: string;+ data: UpsertBlobStorageIntegrationInput;+}) {+ const { prisma, projectId, data } = params;++ const isSelfHosted = !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const canUseHostCredentials =+ isSelfHosted && data.type === BlobStorageIntegrationType.S3;++ if (!canUseHostCredentials && !data.accessKeyId) {+ throw new InvalidRequestError(+ "Access Key ID and Secret Access Key are required",+ );+ }++ const resolvedExportStartDate = resolveExportStartDate({+ exportMode: data.exportMode,+ exportStartDate: data.exportStartDate,+ });++ const writeData = {+ type: data.type,+ bucketName: data.bucketName,+ endpoint: data.endpoint,+ region: data.region,+ accessKeyId: data.accessKeyId,+ prefix: data.prefix,+ exportFrequency: data.exportFrequency,+ enabled: data.enabled,+ forcePathStyle: data.forcePathStyle,+ fileType: data.fileType,+ exportMode: data.exportMode,+ exportStartDate: resolvedExportStartDate,+ exportSource: data.exportSource,+ };++ return prisma.$transaction(async (tx) => {+ const existing = await tx.blobStorageIntegration.findUnique({+ where: { projectId },+ select: { exportMode: true },+ });++ // Require secret key for new integrations (unless using host credentials)+ if (!existing) {+ const isUsingHostCredentials =+ canUseHostCredentials && (!data.accessKeyId || !data.secretAccessKey);+ if (!isUsingHostCredentials && !data.secretAccessKey) {+ throw new InvalidRequestError(+ "Secret access key is required for new configuration",+ );+ }+ }++ const modeChanged = existing && existing.exportMode !== data.exportMode;+ const encryptedSecret = data.secretAccessKey+ ? encrypt(data.secretAccessKey)+ : null;++ return tx.blobStorageIntegration.upsert({+ where: { projectId },+ create: {+ ...writeData,+ projectId,+ secretAccessKey: encryptedSecret,+ },+ update: {+ ...writeData,+ // Only overwrite secretAccessKey when a new value is provided,+ // so partial updates don't wipe the existing encrypted secret.+ ...(encryptedSecret ? { secretAccessKey: encryptedSecret } : {}),+ // Reset sync state when export mode changes so the new mode's+ // start-date logic takes effect instead of continuing from the+ // previous mode's lastSyncAt.+ ...(modeChanged ? { lastSyncAt: null, nextSyncAt: null } : {}),+ },+ });+ });+}diff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex 364d00f3da..b4b86230bb 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -13,7 +13,8 @@ import {UnauthorizedError,ForbiddenError,} from "@langfuse/shared";-import { encrypt } from "@langfuse/shared/encryption";+import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";+import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({GET: handleGetBlobStorageIntegrations,@@ -146,31 +147,32 @@ async function handleUpsertBlobStorageIntegration(throw new LangfuseNotFoundError("Project not found");}- // Prepare data for database- const dbData = {- projectId: validatedData.projectId,- type: validatedData.type,- bucketName: validatedData.bucketName,- endpoint: validatedData.endpoint || null,- region: validatedData.region,- accessKeyId: validatedData.accessKeyId || null,- secretAccessKey: validatedData.secretAccessKey- ? encrypt(validatedData.secretAccessKey)- : null,- prefix: validatedData.prefix,- exportFrequency: validatedData.exportFrequency,- enabled: validatedData.enabled,- forcePathStyle: validatedData.forcePathStyle,- fileType: validatedData.fileType,- exportMode: validatedData.exportMode,- exportStartDate: validatedData.exportStartDate || null,- };+ await auditLog({+ action: "update",+ resourceType: "blobStorageIntegration",+ resourceId: validatedData.projectId,+ apiKeyId: authCheck.scope.apiKeyId,+ orgId: authCheck.scope.orgId,+ });- // Upsert the integration (create or update)- const integration = await prisma.blobStorageIntegration.upsert({- where: { projectId: validatedData.projectId },- update: dbData,- create: dbData,+ const integration = await upsertBlobStorageIntegration({+ prisma,+ projectId: validatedData.projectId,+ data: {+ type: validatedData.type,+ bucketName: validatedData.bucketName,+ endpoint: validatedData.endpoint || null,+ region: validatedData.region,+ accessKeyId: validatedData.accessKeyId || null,+ secretAccessKey: validatedData.secretAccessKey ?? null,+ prefix: validatedData.prefix,+ exportFrequency: validatedData.exportFrequency,+ enabled: validatedData.enabled,+ forcePathStyle: validatedData.forcePathStyle,+ fileType: validatedData.fileType,+ exportMode: validatedData.exportMode,+ exportStartDate: validatedData.exportStartDate ?? null,+ },});// Transform to API response format, exclude secretAccessKey