🪢 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
chore: add instrumentation to auth apis (#3069)
Max Deichmann12458e3d71c0
diff --git a/packages/shared/src/server/instrumentation/index.ts b/packages/shared/src/server/instrumentation/index.tsindex 80e2880257..58b2568a19 100644--- a/packages/shared/src/server/instrumentation/index.ts+++ b/packages/shared/src/server/instrumentation/index.ts@@ -10,43 +10,53 @@ export type SpanCtx = {traceScope?: string;};-type CallbackFn<T> = () => T | Promise<T>;+type AsyncCallbackFn<T> = () => Promise<T>;-export function instrument<T>(+export async function instrumentAsync<T>(ctx: SpanCtx,- callback: CallbackFn<T>-): T extends Promise<any> ? Promise<T> : T {- return getTracer(ctx.traceScope ?? callback.name).startActiveSpan(+ callback: AsyncCallbackFn<T>+): Promise<T> {+ return await getTracer(ctx.traceScope ?? callback.name).startActiveSpan(ctx.name,{root: ctx.rootSpan,kind: ctx.spanKind,},(span) => {- const handleResult = (result: T) => {+ try {+ const result = callback();span.end();return result;- };-- const handleError = (ex: unknown) => {+ } catch (ex) {traceException(ex as opentelemetry.Exception, span);span.end();throw ex;- };+ }+ }+ );+}+type SyncCallbackFn<T> = () => T;++export function instrumentSync<T>(+ ctx: SpanCtx,+ callback: SyncCallbackFn<T>+): T {+ return getTracer(ctx.traceScope ?? callback.name).startActiveSpan(+ ctx.name,+ {+ root: ctx.rootSpan,+ kind: ctx.spanKind,+ },+ (span) => {try {const result = callback();- if (result instanceof Promise) {- return result- .then(handleResult)- .catch(handleError) as T extends Promise<any> ? Promise<T> : T;- } else {- return handleResult(result) as T extends Promise<any>- ? Promise<T>- : T;- }+ span.end();+ return result;} catch (ex) {- return handleError(ex) as T extends Promise<any> ? Promise<T> : T;+ traceException(ex as opentelemetry.Exception, span);+ span.end();+ throw ex;}});diff --git a/web/src/server/api/services/WorkerClient.ts b/web/src/server/api/services/WorkerClient.tsindex d6d6e3ec54..49e3d78ad6 100644--- a/web/src/server/api/services/WorkerClient.ts+++ b/web/src/server/api/services/WorkerClient.ts@@ -1,6 +1,6 @@import { env } from "@/src/env.mjs";import {- instrument,+ instrumentAsync,type EventBodyType,type IngestionApiSchemaWithProjectId,} from "@langfuse/shared/src/server";@@ -31,7 +31,7 @@ export class WorkerClient {}async sendIngestionBatch(params: IngestionApiSchemaWithProjectId) {- await instrument({ name: "insert-clickhouse" }, async () => {+ await instrumentAsync({ name: "insert-clickhouse" }, async () => {await this.sendWorkerRequest({method: "POST",route: "/api/ingestion",diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 20fd186d80..280a53e208 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -34,6 +34,7 @@ import {CustomSSOProvider,traceException,sendResetPasswordVerificationRequest,+ instrumentAsync,} from "@langfuse/shared/src/server";import { getOrganizationPlan } from "@/src/features/entitlements/server/getOrganizationPlan";import { projectRoleAccessRights } from "@/src/features/rbac/constants/projectAccessRights";@@ -302,160 +303,169 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {},callbacks: {async session({ session, token }): Promise<Session> {- const dbUser = await prisma.user.findUnique({- where: {- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion- email: token.email!.toLowerCase(),- },- select: {- id: true,- name: true,- email: true,- image: true,- emailVerified: true,- featureFlags: true,- admin: true,- organizationMemberships: {- include: {- organization: {- include: {- projects: true,+ return instrumentAsync({ name: "next-auth-session" }, async () => {+ const dbUser = await prisma.user.findUnique({+ where: {+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion+ email: token.email!.toLowerCase(),+ },+ select: {+ id: true,+ name: true,+ email: true,+ image: true,+ emailVerified: true,+ featureFlags: true,+ admin: true,+ organizationMemberships: {+ include: {+ organization: {+ include: {+ projects: true,+ },},- },- ProjectMemberships: {- include: {- project: true,+ ProjectMemberships: {+ include: {+ project: true,+ },},},},},- },- });+ });- return {- ...session,- environment: {- enableExperimentalFeatures:- env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",- disableExpensivePostgresQueries:- env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES === "true",- // Enables features that are only available under an enterprise license when self-hosting Langfuse- // If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)- eeEnabled: env.LANGFUSE_EE_LICENSE_KEY !== undefined,- },- user:- dbUser !== null- ? {- ...session.user,- id: dbUser.id,- name: dbUser.name,- email: dbUser.email,- image: dbUser.image,- admin: dbUser.admin,- canCreateOrganizations: canCreateOrganizations(dbUser.email),- organizations: dbUser.organizationMemberships.map(- (orgMembership) => {- const parsedCloudConfig = CloudConfigSchema.safeParse(- orgMembership.organization.cloudConfig,- );- return {- id: orgMembership.organization.id,- name: orgMembership.organization.name,- role: orgMembership.role,- cloudConfig: parsedCloudConfig.data,- projects: orgMembership.organization.projects- .map((project) => {- const projectRole: Role =- orgMembership.ProjectMemberships.find(- (membership) =>- membership.projectId === project.id,- )?.role ?? orgMembership.role;- return {- id: project.id,- name: project.name,- role: projectRole,- };- })- // Only include projects where the user has the required role- .filter((project) =>- projectRoleAccessRights[project.role].includes(- "project:read",+ return {+ ...session,+ environment: {+ enableExperimentalFeatures:+ env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES === "true",+ disableExpensivePostgresQueries:+ env.LANGFUSE_DISABLE_EXPENSIVE_POSTGRES_QUERIES === "true",+ // Enables features that are only available under an enterprise license when self-hosting Langfuse+ // If you edit this line, you risk executing code that is not MIT licensed (self-contained in /ee folders otherwise)+ eeEnabled: env.LANGFUSE_EE_LICENSE_KEY !== undefined,+ },+ user:+ dbUser !== null+ ? {+ ...session.user,+ id: dbUser.id,+ name: dbUser.name,+ email: dbUser.email,+ image: dbUser.image,+ admin: dbUser.admin,+ canCreateOrganizations: canCreateOrganizations(+ dbUser.email,+ ),+ organizations: dbUser.organizationMemberships.map(+ (orgMembership) => {+ const parsedCloudConfig = CloudConfigSchema.safeParse(+ orgMembership.organization.cloudConfig,+ );+ return {+ id: orgMembership.organization.id,+ name: orgMembership.organization.name,+ role: orgMembership.role,+ cloudConfig: parsedCloudConfig.data,+ projects: orgMembership.organization.projects+ .map((project) => {+ const projectRole: Role =+ orgMembership.ProjectMemberships.find(+ (membership) =>+ membership.projectId === project.id,+ )?.role ?? orgMembership.role;+ return {+ id: project.id,+ name: project.name,+ role: projectRole,+ };+ })+ // Only include projects where the user has the required role+ .filter((project) =>+ projectRoleAccessRights[project.role].includes(+ "project:read",+ ),),- ),- // Enables features/entitlements based on the plan of the organization, either cloud or EE version when self-hosting- // If you edit this line, you risk executing code that is not MIT licensed (contained in /ee folders, see LICENSE)- plan: getOrganizationPlan(parsedCloudConfig.data),- };- },- ),- emailVerified: dbUser.emailVerified?.toISOString(),- featureFlags: parseFlags(dbUser.featureFlags),- }- : null,- };+ // Enables features/entitlements based on the plan of the organization, either cloud or EE version when self-hosting+ // If you edit this line, you risk executing code that is not MIT licensed (contained in /ee folders, see LICENSE)+ plan: getOrganizationPlan(parsedCloudConfig.data),+ };+ },+ ),+ emailVerified: dbUser.emailVerified?.toISOString(),+ featureFlags: parseFlags(dbUser.featureFlags),+ }+ : null,+ };+ });},async signIn({ user, account, profile }) {- // Block sign in without valid user.email- const email = user.email?.toLowerCase();- if (!email) {- console.error("No email found in user object");- throw new Error("No email found in user object");- }- if (z.string().email().safeParse(email).success === false) {- console.error("Invalid email found in user object");- throw new Error("Invalid email found in user object");- }-- // EE: Check custom SSO enforcement, enforce the specific SSO provider on email domain- // This also blocks setting a password for an email that is enforced to use SSO via password reset flow- const domain = email.split("@")[1];- const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);- if (customSsoProvider && account?.provider !== customSsoProvider) {- console.log(- "Custom SSO provider enforced for domain, user signed in with other provider",- );- throw new Error(`You must sign in via SSO for this domain.`);- }+ return instrumentAsync({ name: "next-auth-sign-in" }, async () => {+ // Block sign in without valid user.email+ const email = user.email?.toLowerCase();+ if (!email) {+ console.error("No email found in user object");+ throw new Error("No email found in user object");+ }+ if (z.string().email().safeParse(email).success === false) {+ console.error("Invalid email found in user object");+ throw new Error("Invalid email found in user object");+ }- // Only allow sign in via email link if user is already in db as this is used for password reset- if (account?.provider === "email") {- const user = await prisma.user.findUnique({- where: {- email: email,- },- });- if (user) {- return true;- } else {- // Add random delay to prevent leaking if user exists as otherwise it would be instant compared to sending an email- await new Promise((resolve) =>- setTimeout(resolve, Math.random() * 2000 + 200),+ // EE: Check custom SSO enforcement, enforce the specific SSO provider on email domain+ // This also blocks setting a password for an email that is enforced to use SSO via password reset flow+ const domain = email.split("@")[1];+ const customSsoProvider = await getSsoAuthProviderIdForDomain(domain);+ if (customSsoProvider && account?.provider !== customSsoProvider) {+ console.log(+ "Custom SSO provider enforced for domain, user signed in with other provider",);- // Prevents sign in with email link if user does not exist- return false;+ throw new Error(`You must sign in via SSO for this domain.`);}- }- // Optional configuration: validate authorised email domains for google provider- // uses hd (hosted domain) claim from google profile as the domain- // https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payload- if (env.AUTH_GOOGLE_ALLOWED_DOMAINS && account?.provider === "google") {- const allowedDomains =- env.AUTH_GOOGLE_ALLOWED_DOMAINS?.split(",").map((domain) =>- domain.trim().toLowerCase(),- ) ?? [];-- if (allowedDomains.length > 0) {- return await Promise.resolve(- allowedDomains.includes(- (profile as GoogleProfile).hd?.toLowerCase(),- ),- );+ // Only allow sign in via email link if user is already in db as this is used for password reset+ if (account?.provider === "email") {+ const user = await prisma.user.findUnique({+ where: {+ email: email,+ },+ });+ if (user) {+ return true;+ } else {+ // Add random delay to prevent leaking if user exists as otherwise it would be instant compared to sending an email+ await new Promise((resolve) =>+ setTimeout(resolve, Math.random() * 2000 + 200),+ );+ // Prevents sign in with email link if user does not exist+ return false;+ }}- }- return await Promise.resolve(true);+ // Optional configuration: validate authorised email domains for google provider+ // uses hd (hosted domain) claim from google profile as the domain+ // https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payload+ if (+ env.AUTH_GOOGLE_ALLOWED_DOMAINS &&+ account?.provider === "google"+ ) {+ const allowedDomains =+ env.AUTH_GOOGLE_ALLOWED_DOMAINS?.split(",").map((domain) =>+ domain.trim().toLowerCase(),+ ) ?? [];++ if (allowedDomains.length > 0) {+ return await Promise.resolve(+ allowedDomains.includes(+ (profile as GoogleProfile).hd?.toLowerCase(),+ ),+ );+ }+ }++ return await Promise.resolve(true);+ });},},adapter: extendedPrismaAdapter,diff --git a/worker/src/features/tokenisation/usage.ts b/worker/src/features/tokenisation/usage.tsindex cea9c48802..7e3a641be7 100644--- a/worker/src/features/tokenisation/usage.ts+++ b/worker/src/features/tokenisation/usage.ts@@ -10,7 +10,7 @@ import {} from "tiktoken";import { z } from "zod";-import { instrument } from "@langfuse/shared/src/server";+import { instrumentSync } from "@langfuse/shared/src/server";const OpenAiTokenConfig = z.object({tokenizerModel: z.string().refine(isTiktokenModel, {@@ -32,7 +32,7 @@ export function tokenCount(p: {model: Model;text: unknown;}): number | undefined {- return instrument(+ return instrumentSync({name: "token-count",},diff --git a/worker/src/queues/batchExportQueue.ts b/worker/src/queues/batchExportQueue.tsindex f61f21f4ea..d9c7005461 100644--- a/worker/src/queues/batchExportQueue.ts+++ b/worker/src/queues/batchExportQueue.ts@@ -5,7 +5,7 @@ import { kyselyPrisma } from "@langfuse/shared/src/db";import {traceException,- instrument,+ instrumentAsync,createNewRedisInstance,} from "@langfuse/shared/src/server";import logger from "../logger";@@ -19,7 +19,7 @@ const createBatchExportJobExecutor = () => {return new Worker<TQueueJobTypes[QueueName.BatchExport]>(QueueName.BatchExport,async (job: Job<TQueueJobTypes[QueueName.BatchExport]>) => {- return instrument(+ return instrumentAsync({name: "batchExportJobExecutor",spanKind: SpanKind.CONSUMER,diff --git a/worker/src/queues/cloudUsageMeteringQueue.ts b/worker/src/queues/cloudUsageMeteringQueue.tsindex 63e12203da..dd1f207163 100644--- a/worker/src/queues/cloudUsageMeteringQueue.ts+++ b/worker/src/queues/cloudUsageMeteringQueue.ts@@ -4,7 +4,7 @@ import {redis,QueueName,QueueJobs,- instrument,+ instrumentAsync,createNewRedisInstance,} from "@langfuse/shared/src/server";import { handleCloudUsageMeteringJob } from "../ee/cloudUsageMetering/handleCloudUsageMeteringJob";@@ -42,7 +42,7 @@ const createCloudUsageMeteringJobExecutor = () => {QueueName.CloudUsageMeteringQueue,async (job) => {if (job.name === QueueJobs.CloudUsageMeteringJob) {- return instrument(+ return instrumentAsync({ name: "cloudUsageMeteringJobExecutor" },async () => {logger.info("Executing Cloud Usage Metering Job", job.data);diff --git a/worker/src/queues/evalQueue.ts b/worker/src/queues/evalQueue.tsindex 9e92a060b5..9dc3b4be54 100644--- a/worker/src/queues/evalQueue.ts+++ b/worker/src/queues/evalQueue.ts@@ -9,7 +9,7 @@ import {QueueName,TQueueJobTypes,traceException,- instrument,+ instrumentAsync,recordIncrement,recordHistogram,recordGauge,@@ -44,7 +44,7 @@ const createEvalJobCreator = () => {return new Worker<TQueueJobTypes[QueueName.TraceUpsert]>(QueueName.TraceUpsert,async (job: Job<TQueueJobTypes[QueueName.TraceUpsert]>) => {- return instrument(+ return instrumentAsync({name: "evalJobCreator",rootSpan: true,@@ -107,7 +107,7 @@ const createEvalJobExecutor = () => {return new Worker<TQueueJobTypes[QueueName.EvaluationExecution]>(QueueName.EvaluationExecution,async (job: Job<TQueueJobTypes[QueueName.EvaluationExecution]>) => {- return instrument(+ return instrumentAsync({name: "evalJobExecutor",spanKind: SpanKind.CONSUMER,diff --git a/worker/src/queues/ingestionFlushQueueExecutor.ts b/worker/src/queues/ingestionFlushQueueExecutor.tsindex f4ca0f4a69..0188789958 100644--- a/worker/src/queues/ingestionFlushQueueExecutor.ts+++ b/worker/src/queues/ingestionFlushQueueExecutor.ts@@ -9,7 +9,7 @@ import { prisma } from "@langfuse/shared/src/db";import {clickhouseClient,getIngestionFlushQueue,- instrument,+ instrumentAsync,recordIncrement,recordGauge,recordHistogram,@@ -28,7 +28,7 @@ const createIngestionQueueExecutor = () => {return new Worker(QueueName.IngestionFlushQueue,async (job) => {- return instrument(+ return instrumentAsync({name: "flush-ingestion-consumer",spanKind: SpanKind.CONSUMER,diff --git a/worker/src/queues/legacyIngestionQueue.ts b/worker/src/queues/legacyIngestionQueue.tsindex 033e0b0dd0..101a1af168 100644--- a/worker/src/queues/legacyIngestionQueue.ts+++ b/worker/src/queues/legacyIngestionQueue.ts@@ -2,7 +2,7 @@ import { Job, Worker } from "bullmq";import {traceException,getLegacyIngestionQueue,- instrument,+ instrumentAsync,QueueName,recordIncrement,recordGauge,@@ -26,7 +26,7 @@ const createLegacyIngestionExecutor = () => {return new Worker<TQueueJobTypes[QueueName.LegacyIngestionQueue]>(QueueName.LegacyIngestionQueue,async (job: Job<TQueueJobTypes[QueueName.LegacyIngestionQueue]>) => {- return instrument(+ return instrumentAsync({name: "legacyIngestion",spanKind: SpanKind.CONSUMER,diff --git a/worker/src/services/ClickhouseWriter/index.ts b/worker/src/services/ClickhouseWriter/index.tsindex d27f986221..fb12879065 100644--- a/worker/src/services/ClickhouseWriter/index.ts+++ b/worker/src/services/ClickhouseWriter/index.ts@@ -9,7 +9,7 @@ import {import { env } from "../../env";import logger from "../../logger";-import { instrument } from "@langfuse/shared/src/server";+import { instrumentAsync } from "@langfuse/shared/src/server";import { SpanKind } from "@opentelemetry/api";export class ClickhouseWriter {@@ -78,7 +78,7 @@ export class ClickhouseWriter {}private async flushAll(fullQueue = false) {- return instrument(+ return instrumentAsync({name: "write-to-clickhouse",spanKind: SpanKind.CONSUMER,diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 91667dfc29..afe82595f7 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -31,7 +31,7 @@ import {} from "@langfuse/shared/src/server";import { tokenCount } from "../../features/tokenisation/usage";-import { instrument } from "@langfuse/shared/src/server";+import { instrumentAsync } from "@langfuse/shared/src/server";import logger from "../../logger";import { ClickhouseWriter, TableName } from "../ClickhouseWriter";import { convertJsonSchemaToRecord, overwriteObject } from "./utils";@@ -598,7 +598,7 @@ export class IngestionService {};const { projectId, entityId, table } = params;- return await instrument({ name: `get-${table}` }, async () => {+ return await instrumentAsync({ name: `get-${table}` }, async () => {const queryResult = await this.clickhouseClient.query({query: `SELECT * FROM ${table} WHERE project_id = '${projectId}' AND id = '${entityId}' ORDER BY updated_at DESC LIMIT 1`,format: "JSONEachRow",