🪢 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(docker): remove cron process used for telemetry (#528)
Marc Klingen509c8386085e
diff --git a/Dockerfile b/Dockerfileindex 085fb67f2d..4f9ea19001 100644--- a/Dockerfile+++ b/Dockerfile@@ -70,7 +70,6 @@ ENV NEXT_TELEMETRY_DISABLED 1RUN addgroup --system --gid 1001 nodejsRUN adduser --system --uid 1001 nextjs-RUN npm install --no-package-lock --no-save cronRUN npm install -g --no-package-lock --no-save prismaCOPY --from=builder /app/public ./public@@ -81,7 +80,6 @@ COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/staticCOPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma-COPY --chown=nextjs:nodejs cron.js ./cron.jsCOPY --chown=nextjs:nodejs entrypoint.sh ./entrypoint.shRUN chmod +x ./entrypoint.shdiff --git a/cron.js b/cron.jsdeleted file mode 100644index 68d82b79c4..0000000000--- a/cron.js+++ /dev/null@@ -1,40 +0,0 @@-var CronJob = require("cron").CronJob;-var os = require("os");--if (- process.env.TELEMETRY_ENABLED === undefined ||- process.env.TELEMETRY_ENABLED === "true"-) {- try {- // Get internal ip address to ping the telemetry endpoint- var networkInterfaces = os.networkInterfaces();- var ip = undefined;-- if ("eth0" in networkInterfaces) {- var ipaddresses = networkInterfaces["eth0"]- .filter((networkInterface) => networkInterface.family === "IPv4")- .map((networkInterface) => networkInterface.address);- if (ipaddresses.length > 0) {- ip = ipaddresses[0];- }- }-- // Schedule cron job- if (ip) {- var job = new CronJob("*/5 * * * *", function () {- // PORT set to 3000 by Dockerfile, can be overridden by env- fetch(- `http://${ip}:${process.env.PORT ?? 3000}/api/cron/telemetry`,- ).catch((err) => console.log(err));- });-- job.start();- } else {- console.log("CRON: No ip address found, not starting cron job");- }- } catch (err) {- console.log("CRON: Error", err);- }-} else {- console.log("CRON: Telemetry disabled via env");-}diff --git a/entrypoint.sh b/entrypoint.shindex 2a59963b37..3d9b918ebc 100644--- a/entrypoint.sh+++ b/entrypoint.sh@@ -14,8 +14,5 @@ if [ $status -ne 0 ]; thenexit $statusfi-# Start background cron job-node cron.js &-# Start servernode server.jsdiff --git a/prisma/migrations/20231119171939_cron_add_job_started_at/migration.sql b/prisma/migrations/20231119171939_cron_add_job_started_at/migration.sqlnew file mode 100644index 0000000000..2b1ac5cfa7--- /dev/null+++ b/prisma/migrations/20231119171939_cron_add_job_started_at/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "cron_jobs" ADD COLUMN "job_started_at" TIMESTAMP(3);diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex d9c4767e1c..75c83e982b 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -247,9 +247,10 @@ model Pricing {}model CronJobs {- name String @id- lastRun DateTime? @map("last_run")- state String?+ name String @id+ lastRun DateTime? @map("last_run")+ jobStartedAt DateTime? @map("job_started_at")+ state String?@@map("cron_jobs")}diff --git a/src/features/telemetry/README.md b/src/features/telemetry/README.mdnew file mode 100644index 0000000000..27abfdda75--- /dev/null+++ b/src/features/telemetry/README.md@@ -0,0 +1,12 @@+# Telemetry service for Docker deployments++By default, Langfuse automatically reports basic usage statistics to a centralized server (PostHog).++This helps us to:++1. Understand how Langfuse is used and improve the most relevant features.+2. Track overall usage for internal and external (e.g. fundraising) reporting.++None of the data is shared with third parties and does not include any sensitive information. We want to be super transparent about this and you can find the exact data we collect [here](/src/pages/api/cron/telemetry.ts).++You can opt-out by setting `TELEMETRY_ENABLED=false`.diff --git a/src/features/telemetry/index.ts b/src/features/telemetry/index.tsnew file mode 100644index 0000000000..3ac8b89ec1--- /dev/null+++ b/src/features/telemetry/index.ts@@ -0,0 +1,236 @@+import { prisma } from "@/src/server/db";+import { Prisma } from "@prisma/client";+import { PostHog } from "posthog-node";+import { v4 as uuidv4 } from "uuid";++// Safe as it is intended to be public+const POSTHOG_API_KEY = "phc_zkMwFajk8ehObUlMth0D7DtPItFnxETi3lmSvyQDrwB";++// Interval between jobs in milliseconds+const JOB_INTERVAL_MINUTES = Prisma.raw("60");++// Timeout for job in minutes, if job is not finished in this time, it will be retried+const JOB_TIMEOUT_MINUTES = Prisma.raw("10");++export async function telemetry() {+ // Only run in prod+ if (process.env.NODE_ENV !== "production") return;+ // Do not run in Lanfuse cloud, separate telemetry is used+ if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined) return;+ // Check if telemetry is not disabled+ if (process.env.TELEMETRY_ENABLED === "false") return;+ // Do not run in CI+ if (process.env.CI) return;++ // Check via db cron_jobs table if it is time to run job+ const job = await jobScheduler();++ if (job.shouldRunJob) {+ const { jobStartedAt, lastRun, clientId } = job;++ // Run telemetry job+ await posthogTelemetry({+ startTimeframe: lastRun,+ endTimeframe: jobStartedAt,+ clientId,+ });++ // Update cron_jobs table+ await prisma.cronJobs.update({+ where: { name: "telemetry" },+ data: { lastRun: jobStartedAt, state: clientId, jobStartedAt: null },+ });+ }+}++/**+ * Checks if a job should be scheduled and returns the necessary information.+ * @returns A promise that resolves to an object with the following properties:+ * - shouldRunJob: A boolean indicating whether the job should be run.+ * - job_started_at: The timestamp when the job was started.+ * - last_run: The timestamp of the last run of the job, or null if it has never run.+ * - clientId: A unique clienId that identifies the host.+ */+async function jobScheduler(): Promise<+ | { shouldRunJob: false }+ | {+ shouldRunJob: true;+ jobStartedAt: Date;+ lastRun: Date | null;+ clientId: string;+ }+> {+ // Check if job should run, without a lock to not impact performance+ const checkNoLock = await prisma.$queryRaw<Array<{ name: string }>>`+ SELECT name FROM cron_jobs+ WHERE name = 'telemetry'+ AND (last_run IS NULL OR last_run <= (NOW() - INTERVAL '${JOB_INTERVAL_MINUTES} minutes'))+ AND (job_started_at IS NULL OR job_started_at <= (NOW() - INTERVAL '${JOB_TIMEOUT_MINUTES} minutes'))`;+ // Return if job should not run+ if (checkNoLock.length === 0) return { shouldRunJob: false };++ // Lock table and update job_started_at if no other job was created in the meantime+ const res = await prisma.$transaction([+ prisma.$executeRaw`LOCK TABLE cron_jobs IN SHARE ROW EXCLUSIVE MODE`,+ prisma.$queryRaw<+ Array<{+ name: string;+ last_run: Date | null;+ job_started_at: Date | null;+ state: string | null;+ }>+ >`INSERT INTO cron_jobs (name, last_run, job_started_at, state)+ VALUES ('telemetry', NULL, CURRENT_TIMESTAMP, NULL)+ ON CONFLICT (name)+ DO UPDATE+ SET job_started_at = CASE+ WHEN (cron_jobs.last_run IS NULL OR cron_jobs.last_run <= (NOW() - INTERVAL '${JOB_INTERVAL_MINUTES} minutes'))+ AND (cron_jobs.job_started_at IS NULL OR cron_jobs.job_started_at <= (NOW() - INTERVAL '${JOB_TIMEOUT_MINUTES} minutes'))+ THEN CURRENT_TIMESTAMP+ ELSE cron_jobs.job_started_at+ END+ WHERE cron_jobs.name = 'telemetry'+ AND (cron_jobs.last_run IS NULL OR cron_jobs.last_run <= (NOW() - INTERVAL '${JOB_INTERVAL_MINUTES} minutes'))+ AND (cron_jobs.job_started_at IS NULL OR cron_jobs.job_started_at <= (NOW() - INTERVAL '${JOB_TIMEOUT_MINUTES} minutes'))+ RETURNING *`,+ ]);+ const createJobLocked = res[1];++ // Other job was created in the meantime+ if (createJobLocked.length !== 1) {+ console.error("Telemetry job is locked");+ return { shouldRunJob: false };+ }++ const jobStartedAt = createJobLocked[0]?.job_started_at ?? null;++ // should not happen+ if (!jobStartedAt) {+ console.error("Telemetry failed to create job_started_at");+ return { shouldRunJob: false };+ }++ // set vars+ const lastRun = createJobLocked[0]?.last_run ?? null;+ const clientId = createJobLocked[0]?.state ?? uuidv4();++ return { shouldRunJob: true, jobStartedAt, lastRun, clientId };+}++async function posthogTelemetry({+ startTimeframe,+ endTimeframe,+ clientId,+}: {+ startTimeframe: Date | null;+ endTimeframe: Date;+ clientId: string;+}) {+ try {+ const posthog = new PostHog(POSTHOG_API_KEY, {+ host: "https://eu.posthog.com",+ });+ if (process.env.NODE_ENV === "development") posthog.debug();++ // Count projects+ const totalProjects = await prisma.project.count();++ // Count traces+ const countTraces = await prisma.trace.count({+ where: {+ timestamp: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count scores+ const countScores = await prisma.score.count({+ where: {+ timestamp: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count observations+ const countObservations = await prisma.observation.count({+ where: {+ startTime: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count datasets+ const countDatasets = await prisma.dataset.count({+ where: {+ createdAt: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count dataset items+ const countDatasetItems = await prisma.datasetItem.count({+ where: {+ createdAt: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count dataset runs+ const countDatasetRuns = await prisma.datasetRuns.count({+ where: {+ createdAt: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ // Count dataset run items+ const countDatasetRunItems = await prisma.datasetRunItems.count({+ where: {+ createdAt: {+ gte: startTimeframe?.toISOString(),+ lt: endTimeframe.toISOString(),+ },+ },+ });++ posthog.identify({+ distinctId: "docker:" + clientId,+ properties: {+ environment: process.env.NODE_ENV,+ docker: true,+ },+ });+ posthog.capture({+ distinctId: "docker:" + clientId,+ event: "telemetry",+ properties: {+ totalProjects: totalProjects,+ traces: countTraces,+ scores: countScores,+ observations: countObservations,+ datasets: countDatasets,+ datasetItems: countDatasetItems,+ datasetRuns: countDatasetRuns,+ datasetRunItems: countDatasetRunItems,+ startTimeframe: startTimeframe?.toISOString(),+ endTimeframe: endTimeframe.toISOString(),+ },+ });++ await posthog.shutdownAsync();+ } catch (error) {+ console.error(error);+ }+}diff --git a/src/pages/api/cron/telemetry.ts b/src/pages/api/cron/telemetry.tsdeleted file mode 100644index 1aed627e49..0000000000--- a/src/pages/api/cron/telemetry.ts+++ /dev/null@@ -1,137 +0,0 @@-import { prisma } from "@/src/server/db";-import { type NextApiRequest, type NextApiResponse } from "next";-import { PostHog } from "posthog-node";-import { v4 as uuidv4 } from "uuid";--// Safe as it is intended to be public-const POSTHOG_API_KEY = "phc_zkMwFajk8ehObUlMth0D7DtPItFnxETi3lmSvyQDrwB";--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- try {- const posthog = new PostHog(POSTHOG_API_KEY, {- host: "https://eu.posthog.com",- });- if (process.env.NODE_ENV === "development") posthog.debug();-- // Time frame is the last time this cron job ran until now- const dbCronState = await prisma.cronJobs.findUnique({- where: { name: "telemetry" },- });- const startTimeframe = dbCronState?.lastRun ?? undefined;- const clientId = dbCronState?.state ?? uuidv4();- const endTimeframe = new Date(Date.now());-- // Count projects- const totalProjects = await prisma.project.count();-- // Count traces- const countTraces = await prisma.trace.count({- where: {- timestamp: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count scores- const countScores = await prisma.score.count({- where: {- timestamp: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count observations- const countObservations = await prisma.observation.count({- where: {- startTime: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count datasets- const countDatasets = await prisma.dataset.count({- where: {- createdAt: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count dataset items- const countDatasetItems = await prisma.datasetItem.count({- where: {- createdAt: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count dataset runs- const countDatasetRuns = await prisma.datasetRuns.count({- where: {- createdAt: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- // Count dataset run items- const countDatasetRunItems = await prisma.datasetRunItems.count({- where: {- createdAt: {- gte: startTimeframe?.toISOString(),- lt: endTimeframe.toISOString(),- },- },- });-- posthog.identify({- distinctId: "docker:" + clientId,- properties: {- environment: process.env.NODE_ENV,- docker: true,- },- });- posthog.capture({- distinctId: "docker:" + clientId,- event: "telemetry",- properties: {- totalProjects: totalProjects,- traces: countTraces,- scores: countScores,- observations: countObservations,- datasets: countDatasets,- datasetItems: countDatasetItems,- datasetRuns: countDatasetRuns,- datasetRunItems: countDatasetRunItems,- startTimeframe: startTimeframe?.toISOString(),- endTimeframe: endTimeframe.toISOString(),- },- });-- await posthog.shutdownAsync();-- await prisma.cronJobs.upsert({- where: { name: "telemetry" },- update: { lastRun: endTimeframe, state: clientId },- create: { name: "telemetry", lastRun: endTimeframe, state: clientId },- });-- return res.status(200).json({ message: "OK" });- } catch (error) {- console.error(error);- return res.status(500).json({ message: "Internal server error" });- }-}diff --git a/src/pages/api/public/health.ts b/src/pages/api/public/health.tsindex ce5676ae79..a1626c26ac 100644--- a/src/pages/api/public/health.ts+++ b/src/pages/api/public/health.ts@@ -1,4 +1,5 @@import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { telemetry } from "@/src/features/telemetry";import { prisma } from "@/src/server/db";import { type NextApiRequest, type NextApiResponse } from "next";@@ -7,6 +8,7 @@ export default async function handler(res: NextApiResponse,) {await runMiddleware(req, res, cors);+ await telemetry();try {await prisma.$queryRaw`SELECT 1;`;} catch (e) {diff --git a/src/pages/api/public/ingestion.ts b/src/pages/api/public/ingestion.tsindex 029465e9c5..9b5e84c50e 100644--- a/src/pages/api/public/ingestion.ts+++ b/src/pages/api/public/ingestion.ts@@ -20,6 +20,7 @@ import { ObservationProcessor } from "../../../server/api/services/EventProcessoimport { TraceProcessor } from "../../../server/api/services/EventProcessor";import { ScoreProcessor } from "../../../server/api/services/EventProcessor";import { isNotNullOrUndefined } from "@/src/utils/types";+import { telemetry } from "@/src/features/telemetry";export default async function handler(req: NextApiRequest,@@ -81,6 +82,8 @@ export default async function handler(const filteredBatch: z.infer<typeof singleEventSchema>[] =batch.filter(isNotNullOrUndefined);+ await telemetry();+const sortedBatch = sortBatch(filteredBatch);const result = await handleBatch(sortedBatch, req, authCheck);diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.tsindex d8b1da7df8..514efb48de 100644--- a/src/pages/api/public/traces.ts+++ b/src/pages/api/public/traces.ts@@ -14,6 +14,7 @@ import {eventTypes,} from "@/src/features/public-api/server/ingestion-api-schema";import { v4 } from "uuid";+import { telemetry } from "@/src/features/telemetry";const GetTracesSchema = z.object({...paginationZod,@@ -52,6 +53,9 @@ export default async function handler(});const body = TraceSchema.parse(req.body);++ await telemetry();+const event = {id: v4(),type: eventTypes.TRACE_CREATE,