import { Logger, LogLevel, getGlobalLogger, LangfuseAPIClient, LANGFUSE_SDK_VERSION, LangfuseOtelSpanAttributes, LangfuseOtelContextKeys, getEnv, base64Encode, getLangfuseTraceIdFromBaggage, getPropagatedAttributesFromContext, serializeMetadataValue, serializeAvailableSkills, SkillReference, } from "@langfuse/core"; import { Context } from "@opentelemetry/api"; import { hrTimeToMilliseconds } from "@opentelemetry/core"; import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"; import { CompressionAlgorithm } from "@opentelemetry/otlp-exporter-base"; import { Span, BatchSpanProcessor, SimpleSpanProcessor, SpanExporter, ReadableSpan, SpanProcessor, } from "@opentelemetry/sdk-trace-base"; import { withDefaultHeaders } from "./headers.js"; import { MediaService } from "./MediaService.js"; import { SizeLimitedSpanExporter, resolveMaxBatchSizeBytesFromEnvironment, } from "./size-limited-span-exporter.js"; import { isDefaultExportSpan } from "./span-filter.js"; /** * Function type for masking sensitive data in spans before export. * * Applied to the input and output of observations and traces, and to each * observation metadata value, one attribute at a time. Metadata keys are never * passed to the mask, so masked metadata keeps its keys. Trace metadata * propagated with `propagateAttributes` is not masked. * * Observation metadata values are passed decoded, e.g. the string `"prod"`, * the number `3` or an object, not their JSON encoding. The masked value is * JSON-encoded again before export; if it is `null` or `undefined`, the * metadata key is dropped. * * @param params - Object containing the data to be masked * @param params.data - The data that should be masked * @returns The masked data, or a promise resolving to it * * @example * ```typescript * const maskFunction: MaskFunction = async ({ data }) => { * if (typeof data === 'string') { * return data.replace(/password=\w+/g, 'password=***'); * } * return data; * }; * ``` * * @public */ export type MaskFunction = (params: { data: any }) => any | Promise; /** * Function type for determining whether a span should be exported to Langfuse. * If provided, this is treated as a full override of the default filtering behavior. * Langfuse may call this predicate both when a span starts for app-root classification * and when the span ends for export filtering. Prefer side-effect-free predicates; the * start-time call sees only attributes available at span creation, and end-time fields * such as duration may not be populated yet. * * @param params - Object containing the span to evaluate * @param params.otelSpan - The OpenTelemetry span to evaluate * @returns `true` if the span should be exported, `false` otherwise * * @example * ```typescript * const shouldExportSpan: ShouldExportSpan = ({ otelSpan }) => { * // Only export spans that took longer than 100ms * return otelSpan.duration[0] * 1000 + otelSpan.duration[1] / 1000000 > 100; * }; * ``` * * @public */ export type ShouldExportSpan = (params: { otelSpan: ReadableSpan }) => boolean; /** * Configuration parameters for the LangfuseSpanProcessor. * * @public */ export interface LangfuseSpanProcessorParams { /** * Custom OpenTelemetry span exporter. If not provided, a default OTLP exporter will be used. * Custom exporters bypass Langfuse's OTLP batch byte limit and must enforce * any transport-specific request limits themselves. */ exporter?: SpanExporter; /** * Langfuse public API key. Can also be set via LANGFUSE_PUBLIC_KEY environment variable. */ publicKey?: string; /** * Langfuse secret API key. Can also be set via LANGFUSE_SECRET_KEY environment variable. */ secretKey?: string; /** * Langfuse instance base URL. Can also be set via LANGFUSE_BASE_URL environment variable. * @defaultValue "https://cloud.langfuse.com" */ baseUrl?: string; /** * Number of spans to batch before flushing. Can also be set via LANGFUSE_FLUSH_AT environment variable. */ flushAt?: number; /** * Flush interval in seconds. Can also be set via LANGFUSE_FLUSH_INTERVAL environment variable. */ flushInterval?: number; /** * Function to mask sensitive data in spans before export. */ mask?: MaskFunction; /** * Function to determine whether a span should be exported to Langfuse. * If not provided, a smart default filter is applied to export Langfuse spans, * spans with `gen_ai.` attributes, and spans from known LLM instrumentors. */ shouldExportSpan?: ShouldExportSpan; /** * Whether media detection and upload should be attempted by the processor. * Can also be set via LANGFUSE_MEDIA_UPLOAD_ENABLED environment variable. * * Set to `false` to keep base64 media payloads unchanged on exported spans. * * @defaultValue true */ mediaUploadEnabled?: boolean; /** * Environment identifier for the traces. Can also be set via LANGFUSE_TRACING_ENVIRONMENT environment variable. */ environment?: string; /** * Release identifier for the traces. Can also be set via LANGFUSE_RELEASE environment variable. */ release?: string; /** * Available skills to attach when a scope enables via attachSkills. * Propagated skillsAvailable take precedence. */ skills?: { available: SkillReference[]; }; /** * Request timeout in seconds. Can also be set via LANGFUSE_TIMEOUT environment variable. * @defaultValue 5 */ timeout?: number; /** * Additional HTTP headers to include with requests. * Overrides default span export headers with the same name, such as * `x-langfuse-ingestion-version` (default `"4"`). */ additionalHeaders?: Record; /** * Compression for span export requests: `"gzip"` or `"none"`. * Can also be set via LANGFUSE_OTEL_COMPRESSION environment variable. * When unset, falls back to the OTEL_EXPORTER_OTLP_TRACES_COMPRESSION and * OTEL_EXPORTER_OTLP_COMPRESSION environment variables, then to `"gzip"`. * Set any of them to `"none"` to disable compression. * * Ignored when a custom `exporter` is provided. Only takes effect on Node.js and Bun; * browser and edge runtimes ignore it. Every Langfuse v4 server accepts gzip. * * @defaultValue "gzip" */ compression?: "gzip" | "none"; /** * Span export mode to use. * * - **batched**: Recommended for production environments with long-running processes. * Spans are batched and exported in groups for optimal performance. * - **immediate**: Recommended for short-lived environments such as serverless functions. * Spans are exported immediately to prevent data loss when the process terminates / is frozen. * * @defaultValue "batched" */ exportMode?: "immediate" | "batched"; } /** * OpenTelemetry span processor for sending spans to Langfuse. * * This processor extends the standard BatchSpanProcessor to provide: * - Automatic batching and flushing of spans to Langfuse * - Media content extraction and upload from base64 data URIs * - Data masking capabilities for sensitive information * - Conditional span export based on custom logic * (or default smart filtering when no custom filter is provided) * - Environment and release tagging * * @example * ```typescript * import { NodeSDK } from '@opentelemetry/sdk-node'; * import { LangfuseSpanProcessor } from '@langfuse/otel'; * * const sdk = new NodeSDK({ * spanProcessors: [ * new LangfuseSpanProcessor({ * publicKey: 'pk_...', * secretKey: 'sk_...', * baseUrl: 'https://cloud.langfuse.com', * environment: 'production', * mask: ({ data }) => { * // Metadata values reach the mask decoded, so data is not always a string * return typeof data === 'string' * ? data.replace(/api_key=\w+/g, 'api_key=***') * : data; * } * }) * ] * }); * * sdk.start(); * ``` * * @public */ export class LangfuseSpanProcessor implements SpanProcessor { private pendingEndedSpans: Set> = new Set(); private publicKey?: string; private baseUrl?: string; private environment?: string; private release?: string; private availableSkills?: string; private mask?: MaskFunction; private shouldExportSpan: ShouldExportSpan; private mediaUploadEnabled: boolean; private apiClient: LangfuseAPIClient; private processor: SpanProcessor; private mediaService: MediaService; private spanExportExpectationById: Map = new Map(); /** * Creates a new LangfuseSpanProcessor instance. * * @param params - Configuration parameters for the processor * * @example * ```typescript * const processor = new LangfuseSpanProcessor({ * publicKey: 'pk_...', * secretKey: 'sk_...', * environment: 'staging', * flushAt: 10, * flushInterval: 2, * mask: ({ data }) => { * // Custom masking logic * return typeof data === 'string' * ? data.replace(/secret_\w+/g, 'secret_***') * : data; * }, * shouldExportSpan: ({ otelSpan }) => { * // Full override of default filtering: * // export only spans from specific services * return otelSpan.name.startsWith("my-service"); * } * }); * ``` */ constructor(params?: LangfuseSpanProcessorParams) { const logger = getGlobalLogger(); const publicKey = params?.publicKey ?? getEnv("LANGFUSE_PUBLIC_KEY"); const secretKey = params?.secretKey ?? getEnv("LANGFUSE_SECRET_KEY"); const baseUrl = params?.baseUrl ?? getEnv("LANGFUSE_BASE_URL") ?? getEnv("LANGFUSE_BASEURL") ?? // legacy v2 "https://cloud.langfuse.com"; if (!params?.exporter && !publicKey) { logger.warn( "No exporter configured and no public key provided in constructor or as LANGFUSE_PUBLIC_KEY env var. Span exports will fail.", ); } if (!params?.exporter && !secretKey) { logger.warn( "No exporter configured and no secret key provided in constructor or as LANGFUSE_SECRET_KEY env var. Span exports will fail.", ); } if (params?.exporter && params.compression !== undefined) { logger.warn( "The compression option is ignored because a custom exporter was provided. Configure compression on the exporter instead.", ); } const flushAt = params?.flushAt ?? getEnv("LANGFUSE_FLUSH_AT"); const flushIntervalSeconds = params?.flushInterval ?? getEnv("LANGFUSE_FLUSH_INTERVAL"); const authHeaderValue = base64Encode(`${publicKey}:${secretKey}`); const timeoutSeconds = params?.timeout ?? Number(getEnv("LANGFUSE_TIMEOUT") ?? 5); const envMediaUploadEnabled = getEnv("LANGFUSE_MEDIA_UPLOAD_ENABLED"); const mediaUploadEnabled = params?.mediaUploadEnabled ?? (envMediaUploadEnabled ? !["false", "0"].includes(envMediaUploadEnabled.toLowerCase()) : true); const compression = (params?.compression !== undefined ? resolveCompression(params.compression, "compression") : undefined) ?? resolveCompression( getEnv("LANGFUSE_OTEL_COMPRESSION"), "LANGFUSE_OTEL_COMPRESSION", ) ?? getOtelCompressionFromEnv() ?? CompressionAlgorithm.GZIP; const exporter = params?.exporter ? params.exporter : new SizeLimitedSpanExporter({ maxBatchSizeBytes: resolveMaxBatchSizeBytesFromEnvironment(), delegate: new OTLPTraceExporter({ url: `${baseUrl}/api/public/otel/v1/traces`, headers: withDefaultHeaders( { Authorization: `Basic ${authHeaderValue}`, "x-langfuse-sdk-name": "javascript", "x-langfuse-sdk-version": LANGFUSE_SDK_VERSION, "x-langfuse-public-key": publicKey ?? "", "x-langfuse-ingestion-version": "4", }, params?.additionalHeaders, ), timeoutMillis: timeoutSeconds * 1_000, compression, }), }); this.processor = params?.exportMode === "immediate" ? new SimpleSpanProcessor(exporter) : new BatchSpanProcessor(exporter, { maxExportBatchSize: flushAt ? Number(flushAt) : undefined, scheduledDelayMillis: flushIntervalSeconds ? Number(flushIntervalSeconds) * 1_000 : undefined, }); this.publicKey = publicKey; this.baseUrl = baseUrl; this.environment = params?.environment ?? getEnv("LANGFUSE_TRACING_ENVIRONMENT"); this.release = params?.release ?? getEnv("LANGFUSE_RELEASE"); this.availableSkills = serializeAvailableSkills(params?.skills?.available) ?? undefined; this.mask = params?.mask; this.shouldExportSpan = params?.shouldExportSpan ?? (({ otelSpan }) => isDefaultExportSpan(otelSpan)); this.mediaUploadEnabled = mediaUploadEnabled; this.apiClient = new LangfuseAPIClient({ baseUrl: this.baseUrl, username: this.publicKey, password: secretKey, xLangfusePublicKey: this.publicKey, xLangfuseSdkVersion: LANGFUSE_SDK_VERSION, xLangfuseSdkName: "javascript", environment: "", // noop as baseUrl is set headers: params?.additionalHeaders, }); this.mediaService = new MediaService({ apiClient: this.apiClient }); logger.debug("Initialized LangfuseSpanProcessor with params:", { publicKey, baseUrl, environment: this.environment, release: this.release, timeoutSeconds, flushAt, flushIntervalSeconds, mediaUploadEnabled, compression, }); } private get logger(): Logger { return getGlobalLogger(); } /** * Called when a span is started. Adds environment, release, skill availability, and propagated attributes to the span. * * @param span - The span that was started * @param parentContext - The parent context * * @override */ public onStart(span: Span, parentContext: Context): void { const propagatedAttributes = getPropagatedAttributesFromContext(parentContext); // An explicit prompt set at span creation takes precedence over a propagated one if ( span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME] != null ) { delete propagatedAttributes[ LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_NAME ]; delete propagatedAttributes[ LangfuseOtelSpanAttributes.OBSERVATION_PROMPT_VERSION ]; } const skillsKey = LangfuseOtelSpanAttributes.OBSERVATION_SKILLS_AVAILABLE; const hasSkillsOnSpan = span.attributes[skillsKey] != null; const attachSkills = parentContext.getValue(LangfuseOtelContextKeys.attachSkills) === true; if (hasSkillsOnSpan) { delete propagatedAttributes[skillsKey]; } if ( !hasSkillsOnSpan && propagatedAttributes[skillsKey] == null && attachSkills && this.availableSkills !== undefined ) { propagatedAttributes[skillsKey] = this.availableSkills; } // Set propagated attributes, environment and release attributes span.setAttributes({ [LangfuseOtelSpanAttributes.ENVIRONMENT]: this.environment, [LangfuseOtelSpanAttributes.RELEASE]: this.release, ...propagatedAttributes, }); try { this.markAppRootCandidate(span, parentContext); } catch (err) { this.logger.debug( "App-root start-time check failed. Span will not be marked as app root.", { spanName: span.name }, err, ); } return this.processor.onStart(span, parentContext); } /** * Called when a span ends. Processes the span for export to Langfuse. * * This method: * 1. Checks if the span should be exported using shouldExportSpan * (custom override or default smart filter) * 2. Applies data masking to sensitive attributes * 3. Handles media content extraction and upload * 4. Logs span details in debug mode * 5. Passes the span to the parent processor for export * * @param span - The span that ended * * @override */ public onEnd(span: ReadableSpan): void { this.spanExportExpectationById.delete(span.spanContext().spanId); const processEndedSpanPromise = this.processEndedSpan(span).catch((err) => { this.logger.error(err); }); // Enqueue this export to the pending list so it can be flushed by the user. this.pendingEndedSpans.add(processEndedSpanPromise); void processEndedSpanPromise.finally(() => this.pendingEndedSpans.delete(processEndedSpanPromise), ); } private async flush(): Promise { await Promise.all(Array.from(this.pendingEndedSpans)); await this.mediaService.flush(); } /** * Forces an immediate flush of all pending spans and media uploads. * * @returns Promise that resolves when all pending operations are complete * * @override */ public async forceFlush(): Promise { await this.flush(); return this.processor.forceFlush(); } /** * Gracefully shuts down the processor, ensuring all pending operations are completed. * * @returns Promise that resolves when shutdown is complete * * @override */ public async shutdown(): Promise { await this.flush(); return this.processor.shutdown(); } private async processEndedSpan(span: ReadableSpan) { try { if (this.shouldExportSpan({ otelSpan: span }) === false) { this.logger.debug("Dropped span due to shouldExportSpan filter.", { spanName: span.name, instrumentationScope: span.instrumentationScope.name, }); return; } } catch (err) { this.logger.error( "shouldExportSpan failed with error. Dropping span.", { spanName: span.name, instrumentationScope: span.instrumentationScope.name, }, err, ); return; } await this.applyMaskInPlace(span); if (this.mediaUploadEnabled) { await this.mediaService.process(span); } if (this.logger.isLevelEnabled(LogLevel.DEBUG)) { this.logger.debug( `Processed span:\n${JSON.stringify( { name: span.name, traceId: span.spanContext().traceId, spanId: span.spanContext().spanId, parentSpanId: span.parentSpanContext?.spanId ?? null, attributes: span.attributes, startTime: new Date(hrTimeToMilliseconds(span.startTime)), endTime: new Date(hrTimeToMilliseconds(span.endTime)), durationMs: hrTimeToMilliseconds(span.duration), kind: span.kind, status: span.status, resource: span.resource.attributes, instrumentationScope: span.instrumentationScope, }, null, 2, )}`, ); } this.processor.onEnd(span); } private markAppRootCandidate(span: Span, parentContext: Context): void { const traceId = span.spanContext().traceId; const spanId = span.spanContext().spanId; const parentSpanId = span.parentSpanContext?.spanId; const expectedExportedAtStart = this.isExpectedExportedAtStart(span); const propagatedClaim = getLangfuseTraceIdFromBaggage(parentContext); const isParentExpectedExported = parentSpanId !== undefined ? this.spanExportExpectationById.get(parentSpanId) === true : false; const suppressedByParentClaim = propagatedClaim === traceId; this.spanExportExpectationById.set(spanId, expectedExportedAtStart); const markAppRoot = expectedExportedAtStart && !isParentExpectedExported && !suppressedByParentClaim; if (markAppRoot) { span.setAttribute(LangfuseOtelSpanAttributes.IS_APP_ROOT, true); } } private isExpectedExportedAtStart(span: Span): boolean { // Span (from sdk-trace-base) already implements ReadableSpan, so the cast // is safe and avoids depending on private OTel APIs. const readable = span as unknown as ReadableSpan; try { return this.shouldExportSpan({ otelSpan: readable }) === true; } catch (err) { this.logger.debug( "shouldExportSpan threw during app-root start-time check. " + "Span will not be marked as app root.", { spanName: span.name, instrumentationScope: readable.instrumentationScope.name, }, err, ); return false; } } private async applyMaskInPlace(span: ReadableSpan): Promise { if (!this.mask) return; const maskCandidates = [ LangfuseOtelSpanAttributes.OBSERVATION_INPUT, LangfuseOtelSpanAttributes.TRACE_INPUT, LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT, LangfuseOtelSpanAttributes.TRACE_OUTPUT, LangfuseOtelSpanAttributes.TRACE_METADATA, ]; for (const maskCandidate of maskCandidates) { if (maskCandidate in span.attributes) { span.attributes[maskCandidate] = await this.applyMask( span.attributes[maskCandidate], ); } } // Object metadata is written as one attribute per top-level key, e.g. // `langfuse.observation.metadata.`. Mask each value separately so // keys are kept and are never passed to the mask. const observationMetadataPrefix = `${LangfuseOtelSpanAttributes.OBSERVATION_METADATA}.`; for (const key of Object.keys(span.attributes)) { if ( key === LangfuseOtelSpanAttributes.OBSERVATION_METADATA || key.startsWith(observationMetadataPrefix) ) { await this.applyMaskToObservationMetadata(span, key); } } } /** * Observation metadata values are JSON-encoded (see * `serializeMetadataValue`). Decode the value, mask the decoded value and * JSON-encode the result again, so the mask never sees the encoding and the * attribute stays valid JSON. If the masked value is not written by * `serializeMetadataValue` (e.g. the mask returns null or undefined), the * attribute is removed, as if the metadata value had been null. A stored * `"null"` that the mask returns as null is kept. */ private async applyMaskToObservationMetadata( span: ReadableSpan, key: string, ): Promise { const raw = span.attributes[key]; let decoded: unknown = raw; if (typeof raw === "string") { try { decoded = JSON.parse(raw); } catch { // Not written by the SDK; mask the raw string } } const masked = await this.applyMask(decoded); // toJSON() returning null is written as "null", which decodes to null. // That key was set by the user, so keep it. const serialized = decoded === null && masked === null ? "null" : serializeMetadataValue(masked); if (serialized === undefined) { delete span.attributes[key]; } else { span.attributes[key] = serialized; } } private async applyMask(data: T): Promise { if (!this.mask) return data; try { return await this.mask({ data }); } catch (err) { this.logger.warn( `Applying mask function failed due to error, fully masking property. Error: ${err}`, ); return ""; } } } function resolveCompression( value: string | undefined, setting: string, ): CompressionAlgorithm | undefined { const normalized = value?.trim().toLowerCase(); if (!normalized) return undefined; if (normalized === CompressionAlgorithm.GZIP) { return CompressionAlgorithm.GZIP; } if (normalized === CompressionAlgorithm.NONE) { return CompressionAlgorithm.NONE; } getGlobalLogger().warn( `Invalid ${setting} value "${value}". Expected "gzip" or "none". Falling back to the next compression setting, then gzip.`, ); return undefined; } /** * Reads the OpenTelemetry compression environment variables with the same * precedence as the OTLP exporter, ignoring case. Returns undefined outside * Node.js-like runtimes or when neither variable holds a valid value. */ function getOtelCompressionFromEnv(): CompressionAlgorithm | undefined { if (typeof process === "undefined" || !process.env) return undefined; for (const key of [ "OTEL_EXPORTER_OTLP_TRACES_COMPRESSION", "OTEL_EXPORTER_OTLP_COMPRESSION", ]) { const value = process.env[key]?.trim().toLowerCase(); if (value === CompressionAlgorithm.GZIP) return CompressionAlgorithm.GZIP; if (value === CompressionAlgorithm.NONE) return CompressionAlgorithm.NONE; } return undefined; }