Skip to content

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

feat(batch-exports): mint fresh download URLs on the exports page (LFE-14552) (#15536)

Steffen Schmitz41ff45bcf2c6
diff --git a/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
index 68dbb89b33..8ded28ebe2 100644
--- a/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
+++ b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx
@@ -19,6 +19,7 @@ interface BatchExportSuccessTemplateProps {
receiverEmail: string;
downloadLink: string;
batchExportName: string;
+ downloadWindowHours: number;
}
export const BatchExportSuccessEmailTemplate = ({
@@ -26,6 +27,7 @@ export const BatchExportSuccessEmailTemplate = ({
downloadLink,
userName,
batchExportName,
+ downloadWindowHours,
}: BatchExportSuccessTemplateProps) => {
const previewText = `Download your data export from Langfuse`;
@@ -54,7 +56,9 @@ export const BatchExportSuccessEmailTemplate = ({
<Text className="text-sm leading-6 text-black">
Your data export{" "}
<span className="font-mono">{batchExportName}</span> is ready to
- download. The download link is valid for a few hours.
+ download. The download is available for the next{" "}
+ {downloadWindowHours}{" "}
+ {downloadWindowHours === 1 ? "hour" : "hours"}.
</Text>
<Text className="text-sm leading-6 text-black">
Please note data exports do not reflect custom column ordering or
diff --git a/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts b/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts
index 05068a4cec..e0bc9c085e 100644
--- a/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts
+++ b/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts
@@ -12,6 +12,7 @@ type SendBatchExportSuccessParams = {
downloadLink: string;
userName: string;
batchExportName: string;
+ downloadWindowHours: number;
};
export const sendBatchExportSuccessEmail = async ({
@@ -20,6 +21,7 @@ export const sendBatchExportSuccessEmail = async ({
downloadLink,
userName,
batchExportName,
+ downloadWindowHours,
}: SendBatchExportSuccessParams) => {
if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {
logger.error("Missing environment variables for sending email.");
@@ -34,6 +36,7 @@ export const sendBatchExportSuccessEmail = async ({
downloadLink,
userName,
batchExportName,
+ downloadWindowHours,
}),
);
diff --git a/web/src/__tests__/server/unit/batchExportFileKey.servertest.ts b/web/src/__tests__/server/unit/batchExportFileKey.servertest.ts
new file mode 100644
index 0000000000..f87b024f92
--- /dev/null
+++ b/web/src/__tests__/server/unit/batchExportFileKey.servertest.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from "vitest";
+
+import { parseBatchExportFileKeyFromUrl } from "@/src/features/batch-exports/server/batchExportFileKey";
+
+describe("parseBatchExportFileKeyFromUrl", () => {
+ const key = "exports/1753699200000-lf-traces-export-cmproj123.csv";
+
+ it("parses virtual-hosted-style AWS URLs", () => {
+ const url = `https://my-bucket.s3.eu-west-1.amazonaws.com/${key}?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Expires=86400&X-Amz-Signature=abc`;
+ expect(parseBatchExportFileKeyFromUrl(url, "my-bucket")).toBe(key);
+ });
+
+ it("parses path-style URLs (MinIO / forcePathStyle)", () => {
+ const url = `http://localhost:9090/langfuse/${key}?X-Amz-Signature=abc`;
+ expect(parseBatchExportFileKeyFromUrl(url, "langfuse")).toBe(key);
+ });
+
+ it("parses GCS-style URLs where the bucket is the first path segment", () => {
+ const url = `https://storage.googleapis.com/my-bucket/${key}?X-Goog-Signature=abc`;
+ expect(parseBatchExportFileKeyFromUrl(url, "my-bucket")).toBe(key);
+ });
+
+ it("parses Azure-style URLs where the container is the first path segment", () => {
+ const url = `https://myaccount.blob.core.windows.net/my-container/${key}?sv=2023-01-01&sig=abc`;
+ expect(parseBatchExportFileKeyFromUrl(url, "my-container")).toBe(key);
+ });
+
+ it("does not strip a path prefix that merely resembles the bucket name", () => {
+ const url = `https://langfuse.s3.amazonaws.com/langfuse-exports/file.csv`;
+ expect(parseBatchExportFileKeyFromUrl(url, "langfuse")).toBe(
+ "langfuse-exports/file.csv",
+ );
+ });
+
+ it("decodes percent-encoded characters in the key", () => {
+ const url = `https://my-bucket.s3.amazonaws.com/exports/123-lf-sessions%20test.csv`;
+ expect(parseBatchExportFileKeyFromUrl(url, "my-bucket")).toBe(
+ "exports/123-lf-sessions test.csv",
+ );
+ });
+
+ it("returns null for malformed URLs", () => {
+ expect(parseBatchExportFileKeyFromUrl("not a url", "bucket")).toBeNull();
+ });
+
+ it("returns null for URLs without a path", () => {
+ expect(
+ parseBatchExportFileKeyFromUrl(
+ "https://my-bucket.s3.amazonaws.com/",
+ "my-bucket",
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 1fab50b645..87dfd85471 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -373,6 +373,18 @@ export const env = createEnv({
LANGFUSE_S3_MEDIA_UPLOAD_SSE: z.enum(["AES256", "aws:kms"]).optional(),
LANGFUSE_S3_MEDIA_UPLOAD_SSE_KMS_KEY_ID: z.string().optional(),
+ // S3 batch export bucket; must match the worker's config so the exports
+ // page can mint fresh short-lived download URLs for stored export files
+ LANGFUSE_S3_BATCH_EXPORT_BUCKET: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_REGION: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_ENDPOINT: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_EXTERNAL_ENDPOINT: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_ACCESS_KEY_ID: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY: z.string().optional(),
+ LANGFUSE_S3_BATCH_EXPORT_FORCE_PATH_STYLE: z
+ .enum(["true", "false"])
+ .default("false"),
+
LANGFUSE_ALLOWED_ORGANIZATION_CREATORS: z
.string()
.optional()
@@ -823,6 +835,21 @@ export const env = createEnv({
LANGFUSE_S3_MEDIA_UPLOAD_SSE: process.env.LANGFUSE_S3_MEDIA_UPLOAD_SSE,
LANGFUSE_S3_MEDIA_UPLOAD_SSE_KMS_KEY_ID:
process.env.LANGFUSE_S3_MEDIA_UPLOAD_SSE_KMS_KEY_ID,
+ // S3 batch export
+ LANGFUSE_S3_BATCH_EXPORT_BUCKET:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_BUCKET,
+ LANGFUSE_S3_BATCH_EXPORT_REGION:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_REGION,
+ LANGFUSE_S3_BATCH_EXPORT_ENDPOINT:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_ENDPOINT,
+ LANGFUSE_S3_BATCH_EXPORT_EXTERNAL_ENDPOINT:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_EXTERNAL_ENDPOINT,
+ LANGFUSE_S3_BATCH_EXPORT_ACCESS_KEY_ID:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_ACCESS_KEY_ID,
+ LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY,
+ LANGFUSE_S3_BATCH_EXPORT_FORCE_PATH_STYLE:
+ process.env.LANGFUSE_S3_BATCH_EXPORT_FORCE_PATH_STYLE,
// Worker
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
diff --git a/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx b/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx
index eb1bfdacfb..c9080098ec 100644
--- a/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx
+++ b/web/src/features/batch-exports/components/BatchExportsSettingsPage.tsx
@@ -16,8 +16,8 @@ export function BatchExportsSettingsPage(props: { projectId: string }) {
<p className="mb-4 text-sm">
Export large datasets in your preferred format via the export buttons
across Langfuse. Exports are processed asynchronously and remain
- available for download for one hour. You will receive an email
- notification once your export is ready.
+ available for download until the expiry shown for each export below. You
+ will receive an email notification once your export is ready.
</p>
{hasAccess ? (
<SettingsTableCard>
diff --git a/web/src/features/batch-exports/components/BatchExportsTable.tsx b/web/src/features/batch-exports/components/BatchExportsTable.tsx
index e0d920498b..538aade80e 100644
--- a/web/src/features/batch-exports/components/BatchExportsTable.tsx
+++ b/web/src/features/batch-exports/components/BatchExportsTable.tsx
@@ -1,8 +1,8 @@
import { DataTable } from "@/src/components/table/data-table";
import { type LangfuseColumnDef } from "@/src/components/table/types";
-import { api } from "@/src/utils/api";
+import { api, type RouterOutputs } from "@/src/utils/api";
import { safeExtract } from "@/src/utils/map-utils";
-import { type BatchExport } from "@langfuse/shared";
+import { formatDistanceToNow } from "date-fns";
import { StatusBadge } from "@/src/components/ui/StatusBadge/StatusBadge";
import { NumberParam, useQueryParams, withDefault } from "use-query-params";
import { ActionButton } from "@/src/components/ActionButton";
@@ -28,6 +28,8 @@ import {
import { useState } from "react";
import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+type BatchExportRow = RouterOutputs["batchExport"]["all"]["exports"][number];
+
export function BatchExportsTable(props: { projectId: string }) {
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),
@@ -35,6 +37,9 @@ export function BatchExportsTable(props: { projectId: string }) {
});
const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
const [selectedExportId, setSelectedExportId] = useState<string | null>(null);
+ // Per-row pending downloads: a shared mutation with a single scalar id
+ // would cross-wire spinners when two rows are clicked in quick succession.
+ const [downloadingIds, setDownloadingIds] = useState<Set<string>>(new Set());
const batchExports = api.batchExport.all.useQuery({
projectId: props.projectId,
@@ -50,6 +55,8 @@ export function BatchExportsTable(props: { projectId: string }) {
},
});
+ const downloadBatchExport = api.batchExport.downloadUrl.useMutation();
+
const hasAccess = useHasProjectAccess({
projectId: props.projectId,
scope: "batchExports:create",
@@ -63,7 +70,7 @@ export function BatchExportsTable(props: { projectId: string }) {
size: 200,
cell: ({ row }) => {
const name = row.getValue("name") as string;
- const { createdAt, finishedAt } = row.original;
+ const { createdAt, finishedAt, expiresAt } = row.original;
return (
<div className="flex items-center gap-2">
<span className="whitespace-break-spaces">{name}</span>
@@ -79,6 +86,10 @@ export function BatchExportsTable(props: { projectId: string }) {
Finished:{" "}
{finishedAt ? new Date(finishedAt).toLocaleString() : "-"}
</div>
+ <div>
+ Download expires:{" "}
+ {expiresAt ? new Date(expiresAt).toLocaleString() : "-"}
+ </div>
</div>
</TooltipContent>
</Tooltip>
@@ -92,28 +103,137 @@ export function BatchExportsTable(props: { projectId: string }) {
id: "status",
header: "Status",
size: 90,
- cell: (row) => {
- const status = row.getValue() as string;
- return <StatusBadge type={status.toLowerCase()} />;
+ cell: ({ row }) => {
+ const { status, log } = row.original;
+ const badge = <StatusBadge type={status.toLowerCase()} />;
+ // The log only exists on failed exports (worker-written, user-facing
+ // error message); surface it on the badge instead of a dedicated
+ // column that is empty for every successful row.
+ if (!log) {
+ return badge;
+ }
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger>{badge}</TooltipTrigger>
+ <TooltipContent className="max-w-md whitespace-pre-wrap">
+ {log}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ );
},
},
{
- accessorKey: "url",
- id: "url",
- header: "Download URL",
+ accessorKey: "isDownloadable",
+ id: "action",
+ header: "Action",
size: 130,
- cell: (info) => {
- const url = info.getValue() as string | null;
- if (!url) {
- return null;
+ // One state-dependent action per row: Cancel while queued/processing,
+ // Download (or Expired) once completed — the states never coexist.
+ cell: ({ row }) => {
+ const { id, status, isExpired, isDownloadable } = row.original;
+ if (isDownloadable) {
+ return (
+ <ActionButton
+ icon={<DownloadIcon size={16} />}
+ size="sm"
+ loading={downloadingIds.has(id)}
+ onClick={() => {
+ setDownloadingIds((prev) => new Set(prev).add(id));
+ downloadBatchExport.mutate(
+ { projectId: props.projectId, batchExportId: id },
+ {
+ // Content-Disposition is `attachment`, so assigning the
+ // fresh URL triggers a download without leaving the page.
+ onSuccess: (data) => {
+ window.location.href = data.url;
+ },
+ onSettled: () =>
+ setDownloadingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(id);
+ return next;
+ }),
+ },
+ );
+ }}
+ >
+ Download
+ </ActionButton>
+ );
}
- if (url === "expired") {
+ if (status === "COMPLETED" && isExpired) {
return <span className="text-muted-foreground">Expired</span>;
}
+ if (status === "QUEUED" || status === "PROCESSING") {
+ return (
+ <AlertDialog
+ open={cancelDialogOpen && selectedExportId === id}
+ onOpenChange={(open) => {
+ if (!open) {
+ setCancelDialogOpen(false);
+ setSelectedExportId(null);
+ }
+ }}
+ >
+ <AlertDialogTrigger asChild>
+ <ActionButton
+ hasAccess={hasAccess}
+ size="sm"
+ onClick={() => {
+ setSelectedExportId(id);
+ setCancelDialogOpen(true);
+ }}
+ >
+ Cancel
+ </ActionButton>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Cancel batch export?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to cancel this batch export? This
+ action cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>No, keep it</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ cancelBatchExport.mutate({
+ projectId: props.projectId,
+ batchExportId: id,
+ });
+ }}
+ >
+ Yes, cancel export
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+ }
+ return null;
+ },
+ },
+ {
+ accessorKey: "expiresAt",
+ id: "expiresAt",
+ header: "Expires",
+ size: 130,
+ cell: ({ row }) => {
+ const { status, expiresAt, isExpired } = row.original;
+ // The Action column already reads "Expired" for lapsed exports; a
+ // "how long ago" timestamp adds nothing, so show the countdown only
+ // while the download is still available.
+ if (status !== "COMPLETED" || !expiresAt || isExpired) {
+ return null;
+ }
return (
- <ActionButton href={url} icon={<DownloadIcon size={16} />} size="sm">
- Download
- </ActionButton>
+ <span title={new Date(expiresAt).toLocaleString()}>
+ {formatDistanceToNow(new Date(expiresAt), { addSuffix: true })}
+ </span>
);
},
},
@@ -146,79 +266,7 @@ export function BatchExportsTable(props: { projectId: string }) {
);
},
},
- {
- accessorKey: "log",
- id: "log",
- header: "Log",
- size: 300,
- cell: (row) => {
- const log = row.getValue() as string | null;
- return log ?? null;
- },
- },
- {
- accessorKey: "actions",
- id: "actions",
- header: "Actions",
- size: 100,
- cell: ({ row }) => {
- const id = row.original.id;
- const status = row.getValue("status") as string;
-
- // Only show cancel button for queued or processing exports
- if (status !== "QUEUED" && status !== "PROCESSING") {
- return null;
- }
-
- return (
- <AlertDialog
- open={cancelDialogOpen && selectedExportId === id}
- onOpenChange={(open) => {
- if (!open) {
- setCancelDialogOpen(false);
- setSelectedExportId(null);
- }
- }}
- >
- <AlertDialogTrigger asChild>
- <ActionButton
- hasAccess={hasAccess}
- size="sm"
- onClick={() => {
- setSelectedExportId(id);
- setCancelDialogOpen(true);
- }}
- >
- Cancel
- </ActionButton>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Cancel batch export?</AlertDialogTitle>
- <AlertDialogDescription>
- Are you sure you want to cancel this batch export? This action
- cannot be undone.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>No, keep it</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- cancelBatchExport.mutate({
- projectId: props.projectId,
- batchExportId: id,
- });
- }}
- >
- Yes, cancel export
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
- },
- },
- ] as LangfuseColumnDef<BatchExport>[];
+ ] as LangfuseColumnDef<BatchExportRow>[];
return (
<>
diff --git a/web/src/features/batch-exports/server/batchExport.ts b/web/src/features/batch-exports/server/batchExport.ts
index 37773e184a..d4d2b98fb6 100644
--- a/web/src/features/batch-exports/server/batchExport.ts
+++ b/web/src/features/batch-exports/server/batchExport.ts
@@ -1,4 +1,7 @@
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { env } from "@/src/env.mjs";
+import { parseBatchExportFileKeyFromUrl } from "@/src/features/batch-exports/server/batchExportFileKey";
+import { getBatchExportStorageServiceClient } from "@/src/features/batch-exports/server/getBatchExportStorageClient";
import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import {
@@ -9,6 +12,8 @@ import {
BatchExportStatus,
BatchExportTableName,
CreateBatchExportSchema,
+ InvalidRequestError,
+ LangfuseNotFoundError,
paginationZod,
} from "@langfuse/shared";
import {
@@ -20,6 +25,26 @@ import { TRPCError } from "@trpc/server";
import { z } from "zod";
import { assertLegacyTracingIoSearchCanCreateBatchJob } from "@/src/features/traces/server/legacyIoSearch";
+// Fallback for legacy rows that predate the worker stamping expiresAt;
+// matches the worker's BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS default.
+const LEGACY_DOWNLOAD_WINDOW_MS = 24 * 60 * 60 * 1000;
+
+// The fresh URL only needs to cover the click-through: object stores check
+// signature expiry when the request starts, not while the download streams.
+const FRESH_DOWNLOAD_URL_TTL_SECONDS = 10 * 60;
+
+const isDownloadWindowExpired = (batchExport: {
+ finishedAt: Date | null;
+ expiresAt: Date | null;
+}): boolean => {
+ const expiresAt =
+ batchExport.expiresAt ??
+ (batchExport.finishedAt
+ ? new Date(batchExport.finishedAt.getTime() + LEGACY_DOWNLOAD_WINDOW_MS)
+ : null);
+ return expiresAt !== null && expiresAt < new Date();
+};
+
export const batchExportRouter = createTRPCRouter({
create: protectedProjectProcedure
.input(CreateBatchExportSchema)
@@ -126,6 +151,75 @@ export const batchExportRouter = createTRPCRouter({
data: { status: BatchExportStatus.CANCELLED },
});
}),
+ downloadUrl: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ batchExportId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "batchExports:read",
+ });
+
+ const batchExport = await ctx.prisma.batchExport.findFirst({
+ where: { id: input.batchExportId, projectId: input.projectId },
+ });
+ if (!batchExport) {
+ throw new LangfuseNotFoundError("Batch export not found");
+ }
+ if (
+ batchExport.status !== BatchExportStatus.COMPLETED ||
+ !batchExport.url
+ ) {
+ throw new InvalidRequestError("Batch export is not ready for download");
+ }
+ if (isDownloadWindowExpired(batchExport)) {
+ throw new InvalidRequestError(
+ "The download window for this batch export has expired",
+ );
+ }
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "batchExport",
+ resourceId: batchExport.id,
+ projectId: input.projectId,
+ action: "download",
+ });
+
+ // The URL stored at export completion is signed with the worker's
+ // credentials; when those are temporary (e.g. IAM role sessions) the
+ // stored URL dies with the session, long before expiresAt. Re-sign a
+ // fresh short-lived URL from the object key instead.
+ const bucketName = env.LANGFUSE_S3_BATCH_EXPORT_BUCKET;
+ if (bucketName) {
+ const fileKey = parseBatchExportFileKeyFromUrl(
+ batchExport.url,
+ bucketName,
+ );
+ if (fileKey) {
+ // asAttachment must be explicit: S3 defaults it to true, but GCS
+ // and Azure don't — and the client navigates to this URL in the
+ // same tab, so without a Content-Disposition header the browser
+ // would render the export instead of downloading it.
+ const url = await getBatchExportStorageServiceClient(
+ bucketName,
+ ).getSignedUrl(fileKey, FRESH_DOWNLOAD_URL_TTL_SECONDS, true);
+ return { url };
+ }
+ logger.warn(
+ `[BATCH EXPORT] Could not parse file key from stored URL for batch export ${batchExport.id}, falling back to stored URL`,
+ );
+ }
+
+ // Fallback when the web container has no batch export bucket configured:
+ // the stored URL, valid for as long as its signing credentials allow.
+ return { url: batchExport.url };
+ }),
all: protectedProjectProcedure
.input(
z.object({
@@ -187,20 +281,15 @@ export const batchExportRouter = createTRPCRouter({
const userMap = new Map(users.map((u) => [u.id, u]));
const exportsWithExpiration = exports.map((e) => {
- const { finishedAt, url, ...rest } = e;
-
- let isExpired = false;
- if (finishedAt) {
- const finishTime = new Date(finishedAt).getTime();
- const now = new Date().getTime();
- const oneHourInMs = 60 * 60 * 1000;
- isExpired = now - finishTime > oneHourInMs;
- }
+ const { url, ...rest } = e;
return {
...rest,
- finishedAt,
- url: isExpired ? "expired" : url,
+ isExpired: isDownloadWindowExpired(e),
+ isDownloadable:
+ e.status === BatchExportStatus.COMPLETED &&
+ Boolean(url) &&
+ !isDownloadWindowExpired(e),
user: userMap.get(e.userId) ?? null,
};
});
diff --git a/web/src/features/batch-exports/server/batchExportFileKey.ts b/web/src/features/batch-exports/server/batchExportFileKey.ts
new file mode 100644
index 0000000000..b528ef1b32
--- /dev/null
+++ b/web/src/features/batch-exports/server/batchExportFileKey.ts
@@ -0,0 +1,28 @@
+/**
+ * Extracts the storage object key from a stored presigned download URL.
+ *
+ * Completed batch exports persist a presigned URL (`batch_exports.url`), not
+ * the object key. Presigned URLs die with the signing credentials — on AWS a
+ * URL signed with role-session credentials expires with the session (hours),
+ * long before the 24h download window — so the exports page re-signs a fresh
+ * URL on demand and needs the key back out of the stored URL.
+ *
+ * Handles virtual-hosted-style URLs (`https://bucket.s3.../key`) where the
+ * path is the key, and path-style / GCS / Azure URLs (`https://host/bucket/key`)
+ * where the bucket or container name is the first path segment.
+ */
+export function parseBatchExportFileKeyFromUrl(
+ storedUrl: string,
+ bucketName: string,
+): string | null {
+ try {
+ const url = new URL(storedUrl);
+ const path = decodeURIComponent(url.pathname).replace(/^\//, "");
+ if (path.startsWith(`${bucketName}/`)) {
+ return path.slice(bucketName.length + 1) || null;
+ }
+ return path || null;
+ } catch {
+ return null;
+ }
+}
diff --git a/web/src/features/batch-exports/server/getBatchExportStorageClient.ts b/web/src/features/batch-exports/server/getBatchExportStorageClient.ts
new file mode 100644
index 0000000000..c7e7058bef
--- /dev/null
+++ b/web/src/features/batch-exports/server/getBatchExportStorageClient.ts
@@ -0,0 +1,26 @@
+import { env } from "@/src/env.mjs";
+import {
+ type StorageService,
+ StorageServiceFactory,
+} from "@langfuse/shared/src/server";
+
+let batchExportStorageServiceClient: StorageService;
+
+export const getBatchExportStorageServiceClient = (
+ bucketName: string,
+): StorageService => {
+ if (!batchExportStorageServiceClient) {
+ batchExportStorageServiceClient = StorageServiceFactory.getInstance({
+ bucketName,
+ accessKeyId: env.LANGFUSE_S3_BATCH_EXPORT_ACCESS_KEY_ID,
+ secretAccessKey: env.LANGFUSE_S3_BATCH_EXPORT_SECRET_ACCESS_KEY,
+ endpoint: env.LANGFUSE_S3_BATCH_EXPORT_ENDPOINT,
+ externalEndpoint: env.LANGFUSE_S3_BATCH_EXPORT_EXTERNAL_ENDPOINT,
+ region: env.LANGFUSE_S3_BATCH_EXPORT_REGION,
+ forcePathStyle: env.LANGFUSE_S3_BATCH_EXPORT_FORCE_PATH_STYLE === "true",
+ awsSse: undefined,
+ awsSseKmsKeyId: undefined,
+ });
+ }
+ return batchExportStorageServiceClient;
+};
diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.ts
index 78d89e4b82..6116c25726 100644
--- a/worker/src/features/batchExport/handleBatchExportJob.ts
+++ b/worker/src/features/batchExport/handleBatchExportJob.ts
@@ -271,9 +271,14 @@ export const handleBatchExportJob = async (
partSizeBytes: env.BATCH_EXPORT_S3_PART_SIZE_MIB * 1024 * 1024,
});
+ // asAttachment must be explicit: S3 defaults it to true, but GCS and Azure
+ // don't — and the web tier's downloadUrl fallback returns this stored URL
+ // for same-tab navigation, so without a Content-Disposition header the
+ // browser would render the export instead of downloading it.
const signedUrl = await storageService.getSignedUrl(
fileName,
expiresInSeconds,
+ true,
);
logger.info(`[BATCH EXPORT] Batch export file ${fileName} uploaded`);
@@ -300,12 +305,20 @@ export const handleBatchExportJob = async (
});
if (user?.email) {
+ // Link to the exports page rather than the signed URL: the page mints a
+ // fresh download URL on click, while a URL signed with temporary
+ // credentials (e.g. IAM role sessions) can die well before expiresAt.
+ const exportsPageUrl = env.NEXTAUTH_URL
+ ? `${env.NEXTAUTH_URL}/project/${projectId}/settings/exports`
+ : undefined;
+
await sendBatchExportSuccessEmail({
env,
receiverEmail: user.email,
- downloadLink: signedUrl,
+ downloadLink: exportsPageUrl ?? signedUrl,
userName: user?.name || "",
batchExportName: jobDetails.name,
+ downloadWindowHours: env.BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS,
});
logger.info(