🪢 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: safely parse env variables in worker (#1474)
Max Deichmanne46652bcf81c
diff --git a/worker/src/app.ts b/worker/src/app.tsindex 61f3afe0e5..0c899a0b52 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -6,31 +6,36 @@ import { nodeProfilingIntegration } from "@sentry/profiling-node";import * as middlewares from "./middlewares";import api from "./api";import MessageResponse from "./interfaces/MessageResponse";+import { env } from "./env";require("dotenv").config();const app = express();-Sentry.init({- dsn: String(process.env.SENTRY_DSN),- integrations: [- // enable HTTP calls tracing- new Sentry.Integrations.Http({ tracing: true }),- // enable Express.js middleware tracing- new Sentry.Integrations.Express({ app }),- nodeProfilingIntegration(),- ],- // Performance Monitoring- tracesSampleRate: 1.0, // Capture 100% of the transactions- // Set sampling rate for profiling - this is relative to tracesSampleRate- profilesSampleRate: 1.0,-});+const isSentryEnabled = Boolean(env.SENTRY_DSN);++if (isSentryEnabled) {+ Sentry.init({+ dsn: String(env.SENTRY_DSN),+ integrations: [+ // enable HTTP calls tracing+ new Sentry.Integrations.Http({ tracing: true }),+ // enable Express.js middleware tracing+ new Sentry.Integrations.Express({ app }),+ nodeProfilingIntegration(),+ ],+ // Performance Monitoring+ tracesSampleRate: 1.0, // Capture 100% of the transactions+ // Set sampling rate for profiling - this is relative to tracesSampleRate+ profilesSampleRate: 1.0,+ });-// The request handler must be the first middleware on the app-app.use(Sentry.Handlers.requestHandler());+ // The request handler must be the first middleware on the app+ app.use(Sentry.Handlers.requestHandler());-// TracingHandler creates a trace for every incoming request-app.use(Sentry.Handlers.tracingHandler());+ // TracingHandler creates a trace for every incoming request+ app.use(Sentry.Handlers.tracingHandler());+}app.use(cors());app.use(express.json());@@ -42,8 +47,10 @@ app.get<{}, MessageResponse>("/", (req, res) => {});app.use("/api/v1", api);-// The error handler must be before any other error middleware and after all controllers-app.use(Sentry.Handlers.errorHandler());+if (isSentryEnabled) {+ // The error handler must be before any other error middleware and after all controllers+ app.use(Sentry.Handlers.errorHandler());+}app.use(middlewares.notFound);app.use(middlewares.errorHandler);diff --git a/worker/src/database.ts b/worker/src/database.tsindex bc3e3680f6..a1d9bfaa4b 100644--- a/worker/src/database.ts+++ b/worker/src/database.ts@@ -1,11 +1,12 @@import { Kysely, PostgresDialect } from "kysely";import { Pool } from "pg";import { DB } from "@langfuse/shared/prisma/generated/types";+import { env } from "./env";export const db = new Kysely<DB>({dialect: new PostgresDialect({pool: new Pool({- connectionString: process.env.DATABASE_URL,+ connectionString: env.DATABASE_URL,}),}),});diff --git a/worker/src/env.ts b/worker/src/env.tsnew file mode 100644index 0000000000..663bf919f8--- /dev/null+++ b/worker/src/env.ts@@ -0,0 +1,19 @@+import { z } from "zod";++const EnvSchema = z.object({+ NODE_ENV: z+ .enum(["development", "test", "production"])+ .default("development"),+ SENTRY_DSN: z.string().url().optional(),+ DATABASE_URL: z.string(),+ PORT: z.coerce+ .number({+ description:+ ".env files convert numbers to strings, therefoore we have to enforce them to be numbers",+ })+ .positive()+ .max(65536, `options.port should be >= 0 and < 65536`)+ .default(3030),+});++export const env = EnvSchema.parse(process.env);diff --git a/worker/src/index.ts b/worker/src/index.tsindex e9e9ba537c..f136f511a0 100644--- a/worker/src/index.ts+++ b/worker/src/index.ts@@ -1,6 +1,6 @@import app from "./app";+import { env } from "./env";-const port = process.env.PORT ? parseInt(process.env.PORT) : 3030;-app.listen(port, () => {- console.log(`Listening: http://localhost:${port}`);+app.listen(env.PORT, () => {+ console.log(`Listening: http://localhost:${env.PORT}`);});diff --git a/worker/src/middlewares.ts b/worker/src/middlewares.tsindex f841f98716..b65f62c7cb 100644--- a/worker/src/middlewares.ts+++ b/worker/src/middlewares.ts@@ -1,6 +1,7 @@import { NextFunction, Request, Response } from "express";import ErrorResponse from "./interfaces/ErrorResponse";+import { env } from "./env";export function notFound(req: Request, res: Response, next: NextFunction) {res.status(404);@@ -18,6 +19,6 @@ export function errorHandler(res.status(statusCode);res.json({message: err.message,- stack: process.env.NODE_ENV === "production" ? "🥞" : err.stack,+ stack: env.NODE_ENV === "production" ? "🥞" : err.stack,});}