🪢 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: adds exports to sessions table (#2360)
Hassieb Pakzadf8080ca04cdd
diff --git a/ee/src/sso/index.ts b/ee/src/sso/index.tsindex 986555df7f..b76a348596 100644--- a/ee/src/sso/index.ts+++ b/ee/src/sso/index.ts@@ -11,7 +11,7 @@ import { encrypt, decrypt } from "@langfuse/shared/encryption";import { SsoProviderSchema } from "./types";import { type NextApiRequest, type NextApiResponse } from "next";import { env } from "../env";-import { CustomSSOProvider } from "@langfuse/shared/src/server/auth";+import { CustomSSOProvider } from "@langfuse/shared/src/server";// Local cache for SSO configurationslet cachedSsoConfigs: {diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 2d7d7bb77b..970815f7fa 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -17,9 +17,9 @@"import": "./dist/src/db.js","require": "./dist/src/db.js"},- "./src/server/auth": {- "import": "./dist/src/server/auth.js",- "require": "./dist/src/server/auth.js"+ "./src/server": {+ "import": "./dist/src/server/index.js",+ "require": "./dist/src/server/index.js"},"./encryption": {"import": "./dist/src/encryption/index.js",@@ -44,16 +44,22 @@"seed": "ts-node -r tsconfig-paths/register -r dotenv/config --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"},"dependencies": {+ "@aws-sdk/client-s3": "^3.550.0",+ "@aws-sdk/lib-storage": "^3.568.0",+ "@aws-sdk/s3-request-presigner": "^3.554.0","@langchain/anthropic": "^0.1.21","@langchain/core": "^0.1.61","@langchain/openai": "^0.0.33","@prisma/client": "^5.13.0",+ "@react-email/components": "^0.0.19",+ "@react-email/render": "^0.0.15","@types/bcryptjs": "^2.4.6","bcryptjs": "^2.4.3","kysely": "^0.27.3","langchain": "^0.1.36","lodash": "^4.17.21","next-auth": "^4.24.7",+ "nodemailer": "^6.9.13","prisma-extension-kysely": "^2.1.0","zod": "^3.22.4","zod-to-json-schema": "^3.22.5"@@ -63,6 +69,7 @@"@repo/typescript-config": "*","@types/lodash": "^4.17.5","@types/node": "^20.11.29",+ "@types/nodemailer": "^6.4.15","@types/pg": "^8.11.6","@types/uuid": "^9.0.8","@typescript-eslint/parser": "^7.12.0",@@ -80,5 +87,9 @@"tsc-watch": "^6.2.0","typescript": "^5.4.5","vitest": "^1.5.3"+ },+ "peerDependencies": {+ "@types/react": "^18.2.79",+ "react": "^18.0.0"}}diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 52ea5c39a9..b3466ab9cc 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -98,6 +98,21 @@ export type AuditLog = {before: string | null;after: string | null;};+export type BatchExport = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ user_id: string;+ finished_at: Timestamp | null;+ expires_at: Timestamp | null;+ name: string;+ status: string;+ query: unknown;+ format: string;+ url: string | null;+ log: string | null;+};export type CronJobs = {name: string;last_run: Timestamp | null;@@ -442,6 +457,7 @@ export type DB = {Account: Account;api_keys: ApiKey;audit_logs: AuditLog;+ batch_exports: BatchExport;cron_jobs: CronJobs;dataset_items: DatasetItem;dataset_run_items: DatasetRunItems;diff --git a/packages/shared/prisma/migrations/20240618134129_add_batch_exports_table/migration.sql b/packages/shared/prisma/migrations/20240618134129_add_batch_exports_table/migration.sqlnew file mode 100644index 0000000000..880f6e8aca--- /dev/null+++ b/packages/shared/prisma/migrations/20240618134129_add_batch_exports_table/migration.sql@@ -0,0 +1,27 @@+-- CreateTable+CREATE TABLE "batch_exports" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "user_id" TEXT NOT NULL,+ "finished_at" TIMESTAMP(3),+ "expires_at" TIMESTAMP(3),+ "name" TEXT NOT NULL,+ "status" TEXT NOT NULL,+ "query" JSONB NOT NULL,+ "format" TEXT NOT NULL,+ "url" TEXT,+ "log" TEXT,++ CONSTRAINT "batch_exports_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "batch_exports_project_id_user_id_idx" ON "batch_exports"("project_id", "user_id");++-- CreateIndex+CREATE INDEX "batch_exports_status_idx" ON "batch_exports"("status");++-- AddForeignKey+ALTER TABLE "batch_exports" ADD CONSTRAINT "batch_exports_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.prismaindex 4220a20201..592b636a65 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -115,6 +115,7 @@ model Project {PosthogIntegration PosthogIntegration[]Score Score[]scoreConfig ScoreConfig[]+ BatchExport BatchExport[]@@map("projects")}@@ -781,3 +782,27 @@ model PosthogIntegration {@@index([projectId])@@map("posthog_integrations")}++model BatchExport {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ userId String @map("user_id")++ finishedAt DateTime? @map("finished_at")+ expiresAt DateTime? @map("expires_at")++ name String+ status String+ query Json+ format String+ url String?+ log String?++ @@index([projectId, userId])+ @@index([status])+ @@map("batch_exports")+}diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 010c7db3f4..512081c18c 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -12,7 +12,7 @@ import { parseArgs } from "node:util";import { chunk } from "lodash";import { v4 } from "uuid";import { ModelUsageUnit } from "../src";-import { getDisplaySecretKey, hashSecretKey } from "../src/server/auth";+import { getDisplaySecretKey, hashSecretKey } from "../src/server";import { encrypt } from "../src/encryption";const LOAD_TRACE_VOLUME = 10_000;diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.tsnew file mode 100644index 0000000000..7bc51eecb9--- /dev/null+++ b/packages/shared/src/features/batchExport/types.ts@@ -0,0 +1,73 @@+import z from "zod";++import { BatchExport } from "@prisma/client";++import { singleFilter } from "../../interfaces/filters";+import { orderBy } from "../../interfaces/orderBy";++export enum BatchExportStatus {+ QUEUED = "QUEUED",+ PROCESSING = "PROCESSING",+ COMPLETED = "COMPLETED",+ FAILED = "FAILED",+}++export enum BatchExportFileFormat {+ JSON = "JSON",+ CSV = "CSV",+}++export enum BatchExportTableName {+ Sessions = "sessions",+}++export const exportOptions: Record<+ BatchExportFileFormat,+ {+ label: string;+ extension: string;+ fileType: string;+ }+> = {+ CSV: { label: "CSV", extension: "csv", fileType: "text/csv" },+ JSON: { label: "JSON", extension: "json", fileType: "application/json" },+} as const;++export const BatchExportQuerySchema = z.object({+ tableName: z.nativeEnum(BatchExportTableName),+ filter: z.array(singleFilter).nullable(),+ orderBy,+ limit: z.number().optional(),+ page: z.number().optional(),+});++export type BatchExportQueryType = z.infer<typeof BatchExportQuerySchema>;++export const CreateBatchExportSchema = z.object({+ projectId: z.string(),+ name: z.string(),+ query: BatchExportQuerySchema,+ format: z.nativeEnum(BatchExportFileFormat),+});++export const BatchExportSchema = z.object({+ id: z.string(),+ createdAt: z.date(),+ updatedAt: z.date(),+ projectId: z.string(),+ userId: z.string(),+ finishedAt: z.date().nullable(),+ expiresAt: z.date().nullable(),+ name: z.string(),+ status: z.nativeEnum(BatchExportStatus),+ query: BatchExportQuerySchema,+ format: z.nativeEnum(BatchExportFileFormat),+ url: z.string().nullable(),+ log: z.string().nullable(),+});++// Ensure that zod type matches the Prisma type+export type BatchExportType =+ z.infer<typeof BatchExportSchema> extends BatchExport+ ? z.infer<typeof BatchExportSchema>+ : never;diff --git a/packages/shared/src/filterToPrisma.ts b/packages/shared/src/filterToPrisma.tsindex c651be33e0..24eed028e9 100644--- a/packages/shared/src/filterToPrisma.ts+++ b/packages/shared/src/filterToPrisma.ts@@ -1,8 +1,5 @@import { Prisma } from "@prisma/client";-import {- ColumnDefinition,- type TableNames,-} from "./interfaces/tableDefinition";+import { ColumnDefinition, type TableNames } from "./tableDefinitions";import { FilterState } from "./types";import { filterOperators } from "./interfaces/filters";diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 022334df8e..706b38c611 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1,11 +1,12 @@export * from "./constants";+export * from "./queries";export * from "./queues";-export * from "./interfaces/exportTypes";export * from "./interfaces/filters";export * from "./interfaces/orderBy";-export * from "./interfaces/tableDefinition";+export * from "./tableDefinitions";export * from "./types";export * from "./filterToPrisma";+export * from "./orderByToPrisma";export * from "./tracesTable";export * from "./server/auth";export * from "./observationsTable";@@ -20,6 +21,7 @@ export * from "./server/llm/fetchLLMCompletion";// evalsexport * from "./features/evals/types";+export * from "./features/batchExport/types";// annotationexport * from "./features/annotation/types";diff --git a/packages/shared/src/interfaces/exportTypes.ts b/packages/shared/src/interfaces/exportTypes.tsdeleted file mode 100644index ae69d37487..0000000000--- a/packages/shared/src/interfaces/exportTypes.ts+++ /dev/null@@ -1,19 +0,0 @@-export const exportFileFormats = ["CSV", "JSON", "OPENAI-JSONL"] as const;-export type ExportFileFormats = (typeof exportFileFormats)[number];--export const exportOptions: Record<- ExportFileFormats,- {- label: string;- extension: string;- fileType: string;- }-> = {- CSV: { label: "CSV", extension: "csv", fileType: "text/csv" },- JSON: { label: "JSON", extension: "json", fileType: "application/json" },- "OPENAI-JSONL": {- label: "OpenAI JSONL (fine-tuning)",- extension: "jsonl",- fileType: "application/json",- },-} as const;diff --git a/packages/shared/src/interfaces/orderBy.ts b/packages/shared/src/interfaces/orderBy.tsindex 9080c0f58d..31b1e320ad 100644--- a/packages/shared/src/interfaces/orderBy.ts+++ b/packages/shared/src/interfaces/orderBy.ts@@ -6,3 +6,5 @@ export const orderBy = zorder: z.enum(["ASC", "DESC"]),}).nullable();++export type OrderByState = z.infer<typeof orderBy>;diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.tsindex 44a85804f1..dfe1097e2e 100644--- a/packages/shared/src/observationsTable.ts+++ b/packages/shared/src/observationsTable.ts@@ -2,7 +2,7 @@ import { ObservationLevel } from "@prisma/client";import {type OptionsDefinition,type ColumnDefinition,-} from "./interfaces/tableDefinition";+} from "./tableDefinitions/types";// to be used server sideexport const observationsTableCols: ColumnDefinition[] = [diff --git a/web/src/features/orderBy/server/orderByToPrisma.ts b/packages/shared/src/orderByToPrisma.tssimilarity index 79%rename from web/src/features/orderBy/server/orderByToPrisma.tsrename to packages/shared/src/orderByToPrisma.tsindex ac7e0e370e..4c654f105d 100644--- a/web/src/features/orderBy/server/orderByToPrisma.ts+++ b/packages/shared/src/orderByToPrisma.ts@@ -1,8 +1,10 @@-import { type OrderByState } from "@/src/features/orderBy/types";-import { type ColumnDefinition } from "@langfuse/shared";-import { Prisma } from "@langfuse/shared";import { z } from "zod";+import { Prisma } from "@prisma/client";++import type { ColumnDefinition } from "./tableDefinitions/types";+import type { OrderByState } from "./interfaces/orderBy";+/*** Convert orderBy to SQL ORDER BY clause* @param orderBy orderBy state@@ -11,7 +13,7 @@ import { z } from "zod";*/export function orderByToPrismaSql(orderBy: OrderByState,- tableColumns: ColumnDefinition[],+ tableColumns: ColumnDefinition[]): Prisma.Sql {if (!orderBy) {return Prisma.sql`ORDER BY t.timestamp DESC NULLS LAST`;@@ -20,7 +22,7 @@ export function orderByToPrismaSql(const col = tableColumns.find(// TODO: Only use id instead of name.// It's less error-prone & decouples data fetching from the human-readable UI labels- (c) => c.name === orderBy.column || c.id === orderBy.column,+ (c) => c.name === orderBy.column || c.id === orderBy.column);if (!col) {@@ -38,6 +40,6 @@ export function orderByToPrismaSql(// Both column and order are safe, can use raw SQLreturn Prisma.raw(- `ORDER BY ${col.internal} ${order.data} ${orderBy.order === "DESC" ? "NULLS LAST" : "NULLS FIRST"}`,+ `ORDER BY ${col.internal} ${order.data} ${orderBy.order === "DESC" ? "NULLS LAST" : "NULLS FIRST"}`);}diff --git a/packages/shared/src/queries/getSessionTableSQL.ts b/packages/shared/src/queries/getSessionTableSQL.tsnew file mode 100644index 0000000000..cd7e74dcc3--- /dev/null+++ b/packages/shared/src/queries/getSessionTableSQL.ts@@ -0,0 +1,88 @@+import { z } from "zod";++import { Prisma } from "@prisma/client";+import { tableColumnsToSqlFilterAndPrefix } from "../filterToPrisma";+import { singleFilter } from "../interfaces/filters";+import { orderBy } from "../interfaces/orderBy";+import { orderByToPrismaSql } from "../orderByToPrisma";+import { sessionsViewCols } from "../tableDefinitions/index";++const GetSessionTableSQLParamsSchema = z.object({+ projectId: z.string(),+ filter: z.array(singleFilter).nullable(),+ orderBy: orderBy,+ page: z.number(),+ limit: z.number(),+});+type GetSessionTableSQLParams = z.infer<typeof GetSessionTableSQLParamsSchema>;++export const getSessionTableSQL = (+ params: GetSessionTableSQLParams+): Prisma.Sql => {+ const { projectId, filter, orderBy, page, limit } =+ GetSessionTableSQLParamsSchema.parse(params);++ const filterCondition = tableColumnsToSqlFilterAndPrefix(+ filter ?? [],+ sessionsViewCols,+ "sessions"+ );+ const orderByCondition = orderByToPrismaSql(orderBy, sessionsViewCols);++ const sql = Prisma.sql`+ SELECT+ s.id,+ s. "created_at" AS "createdAt",+ s.bookmarked,+ s.public,+ t. "userIds",+ t. "countTraces",+ o. "sessionDuration",+ o. "totalCost" AS "totalCost",+ o. "inputCost" AS "inputCost",+ o. "outputCost" AS "outputCost",+ o. "promptTokens" AS "promptTokens",+ o. "completionTokens" AS "completionTokens",+ o. "totalTokens" AS "totalTokens",+ (count(*) OVER ())::int AS "totalCount"+ FROM+ trace_sessions AS s+ LEFT JOIN LATERAL (+ SELECT+ t.session_id,+ MAX(t. "timestamp") AS "max_timestamp",+ MIN(t. "timestamp") AS "min_timestamp",+ array_agg(t.id) AS "traceIds",+ array_agg(DISTINCT t.user_id) AS "userIds",+ count(t.id)::int AS "countTraces"+ FROM+ traces t+ WHERE+ t.project_id = ${projectId}+ AND t.session_id = s.id+ GROUP BY+ t.session_id) AS t ON TRUE+ LEFT JOIN LATERAL (+ SELECT+ EXTRACT(EPOCH FROM COALESCE(MAX(o. "end_time"), MAX(o. "start_time"), t. "max_timestamp")) - EXTRACT(EPOCH FROM COALESCE(MIN(o. "start_time"), t. "min_timestamp"))::double precision AS "sessionDuration",+ SUM(COALESCE(o. "calculated_input_cost", 0)) AS "inputCost",+ SUM(COALESCE(o. "calculated_output_cost", 0)) AS "outputCost",+ SUM(COALESCE(o. "calculated_total_cost", 0)) AS "totalCost",+ SUM(o.prompt_tokens) AS "promptTokens",+ SUM(o.completion_tokens) AS "completionTokens",+ SUM(o.total_tokens) AS "totalTokens"+ FROM+ observations_view o+ WHERE+ o.project_id = ${projectId}+ AND o.trace_id = ANY (t. "traceIds")) AS o ON TRUE+ WHERE+ s. "project_id" = ${projectId}+ ${filterCondition}+ ${orderByCondition}+ LIMIT ${limit}+ OFFSET ${page * limit}+ `;++ return sql;+};diff --git a/packages/shared/src/queries/index.ts b/packages/shared/src/queries/index.tsnew file mode 100644index 0000000000..ab169e6d41--- /dev/null+++ b/packages/shared/src/queries/index.ts@@ -0,0 +1 @@+export { getSessionTableSQL } from "./getSessionTableSQL";diff --git a/packages/shared/src/queues.ts b/packages/shared/src/queues.tsindex 034c51eff8..4662809111 100644--- a/packages/shared/src/queues.ts+++ b/packages/shared/src/queues.ts@@ -1,36 +1,75 @@import { z } from "zod";-export const TraceUpsertEvent = z.object({+export enum EventName {+ TraceUpsert = "TraceUpsert",+ BatchExport = "BatchExport",+ EvaluationExecution = "EvaluationExecution",+}++export const BatchExportJobSchema = z.object({+ projectId: z.string(),+ batchExportId: z.string(),+});+export const TraceUpsertEventSchema = z.object({projectId: z.string(),traceId: z.string(),});-export const EvalExecutionEvent = z.object({projectId: z.string(),jobExecutionId: z.string(),});+export type BatchExportJobType = z.infer<typeof BatchExportJobSchema>;+export type TraceUpsertEventType = z.infer<typeof TraceUpsertEventSchema>;+export type EvalExecutionEventType = z.infer<typeof EvalExecutionEvent>;++export const EventBodySchema = z.union([+ z.object({+ name: z.literal(EventName.TraceUpsert),+ payload: z.array(TraceUpsertEventSchema),+ }),+ z.object({+ name: z.literal(EventName.EvaluationExecution),+ payload: EvalExecutionEvent,+ }),+ z.object({+ name: z.literal(EventName.BatchExport),+ payload: BatchExportJobSchema,+ }),+]);+export type EventBodyType = z.infer<typeof EventBodySchema>;+export enum QueueName {TraceUpsert = "trace-upsert", // Ingestion pipeline adds events on each Trace upsertEvaluationExecution = "evaluation-execution-queue", // Worker executes Evals+ BatchExport = "batch-export-queue",+ RepeatQueue = "repeat-queue",}export enum QueueJobs {TraceUpsert = "trace-upsert",EvaluationExecution = "evaluation-execution-job",+ BatchExportJob = "batch-export-job",+ EnqueueBatchExportJobs = "enqueue-batch-export-jobs",}export type TQueueJobTypes = {[QueueName.TraceUpsert]: {timestamp: Date;id: string;- payload: z.infer<typeof TraceUpsertEvent>;+ payload: TraceUpsertEventType;name: QueueJobs.TraceUpsert;};[QueueName.EvaluationExecution]: {timestamp: Date;id: string;- payload: z.infer<typeof EvalExecutionEvent>;+ payload: EvalExecutionEventType;name: QueueJobs.EvaluationExecution;};+ [QueueName.BatchExport]: {+ timestamp: Date;+ id: string;+ payload: BatchExportJobType;+ name: QueueJobs.BatchExportJob;+ };};diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsnew file mode 100644index 0000000000..4eea486810--- /dev/null+++ b/packages/shared/src/server/index.ts@@ -0,0 +1,9 @@+export * from "./services/S3StorageService";+export * from "./services/email/projectInvitation/sendProjectInvitationEmail";+export * from "./services/email/batchExportSuccess/sendBatchExportSuccessEmail";+export * from "./services/email/passwordReset/sendResetPasswordVerificationRequest";+export * from "./auth";+export * from "./llm/fetchLLMCompletion";+export * from "./llm/types";+export * from "./utils/DatabaseReadStream";+export * from "./utils/transforms";diff --git a/web/src/server/api/services/S3StorageService.ts b/packages/shared/src/server/services/S3StorageService.tssimilarity index 55%rename from web/src/server/api/services/S3StorageService.tsrename to packages/shared/src/server/services/S3StorageService.tsindex 4738eab96a..04ea0e6a9d 100644--- a/web/src/server/api/services/S3StorageService.ts+++ b/packages/shared/src/server/services/S3StorageService.ts@@ -1,5 +1,4 @@import type { Readable } from "stream";-import { env } from "@/src/env.mjs";import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";import { Upload } from "@aws-sdk/lib-storage";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";@@ -8,44 +7,53 @@ type UploadFile = {fileName: string;fileType: string;data: Readable | string;+ expiresInMinutes?: number;};-class S3StorageService {+export class S3StorageService {private client: S3Client;+ private bucketName: string;- constructor() {- if (!S3StorageService.getIsS3StorageConfigured(env)) {- throw new Error("S3 bucket is not configured");- }+ constructor(params: {+ accessKeyId: string;+ secretAccessKey: string;+ bucketName: string;+ endpoint: string;+ region: string;+ }) {+ const { accessKeyId, secretAccessKey, bucketName, endpoint, region } =+ params;this.client = new S3Client({credentials: {- accessKeyId: env.S3_ACCESS_KEY_ID,- secretAccessKey: env.S3_SECRET_ACCESS_KEY,+ accessKeyId,+ secretAccessKey,},- endpoint: env.S3_ENDPOINT,- region: env.S3_REGION,+ endpoint,+ region,});+ this.bucketName = bucketName;}public async uploadFile({fileName,fileType,data,+ expiresInMinutes,}: UploadFile): Promise<{ signedUrl: string }> {try {await new Upload({client: this.client,params: {- Bucket: env.S3_BUCKET_NAME,+ Bucket: this.bucketName,Key: fileName,Body: data,ContentType: fileType,},}).done();- const expiresInOneHour = 60 * 60;- const signedUrl = await this.getSignedUrl(fileName, expiresInOneHour);+ const expiresIn = (expiresInMinutes ?? 60) * 60; // Convert minutes to seconds, default to 1 hour+ const signedUrl = await this.getSignedUrl(fileName, expiresIn);return { signedUrl };} catch (err) {@@ -57,42 +65,20 @@ class S3StorageService {private async getSignedUrl(fileName: string,- ttlSeconds: number,+ ttlSeconds: number): Promise<string> {try {return await getSignedUrl(this.client,new GetObjectCommand({- Bucket: env.S3_BUCKET_NAME,+ Bucket: this.bucketName,Key: fileName,ResponseContentDisposition: `attachment; filename="${fileName}"`,}),- { expiresIn: ttlSeconds },+ { expiresIn: ttlSeconds });} catch (err) {throw Error("Failed to generate signed URL");}}-- static getIsS3StorageConfigured(- currentEnv: Env,- ): currentEnv is S3ConfiguredEnv {- return Boolean(- currentEnv.S3_BUCKET_NAME &&- currentEnv.S3_ACCESS_KEY_ID &&- currentEnv.S3_SECRET_ACCESS_KEY &&- currentEnv.S3_ENDPOINT &&- currentEnv.S3_REGION,- );- }}--export { S3StorageService };--type Env = typeof env;-type S3ConfiguredEnv = Env & {- S3_ACCESS_KEY_ID: string;- S3_SECRET_ACCESS_KEY: string;- S3_ENDPOINT: string;- S3_REGION: string;-};diff --git a/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsxnew file mode 100644index 0000000000..c1cc416fc7--- /dev/null+++ b/packages/shared/src/server/services/email/batchExportSuccess/BatchExportSuccessEmailTemplate.tsx@@ -0,0 +1,83 @@+import * as React from "react";+import {+ Body,+ Button,+ Container,+ Head,+ Heading,+ Hr,+ Html,+ Img,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";++interface BatchExportSuccessTemplateProps {+ userName: string;+ receiverEmail: string;+ downloadLink: string;+ batchExportName: string;+ expiresInHours: number;+}++export const BatchExportSuccessEmailTemplate = ({+ receiverEmail,+ downloadLink,+ userName,+ batchExportName,+ expiresInHours,+}: BatchExportSuccessTemplateProps) => {+ const previewText = `Download your data export from Langfuse`;++ return (+ <Html>+ <Head />+ <Preview>{previewText}</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-background font-sans">+ <Container className="mx-auto my-10 w-[465px] rounded border border-solid border-[#eaeaea] p-5">+ <Section className="mt-8">+ <Img+ src="https://static.langfuse.com/langfuse_logo_transactional_email.png"+ width="40"+ height="40"+ alt="Langfuse"+ className="mx-auto my-0"+ />+ </Section>+ <Heading className="mx-0 my-[30px] p-0 text-center text-2xl font-normal text-black">+ Your data export is ready+ </Heading>+ <Text className="text-sm leading-6 text-black">+ Hello <strong>{userName}</strong>+ </Text>+ <Text className="text-sm leading-6 text-black">+ Your data export{" "}+ <span className="font-mono">{batchExportName}</span> is ready to+ download. The download link will expire in{" "}+ <strong>{expiresInHours} hours</strong>.+ </Text>+ <Section className="mb-4 mt-8 text-center">+ <Button+ className="rounded bg-black px-5 py-3 text-center text-xs font-semibold text-white no-underline"+ href={downloadLink}+ >+ Download Export+ </Button>+ </Section>+ <Hr className="mx-0 my-[26px] w-full border border-solid border-[#eaeaea]" />+ <Text className="text-xs leading-6 text-[#666666]">+ This email was intended for{" "}+ <span className="text-black">{receiverEmail}</span>. If you were+ not expecting this email, please delete it.+ </Text>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+};++export default BatchExportSuccessEmailTemplate;diff --git a/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts b/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.tsnew file mode 100644index 0000000000..c09e72372d--- /dev/null+++ b/packages/shared/src/server/services/email/batchExportSuccess/sendBatchExportSuccessEmail.ts@@ -0,0 +1,56 @@+import { createTransport } from "nodemailer";+import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";+import { render } from "@react-email/render";++import { BatchExportSuccessEmailTemplate } from "./BatchExportSuccessEmailTemplate";++type SendBatchExportSuccessParams = {+ env: Partial<+ Record<"EMAIL_FROM_ADDRESS" | "SMTP_CONNECTION_URL", string | undefined>+ >;+ receiverEmail: string;+ downloadLink: string;+ userName: string;+ batchExportName: string;+ expiresInHours: number;+};++export const sendBatchExportSuccessEmail = async ({+ env,+ receiverEmail,+ downloadLink,+ userName,+ batchExportName,+ expiresInHours,+}: SendBatchExportSuccessParams) => {+ if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {+ console.error("Missing environment variables for sending email.");++ return;+ }++ try {+ const mailer = createTransport(parseConnectionUrl(env.SMTP_CONNECTION_URL));+ const htmlTemplate = render(+ BatchExportSuccessEmailTemplate({+ receiverEmail,+ downloadLink,+ userName,+ batchExportName,+ expiresInHours,+ })+ );++ await mailer.sendMail({+ to: receiverEmail,+ from: {+ address: env.EMAIL_FROM_ADDRESS,+ name: "Langfuse",+ },+ subject: "Your data export is ready",+ html: htmlTemplate,+ });+ } catch (error) {+ console.error(error);+ }+};diff --git a/web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsx b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsxsimilarity index 98%rename from web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsxrename to packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsxindex 5144d3e8ad..a0d9cd7499 100644--- a/web/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest.tsx+++ b/packages/shared/src/server/services/email/passwordReset/sendResetPasswordVerificationRequest.tsx@@ -67,7 +67,7 @@ const ResetPasswordTemplate = ({ url }: ResetPasswordTemplateProps) => {};export async function sendResetPasswordVerificationRequest(- params: SendVerificationRequestParams,+ params: SendVerificationRequestParams) {const { identifier, url, provider } = params;const transport = createTransport(provider.server);diff --git a/web/src/features/email/templates/ProjectInvitation.tsx b/packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsxsimilarity index 94%rename from web/src/features/email/templates/ProjectInvitation.tsxrename to packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsxindex fb3fcb88ab..f6ffb49741 100644--- a/web/src/features/email/templates/ProjectInvitation.tsx+++ b/packages/shared/src/server/services/email/projectInvitation/ProjectInvitationEmailTemplate.tsx@@ -15,14 +15,13 @@ import {Text,} from "@react-email/components";-import { env } from "@/src/env.mjs";-interface ProjectInvitationTemplateProps {invitedByUsername: string;invitedByUserEmail: string;projectName: string;recieverEmail: string;inviteLink: string;+ emailFromAddress: string;langfuseCloudRegion?: string;}@@ -32,6 +31,7 @@ export const ProjectInvitationTemplate = ({projectName,recieverEmail,inviteLink,+ emailFromAddress,langfuseCloudRegion,}: ProjectInvitationTemplateProps) => {const previewText = `Join ${invitedByUsername} on Langfuse`;@@ -92,8 +92,8 @@ export const ProjectInvitationTemplate = ({This invitation was intended for{" "}<span className="text-black">{recieverEmail}</span>. This invitewas sent from{" "}- <span className="text-black">{env.EMAIL_FROM_ADDRESS}</span>. If- you were not expecting this invitation, you can ignore this email.+ <span className="text-black">{emailFromAddress}</span>. If you+ were not expecting this invitation, you can ignore this email.</Text></Container></Body>diff --git a/web/src/features/email/lib/project-invitation.ts b/packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.tssimilarity index 50%rename from web/src/features/email/lib/project-invitation.tsrename to packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.tsindex 7c416909fb..98959ea938 100644--- a/web/src/features/email/lib/project-invitation.ts+++ b/packages/shared/src/server/services/email/projectInvitation/sendProjectInvitationEmail.ts@@ -2,8 +2,7 @@ import { createTransport } from "nodemailer";import { parseConnectionUrl } from "nodemailer/lib/shared/index.js";import { render } from "@react-email/render";-import { env } from "@/src/env.mjs";-import ProjectInvitationTemplate from "@/src/features/email/templates/ProjectInvitation";+import ProjectInvitationTemplate from "./ProjectInvitationEmailTemplate";const langfuseUrls = {US: "https://us.cloud.langfuse.com",@@ -11,22 +10,47 @@ const langfuseUrls = {STAGING: "https://staging.langfuse.com",};-const getAuthURL = () =>- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "US" ||- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU" ||- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"- ? langfuseUrls[env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION]- : env.NEXTAUTH_URL;--export const sendProjectInvitation = async (- to: string,- inviterName: string,- inviterEmail: string,- projectName: string,-) => {+type SendProjectInvitationParams = {+ env: Partial<+ Record<+ | "EMAIL_FROM_ADDRESS"+ | "SMTP_CONNECTION_URL"+ | "NEXT_PUBLIC_LANGFUSE_CLOUD_REGION"+ | "NEXTAUTH_URL",+ string | undefined+ >+ >;+ to: string;+ inviterName: string;+ inviterEmail: string;+ projectName: string;+};++export const sendProjectInvitationEmail = async ({+ env,+ to,+ inviterName,+ inviterEmail,+ projectName,+}: SendProjectInvitationParams) => {if (!env.EMAIL_FROM_ADDRESS || !env.SMTP_CONNECTION_URL) {console.error(- "Missing environment variables for sending project invitation email.",+ "Missing environment variables for sending project invitation email."+ );+ return;+ }++ const getAuthURL = () =>+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "US" ||+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU" ||+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"+ ? langfuseUrls[env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION]+ : env.NEXTAUTH_URL;++ const authUrl = getAuthURL();+ if (!authUrl) {+ console.error(+ "Missing NEXTAUTH_URL or NEXT_PUBLIC_LANGFUSE_CLOUD_REGION environment variable.");return;}@@ -40,13 +64,14 @@ export const sendProjectInvitation = async (invitedByUserEmail: inviterEmail,projectName: projectName,recieverEmail: to,- inviteLink: getAuthURL(),+ inviteLink: authUrl,+ emailFromAddress: env.EMAIL_FROM_ADDRESS,langfuseCloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,- }),+ }));await mailer.sendMail({- to: to,+ to,from: {address: env.EMAIL_FROM_ADDRESS,name: "Langfuse",diff --git a/web/src/server/api/routers/generations/db/DatabaseReadStream.ts b/packages/shared/src/server/utils/DatabaseReadStream.tssimilarity index 87%rename from web/src/server/api/routers/generations/db/DatabaseReadStream.tsrename to packages/shared/src/server/utils/DatabaseReadStream.tsindex 5268448d4d..6b822d04ab 100644--- a/web/src/server/api/routers/generations/db/DatabaseReadStream.ts+++ b/packages/shared/src/server/utils/DatabaseReadStream.ts@@ -26,9 +26,10 @@ export class DatabaseReadStream<EntityType> extends Readable {// the delegate function takes care of querying the database in a paginated mannerprivate queryDelegate: (pageSize: number,- offset: number,+ offset: number) => Promise<Array<EntityType>>,private pageSize: number,+ private maxRecords?: number) {super({ objectMode: true }); // Set object mode to true to allow pushing objects to the stream rather than strings or buffers@@ -43,10 +44,19 @@ export class DatabaseReadStream<EntityType> extends Readable {this.isReading = true;try {+ // Stop reading if the maximum number of records has been reached+ if (this.maxRecords && this.offset >= this.maxRecords) {+ this.hasNextPage = false;+ this.push(null); // Signal end of stream++ return;+ }+const rows = await this.queryDelegate(this.pageSize, this.offset);+if (rows.length > 0) {rows.forEach((row) => this.push(row));- this.offset += rows.length;+ this.offset += this.pageSize;} else {this.hasNextPage = false;this.push(null); // Signal end of streamdiff --git a/packages/shared/src/server/utils/transforms/index.ts b/packages/shared/src/server/utils/transforms/index.tsnew file mode 100644index 0000000000..2e93509479--- /dev/null+++ b/packages/shared/src/server/utils/transforms/index.ts@@ -0,0 +1,13 @@+import { Transform } from "stream";++import { BatchExportFileFormat } from "../../../features/batchExport/types";+import { transformStreamToCsv } from "./transformStreamToCsv";+import { transformStreamToJson } from "./transformStreamToJson";++export const streamTransformations: Record<+ BatchExportFileFormat,+ () => Transform+> = {+ CSV: transformStreamToCsv,+ JSON: transformStreamToJson,+};diff --git a/packages/shared/src/server/utils/transforms/stringify.ts b/packages/shared/src/server/utils/transforms/stringify.tsnew file mode 100644index 0000000000..67a11ed8eb--- /dev/null+++ b/packages/shared/src/server/utils/transforms/stringify.ts@@ -0,0 +1,5 @@+export const stringify = (data: any): string => {+ return JSON.stringify(data, (key, value) =>+ typeof value === "bigint" ? Number.parseInt(value.toString()) : value+ );+};diff --git a/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts b/packages/shared/src/server/utils/transforms/transformStreamToCsv.tsnew file mode 100644index 0000000000..4c284b365d--- /dev/null+++ b/packages/shared/src/server/utils/transforms/transformStreamToCsv.ts@@ -0,0 +1,39 @@+import { Transform, type TransformCallback } from "stream";+import { stringify } from "./stringify";++export function transformStreamToCsv(): Transform {+ let isFirstChunk = true;+ let headers: string[] = [];++ return new Transform({+ objectMode: true,+ transform(+ row: Record<string, any>,+ encoding: BufferEncoding,+ callback: TransformCallback+ ): void {+ if (isFirstChunk) {+ // Extract headers from the first object+ headers = Object.keys(row);+ this.push(headers.join(",") + "\n");+ isFirstChunk = false;+ }++ // Convert the object to a CSV line and push it+ const csvRow = headers.map((header) => {+ const field = row[header];+ const str = stringify(field);++ if (str.startsWith('"') && str.endsWith('"')) {+ return str;+ } else {+ return `"${str?.replace(/"/g, '""') ?? ""}"`;+ }+ });++ this.push(csvRow.join(",") + "\n");++ callback();+ },+ });+}diff --git a/packages/shared/src/server/utils/transforms/transformStreamToJson.ts b/packages/shared/src/server/utils/transforms/transformStreamToJson.tsnew file mode 100644index 0000000000..71fd50431c--- /dev/null+++ b/packages/shared/src/server/utils/transforms/transformStreamToJson.ts@@ -0,0 +1,39 @@+import { Transform, type TransformCallback } from "stream";+import { stringify } from "./stringify";++export function transformStreamToJson(): Transform {+ let isFirstElement = true;++ return new Transform({+ objectMode: true,++ transform(+ row: any,+ encoding: BufferEncoding,+ callback: TransformCallback+ ): void {+ if (isFirstElement) {+ this.push("["); // Push the opening bracket for the first element+ isFirstElement = false; // Reset the flag after the first element+ } else {+ this.push(","); // For subsequent elements, prepend a comma+ }++ this.push(stringify(row)); // Push the current row as a JSON string++ callback();+ },++ // 'final' is called when there is no more data to be consumed, but before the stream is finished.+ final(callback: TransformCallback): void {+ if (isFirstElement) {+ // If no rows were processed, the opening bracket has not been pushed yet.+ this.push("[]"); // Push an empty array to ensure valid JSON.+ } else {+ this.push("]"); // Close JSON array+ }++ callback();+ },+ });+}diff --git a/packages/shared/src/tableDefinitions/index.ts b/packages/shared/src/tableDefinitions/index.tsnew file mode 100644index 0000000000..10d2a85b2e--- /dev/null+++ b/packages/shared/src/tableDefinitions/index.ts@@ -0,0 +1,2 @@+export * from "./sessionsView";+export * from "./types";diff --git a/web/src/server/api/definitions/sessionsView.ts b/packages/shared/src/tableDefinitions/sessionsView.tssimilarity index 96%rename from web/src/server/api/definitions/sessionsView.tsrename to packages/shared/src/tableDefinitions/sessionsView.tsindex 4426696202..c8335a61ac 100644--- a/web/src/server/api/definitions/sessionsView.ts+++ b/packages/shared/src/tableDefinitions/sessionsView.ts@@ -1,7 +1,7 @@import {type OptionsDefinition,type ColumnDefinition,-} from "@langfuse/shared";+} from "../tableDefinitions/types";export const sessionsViewCols: ColumnDefinition[] = [{ name: "⭐️", id: "bookmarked", type: "boolean", internal: "s.bookmarked" },@@ -85,7 +85,7 @@ export type SessionOptions = {};export function sessionsTableColsWithOptions(- options?: SessionOptions,+ options?: SessionOptions): ColumnDefinition[] {return sessionsViewCols.map((col) => {if (col.id === "userIds") {diff --git a/packages/shared/src/interfaces/tableDefinition.ts b/packages/shared/src/tableDefinitions/types.tssimilarity index 100%rename from packages/shared/src/interfaces/tableDefinition.tsrename to packages/shared/src/tableDefinitions/types.tsdiff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.jsonindex af062c239e..efec50459e 100644--- a/packages/shared/tsconfig.json+++ b/packages/shared/tsconfig.json@@ -1,6 +1,7 @@{"extends": "@repo/typescript-config/base.json","compilerOptions": {+ "jsx": "react","moduleResolution": "NodeNext","module": "NodeNext","lib": ["ES2020"],diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c06a0c7114..88e0c18c67 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -40,7 +40,7 @@ importers:version: 14.2.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])next-auth:specifier: ^4.24.7zod:specifier: ^3.22.4version: 3.22.4@@ -113,6 +113,15 @@ importers:packages/shared:dependencies:+ '@aws-sdk/client-s3':+ specifier: ^3.550.0+ version: 3.550.0+ '@aws-sdk/lib-storage':+ specifier: ^3.568.0+ version: 3.568.0(@aws-sdk/[email protected])+ '@aws-sdk/s3-request-presigner':+ specifier: ^3.554.0+ version: 3.554.0'@langchain/anthropic':specifier: ^0.1.21version: 0.1.21@@ -125,9 +134,18 @@ importers:'@prisma/client':specifier: ^5.13.0version: 5.13.0([email protected])+ '@react-email/components':+ specifier: ^0.0.19+ version: 0.0.19(@types/[email protected])([email protected])+ '@react-email/render':+ specifier: ^0.0.15+ version: 0.0.15'@types/bcryptjs':specifier: ^2.4.6version: 2.4.6+ '@types/react':+ specifier: ^18.2.79+ version: 18.2.79bcryptjs:specifier: ^2.4.3version: 2.4.3@@ -142,10 +160,16 @@ importers:version: 4.17.21next-auth:specifier: ^4.24.7+ nodemailer:+ specifier: ^6.9.13+ version: 6.9.13prisma-extension-kysely:specifier: ^2.1.0version: 2.1.0(@prisma/[email protected])+ react:+ specifier: ^18.0.0+ version: 18.2.0zod:specifier: ^3.22.4version: 3.22.4@@ -165,6 +189,9 @@ importers:'@types/node':specifier: ^20.11.29version: 20.11.29+ '@types/nodemailer':+ specifier: ^6.4.15+ version: 6.4.15'@types/pg':specifier: ^8.11.6version: 8.11.6@@ -222,15 +249,6 @@ importers:'@anthropic-ai/tokenizer':specifier: ^0.0.4version: 0.0.4- '@aws-sdk/client-s3':- specifier: ^3.550.0- version: 3.550.0- '@aws-sdk/lib-storage':- specifier: ^3.568.0- version: 3.568.0(@aws-sdk/[email protected])- '@aws-sdk/s3-request-presigner':- specifier: ^3.554.0- version: 3.554.0'@codemirror/lang-json':specifier: ^6.0.1version: 6.0.1@@ -336,12 +354,6 @@ importers:'@radix-ui/react-tooltip':specifier: ^1.0.7version: 1.0.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])- '@react-email/components':- specifier: ^0.0.19- version: 0.0.19(@types/[email protected])([email protected])- '@react-email/render':- specifier: ^0.0.15- version: 0.0.15'@remixicon/react':specifier: ^4.2.0version: 4.2.0([email protected])@@ -452,16 +464,13 @@ importers:version: 14.2.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])next-auth:specifier: ^4.24.7next-query-params:specifier: ^5.0.0next-themes:specifier: ^0.3.0version: 0.3.0([email protected])([email protected])- nodemailer:- specifier: ^6.9.13- version: 6.9.13posthog-js:specifier: ^1.122.0version: 1.122.0@@ -560,9 +569,6 @@ importers:'@types/node':specifier: 20.10.5version: 20.10.5- '@types/nodemailer':- specifier: ^6.4.15- version: 6.4.15'@types/react':specifier: ^18.2.79version: 18.2.79@@ -983,7 +989,7 @@ packages:'@smithy/util-stream': 2.2.0'@smithy/util-utf8': 2.3.0'@smithy/util-waiter': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- aws-crtdev: false@@ -1033,7 +1039,7 @@ packages:'@smithy/util-middleware': 2.2.0'@smithy/util-retry': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- aws-crtdev: false@@ -1079,7 +1085,7 @@ packages:'@smithy/util-middleware': 2.2.0'@smithy/util-retry': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- aws-crtdev: false@@ -1128,7 +1134,7 @@ packages:'@smithy/util-middleware': 2.2.0'@smithy/util-retry': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- aws-crtdev: false@@ -1143,7 +1149,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0fast-xml-parser: 4.2.5- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1153,7 +1159,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/property-provider': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1168,7 +1174,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0'@smithy/util-stream': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected](@aws-sdk/[email protected]):@@ -1185,7 +1191,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- '@aws-sdk/credential-provider-node'- aws-crt@@ -1206,7 +1212,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- aws-crtdev: false@@ -1219,7 +1225,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected](@aws-sdk/[email protected]):@@ -1232,7 +1238,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- '@aws-sdk/credential-provider-node'- aws-crt@@ -1246,7 +1252,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/property-provider': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- '@aws-sdk/credential-provider-node'- aws-crt@@ -1265,7 +1271,7 @@ packages:buffer: 5.6.0events: 3.3.0stream-browserify: 3.0.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1278,7 +1284,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0'@smithy/util-config-provider': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1288,7 +1294,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1302,7 +1308,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1312,7 +1318,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1321,7 +1327,7 @@ packages:dependencies:'@aws-sdk/types': 3.535.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1330,7 +1336,7 @@ packages:dependencies:'@aws-sdk/types': 3.535.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1340,7 +1346,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1355,7 +1361,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0'@smithy/util-config-provider': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1370,7 +1376,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0'@smithy/util-config-provider': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1383,7 +1389,7 @@ packages:'@smithy/signature-v4': 2.3.0'@smithy/types': 2.12.0'@smithy/util-middleware': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1392,7 +1398,7 @@ packages:dependencies:'@aws-sdk/types': 3.535.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1403,7 +1409,7 @@ packages:'@aws-sdk/util-endpoints': 3.540.0'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1415,7 +1421,7 @@ packages:'@smithy/types': 2.12.0'@smithy/util-config-provider': 2.3.0'@smithy/util-middleware': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1429,7 +1435,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1441,7 +1447,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/signature-v4': 2.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1453,7 +1459,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/signature-v4': 2.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected](@aws-sdk/[email protected]):@@ -1465,7 +1471,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3transitivePeerDependencies:- '@aws-sdk/credential-provider-node'- aws-crt@@ -1476,14 +1482,14 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:resolution: {integrity: sha512-smVo29nUPAOprp8Z5Y3GHuhiOtw6c8/EtLCm5AVMtRsTPw4V414ZXL2H66tzmb5kEeSzQlbfBSBEdIFZoxO9kg==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1493,7 +1499,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/types': 2.12.0'@smithy/util-endpoints': 1.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1503,14 +1509,14 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/querystring-builder': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:resolution: {integrity: sha512-PHJ3SL6d2jpcgbqdgiPxkXpu7Drc2PYViwxSIqvvMKhDwzSB1W3mMvtpzwKM4IE7zLFodZo0GKjJ9AsoXndXhA==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1519,7 +1525,7 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/types': 2.12.0bowser: 2.11.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1534,13 +1540,13 @@ packages:'@aws-sdk/types': 3.535.0'@smithy/node-config-provider': 2.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:resolution: {integrity: sha512-UvFa/vR+e19XookZF8RzFZBrw2EUkQWxiBW0yYQAhvk3C+QVGl0H3ouca8LDBlBfQKXwmW3huo/59H8rwb1wJw==}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@aws-sdk/[email protected]:@@ -1548,7 +1554,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@babel/[email protected]:@@ -3948,7 +3954,7 @@ packages:next-auth: ^4dependencies:'@prisma/client': 5.15.0([email protected])dev: false/@next/[email protected]:@@ -6666,20 +6672,20 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-VNB5+1oCgX3Fzs072yuRsUoC2N4Zg/LJ11DTxX3+Qu+Paa6AmbIF0E9sc2wthz9Psrk/zcOlTCyuposlIhPjZQ==}dependencies:'@smithy/util-base64': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-3GJNvRwXBGdkDZZOGiziVYzDpn4j6zfyULHMDKAGIUo72yHALpE9CbhfQp/XcLNVoc1byfMpn6uW5H2BqPjgaQ==}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6690,7 +6696,7 @@ packages:'@smithy/types': 2.12.0'@smithy/util-config-provider': 2.3.0'@smithy/util-middleware': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6704,7 +6710,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0'@smithy/util-middleware': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6715,7 +6721,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/types': 2.12.0'@smithy/url-parser': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6724,7 +6730,7 @@ packages:'@aws-crypto/crc32': 3.0.0'@smithy/types': 2.12.0'@smithy/util-hex-encoding': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6733,7 +6739,7 @@ packages:dependencies:'@smithy/eventstream-serde-universal': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6741,7 +6747,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6750,7 +6756,7 @@ packages:dependencies:'@smithy/eventstream-serde-universal': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6759,7 +6765,7 @@ packages:dependencies:'@smithy/eventstream-codec': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6769,7 +6775,7 @@ packages:'@smithy/querystring-builder': 2.2.0'@smithy/types': 2.12.0'@smithy/util-base64': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6778,7 +6784,7 @@ packages:'@smithy/chunked-blob-reader': 2.2.0'@smithy/chunked-blob-reader-native': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6788,7 +6794,7 @@ packages:'@smithy/types': 2.12.0'@smithy/util-buffer-from': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6797,21 +6803,21 @@ packages:dependencies:'@smithy/types': 2.12.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-nEDASdbKFKPXN2O6lOlTgrEEOO9NHIeO+HVvZnkqc8h5U9g3BIhWsvzFo+UcUbliMHvKNPD/zVxDrkP1Sbgp8Q==}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6819,7 +6825,7 @@ packages:dependencies:'@smithy/types': 2.12.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6828,7 +6834,7 @@ packages:dependencies:'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6841,7 +6847,7 @@ packages:'@smithy/types': 2.12.0'@smithy/url-parser': 2.2.0'@smithy/util-middleware': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6855,7 +6861,7 @@ packages:'@smithy/types': 2.12.0'@smithy/util-middleware': 2.2.0'@smithy/util-retry': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3uuid: 9.0.1dev: false@@ -6864,7 +6870,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6872,7 +6878,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6882,7 +6888,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/shared-ini-file-loader': 2.4.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6893,7 +6899,7 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/querystring-builder': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6901,7 +6907,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6909,7 +6915,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6918,7 +6924,7 @@ packages:dependencies:'@smithy/types': 2.12.0'@smithy/util-uri-escape': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6926,7 +6932,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6941,7 +6947,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6954,7 +6960,7 @@ packages:'@smithy/util-middleware': 2.2.0'@smithy/util-uri-escape': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6966,14 +6972,14 @@ packages:'@smithy/protocol-http': 3.3.0'@smithy/types': 2.12.0'@smithy/util-stream': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-QwYgloJ0sVNBeBuBs65cIkTbfzV/Q6ZNPCJ99EICFEdJYG50nGIY/uYXp+TbsdJReIuPr0a0kXmCvren3MbRRw==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6981,7 +6987,7 @@ packages:dependencies:'@smithy/querystring-parser': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -6990,20 +6996,20 @@ packages:dependencies:'@smithy/util-buffer-from': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-dtpw9uQP7W+n3vOtx0CfBD5EWd7EPdIdsQnWTDoFf77e3VUf05uA7R7TGipIo8e4WL2kuPdnsr3hMQn9ziYj5w==}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-ITWT1Wqjubf2CJthb0BuT9+bpzBfXeMokH/AAa5EJQgbv9aPMVfnM76iFIZVFf50hYXGbtiV71BHAthNWd6+dw==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7011,14 +7017,14 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/is-array-buffer': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-HZkzrRcuFN1k70RLqlNK4FnPXKOpkik1+4JaBoHNJn+RnJGYqaa3c5/+XtLOXhlKzlRgNvyaLieHTW2VwGN0VQ==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7029,7 +7035,7 @@ packages:'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0bowser: 2.11.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7042,7 +7048,7 @@ packages:'@smithy/property-provider': 2.2.0'@smithy/smithy-client': 2.5.1'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7051,14 +7057,14 @@ packages:dependencies:'@smithy/node-config-provider': 2.3.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-7iKXR+/4TpLK194pVjKiasIyqMtTYJsgKgM242Y9uzt5dhHnUDvMNb+3xIhRJ9QhvqGii/5cRUt4fJn3dtXNHQ==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7066,7 +7072,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7075,7 +7081,7 @@ packages:dependencies:'@smithy/service-error-classification': 2.1.5'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7089,14 +7095,14 @@ packages:'@smithy/util-buffer-from': 2.2.0'@smithy/util-hex-encoding': 2.2.0'@smithy/util-utf8': 2.3.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:resolution: {integrity: sha512-jtmJMyt1xMD/d8OtbVJ2gFZOSKc+ueYJZPW20ULW1GOp/q/YIM0wNh+u8ZFao9UaIGz4WoPW8hC64qlWLIfoDA==}engines: {node: '>=14.0.0'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7104,7 +7110,7 @@ packages:engines: {node: '>=14.0.0'}dependencies:'@smithy/util-buffer-from': 2.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@smithy/[email protected]:@@ -7113,7 +7119,7 @@ packages:dependencies:'@smithy/abort-controller': 2.2.0'@smithy/types': 2.12.0- tslib: 2.6.2+ tslib: 2.6.3dev: false/@swc/[email protected]:@@ -7124,7 +7130,7 @@ packages:resolution: {integrity: sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==}dependencies:'@swc/counter': 0.1.3- tslib: 2.6.2+ tslib: 2.6.3dev: false/@szmarczak/[email protected]:@@ -8904,7 +8910,7 @@ packages:resolution: {integrity: sha512-xcLxITLe2HYa1cnYnwCjkOO1PqUHQpozB8x9AR0OgWN2woOBi5kSDVxKfd0b7sb1hw5qFeJhXm9H1nu3xSfLeQ==}engines: {node: '>=10'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: false@@ -9039,7 +9045,7 @@ packages:resolution: {integrity: sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==}engines: {node: '>=4'}dependencies:- tslib: 2.6.2+ tslib: 2.6.3dev: true@@ -14665,7 +14671,7 @@ packages:type-fest: 2.19.0dev: trueresolution: {integrity: sha512-iChjE8ov/1K/z98gdKbn2Jw+2vLgJtVV39X+rCP5SGnVQuco7QOr19FRNGMIrD8d3LYhHWV9j9sKLzq1aDWWQQ==}peerDependencies:next: ^12.2.5 || ^13 || ^14@@ -14681,7 +14687,6 @@ packages:cookie: 0.5.0jose: 4.15.5next: 14.2.3(@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected])- nodemailer: 6.9.13oauth: 0.9.15openid-client: 5.6.5preact: 10.19.7@@ -14691,7 +14696,7 @@ packages:uuid: 8.3.2dev: falseresolution: {integrity: sha512-iChjE8ov/1K/z98gdKbn2Jw+2vLgJtVV39X+rCP5SGnVQuco7QOr19FRNGMIrD8d3LYhHWV9j9sKLzq1aDWWQQ==}peerDependencies:next: ^12.2.5 || ^13 || ^14@@ -14707,6 +14712,7 @@ packages:cookie: 0.5.0jose: 4.15.5next: 14.2.4([email protected])([email protected])+ nodemailer: 6.9.13oauth: 0.9.15openid-client: 5.6.5preact: 10.19.7@@ -16290,7 +16296,7 @@ packages:'@types/react': 18.2.79react: 18.2.0react-style-singleton: 2.2.1(@types/[email protected])([email protected])- tslib: 2.6.2+ tslib: 2.6.3dev: false@@ -16307,7 +16313,7 @@ packages:react: 18.2.0react-remove-scroll-bar: 2.3.6(@types/[email protected])([email protected])react-style-singleton: 2.2.1(@types/[email protected])([email protected])- tslib: 2.6.2+ tslib: 2.6.3use-callback-ref: 1.3.1(@types/[email protected])([email protected])use-sidecar: 1.1.2(@types/[email protected])([email protected])dev: false@@ -16352,7 +16358,7 @@ packages:get-nonce: 1.0.1invariant: 2.2.4react: 18.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false@@ -17559,7 +17565,7 @@ packages:engines: {node: ^14.18.0 || >=16.0.0}dependencies:'@pkgr/core': 0.1.1- tslib: 2.6.2+ tslib: 2.6.3dev: true@@ -17930,7 +17936,6 @@ packages:resolution: {integrity: sha512-xNvxJEOUiWPGhUuUdQgAJPKOOJfGnIyKySOc09XkKsgdUV/3E2zvwZYdejjmRgPCgcym1juLH3226yA7sEFJKQ==}- dev: trueresolution: {integrity: sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==}@@ -18282,7 +18287,7 @@ packages:dependencies:'@types/react': 18.2.79react: 18.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: false@@ -18316,7 +18321,7 @@ packages:'@types/react': 18.2.79detect-node-es: 1.1.0react: 18.2.0- tslib: 2.6.2+ tslib: 2.6.3dev: falsediff --git a/web/package.json b/web/package.jsonindex a187c7f888..dd5776f726 100644--- a/web/package.json+++ b/web/package.json@@ -21,9 +21,6 @@},"dependencies": {"@anthropic-ai/tokenizer": "^0.0.4",- "@aws-sdk/client-s3": "^3.550.0",- "@aws-sdk/lib-storage": "^3.568.0",- "@aws-sdk/s3-request-presigner": "^3.554.0","@codemirror/lang-json": "^6.0.1","@codemirror/lint": "^6.8.0","@headlessui/react": "1.7.18",@@ -59,8 +56,6 @@"@radix-ui/react-toggle": "^1.0.3","@radix-ui/react-toggle-group": "^1.0.4","@radix-ui/react-tooltip": "^1.0.7",- "@react-email/components": "^0.0.19",- "@react-email/render": "^0.0.15","@remixicon/react": "^4.2.0","@repo/eslint-config": "workspace:*","@repo/typescript-config": "workspace:*",@@ -100,7 +95,6 @@"next-auth": "^4.24.7","next-query-params": "^5.0.0","next-themes": "^0.3.0",- "nodemailer": "^6.9.13","posthog-js": "^1.122.0","posthog-node": "^3.6.3","prisma": "^5.13.0",@@ -134,7 +128,6 @@"@types/jest": "^29.5.12","@types/lodash": "^4.17.5","@types/node": "20.10.5",- "@types/nodemailer": "^6.4.15","@types/react": "^18.2.79","@types/react-dom": "^18.2.25","@types/uuid": "^9.0.8",diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.tsindex 095776249d..972b3ee187 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/api-auth.servertest.ts@@ -1,7 +1,7 @@import {getDisplaySecretKey,hashSecretKey,-} from "@langfuse/shared/src/server/auth";+} from "@langfuse/shared/src/server";import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";import { prisma } from "@langfuse/shared/src/db";diff --git a/web/src/__tests__/generation-exports.servertest.ts b/web/src/__tests__/generation-exports.servertest.tsindex f2f42aad42..9d52bcb130 100644--- a/web/src/__tests__/generation-exports.servertest.ts+++ b/web/src/__tests__/generation-exports.servertest.ts@@ -3,7 +3,7 @@import type { Session } from "next-auth";import { pruneDatabase } from "@/src/__tests__/test-utils";-import { ModelUsageUnit } from "@langfuse/shared";+import { BatchExportFileFormat, ModelUsageUnit } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";@@ -84,6 +84,7 @@ describe("observations.export RPC", () => {},admin: true,},+ environment: {} as any,};const ctx = createInnerTRPCContext({ session });@@ -91,7 +92,7 @@ describe("observations.export RPC", () => {it("should return a CSV file", async () => {const result = await caller.generations.export({- fileFormat: "CSV",+ fileFormat: BatchExportFileFormat.CSV,orderBy: { column: "id", order: "ASC" },filter: [{@@ -119,7 +120,7 @@ describe("observations.export RPC", () => {it("should return a JSON file", async () => {const result = await caller.generations.export({- fileFormat: "JSON",+ fileFormat: BatchExportFileFormat.JSON,orderBy: { column: "id", order: "ASC" },filter: [{@@ -144,38 +145,11 @@ describe("observations.export RPC", () => {expect(JSON.parse(data).length).toBe(numberOfGenerations);});- it("should return a OPENAI-JSONL file", async () => {- const result = await caller.generations.export({- fileFormat: "OPENAI-JSONL",- orderBy: { column: "id", order: "ASC" },- filter: [- {- column: "Start Time",- type: "datetime",- operator: ">",- value: new Date("1990-01-01"),- },- ],- projectId,- searchQuery: null,- });-- if (result.type !== "data")- throw new Error("No data returned. Is S3 accidentally enabled?");- const { data, fileName } = result;-- const fileExtension = fileName.split(".").pop();- expect(fileName).toContain(`lf-export-${projectId}`);- expect(fileExtension).toBe("jsonl");-- expect(data.split("\n").filter(Boolean).length).toBe(numberOfGenerations);- });-it("should throw on unsupported file formats", async () => {const unsupportedFileFormat = "XLSX";const call = caller.generations.export({- fileFormat: unsupportedFileFormat as unknown as "JSON",+ fileFormat: unsupportedFileFormat as unknown as BatchExportFileFormat,orderBy: { column: "id", order: "ASC" },filter: [{diff --git a/web/src/__tests__/orderByToPrisma.servertest.ts b/web/src/__tests__/orderByToPrisma.servertest.tsindex 620755c071..2e3c1a057a 100644--- a/web/src/__tests__/orderByToPrisma.servertest.ts+++ b/web/src/__tests__/orderByToPrisma.servertest.ts@@ -1,4 +1,4 @@-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";+import { orderByToPrismaSql } from "@langfuse/shared";import { tracesTableCols } from "@langfuse/shared";// The test for the orderByToPrisma functiondiff --git a/web/src/components/BatchExportTableButton.tsx b/web/src/components/BatchExportTableButton.tsxnew file mode 100644index 0000000000..07500a2475--- /dev/null+++ b/web/src/components/BatchExportTableButton.tsx@@ -0,0 +1,82 @@+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { Button } from "@/src/components/ui/button";+import { ChevronDownIcon, Loader } from "lucide-react";+import {+ type BatchExportTableName,+ exportOptions,+ type BatchExportFileFormat,+ type OrderByState,+} from "@langfuse/shared";+import React from "react";+import { api } from "@/src/utils/api";+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";++export type BatchExportTableButtonProps = {+ projectId: string;+ tableName: BatchExportTableName;+ orderByState: OrderByState;+ filterState: any;+ searchQuery?: any;+};++export const BatchExportTableButton: React.FC<BatchExportTableButtonProps> = (+ props,+) => {+ const [isExporting, setIsExporting] = React.useState(false);+ const createExport = api.batchExport.create.useMutation();++ const handleExport = async (format: BatchExportFileFormat) => {+ setIsExporting(true);+ await createExport.mutateAsync({+ projectId: props.projectId,+ name: `${new Date().toISOString()} - ${props.tableName} as ${format}`,+ format,+ query: {+ tableName: props.tableName,+ filter: props.filterState,+ orderBy: props.orderByState,+ },+ });+ setIsExporting(false);+ showSuccessToast({+ title: "Export queued",+ description: "You will receive an email when the export is ready.",+ });+ };++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="outline" className="ml-auto whitespace-nowrap">+ <span className="hidden @6xl:inline">+ {props.filterState.length > 0 || props.searchQuery+ ? "Export selection"+ : "Export all"}{" "}+ </span>+ <span className="@6xl:hidden">Export</span>+ {isExporting ? (+ <Loader className="ml-2 h-4 w-4 animate-spin" />+ ) : (+ <ChevronDownIcon className="ml-2 h-4 w-4" />+ )}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {Object.entries(exportOptions).map(([key, options]) => (+ <DropdownMenuItem+ key={key}+ className="capitalize"+ onClick={() => void handleExport(key as BatchExportFileFormat)}+ >+ as {options.label}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+};diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsxindex 008dd9ee40..ceb5ad3b7a 100644--- a/web/src/components/table/data-table.tsx+++ b/web/src/components/table/data-table.tsx@@ -1,4 +1,5 @@"use client";+import { type OrderByState } from "@langfuse/shared";import DocPopup from "@/src/components/layouts/doc-popup";import { DataTablePagination } from "@/src/components/table/data-table-pagination";@@ -16,7 +17,6 @@ import {TableHeader,TableRow,} from "@/src/components/ui/table";-import { type OrderByState } from "@/src/features/orderBy/types";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { cn } from "@/src/utils/tailwind";import {diff --git a/web/src/components/table/use-cases/generations.tsx b/web/src/components/table/use-cases/generations.tsxindex 6e8550ce05..65ed383814 100644--- a/web/src/components/table/use-cases/generations.tsx+++ b/web/src/components/table/use-cases/generations.tsx@@ -35,7 +35,7 @@ import { LevelColors } from "@/src/components/level-colors";import { usdFormatter } from "@/src/utils/numbers";import {exportOptions,- type ExportFileFormats,+ type BatchExportFileFormat,observationsTableColsWithOptions,} from "@langfuse/shared";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";@@ -186,15 +186,11 @@ export default function GenerationsTable({);};- const handleExport = async (fileFormat: ExportFileFormats) => {+ const handleExport = async (fileFormat: BatchExportFileFormat) => {if (isExporting) return;setIsExporting(true);capture("generations:export", { file_format: fileFormat });- if (fileFormat === "OPENAI-JSONL")- alert(- "When exporting in OpenAI-JSONL, only generations that exactly match the `ChatML` format will be exported. For any questions, reach out to support.",- );try {const fileData = await directApi.generations.export.query({projectId,@@ -673,7 +669,9 @@ export default function GenerationsTable({<DropdownMenuItemkey={key}className="capitalize"- onClick={() => void handleExport(key as ExportFileFormats)}+ onClick={() =>+ void handleExport(key as BatchExportFileFormat)+ }>as {options.label}</DropdownMenuItem>diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsxindex 2caeb20fb2..d5889ca890 100644--- a/web/src/components/table/use-cases/sessions.tsx+++ b/web/src/components/table/use-cases/sessions.tsx@@ -6,10 +6,13 @@ import { type LangfuseColumnDef } from "@/src/components/table/types";import { TokenUsageBadge } from "@/src/components/token-usage-badge";import useColumnVisibility from "@/src/features/column-visibility/hooks/useColumnVisibility";import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";-import { type FilterState } from "@langfuse/shared";+import {+ type FilterState,+ sessionsTableColsWithOptions,+ BatchExportTableName,+} from "@langfuse/shared";import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";-import { sessionsTableColsWithOptions } from "@/src/server/api/definitions/sessionsView";import { api } from "@/src/utils/api";import { formatIntervalSeconds, utcDateOffsetByDays } from "@/src/utils/dates";import { usdFormatter } from "@/src/utils/numbers";@@ -18,6 +21,7 @@ import type Decimal from "decimal.js";import { useEffect } from "react";import { NumberParam, useQueryParams, withDefault } from "use-query-params";import { useSession } from "next-auth/react";+import { BatchExportTableButton } from "@/src/components/BatchExportTableButton";export type SessionTableRow = {id: string;@@ -343,6 +347,13 @@ export default function SessionsTable({columns={columns}columnVisibility={columnVisibility}setColumnVisibility={setColumnVisibility}+ actionButtons={[+ <BatchExportTableButton+ {...{ projectId, filterState, orderByState }}+ tableName={BatchExportTableName.Sessions}+ key="batchExport"+ />,+ ]}columnsWithCustomSelect={["userIds"]}/><DataTablediff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex 3a84e568c4..0cc9b9922f 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -17,7 +17,8 @@ export type AuditableResource =| "evalTemplate"| "job"| "posthogIntegration"- | "llmApiKey";+ | "llmApiKey"+ | "batchExport";type AuditLog = {resourceType: AuditableResource;diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.tsindex 9bfe2fd311..41249e4877 100644--- a/web/src/features/filters/hooks/useFilterState.ts+++ b/web/src/features/filters/hooks/useFilterState.ts@@ -4,9 +4,9 @@ import {observationsTableCols,tracesTableCols,singleFilter,+ sessionsViewCols,} from "@langfuse/shared";import { scoresTableCols } from "@/src/server/api/definitions/scoresTable";-import { sessionsViewCols } from "@/src/server/api/definitions/sessionsView";import { useState } from "react";import {useQueryParam,diff --git a/web/src/features/notifications/SuccessNotification.tsx b/web/src/features/notifications/SuccessNotification.tsxnew file mode 100644index 0000000000..39613f796a--- /dev/null+++ b/web/src/features/notifications/SuccessNotification.tsx@@ -0,0 +1,38 @@+import { BadgeCheck, X } from "lucide-react";++export type SuccessNotificationProps = {+ title: string;+ description: string;+ onDismiss: () => void;+};++export const SuccessNotification: React.FC<SuccessNotificationProps> = ({+ title,+ description,+ onDismiss,+}) => {+ return (+ <div className="flex justify-between">+ <div className="flex min-w-[300px] flex-1 flex-col gap-2">+ <div className="flex items-center gap-2">+ <BadgeCheck size={20} className="text-destructive-foreground" />+ <div className="m-0 text-sm font-medium leading-tight text-destructive-foreground">+ {title}+ </div>+ </div>+ {description && (+ <div className="text-sm leading-tight text-destructive-foreground">+ {description}+ </div>+ )}+ </div>+ <button+ className="flex h-6 w-6 cursor-pointer items-start justify-end border-none bg-transparent p-0 text-destructive-foreground transition-colors duration-200"+ onClick={onDismiss}+ aria-label="Close"+ >+ <X size={14} />+ </button>+ </div>+ );+};diff --git a/web/src/features/notifications/showSuccessToast.tsx b/web/src/features/notifications/showSuccessToast.tsxnew file mode 100644index 0000000000..45657bd11f--- /dev/null+++ b/web/src/features/notifications/showSuccessToast.tsx@@ -0,0 +1,24 @@+import { toast } from "sonner";+import {+ SuccessNotification,+ type SuccessNotificationProps,+} from "@/src/features/notifications/SuccessNotification";++export const showSuccessToast = (+ params: Omit<SuccessNotificationProps, "onDismiss">,+) => {+ toast.custom(+ (t) => (+ <SuccessNotification {...params} onDismiss={() => toast.dismiss(t)} />+ ),+ {+ duration: 5000,+ style: {+ padding: "1rem",+ border: "1px solid hsl(var(--dark-green))",+ borderRadius: "0.5rem",+ backgroundColor: "hsl(var(--dark-green))",+ },+ },+ );+};diff --git a/web/src/features/orderBy/hooks/useOrderByState.ts b/web/src/features/orderBy/hooks/useOrderByState.tsindex 4566fd1650..cde4fd983b 100644--- a/web/src/features/orderBy/hooks/useOrderByState.ts+++ b/web/src/features/orderBy/hooks/useOrderByState.ts@@ -1,4 +1,4 @@-import { type OrderByState } from "@/src/features/orderBy/types";+import { type OrderByState } from "@langfuse/shared";import { ObjectParam, useQueryParam, withDefault } from "use-query-params";type OrderByQueryParamState =diff --git a/web/src/features/orderBy/types.ts b/web/src/features/orderBy/types.tsdeleted file mode 100644index 92b876c530..0000000000--- a/web/src/features/orderBy/types.ts+++ /dev/null@@ -1,5 +0,0 @@-import { type orderBy } from "@langfuse/shared";-import { type z } from "zod";--// to be sent to the server-export type OrderByState = z.infer<typeof orderBy>;diff --git a/web/src/features/prompts/server/routers/promptRouter.ts b/web/src/features/prompts/server/routers/promptRouter.tsindex 7ff285edfa..75f5b54d4c 100644--- a/web/src/features/prompts/server/routers/promptRouter.ts+++ b/web/src/features/prompts/server/routers/promptRouter.ts@@ -10,7 +10,7 @@ import {import { type Prompt, Prisma } from "@langfuse/shared/src/db";import { createPrompt } from "../actions/createPrompt";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";+import { orderByToPrismaSql } from "@langfuse/shared";import { promptsTableCols } from "@/src/server/api/definitions/promptsTable";import { optionalPaginationZod, paginationZod } from "@langfuse/shared";import {diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 686257ec36..dfb6f1cdd3 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -1,8 +1,5 @@import { env } from "@/src/env.mjs";-import {- createShaHash,- verifySecretKey,-} from "@langfuse/shared/src/server/auth";+import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";import { type ApiAccessScope } from "@/src/features/public-api/server/types";import { prisma } from "@langfuse/shared/src/db";import { isPrismaException } from "@/src/utils/exceptions";diff --git a/web/src/features/public-api/server/apiKeyRouter.ts b/web/src/features/public-api/server/apiKeyRouter.tsindex ac962c758e..481f76deb8 100644--- a/web/src/features/public-api/server/apiKeyRouter.ts+++ b/web/src/features/public-api/server/apiKeyRouter.ts@@ -1,5 +1,5 @@import { auditLog } from "@/src/features/audit-logs/auditLog";-import { generateKeySet } from "@langfuse/shared/src/server/auth";+import { generateKeySet } from "@langfuse/shared/src/server";import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import {createTRPCRouter,diff --git a/web/src/features/rbac/constants/roleAccessRights.ts b/web/src/features/rbac/constants/roleAccessRights.tsindex 4ea278de6a..3cb97cbe4b 100644--- a/web/src/features/rbac/constants/roleAccessRights.ts+++ b/web/src/features/rbac/constants/roleAccessRights.ts@@ -32,6 +32,8 @@ const scopes = ["models:CUD",+ "batchExport:create",+"evalTemplate:create","evalTemplate:read","evalJob:read",@@ -77,6 +79,7 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",+ "batchExport:create",],ADMIN: ["project:update",@@ -106,6 +109,7 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",+ "batchExport:create",],MEMBER: ["members:read",@@ -125,6 +129,7 @@ export const roleAccessRights: Record<ProjectRole, Scope[]> = {"evalJob:CUD","evalJobExecution:read","llmApiKeys:read",+ "batchExport:create",],VIEWER: ["prompts:read",diff --git a/web/src/features/rbac/server/projectMembersRouter.ts b/web/src/features/rbac/server/projectMembersRouter.tsindex 6ddbe48b41..52a341a1a6 100644--- a/web/src/features/rbac/server/projectMembersRouter.ts+++ b/web/src/features/rbac/server/projectMembersRouter.ts@@ -1,13 +1,15 @@+import * as z from "zod";++import { env } from "@/src/env.mjs";import { auditLog } from "@/src/features/audit-logs/auditLog";-import { sendProjectInvitation } from "@/src/features/email/lib/project-invitation";import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import {createTRPCRouter,protectedProjectProcedure,} from "@/src/server/api/trpc";import { ProjectRole } from "@langfuse/shared/src/db";+import { sendProjectInvitationEmail } from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";-import * as z from "zod";export const projectMembersRouter = createTRPCRouter({get: protectedProjectProcedure@@ -200,12 +202,13 @@ export const projectMembersRouter = createTRPCRouter({if (!project) throw new Error("Project not found");- await sendProjectInvitation(- input.email,- ctx.session.user.name!,- ctx.session.user.email!,- project.name,- );+ await sendProjectInvitationEmail({+ env,+ to: input.email,+ inviterName: ctx.session.user.name!,+ inviterEmail: ctx.session.user.email!,+ projectName: project.name,+ });return invitation;}diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex cfb68456f4..8f6a567b8f 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -10,6 +10,9 @@ import {type ingestionApiSchema,eventTypes,ingestionEvent,+ type TraceUpsertEventType,+ type EventBodyType,+ EventName,} from "@langfuse/shared";import { type ApiAccessScope } from "@/src/features/public-api/server/types";import { persistEventMiddleware } from "@/src/server/api/services/event-service";@@ -446,18 +449,23 @@ export const sendToWorkerIfEnvironmentConfigured = async (env.LANGFUSE_WORKER_PASSWORD &&env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- const traceEvents = batchResults+ const traceEvents: TraceUpsertEventType[] = batchResults.filter((result) => result.type === eventTypes.TRACE_CREATE) // we only have create, no update..map((result) =>result.result &&typeof result.result === "object" &&"id" in result.result? // ingestion API only gets traces for one projectId- { traceId: result.result.id, projectId: projectId }+ { traceId: result.result.id as string, projectId }: null,).filter(isNotNullOrUndefined);+ const body: EventBodyType = {+ name: EventName.TraceUpsert,+ payload: traceEvents,+ };+if (traceEvents.length > 0) {await fetch(`${env.LANGFUSE_WORKER_HOST}/api/events`, {method: "POST",@@ -469,7 +477,7 @@ export const sendToWorkerIfEnvironmentConfigured = async ("admin" + ":" + env.LANGFUSE_WORKER_PASSWORD,).toString("base64"),},- body: JSON.stringify(traceEvents),+ body: JSON.stringify(body),});}}diff --git a/web/src/pages/api/public/traces.ts b/web/src/pages/api/public/traces.tsindex 9fdbf34611..ee453c4d57 100644--- a/web/src/pages/api/public/traces.ts+++ b/web/src/pages/api/public/traces.ts@@ -12,8 +12,7 @@ import {import { TraceBody, eventTypes, stringDate } from "@langfuse/shared";import { v4 } from "uuid";import { telemetry } from "@/src/features/telemetry";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";-import { tracesTableCols, orderBy } from "@langfuse/shared";+import { tracesTableCols, orderBy, orderByToPrismaSql } from "@langfuse/shared";import { isPrismaException } from "@/src/utils/exceptions";const GetTracesSchema = z.object({diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 9594bc419c..fb49e1ecdd 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -19,6 +19,7 @@ import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";import { publicRouter } from "@/src/server/api/routers/public";import { credentialsRouter } from "@/src/features/auth-credentials/server/credentialsRouter";+import { batchExportRouter } from "@/src/server/api/routers/batchExport";/*** This is the primary router for your server.@@ -26,6 +27,7 @@ import { credentialsRouter } from "@/src/features/auth-credentials/server/creden* All routers added in /api/routers should be manually added here.*/export const appRouter = createTRPCRouter({+ batchExport: batchExportRouter,traces: traceRouter,sessions: sessionRouter,generations: generationsRouter,diff --git a/web/src/server/api/routers/batchExport.ts b/web/src/server/api/routers/batchExport.tsnew file mode 100644index 0000000000..38b8c1d8f3--- /dev/null+++ b/web/src/server/api/routers/batchExport.ts@@ -0,0 +1,77 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";+import { WorkerClient } from "@/src/server/api/services/WorkerClient";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import {+ BatchExportStatus,+ type EventBodyType,+ EventName,+ CreateBatchExportSchema,+} from "@langfuse/shared";+import { TRPCError } from "@trpc/server";++export const batchExportRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateBatchExportSchema)+ .mutation(async ({ input, ctx }) => {+ try {+ // Check permissions, esp. projectId+ throwIfNoAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "batchExport:create",+ });++ const { projectId, query, format, name } = input;+ console.log(+ "[TRPC] Creating export job",+ JSON.stringify(input, null, 2),+ );+ const userId = ctx.session.user.id;++ // Create export job+ const exportJob = await ctx.prisma.batchExport.create({+ data: {+ projectId,+ userId,+ status: BatchExportStatus.QUEUED,+ name,+ format,+ query,+ },+ });++ // Create audit log+ await auditLog({+ session: ctx.session,+ resourceType: "batchExport",+ resourceId: exportJob.id,+ projectId,+ action: "create",+ after: exportJob,+ });++ // Notify worker+ const event: EventBodyType = {+ name: EventName.BatchExport,+ payload: {+ batchExportId: exportJob.id,+ projectId,+ },+ };++ await new WorkerClient().sendEvent(event);++ return;+ } catch (e) {+ console.error(e);+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Creating export job failed.",+ });+ }+ }),+});diff --git a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.tsindex 2db7863dda..f808309af8 100644--- a/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts+++ b/web/src/server/api/routers/generations/db/getAllGenerationsSqlQuery.ts@@ -3,7 +3,7 @@ import {tableColumnsToSqlFilterAndPrefix,observationsTableCols,} from "@langfuse/shared";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";+import { orderByToPrismaSql } from "@langfuse/shared";import { type ObservationView, Prisma } from "@langfuse/shared/src/db";import { prisma } from "@langfuse/shared/src/db";import { type GetAllGenerationsInput } from "../getAllQuery";diff --git a/web/src/server/api/routers/generations/exportQuery/index.ts b/web/src/server/api/routers/generations/exportQuery/index.tsindex 863251133f..a3d170f248 100644--- a/web/src/server/api/routers/generations/exportQuery/index.ts+++ b/web/src/server/api/routers/generations/exportQuery/index.ts@@ -1,24 +1,22 @@-import { type Transform } from "stream";import { z } from "zod";import { env } from "@/src/env.mjs";-import { exportFileFormats, exportOptions } from "@langfuse/shared";-import { S3StorageService } from "@/src/server/api/services/S3StorageService";+import { BatchExportFileFormat, exportOptions } from "@langfuse/shared";+import { S3StorageService } from "@langfuse/shared/src/server";import { protectedProjectProcedure } from "@/src/server/api/trpc";import { type ObservationView } from "@langfuse/shared/src/db";--import { DatabaseReadStream } from "../db/DatabaseReadStream";+import {+ DatabaseReadStream,+ streamTransformations,+} from "@langfuse/shared/src/server";import {type FullObservations,getAllGenerations as getAllGenerations,} from "../db/getAllGenerationsSqlQuery";import { GenerationTableOptions } from "../utils/GenerationTableOptions";-import { transformStreamToCsv } from "./transforms/transformStreamToCsv";-import { transformStreamToJson } from "./transforms/transformStreamToJson";-import { transformStreamToJsonLines } from "./transforms/transformStreamToJsonLines";const generationsExportInput = GenerationTableOptions.extend({- fileFormat: z.enum(exportFileFormats),+ fileFormat: z.nativeEnum(BatchExportFileFormat),});export type GenerationsExportInput = z.infer<typeof generationsExportInput>;export type GenerationsExportResult =@@ -61,14 +59,6 @@ export const generationsExportQuery = protectedProjectProcedurequeryPageSize,);- const streamTransformations: Record<- typeof input.fileFormat,- () => Transform- > = {- CSV: transformStreamToCsv,- JSON: transformStreamToJson,- "OPENAI-JSONL": transformStreamToJsonLines,- };const transformation = streamTransformations[input.fileFormat];const fileStream = dbReadStream.pipe(transformation());@@ -76,8 +66,20 @@ export const generationsExportQuery = protectedProjectProcedureconst fileExtension = exportOptions[input.fileFormat].extension;const fileName = `lf-export-${input.projectId}-${fileDate}.${fileExtension}`;- if (S3StorageService.getIsS3StorageConfigured(env)) {- const { signedUrl } = await new S3StorageService().uploadFile({+ const accessKeyId = env.S3_ACCESS_KEY_ID;+ const secretAccessKey = env.S3_SECRET_ACCESS_KEY;+ const bucketName = env.S3_BUCKET_NAME;+ const endpoint = env.S3_ENDPOINT;+ const region = env.S3_REGION;++ if (accessKeyId && secretAccessKey && bucketName && endpoint && region) {+ const { signedUrl } = await new S3StorageService({+ accessKeyId,+ secretAccessKey,+ bucketName,+ endpoint,+ region,+ }).uploadFile({fileName,fileType: exportOptions[input.fileFormat].fileType,data: fileStream,diff --git a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToCsv.ts b/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToCsv.tsdeleted file mode 100644index a3cab5d024..0000000000--- a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToCsv.ts+++ /dev/null@@ -1,95 +0,0 @@-import { Transform, type TransformCallback } from "stream";--import { type ObservationViewWithScores } from "@/src/server/api/routers/generations/getAllQuery";-import { formatIntervalSeconds } from "@/src/utils/dates";--export function transformStreamToCsv(): Transform {- let isFirstChunk = true;-- return new Transform({- objectMode: true,- transform(- row: ObservationViewWithScores,- encoding: BufferEncoding,- callback: TransformCallback,- ): void {- if (isFirstChunk) {- // Output the header if it's the first chunk- const csvHeader = [- "id",- "name",- "traceId",- "traceName",- "startTime",- "endTime",- "completionStartTime",- "timeToFirstToken",- "scores",- "latency",- "latencyPerToken",- "inputCost",- "outputCost",- "totalCost",- "level",- "statusMessage",- "model",- "modelParameters",- "promptTokens",- "completionTokens",- "totalTokens",- "unit",- "input",- "output",- "metadata",- "promptName",- "promptVersion",- ];-- this.push(csvHeader.join(",") + "\n");-- isFirstChunk = false;- }- // Convert the generation object to a CSV line and push it- const csvRow = [- row.id,- row.name ?? "",- row.traceId,- row.traceName,- row.startTime.toISOString(),- row.endTime?.toISOString() ?? "",- row.completionStartTime?.toISOString() ?? "",- // time to first token- row.timeToFirstToken?.toFixed(2) ?? "",- row.scores ? JSON.stringify(row.scores) : "",- row.latency ? formatIntervalSeconds(row.latency).slice(0, -1) : "",- // latency per token- row.latency && row.completionTokens !== 0- ? row.latency / row.completionTokens- : "",- row.calculatedInputCost ? row.calculatedInputCost.toNumber() : "",- row.calculatedOutputCost ? row.calculatedOutputCost.toNumber() : "",- row.calculatedTotalCost ? row.calculatedTotalCost.toNumber() : "",- row.level,- row.statusMessage ?? "",- row.model ?? "",- JSON.stringify(row.modelParameters),- row.promptTokens,- row.completionTokens,- row.totalTokens,- row.unit ?? "",- JSON.stringify(row.input),- JSON.stringify(row.output),- JSON.stringify(row.metadata),- row.promptName ?? "",- row.promptVersion ?? "",- ].map((field) => {- const str = typeof field === "string" ? field : String(field);- return `"${str.replace(/"/g, '""')}"`;- });-- this.push(csvRow.join(",") + "\n");-- callback();- },- });-}diff --git a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJson.ts b/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJson.tsdeleted file mode 100644index 134d63d7e4..0000000000--- a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJson.ts+++ /dev/null@@ -1,63 +0,0 @@-import { Transform, type TransformCallback } from "stream";--import { type ObservationViewWithScores } from "@/src/server/api/routers/generations/getAllQuery";-import { intervalInSeconds } from "@/src/utils/dates";--export function transformStreamToJson(): Transform {- let isFirstElement = true;-- return new Transform({- objectMode: true,-- transform(- row: ObservationViewWithScores,- encoding: BufferEncoding,- callback: TransformCallback,- ): void {- if (isFirstElement) {- this.push("["); // Push the opening bracket for the first element- isFirstElement = false; // Reset the flag after the first element- } else {- this.push(","); // For subsequent elements, prepend a comma- }- const {- calculatedInputCost,- calculatedOutputCost,- calculatedTotalCost,- latency,- ...rest- } = row;-- const rowToPush = {- ...rest,- calculatedInputCost: calculatedInputCost?.toNumber() ?? null,- calculatedOutputCost: calculatedOutputCost?.toNumber() ?? null,- calculatedTotalCost: calculatedTotalCost?.toNumber() ?? null,- latency: latency,- latencyPerToken:- row.latency && row.totalTokens !== 0- ? row.latency / row.totalTokens- : null,- timeToFirstToken: row.completionStartTime- ? intervalInSeconds(row.startTime, row.completionStartTime)- : null,- };-- this.push(JSON.stringify(rowToPush)); // Push the current row as a JSON string-- callback();- },-- // 'final' is called when there is no more data to be consumed, but before the stream is finished.- final(callback: TransformCallback): void {- if (isFirstElement) {- // If no rows were processed, the opening bracket has not been pushed yet.- this.push("[]"); // Push an empty array to ensure valid JSON.- } else {- this.push("]"); // Close JSON array- }-- callback();- },- });-}diff --git a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJsonLines.ts b/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJsonLines.tsdeleted file mode 100644index 9593779a11..0000000000--- a/web/src/server/api/routers/generations/exportQuery/transforms/transformStreamToJsonLines.ts+++ /dev/null@@ -1,51 +0,0 @@-import { Transform, type TransformCallback } from "stream";-import { z } from "zod";--import { jsonSchema } from "@langfuse/shared";-import { type ObservationViewWithScores } from "@/src/server/api/routers/generations/getAllQuery";--export function transformStreamToJsonLines(): Transform {- return new Transform({- objectMode: true,- transform(- row: ObservationViewWithScores,- encoding: BufferEncoding,- callback: TransformCallback,- ): void {- const inputSchemaOpenAI = z.array(- z.object({- role: z.enum(["system", "user", "assistant"]),- content: z.string(),- }),- );-- const outputSchema = z- .object({- completion: jsonSchema,- })- .or(jsonSchema);-- const parsedInput = inputSchemaOpenAI.safeParse(row.input);- const parsedOutput = outputSchema.safeParse(row.output);-- if (parsedInput.success && parsedOutput.success) {- const output = JSON.stringify({- messages: [- ...parsedInput.data,- {- role: "assistant",- content:- typeof parsedOutput.data === "object" &&- "completion" in parsedOutput.data- ? JSON.stringify(parsedOutput.data.completion)- : JSON.stringify(parsedOutput.data),- },- ],- });- this.push(output + "\n");- }-- callback();- },- });-}diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.tsindex 1c22241a7a..42c15a8c89 100644--- a/web/src/server/api/routers/scores.ts+++ b/web/src/server/api/routers/scores.ts@@ -8,13 +8,15 @@ import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import { type ProjectRole, Prisma, type Score } from "@langfuse/shared/src/db";import { paginationZod } from "@langfuse/shared";import { ScoreDataType, singleFilter } from "@langfuse/shared";-import { tableColumnsToSqlFilterAndPrefix } from "@langfuse/shared";+import {+ tableColumnsToSqlFilterAndPrefix,+ orderByToPrismaSql,+} from "@langfuse/shared";import {type ScoreOptions,scoresTableCols,} from "@/src/server/api/definitions/scoresTable";import { orderBy } from "@langfuse/shared";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";import { auditLog } from "@/src/features/audit-logs/auditLog";const ScoreFilterOptions = z.object({diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 739c7e3d0e..28e49fa275 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -6,20 +6,16 @@ import {} from "@/src/server/api/trpc";import {singleFilter,- tableColumnsToSqlFilterAndPrefix,+ type SessionOptions,+ getSessionTableSQL,} from "@langfuse/shared";import { Prisma } from "@langfuse/shared/src/db";import { paginationZod } from "@langfuse/shared";import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import { TRPCError } from "@trpc/server";import { orderBy } from "@langfuse/shared";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";import { auditLog } from "@/src/features/audit-logs/auditLog";import type Decimal from "decimal.js";-import {- type SessionOptions,- sessionsViewCols,-} from "@/src/server/api/definitions/sessionsView";const SessionFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedure@@ -33,16 +29,7 @@ export const sessionRouter = createTRPCRouter({.input(SessionFilterOptions).query(async ({ input, ctx }) => {try {- const filterCondition = tableColumnsToSqlFilterAndPrefix(- input.filter ?? [],- sessionsViewCols,- "sessions",- );-- const orderByCondition = orderByToPrismaSql(- input.orderBy,- sessionsViewCols,- );+ const query = getSessionTableSQL(input);const sessions = await ctx.prisma.$queryRaw<Array<{@@ -61,60 +48,8 @@ export const sessionRouter = createTRPCRouter({completionTokens: number;totalTokens: number;}>- >(Prisma.sql`- SELECT- s.id,- s. "created_at" AS "createdAt",- s.bookmarked,- s.public,- t. "userIds",- t. "countTraces",- o. "sessionDuration",- o. "totalCost" AS "totalCost",- o. "inputCost" AS "inputCost",- o. "outputCost" AS "outputCost",- o. "promptTokens" AS "promptTokens",- o. "completionTokens" AS "completionTokens",- o. "totalTokens" AS "totalTokens",- (count(*) OVER ())::int AS "totalCount"- FROM- trace_sessions AS s- LEFT JOIN LATERAL (- SELECT- t.session_id,- MAX(t. "timestamp") AS "max_timestamp",- MIN(t. "timestamp") AS "min_timestamp",- array_agg(t.id) AS "traceIds",- array_agg(DISTINCT t.user_id) AS "userIds",- count(t.id)::int AS "countTraces"- FROM- traces t- WHERE- t.project_id = ${input.projectId}- AND t.session_id = s.id- GROUP BY- t.session_id) AS t ON TRUE- LEFT JOIN LATERAL (- SELECT- EXTRACT(EPOCH FROM COALESCE(MAX(o. "end_time"), MAX(o. "start_time"), t. "max_timestamp")) - EXTRACT(EPOCH FROM COALESCE(MIN(o. "start_time"), t. "min_timestamp"))::double precision AS "sessionDuration",- SUM(COALESCE(o. "calculated_input_cost", 0)) AS "inputCost",- SUM(COALESCE(o. "calculated_output_cost", 0)) AS "outputCost",- SUM(COALESCE(o. "calculated_total_cost", 0)) AS "totalCost",- SUM(o.prompt_tokens) AS "promptTokens",- SUM(o.completion_tokens) AS "completionTokens",- SUM(o.total_tokens) AS "totalTokens"- FROM- observations_view o- WHERE- o.project_id = ${input.projectId}- AND o.trace_id = ANY (t. "traceIds")) AS o ON TRUE- WHERE- s. "project_id" = ${input.projectId}- ${filterCondition}- ${orderByCondition}- LIMIT ${input.limit}- OFFSET ${input.page * input.limit}- `);+ >(query);+return sessions.map((s) => ({...s,userIds: (s.userIds?.filter((t) => t !== null) ?? []) as string[],diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.tsindex 3858c3cc13..97c2e36318 100644--- a/web/src/server/api/routers/traces.ts+++ b/web/src/server/api/routers/traces.ts@@ -21,7 +21,7 @@ import {import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";import { TRPCError } from "@trpc/server";import { orderBy } from "@langfuse/shared";-import { orderByToPrismaSql } from "@/src/features/orderBy/server/orderByToPrisma";+import { orderByToPrismaSql } from "@langfuse/shared";import { instrumentAsync } from "@/src/utils/instrumentation";import type Decimal from "decimal.js";import { auditLog } from "@/src/features/audit-logs/auditLog";diff --git a/web/src/server/api/services/WorkerClient.ts b/web/src/server/api/services/WorkerClient.tsnew file mode 100644index 0000000000..ae73c5ccd6--- /dev/null+++ b/web/src/server/api/services/WorkerClient.ts@@ -0,0 +1,37 @@+import { env } from "@/src/env.mjs";+import { type EventBodyType } from "@langfuse/shared";++export class WorkerClient {+ readonly enabled: boolean;++ constructor() {+ this.enabled = Boolean(+ env.LANGFUSE_WORKER_HOST &&+ env.LANGFUSE_WORKER_PASSWORD &&+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,+ );++ if (!this.enabled) {+ console.warn("Langfuse Worker is not supported in this environment.");+ }+ }++ async sendEvent(event: EventBodyType): Promise<void> {+ if (!this.enabled) return;++ await fetch(`${env.LANGFUSE_WORKER_HOST}/api/events`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization:+ "Basic " ++ Buffer.from("admin" + ":" + env.LANGFUSE_WORKER_PASSWORD).toString(+ "base64",+ ),+ },+ body: JSON.stringify(event),+ }).catch((error) => {+ console.error("Error sending events to worker", error);+ });+ }+}diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex f8b73ca303..9849fa2744 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -30,8 +30,10 @@ import {} from "@langfuse/ee/sso";import { z } from "zod";import * as Sentry from "@sentry/nextjs";-import { sendResetPasswordVerificationRequest } from "@/src/features/auth-credentials/lib/sendResetPasswordVerificationRequest";-import { CustomSSOProvider } from "@langfuse/shared/src/server/auth";+import {+ CustomSSOProvider,+ sendResetPasswordVerificationRequest,+} from "@langfuse/shared/src/server";const staticProviders: Provider[] = [CredentialsProvider({diff --git a/worker/src/__tests__/redis-consumer.test.ts b/worker/src/__tests__/redis-consumer.test.tsindex bccfcc68c2..e21f25078d 100644--- a/worker/src/__tests__/redis-consumer.test.ts+++ b/worker/src/__tests__/redis-consumer.test.ts@@ -1,10 +1,10 @@import { expect, test, describe, vi } from "vitest";import { evalQueue } from "../api";-import { QueueJobs, TraceUpsertEvent } from "@langfuse/shared";+import { QueueJobs, TraceUpsertEventSchema } from "@langfuse/shared";import { randomUUID } from "crypto";import { z } from "zod";import logger from "../logger";-import { evalJobCreator } from "../redis/consumer";+import { evalJobCreator } from "../queues/evalQueue";describe.sequential("handle redis events", () => {test("handle redis job succeeding", async () => {@@ -12,7 +12,7 @@ describe.sequential("handle redis events", () => {createEvalJobs: async ({data,}: {- data: z.infer<typeof TraceUpsertEvent>;+ data: z.infer<typeof TraceUpsertEventSchema>;}) => {return true;},diff --git a/worker/src/api/index.ts b/worker/src/api/index.tsindex d2d077e0d8..3fba43c5aa 100644--- a/worker/src/api/index.ts+++ b/worker/src/api/index.ts@@ -1,15 +1,24 @@-import express from "express";-import emojis from "./emojis";-import { z } from "zod";-import logger from "../logger";import { Queue } from "bullmq";-import { redis } from "../redis/redis";import { randomUUID } from "crypto";+import express from "express";import basicAuth from "express-basic-auth";-import { env } from "../env";-import { QueueJobs, QueueName, TQueueJobTypes } from "@langfuse/shared";++import {+ EventBodySchema,+ EventName,+ QueueJobs,+ QueueName,+ TQueueJobTypes,+ TraceUpsertEventType,+} from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";+import { env } from "../env";+import logger from "../logger";+import { batchExportQueue } from "../queues/batchExportQueue";+import { redis } from "../redis";+import emojis from "./emojis";+const router = express.Router();export const evalQueue = redis@@ -18,13 +27,6 @@ export const evalQueue = redis}): null;-const eventBody = z.array(- z.object({- traceId: z.string(),- projectId: z.string(),- })-);-type EventsResponse = {status: "success";};@@ -69,24 +71,40 @@ routerconst { body } = req;logger.info(`Received events, ${JSON.stringify(body)}`);- const events = eventBody.parse(body);+ const event = EventBodySchema.parse(body);++ if (event.name === EventName.TraceUpsert) {+ // Find set of traces per project. There might be two events for the same trace in one API call.+ // If we don't deduplicate, we will end up processing the same trace twice on two different workers in parallel.+ const jobs = createRedisEvents(event.payload);+ await evalQueue?.addBulk(jobs); // add all jobs as bulk- // Find set of traces per project. There might be two events for the same trace in one API call.- // If we don't deduplicate, we will end up processing the same trace twice on two different workers in parallel.- const jobs = createRedisEvents(events);+ return res.json({+ status: "success",+ });+ }- await evalQueue?.addBulk(jobs); // add all jobs as bulk+ if (event.name === EventName.BatchExport) {+ await batchExportQueue?.add(event.name, {+ id: event.payload.batchExportId, // Use the batchExportId to deduplicate when the same job is sent multiple times+ name: QueueJobs.BatchExportJob,+ timestamp: new Date(),+ payload: event.payload,+ });++ return res.json({+ status: "success",+ });+ }- res.json({- status: "success",- });+ return res.status(400);});router.use("/emojis", emojis);export default router;-export function createRedisEvents(events: z.infer<typeof eventBody>) {+export function createRedisEvents(events: TraceUpsertEventType[]) {const uniqueTracesPerProject = events.reduce((acc, event) => {if (!acc.get(event.projectId)) {acc.set(event.projectId, new Set());diff --git a/worker/src/app.ts b/worker/src/app.tsindex 88fecb77a9..d19381d2ca 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -12,7 +12,9 @@ require("dotenv").config();import logger from "./logger";-import { evalJobCreator, evalJobExecutor } from "./redis/consumer";+import { evalJobCreator, evalJobExecutor } from "./queues/evalQueue";+import { batchExportJobExecutor } from "./queues/batchExportQueue";+import { repeatQueueExecutor } from "./queues/repeatQueue";import helmet from "helmet";const app = express();@@ -57,18 +59,36 @@ app.use(middlewares.notFound);app.use(middlewares.errorHandler);logger.info("Eval Job Creator started", evalJobCreator?.isRunning());-logger.info("Eval Job Executor started", evalJobExecutor?.isRunning());+logger.info(+ "Batch Export Job Executor started",+ batchExportJobExecutor?.isRunning()+);+logger.info("Repeat Queue Executor started", repeatQueueExecutor?.isRunning());evalJobCreator?.on("failed", (job, err) => {logger.error(err, `Eval Job with id ${job?.id} failed with error ${err}`);});-evalJobCreator?.on("failed", (job, err) => {+evalJobExecutor?.on("failed", (job, err) => {logger.error(err,`Eval execution Job with id ${job?.id} failed with error ${err}`);});+batchExportJobExecutor?.on("failed", (job, err) => {+ logger.error(+ err,+ `Batch Export Job with id ${job?.id} failed with error ${err}`+ );+});++repeatQueueExecutor?.on("failed", (job, err) => {+ logger.error(+ err,+ `Repeat Queue Job with id ${job?.id} failed with error ${err}`+ );+});+export default app;diff --git a/worker/src/env.ts b/worker/src/env.tsindex 8eced077dd..1f68354a36 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -25,6 +25,18 @@ const EnvSchema = z.object({.default(6379),REDIS_AUTH: z.string(),LANGFUSE_WORKER_PASSWORD: z.string(),+ S3_ACCESS_KEY_ID: z.string().optional(),+ S3_SECRET_ACCESS_KEY: z.string().optional(),+ S3_BUCKET_NAME: z.string().optional(),+ S3_ENDPOINT: z.string().optional(),+ S3_REGION: z.string().optional(),+ BATCH_EXPORT_ROW_LIMIT: z.coerce.number().positive().default(50_000),+ BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS: z.coerce+ .number()+ .positive()+ .default(24),+ EMAIL_FROM_ADDRESS: z.string().optional(),+ SMTP_CONNECTION_URL: z.string().optional(),});export const env = EnvSchema.parse(process.env);diff --git a/worker/src/features/batchExport/enqueueBatchExportJobs.ts b/worker/src/features/batchExport/enqueueBatchExportJobs.tsnew file mode 100644index 0000000000..816d86a13e--- /dev/null+++ b/worker/src/features/batchExport/enqueueBatchExportJobs.ts@@ -0,0 +1,48 @@+import { BatchExportStatus, QueueJobs } from "@langfuse/shared";+import { kyselyPrisma } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";++import logger from "../../logger";+import { batchExportQueue } from "../../queues/batchExportQueue";++/**+ * Enqueues batch export jobs from the database to the job queue.+ *+ * @returns A promise that resolves when the jobs are enqueued successfully.+ */+export async function enqueueBatchExportJobs() {+ try {+ const queuedJobs = await kyselyPrisma.$kysely+ .selectFrom("batch_exports")+ .selectAll()+ .where("status", "=", BatchExportStatus.QUEUED)+ .execute();++ if (batchExportQueue) {+ const newJobs = queuedJobs.map(+ (job) =>+ ({+ name: QueueJobs.BatchExportJob,+ data: {+ id: job.id, // Important to deduplicate when the same job is already in the queue+ name: QueueJobs.BatchExportJob,+ timestamp: new Date(),+ payload: {+ batchExportId: job.id,+ projectId: job.project_id,+ },+ },+ }) as const+ );++ await batchExportQueue.addBulk(newJobs);+ logger.info(`Enqueued ${newJobs.length} batch export jobs from postgres`);+ }+ } catch (error) {+ logger.error(+ "Error while checking for QUEUED batch export jobs in postgres",+ error+ );+ Sentry.captureException(error);+ }+}diff --git a/worker/src/features/batchExport/handleBatchExportJob.ts b/worker/src/features/batchExport/handleBatchExportJob.tsnew file mode 100644index 0000000000..07e2b1896b--- /dev/null+++ b/worker/src/features/batchExport/handleBatchExportJob.ts@@ -0,0 +1,169 @@+import { pipeline } from "stream";++import {+ BatchExportFileFormat,+ BatchExportJobType,+ BatchExportQuerySchema,+ BatchExportStatus,+ exportOptions,+ FilterCondition,+ getSessionTableSQL,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import {+ DatabaseReadStream,+ S3StorageService,+ sendBatchExportSuccessEmail,+ streamTransformations,+} from "@langfuse/shared/src/server";++import { env } from "../../env";+import logger from "../../logger";++export const handleBatchExportJob = async (+ batchExportJob: BatchExportJobType+) => {+ const { projectId, batchExportId } = batchExportJob;++ // Get job details from DB+ const jobDetails = await prisma.batchExport.findFirst({+ where: {+ projectId,+ id: batchExportId,+ },+ });++ if (!jobDetails) {+ throw new Error("Job not found");+ }+ if (jobDetails.status !== BatchExportStatus.QUEUED) {+ throw new Error("Job has invalid status: " + jobDetails.status);+ }++ // Set job status to processing+ await prisma.batchExport.update({+ where: {+ id: batchExportId,+ projectId,+ },+ data: {+ status: BatchExportStatus.PROCESSING,+ },+ });++ // Parse query from job+ const parsedQuery = BatchExportQuerySchema.safeParse(jobDetails.query);+ if (!parsedQuery.success) {+ throw new Error("Failed to parse query: " + parsedQuery.error.message);+ }++ // Get database read stream+ let { filter, orderBy, tableName } = parsedQuery.data;++ // Set createdAt cutoff to prevent exporting data that was created after the job was queued+ const createdAtCutoffFilter: FilterCondition = {+ column: "createdAt",+ operator: "<",+ value: jobDetails.createdAt,+ type: "datetime",+ };++ const dbReadStream = new DatabaseReadStream<unknown>(+ async (pageSize: number, offset: number) => {+ const query = getSessionTableSQL({+ projectId,+ filter: filter+ ? [...filter, createdAtCutoffFilter]+ : [createdAtCutoffFilter],+ orderBy,+ limit: pageSize,+ page: Math.floor(offset / pageSize),+ });++ const chunk = await prisma.$queryRaw<unknown[]>(query);++ return chunk;+ },+ 1000,+ env.BATCH_EXPORT_ROW_LIMIT+ );++ // Transform data to desired format+ const fileStream = pipeline(+ dbReadStream,+ streamTransformations[jobDetails.format as BatchExportFileFormat](),+ (err) => {+ if (err) {+ console.error("Getting data from DB and transform failed: ", err);+ }+ }+ );++ // Stream upload results to S3+ const accessKeyId = env.S3_ACCESS_KEY_ID;+ const secretAccessKey = env.S3_SECRET_ACCESS_KEY;+ const bucketName = env.S3_BUCKET_NAME;+ const endpoint = env.S3_ENDPOINT;+ const region = env.S3_REGION;++ if (!accessKeyId || !secretAccessKey || !bucketName || !endpoint || !region) {+ throw new Error("S3 credentials not found");+ }++ const fileDate = new Date().toISOString();+ const fileExtension =+ exportOptions[jobDetails.format as BatchExportFileFormat].extension;+ const fileName = `${fileDate}-lf-${tableName}-export-${projectId}.${fileExtension}`;++ const { signedUrl } = await new S3StorageService({+ accessKeyId,+ secretAccessKey,+ bucketName,+ endpoint,+ region,+ }).uploadFile({+ fileName,+ fileType:+ exportOptions[jobDetails.format as BatchExportFileFormat].fileType,+ data: fileStream,+ });++ logger.info(`Batch export file uploaded to S3`);++ // Update job status+ await prisma.batchExport.update({+ where: {+ id: batchExportId,+ projectId,+ },+ data: {+ status: BatchExportStatus.COMPLETED,+ url: signedUrl,+ finishedAt: new Date(),+ expiresAt: new Date(+ Date.now() ++ env.BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS * 3600 * 1000+ ),+ },+ });++ // Send email to user+ const user = await prisma.user.findFirst({+ where: {+ id: jobDetails.userId,+ },+ });++ if (user?.email) {+ await sendBatchExportSuccessEmail({+ env,+ receiverEmail: user.email,+ downloadLink: signedUrl,+ userName: user?.name || "",+ batchExportName: jobDetails.name,+ expiresInHours: env.BATCH_EXPORT_DOWNLOAD_LINK_EXPIRATION_HOURS,+ });++ logger.info(`Batch export success email sent to user ${user.id}`);+ }+};diff --git a/worker/src/features/evaluation/eval-service.ts b/worker/src/features/evaluation/eval-service.tsindex 907e714054..b3f24cd3bf 100644--- a/worker/src/features/evaluation/eval-service.ts+++ b/worker/src/features/evaluation/eval-service.ts@@ -18,7 +18,7 @@ import {QueueName,singleFilter,tableColumnsToSqlFilterAndPrefix,- TraceUpsertEvent,+ TraceUpsertEventSchema,ValidationError,variableMappingList,ZodModelConfig,@@ -27,14 +27,14 @@ import { decrypt } from "@langfuse/shared/encryption";import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";import logger from "../../logger";-import { evalQueue } from "../../redis/consumer";+import { evalQueue } from "../../queues/evalQueue";// this function is used to determine which eval jobs to create for a given trace// there might be multiple eval jobs to create for a single traceexport const createEvalJobs = async ({event,}: {- event: z.infer<typeof TraceUpsertEvent>;+ event: z.infer<typeof TraceUpsertEventSchema>;}) => {const configs = await kyselyPrisma.$kysely.selectFrom("job_configurations")diff --git a/worker/src/index.ts b/worker/src/index.tsindex 6bebb4fd79..d245ffceaa 100644--- a/worker/src/index.ts+++ b/worker/src/index.ts@@ -1,7 +1,8 @@import app from "./app";import { env } from "./env";import logger from "./logger";-import { evalJobCreator, evalJobExecutor } from "./redis/consumer";+import { evalJobCreator, evalJobExecutor } from "./queues/evalQueue";+import { batchExportJobExecutor } from "./queues/batchExportQueue";const server = app.listen(env.PORT, () => {logger.info(`Listening: http://localhost:${env.PORT}`);@@ -22,6 +23,9 @@ function onShutdown() {evalJobExecutor?.close().then(() => logger.info("Eval Job Executor has been closed."));+ batchExportJobExecutor+ ?.close()+ .then(() => logger.info("Batch Export Executor has been closed."));}// Capture shutdown signalsdiff --git a/worker/src/queues/batchExportQueue.ts b/worker/src/queues/batchExportQueue.tsnew file mode 100644index 0000000000..26423cbd4f--- /dev/null+++ b/worker/src/queues/batchExportQueue.ts@@ -0,0 +1,75 @@+import { Job, Queue, Worker } from "bullmq";++import {+ BaseError,+ BatchExportStatus,+ QueueName,+ TQueueJobTypes,+} from "@langfuse/shared";+import { kyselyPrisma } from "@langfuse/shared/src/db";+import * as Sentry from "@sentry/node";++import { instrumentAsync } from "../instrumentation";+import logger from "../logger";+import { redis } from "../redis";+import { handleBatchExportJob } from "../features/batchExport/handleBatchExportJob";++export const batchExportQueue = redis+ ? new Queue<TQueueJobTypes[QueueName.BatchExport]>(QueueName.BatchExport, {+ connection: redis,+ })+ : null;++export const batchExportJobExecutor = redis+ ? new Worker<TQueueJobTypes[QueueName.BatchExport]>(+ QueueName.BatchExport,+ async (job: Job<TQueueJobTypes[QueueName.BatchExport]>) => {+ return instrumentAsync(+ { name: "batchExportJobExecutor" },+ async (span) => {+ try {+ logger.info("Executing Batch Export Job", job.data.payload);+ await handleBatchExportJob(job.data.payload);++ logger.info("Finished Batch Export Job", job.data.payload);++ return true;+ } catch (e) {+ const displayError =+ e instanceof BaseError+ ? e.message+ : "An internal error occurred";++ await kyselyPrisma.$kysely+ .updateTable("batch_exports")+ .set("status", BatchExportStatus.FAILED)+ .set("finished_at", new Date())+ .set("log", displayError)+ .where("id", "=", job.data.payload.batchExportId)+ .where("project_id", "=", job.data.payload.projectId)+ .execute();++ logger.error(+ e,+ `Failed Batch Export job for id ${job.data.payload.batchExportId} ${e}`+ );+ Sentry.captureException(e);++ throw e;+ } finally {+ span?.end();+ }+ }+ );+ },+ {+ connection: redis,+ concurrency: 1, // only 1 job at a time+ limiter: {+ // execute 1 batch export in 5 seconds to avoid overloading the DB+ max: 1,+ duration: 5_000,+ },+ }+ )+ : null;diff --git a/worker/src/redis/consumer.ts b/worker/src/queues/evalQueue.tssimilarity index 98%rename from worker/src/redis/consumer.tsrename to worker/src/queues/evalQueue.tsindex 4d1a878f94..a654493750 100644--- a/worker/src/redis/consumer.ts+++ b/worker/src/queues/evalQueue.ts@@ -9,7 +9,7 @@ import { evaluate, createEvalJobs } from "../features/evaluation/eval-service";import { kyselyPrisma } from "@langfuse/shared/src/db";import logger from "../logger";import { sql } from "kysely";-import { redis } from "./redis";+import { redis } from "../redis";import { instrumentAsync } from "../instrumentation";import * as Sentry from "@sentry/node";diff --git a/worker/src/queues/repeatQueue.ts b/worker/src/queues/repeatQueue.tsnew file mode 100644index 0000000000..33d2b83884--- /dev/null+++ b/worker/src/queues/repeatQueue.ts@@ -0,0 +1,33 @@+import { Queue, Worker } from "bullmq";++import { redis } from "../redis";+import { enqueueBatchExportJobs } from "../features/batchExport/enqueueBatchExportJobs";+import { QueueJobs, QueueName } from "@langfuse/shared";++export const repeatQueue = redis+ ? new Queue(QueueName.RepeatQueue, { connection: redis })+ : null;++if (repeatQueue) {+ repeatQueue.add(+ QueueJobs.EnqueueBatchExportJobs,+ {},+ {+ repeat: { pattern: "*/10 * * * *" },+ }+ );+}++export const repeatQueueExecutor = redis+ ? new Worker(+ QueueName.RepeatQueue,+ async (job) => {+ if (job.name === QueueJobs.EnqueueBatchExportJobs) {+ return enqueueBatchExportJobs();+ }+ },+ {+ connection: redis,+ }+ )+ : null;diff --git a/worker/src/redis/redis.ts b/worker/src/redis.tssimilarity index 90%rename from worker/src/redis/redis.tsrename to worker/src/redis.tsindex 1704f34f20..5739125246 100644--- a/worker/src/redis/redis.ts+++ b/worker/src/redis.ts@@ -1,6 +1,6 @@import Redis from "ioredis";-import { env } from "../env";-import logger from "../logger";+import { env } from "./env";+import logger from "./logger";const createRedisClient = () => {try {