🪢 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(cloud): add stripe checkout, customer portal, and usage metering (#2962)
Marc Klingen9daf348d6166
diff --git a/.env.prod.example b/.env.prod.exampleindex 6ac3f70d32..8d4304df5c 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -174,6 +174,10 @@ ENCRYPTION_KEY="0000000000000000000000000000000000000000000000000000000000000000# LANGFUSE_CACHE_PROMPT_ENABLED=# LANGFUSE_CACHE_PROMPT_TTL_SECONDS=+# Stripe+# STRIPE_SECRET_KEY=+# STRIPE_WEBHOOK_SIGNING_SECRET=+### END Langfuse Cloud Configdiff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 40d3fbc210..3ad1135a69 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -611,6 +611,7 @@ function createObjects(const trace = {id: `trace-${v4()}`,timestamp: traceTs,+ createdAt: traceTs,projectId: projectId,name: ["generate-outreach", "label-inbound", "draft-response"][i % 3@@ -669,6 +670,7 @@ function createObjects(traceId: trace.id,name: annotationScoreName,timestamp: traceTs,+ createdAt: traceTs,source: ScoreSource.ANNOTATION,projectId,authorUserId: `user-${i}`,@@ -685,6 +687,7 @@ function createObjects(name: "sentiment",value: Math.floor(Math.random() * 10) - 5,timestamp: traceTs,+ createdAt: traceTs,source: ScoreSource.API,projectId,dataType: ScoreDataType.NUMERIC,@@ -697,6 +700,7 @@ function createObjects(traceId: trace.id,name: "Completeness",timestamp: traceTs,+ createdAt: traceTs,source: ScoreSource.API,projectId,dataType: ScoreDataType.CATEGORICAL,@@ -725,6 +729,7 @@ function createObjects(type: ObservationType.SPAN,id: `span-${v4()}`,startTime: spanTsStart,+ createdAt: spanTsStart,endTime: spanTsEnd,name: `span-${i}-${j}`,metadata: {@@ -796,6 +801,7 @@ function createObjects(type: ObservationType.GENERATION,id: `generation-${v4()}`,startTime: generationTsStart,+ createdAt: generationTsStart,endTime: generationTsEnd,completionStartTime:Math.random() > 0.5 ? generationTsCompletionStart : undefined,@@ -867,6 +873,7 @@ function createObjects(source: ScoreSource.API,projectId: trace.projectId,timestamp: generationTsEnd,+ createdAt: traceTs,});if (Math.random() > 0.6)scores.push({@@ -877,6 +884,7 @@ function createObjects(source: ScoreSource.API,projectId: trace.projectId,timestamp: generationTsEnd,+ createdAt: traceTs,});for (let l = 0; l < Math.floor(Math.random() * 2); l++) {@@ -892,6 +900,7 @@ function createObjects(type: ObservationType.EVENT,id: `event-${v4()}`,startTime: eventTs,+ createdAt: eventTs,name: `event-${i}-${j}-${k}-${l}`,metadata: {user: `user-${i}@langfuse.com`,diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 1f785c8c11..35a41d5b7e 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -2,6 +2,8 @@ export * from "./constants";export * from "./queries";export * from "./interfaces/filters";export * from "./interfaces/orderBy";+export * from "./interfaces/cloudConfigSchema";+export * from "./interfaces/parseDbOrg";export * from "./tableDefinitions";export * from "./types";export * from "./filterToPrisma";diff --git a/web/src/features/organizations/utils/cloudConfigSchema.ts b/packages/shared/src/interfaces/cloudConfigSchema.tssimilarity index 57%rename from web/src/features/organizations/utils/cloudConfigSchema.tsrename to packages/shared/src/interfaces/cloudConfigSchema.tsindex 0b43b2d3e9..cd6f5be8bc 100644--- a/web/src/features/organizations/utils/cloudConfigSchema.ts+++ b/packages/shared/src/interfaces/cloudConfigSchema.ts@@ -5,5 +5,13 @@ export const CloudConfigSchema = z.object({monthlyObservationLimit: z.number().int().positive().optional(),// used for table and dashboard queriesdefaultLookBackDays: z.number().int().positive().optional(),+ // need to update stripe webhook if you change this, it fetches from db via these fields+ stripe: z+ .object({+ customerId: z.string().optional(),+ activeSubscriptionId: z.string().optional(),+ activeProductId: z.string().optional(),+ })+ .optional(),});export type CloudConfigSchema = z.infer<typeof CloudConfigSchema>;diff --git a/web/src/features/organizations/utils/parseDbOrg.ts b/packages/shared/src/interfaces/parseDbOrg.tssimilarity index 74%rename from web/src/features/organizations/utils/parseDbOrg.tsrename to packages/shared/src/interfaces/parseDbOrg.tsindex 03e0ed5899..b168ebd275 100644--- a/web/src/features/organizations/utils/parseDbOrg.ts+++ b/packages/shared/src/interfaces/parseDbOrg.ts@@ -1,5 +1,5 @@-import { CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";-import { type Organization } from "@langfuse/shared";+import { type Organization } from "@prisma/client";+import { CloudConfigSchema } from "./cloudConfigSchema";type parsedOrg = Omit<Organization, "cloudConfig"> & {cloudConfig: CloudConfigSchema | null;diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 1d43a52bda..e493cdf145 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -6,6 +6,7 @@ export enum EventName {BatchExport = "BatchExport",EvaluationExecution = "EvaluationExecution",LegacyIngestion = "LegacyIngestion",+ CloudUsageMetering = "CloudUsageMetering",}export const LegacyIngestionEvent = z.object({@@ -60,6 +61,7 @@ export enum QueueName {RepeatQueue = "repeat-queue",IngestionFlushQueue = "ingestion-flush-queue",LegacyIngestionQueue = "legacy-ingestion-queue",+ CloudUsageMeteringQueue = "cloud-usage-metering-queue",}export enum QueueJobs {@@ -69,6 +71,7 @@ export enum QueueJobs {EnqueueBatchExportJobs = "enqueue-batch-export-jobs",FlushIngestionEntity = "flush-ingestion-entity",LegacyIngestionJob = "legacy-ingestion-job",+ CloudUsageMeteringJob = "cloud-usage-metering-job",}export type TQueueJobTypes = {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 40961e1c3a..98a875ebe1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -606,6 +606,9 @@ importers:sonner:specifier: ^1.4.41+ stripe:+ specifier: ^16.8.0+ version: 16.8.0superjson:specifier: 2.2.1version: 2.2.1@@ -839,6 +842,9 @@ importers:pino-pretty:specifier: ^10.3.1version: 10.3.1+ stripe:+ specifier: ^16.8.0+ version: 16.8.0tiktoken:specifier: ^1.0.15version: 1.0.15@@ -9642,7 +9648,7 @@ packages:resolution: {integrity: sha512-39olGaX2djYUdhaQQHDZ0T0GwEp+5f9UB9HmEP0qHfdQHIq0xGQZuAZ5TLnJIc/88SrPLpEflPC+xUqOTv3c5g==}- deprecated: < 22.8.2 is no longer supported+ deprecated: < 22.6.4 is no longer supportedresolution: {integrity: sha512-LA0Y9kxMYv47GIPJy6MI84fqTd2HmYZI83W/kM/SkKfDlajnZYfmXFTxkbY+xSBPkLJxltMa9hIkmdc29eguMA==}@@ -10403,6 +10409,10 @@ packages:resolution: {integrity: sha512-f9vHgsCWBq2ugHAkGMiiYY+AYG0D/cbloKKg0nhaaaSNsujdGIpVXCNsrJpCKr5M0f4aI31mr13UjY6GAuXCKA==}+ resolution: {integrity: sha512-6rOIcGOkxcc29jvhEyOYmpPFilekOBV+7vpemAoIAfbtCRW1yxzdDGM0/0vyekHglLL+wqGpP5ldrhO3dJ2JEQ==}+ engines: {node: '>=12.*'}+resolution: {integrity: sha512-J8bbNyKKXl5qYcR36TIO8W3mVGVHrmmxsd5PAItGkmyzwJvybiw2IVq5nqd0i4LSNSkB/sx9VHllbfFdr9k1JA==}@@ -11351,7 +11361,7 @@ snapshots:'@anthropic-ai/[email protected]':dependencies:- '@types/node': 18.19.25+ '@types/node': 18.19.39'@types/node-fetch': 2.6.11abort-controller: 3.0.0agentkeepalive: 4.5.0@@ -12812,14 +12822,14 @@ snapshots:'@jest/test-result': 29.7.0'@jest/transform': 29.7.0'@jest/types': 29.6.3- '@types/node': 20.12.11+ '@types/node': 20.14.8ansi-escapes: 4.3.2chalk: 4.1.2ci-info: 3.9.0exit: 0.1.2graceful-fs: 4.2.11jest-changed-files: 29.7.0- jest-config: 29.7.0(@types/[email protected])+ jest-config: 29.7.0(@types/[email protected])jest-haste-map: 29.7.0jest-message-util: 29.7.0jest-regex-util: 29.6.3@@ -12848,14 +12858,14 @@ snapshots:'@jest/test-result': 29.7.0'@jest/transform': 29.7.0'@jest/types': 29.6.3- '@types/node': 20.12.11+ '@types/node': 20.14.8ansi-escapes: 4.3.2chalk: 4.1.2ci-info: 3.9.0exit: 0.1.2graceful-fs: 4.2.11jest-changed-files: 29.7.0- jest-config: 29.7.0(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))+ jest-config: 29.7.0(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))jest-haste-map: 29.7.0jest-message-util: 29.7.0jest-regex-util: 29.6.3@@ -12880,7 +12890,7 @@ snapshots:dependencies:'@jest/fake-timers': 29.7.0'@jest/types': 29.6.3- '@types/node': 20.12.11+ '@types/node': 20.14.8jest-mock: 29.7.0'@jest/[email protected]':@@ -12898,7 +12908,7 @@ snapshots:dependencies:'@jest/types': 29.6.3'@sinonjs/fake-timers': 10.3.0- '@types/node': 20.12.11+ '@types/node': 20.14.8jest-message-util: 29.7.0jest-mock: 29.7.0jest-util: 29.7.0@@ -12990,7 +13000,7 @@ snapshots:'@jest/schemas': 29.6.3'@types/istanbul-lib-coverage': 2.0.6'@types/istanbul-reports': 3.0.4- '@types/node': 20.12.11+ '@types/node': 20.14.8'@types/yargs': 17.0.32chalk: 4.1.2@@ -16355,7 +16365,7 @@ snapshots:'@types/[email protected]':dependencies:'@types/connect': 3.4.38- '@types/node': 20.12.11+ '@types/node': 20.14.8'@types/[email protected]':dependencies:@@ -16517,7 +16527,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 20.12.11+ '@types/node': 20.14.8'@types/tough-cookie': 4.0.5parse5: 7.1.2@@ -16659,13 +16669,13 @@ snapshots:'@types/[email protected]':dependencies:'@types/mime': 1.3.5- '@types/node': 20.12.11+ '@types/node': 20.14.8'@types/[email protected]':dependencies:'@types/http-errors': 2.0.4'@types/mime': 3.0.4- '@types/node': 20.12.11+ '@types/node': 20.14.8'@types/[email protected]': {}@@ -18064,7 +18074,7 @@ snapshots:chalk: 4.1.2exit: 0.1.2graceful-fs: 4.2.11- jest-config: 29.7.0(@types/[email protected])+ jest-config: 29.7.0(@types/[email protected])jest-util: 29.7.0prompts: 2.4.2transitivePeerDependencies:@@ -20284,7 +20294,7 @@ snapshots:create-jest: 29.7.0exit: 0.1.2import-local: 3.1.0- jest-config: 29.7.0(@types/[email protected])+ jest-config: 29.7.0(@types/[email protected])jest-util: 29.7.0jest-validate: 29.7.0yargs: 17.7.2@@ -20345,7 +20355,7 @@ snapshots:- babel-plugin-macros- supports-color- [email protected](@types/[email protected]):+ [email protected](@types/[email protected]):dependencies:'@babel/core': 7.24.3'@jest/test-sequencer': 29.7.0@@ -20370,13 +20380,13 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- '@types/node': 20.12.11+ '@types/node': 20.14.8transitivePeerDependencies:- babel-plugin-macros- supports-coloroptional: true- [email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])):+ [email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])):dependencies:'@babel/core': 7.24.3'@jest/test-sequencer': 29.7.0@@ -20401,7 +20411,7 @@ snapshots:slash: 3.0.0strip-json-comments: 3.1.1optionalDependencies:- '@types/node': 20.12.11+ '@types/node': 20.14.8ts-node: 10.9.2(@types/[email protected])([email protected])transitivePeerDependencies:- babel-plugin-macros@@ -20495,7 +20505,7 @@ snapshots:dependencies:'@jest/types': 29.6.3- '@types/node': 20.12.11+ '@types/node': 20.14.8jest-util: 29.7.0@@ -20604,7 +20614,7 @@ snapshots:dependencies:'@jest/types': 29.6.3- '@types/node': 20.12.11+ '@types/node': 20.14.8chalk: 4.1.2ci-info: 3.9.0graceful-fs: 4.2.11@@ -21948,7 +21958,7 @@ snapshots:dependencies:- '@types/node': 18.19.25+ '@types/node': 18.19.39'@types/node-fetch': 2.6.11abort-controller: 3.0.0agentkeepalive: 4.5.0@@ -23536,6 +23546,11 @@ snapshots:dependencies:js-tokens: 8.0.3+ dependencies:+ '@types/node': 20.14.8+ qs: 6.11.0+diff --git a/web/package.json b/web/package.jsonindex 3671d119ae..5c39c9c4f1 100644--- a/web/package.json+++ b/web/package.json@@ -132,6 +132,7 @@"remark-gfm": "^4.0.0","remark-math": "^6.0.0","sonner": "^1.4.41",+ "stripe": "^16.8.0","superjson": "2.2.1","tailwind-merge": "^2.2.1","tailwindcss-animate": "^1.0.7",diff --git a/web/src/app/api/billing/stripe-webhook/route.ts b/web/src/app/api/billing/stripe-webhook/route.tsnew file mode 100644index 0000000000..d67829f784--- /dev/null+++ b/web/src/app/api/billing/stripe-webhook/route.ts@@ -0,0 +1,5 @@+import { stripeWebhookApiHandler } from "@/src/ee/features/billing/server/stripeWebhookApiHandler";++export const dynamic = "force-dynamic";++export const POST = stripeWebhookApiHandler;diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsxnew file mode 100644index 0000000000..a14e64fcd5--- /dev/null+++ b/web/src/app/layout.tsx@@ -0,0 +1,16 @@+export const metadata = {+ title: 'Next.js',+ description: 'Generated by Next.js',+}++export default function RootLayout({+ children,+}: {+ children: React.ReactNode+}) {+ return (+ <html lang="en">+ <body>{children}</body>+ </html>+ )+}diff --git a/web/src/components/layouts/header.tsx b/web/src/components/layouts/header.tsxindex 9c5b5ea723..b87ce31913 100644--- a/web/src/components/layouts/header.tsx+++ b/web/src/components/layouts/header.tsx@@ -43,6 +43,10 @@ export default function Header({title: string;breadcrumb?: { name: string; href?: string }[];status?: Status;+ label?: {+ text: string;+ href: string;+ };help?: { description: string; href?: string };featureBetaURL?: string;actionButtons?: React.ReactNode;@@ -91,6 +95,11 @@ export default function Header({) : null}</div>{props.status && <StatusBadge type={props.status} />}+ {props.label && (+ <Link href={props.label.href}>+ <StatusBadge type={props.label.text} />+ </Link>+ )}</div><div className="flex flex-wrap items-center gap-3">{props.actionButtons ?? null}diff --git a/web/src/components/layouts/status-badge.tsx b/web/src/components/layouts/status-badge.tsxindex 9f07365257..a776b75f39 100644--- a/web/src/components/layouts/status-badge.tsx+++ b/web/src/components/layouts/status-badge.tsx@@ -11,28 +11,32 @@ const statusCategories = {export type Status =(typeof statusCategories)[keyof typeof statusCategories][number];-export const StatusBadge = (props: { className?: string; type: Status }) => {+export const StatusBadge = (props: {+ className?: string;+ type: Status | (string & {});+}) => {let badgeColor = "bg-muted-gray text-primary";let dotColor = "bg-muted-foreground";let dotPingColor = "bg-muted-foreground";- let showDot = true;+ let showDot = false;if (statusCategories.active.includes(props.type)) {badgeColor = "bg-light-green text-dark-green";dotColor = "animate-ping bg-dark-green";dotPingColor = "bg-dark-green";+ showDot = true;} else if (statusCategories.pending.includes(props.type)) {badgeColor = "bg-light-yellow text-dark-yellow";dotColor = "animate-ping bg-dark-yellow";dotPingColor = "bg-dark-yellow";+ showDot = true;} else if (statusCategories.error.includes(props.type)) {badgeColor = "bg-light-red text-dark-red";dotColor = "animate-ping bg-dark-red";dotPingColor = "bg-dark-red";- showDot = false;+ showDot = true;} else if (statusCategories.completed.includes(props.type)) {badgeColor = "bg-light-green text-dark-green";- showDot = false;}return (diff --git a/web/src/ee/features/billing/README.md b/web/src/ee/features/billing/README.mdnew file mode 100644index 0000000000..9834b5029a--- /dev/null+++ b/web/src/ee/features/billing/README.md@@ -0,0 +1,61 @@+# Billing++## Overview++This page outlines our integration with **Stripe billing**. The integration supports **usage-based billing** for each organization and project within our product.++## Key Concepts++- **Organizations**: Entities within the product that can have multiple projects.+- **Projects**: Sub-entities under organizations where usage is tracked.+- **Observations**: Units of usage, essentially API calls, tracked at the project level and aggregated for billing on the organization level.++## Implementation Details++### Checkout and Subscription Management++1. **Upgrade Process**:++ - Organizations can upgrade their plan via the **billing settings**.+ - On the **select plans popup**, only product listed in `stripeProducts.ts` are included.+ - A new **Stripe Checkout session** is created via the API.+ - The **organization ID** is passed to Stripe as a reference.+ - The default price in stripe for each product is used.++2. **Stripe WebHooks**:++ - **Checkout Session Completion**:+ - On completion, the `customerID` and `activeSubscriptionId` are added to the cloud config of the organization's object.+ - Linked based on the stripe client reference (`stripeClientReference.ts`).+ - **Subscription Changes**:+ - On creation, update, or deletion of a subscription, the **active product ID** is updated in the cloud config of the organization which includes the `activeSubscriptionId`.++3. **Cloud Config**:+ - Contains the **customer ID**, **activeSubscriptionId**, and **active product ID**.+ - All entitlements within the application are based on the **active product ID** and it's mapping to `Plan` in Langfuse (`stripeProducts.ts`).+ - If a `plan` is included in the cloud config (legacy), no new subscription can be created for the organization. Organizations need to be migrated to the new system.++### Usage-Based Pricing++1. **Usage Meter in Stripe**:++ - A meter with the ID `trace_observations` is used to track usage.+ - This meter tracks observations at the _customer_ level within Stripe.++2. **Hourly Job**:++ - An hourly job runs in the **worker container** (`cloudUsageMeteringQueue`).+ - Logs the number of observations within the last hour to Stripe for all organizations which include a customer ID in the cloud config.+ - The job is managed via+ - BullMQ repeatable jobs: trigger run each hour + potential backfill job on startup of worker container+ - `cron_jobs` postgres table to track the last run time of the job and to prevent multiple instances of the job running.++## Webhook development++You can test webhooks via the `stripe` CLI. Step by step guide: https://dashboard.stripe.com/test/webhooks/create?endpoint_location=local++1. `stripe login`+2. `stripe listen --forward-to localhost:3000/api/billing/stripe-webhook`+3. Add the API key from the Stripe test environment and the webhook signing secret from the CLI to the `.env` file.++Upgrade/downgrade projects via the Langfuse billing settings.diff --git a/web/src/ee/features/billing/components/BillingSettings.tsx b/web/src/ee/features/billing/components/BillingSettings.tsxnew file mode 100644index 0000000000..d00ee13b0f--- /dev/null+++ b/web/src/ee/features/billing/components/BillingSettings.tsx@@ -0,0 +1,233 @@+// Langfuse Cloud only++import { Button } from "@/src/components/ui/button";+import { api } from "@/src/utils/api";+import { Flex, MarkerBar, Metric, Text } from "@tremor/react";+import Link from "next/link";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import Header from "@/src/components/layouts/header";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useQueryOrganization } from "@/src/features/organizations/hooks";+import { Card } from "@/src/components/ui/card";+import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";+import {+ type Plan,+ planLabels,+} from "@/src/features/entitlements/constants/plans";+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";+import { useRouter } from "next/router";+import {+ chatAvailable,+ sendUserChatMessage,+} from "@/src/features/support-chat/chat";+import { env } from "@/src/env.mjs";+import { useHasOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";++export const BillingSettings = () => {+ const router = useRouter();+ const orgId = router.query.organizationId as string | undefined;+ const hasAccess = useHasOrganizationAccess({+ organizationId: orgId,+ scope: "langfuseCloudBilling:CRUD",+ });++ const entitled = useHasOrgEntitlement("cloud-billing");+ if (!entitled) return null;++ if (!hasAccess)+ return (+ <Alert>+ <AlertTitle>Access Denied</AlertTitle>+ <AlertDescription>+ You do not have permission to view the billing settings of this+ organization.+ </AlertDescription>+ </Alert>+ );+ return (+ <div className="p-4">+ <Header title="Usage & Billing" level="h3" />+ <OrganizationUsageChart />+ </div>+ );+};++const OrganizationUsageChart = () => {+ const organization = useQueryOrganization();+ const usage = api.cloudBilling.getUsage.useQuery(+ {+ orgId: organization?.id as string,+ },+ {+ enabled: organization !== undefined,+ trpc: {+ context: {+ skipBatch: true,+ },+ },+ },+ );+ const planLimit =+ organization?.cloudConfig?.monthlyObservationLimit ?? 50_000;+ const plan: Plan = organization?.plan ?? "cloud:hobby";+ const planLabel = planLabels[plan];++ return (+ <div>+ <Card className="p-4">+ {usage.data !== undefined ? (+ <>+ <Text>+ {usage.data.billingPeriodStart+ ? `Observations since start of billing period (${usage.data.billingPeriodStart.toLocaleDateString()})`+ : "Observations / last 30d"}+ </Text>+ <Metric>{numberFormatter(usage.data.countObservations, 0)}</Metric>+ {plan === "cloud:hobby" && (+ <>+ <Flex className="mt-4">+ <Text>{`${numberFormatter((usage.data.countObservations / planLimit) * 100)}%`}</Text>+ <Text>Plan limit: {compactNumberFormatter(planLimit)}</Text>+ </Flex>+ <MarkerBar+ value={Math.min(+ (usage.data.countObservations / planLimit) * 100,+ 100,+ )}+ className="mt-3"+ />+ </>+ )}+ </>+ ) : (+ "Loading (might take a moment) ..."+ )}+ </Card>+ <div className="mt-4 flex flex-row items-center gap-2">+ <BillingPortalOrPricingPageButton />+ <Button variant="secondary" asChild>+ <Link href={"https://langfuse.com/pricing"} target="_blank">+ Compare plans+ </Link>+ </Button>+ <div className="inline-block text-sm text-muted-foreground">+ Current plan: {planLabel}+ </div>+ </div>+ </div>+ );+};++const BillingPortalOrPricingPageButton = () => {+ const organization = useQueryOrganization();+ const billingPortalUrl = api.cloudBilling.getStripeCustomerPortalUrl.useQuery(+ {+ orgId: organization?.id as string,+ },+ {+ enabled: organization !== undefined,+ },+ );+ if (billingPortalUrl.isLoading) return null;+ if (!billingPortalUrl.data) return <PricingPageButton />;++ return (+ <Button asChild>+ <Link href={billingPortalUrl.data}>Billing portal</Link>+ </Button>+ );+};++const PricingPageButton = () => {+ const capture = usePostHogClientCapture();+ const organization = useQueryOrganization();+ const router = useRouter();+ const mutCreateCheckoutSession =+ api.cloudBilling.createStripeCheckoutSession.useMutation({+ onSuccess: (url) => {+ router.push(url);+ },+ });+ if (!organization) return null;++ // Do not show checkout or customer portal if manual plan is set in cloud config+ if (organization.cloudConfig?.plan) {+ if (chatAvailable)+ return (+ <Button+ variant="secondary"+ onClick={() =>+ sendUserChatMessage(+ `I'd like to change my current plan, region ${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}, organization id ${organization.id}`,+ )+ }+ >+ Change plan+ </Button>+ );+ else return null;+ }++ return (+ <Dialog+ onOpenChange={(open) => {+ if (open) {+ capture("project_settings:pricing_dialog_opened");+ }+ }}+ >+ <DialogTrigger asChild>+ <Button>Change plan</Button>+ </DialogTrigger>+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <Header+ title="Plans"+ level="h3"+ actionButtons={+ <Button variant="secondary" asChild>+ <Link href="https://langfuse.com/pricing" target="_blank">+ Comparison of plans ↗+ </Link>+ </Button>+ }+ />+ </DialogHeader>+ <div className="mb-3 flex flex-col justify-center gap-10 md:flex-row">+ {stripeProducts+ .filter((product) => Boolean(product.checkout))+ .map((product) => (+ <div key={product.stripeProductId}>+ <div className="mb-2 text-lg font-semibold">+ {product.checkout?.title}+ </div>+ <div>+ <p>{product.checkout?.description}</p>+ <p>{product.checkout?.price}</p>+ </div>+ <Button+ onClick={() => {+ if (organization)+ mutCreateCheckoutSession.mutate({+ orgId: organization.id,+ stripeProductId: product.stripeProductId,+ });+ }}+ className="mt-4"+ >+ Select plan+ </Button>+ </div>+ ))}+ </div>+ </DialogContent>+ </Dialog>+ );+};diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.tsnew file mode 100644index 0000000000..98f0897ae8--- /dev/null+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts@@ -0,0 +1,266 @@+import { createStripeClientReference } from "@/src/ee/features/billing/stripeClientReference";+import { stripeClient } from "@/src/ee/features/billing/utils/stripe";+import { stripeProducts } from "@/src/ee/features/billing/utils/stripeProducts";+import { env } from "@/src/env.mjs";+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";+import { parseDbOrg } from "@langfuse/shared";+import {+ createTRPCRouter,+ protectedOrganizationProcedure,+} from "@/src/server/api/trpc";+import { TRPCError } from "@trpc/server";+import * as z from "zod";+import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { auditLog } from "@/src/features/audit-logs/auditLog";++export const cloudBillingRouter = createTRPCRouter({+ createStripeCheckoutSession: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ stripeProductId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ throwIfNoOrganizationAccess({+ organizationId: input.orgId,+ scope: "langfuseCloudBilling:CRUD",+ session: ctx.session,+ });+ throwIfNoEntitlement({+ entitlement: "cloud-billing",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });++ const org = await ctx.prisma.organization.findUnique({+ where: {+ id: input.orgId,+ },+ });+ if (!org) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Organization not found",+ });+ }++ const parsedOrg = parseDbOrg(org);+ if (parsedOrg.cloudConfig?.plan)+ throw new TRPCError({+ code: "FORBIDDEN",+ message:+ "Cannot initialize stripe checkout for orgs that have a manual/legacy plan",+ });++ if (!stripeClient)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Stripe client not initialized",+ });++ const stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;+ const stripeActiveSubscriptionId =+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;+ if (stripeActiveSubscriptionId) {+ // If the org has a customer ID, do not return checkout options, should use the billing portal instead+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Organization already has an active subscription",+ });+ }++ if (+ !stripeProducts.some(+ (product) =>+ Boolean(product.checkout) &&+ product.stripeProductId === input.stripeProductId,+ )+ )+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Invalid stripe product id",+ });++ const product = await stripeClient.products.retrieve(+ input.stripeProductId,+ );+ if (!product.default_price) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Product does not have a default price in Stripe",+ });+ }++ const returnUrl = `${env.NEXTAUTH_URL}/organization/${input.orgId}/settings`;+ const session = await stripeClient.checkout.sessions.create({+ customer: stripeCustomerId,+ line_items: [+ {+ price: product.default_price as string,+ },+ ],+ client_reference_id:+ createStripeClientReference(input.orgId) ?? undefined,+ allow_promotion_codes: true,+ tax_id_collection: {+ enabled: true,+ },+ consent_collection: {+ terms_of_service: "required",+ },+ ...(stripeCustomerId+ ? {+ customer_update: {+ name: "auto",+ address: "auto",+ },+ }+ : {}),+ billing_address_collection: "required",+ success_url: returnUrl,+ cancel_url: returnUrl,+ mode: "subscription",+ metadata: {+ orgId: input.orgId,+ cloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION ?? null,+ },+ });++ if (!session.url)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to create checkout session",+ });++ auditLog({+ session: ctx.session,+ orgId: input.orgId,+ resourceType: "stripeCheckoutSession",+ resourceId: session.id,+ action: "create",+ });++ return session.url;+ }),+ getStripeCustomerPortalUrl: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoEntitlement({+ entitlement: "cloud-billing",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });+ throwIfNoOrganizationAccess({+ organizationId: input.orgId,+ scope: "langfuseCloudBilling:CRUD",+ session: ctx.session,+ });++ const org = await ctx.prisma.organization.findUnique({+ where: {+ id: input.orgId,+ },+ });+ if (!org) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Organization not found",+ });+ }++ if (!stripeClient)+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Stripe client not initialized",+ });++ const parsedOrg = parseDbOrg(org);+ let stripeCustomerId = parsedOrg.cloudConfig?.stripe?.customerId;+ let stripeSubscriptionId =+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId;+ if (!stripeCustomerId || !stripeSubscriptionId) {+ // Do not create a new customer if the org is on a plan (assigned manually)+ return null;+ }++ const billingPortalSession =+ await stripeClient.billingPortal.sessions.create({+ customer: stripeCustomerId,+ return_url: `${env.NEXTAUTH_URL}/organization/${input.orgId}/settings/billing`,+ });++ return billingPortalSession.url;+ }),+ getUsage: protectedOrganizationProcedure+ .input(+ z.object({+ orgId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ throwIfNoEntitlement({+ entitlement: "cloud-billing",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });+ throwIfNoOrganizationAccess({+ organizationId: input.orgId,+ scope: "langfuseCloudBilling:CRUD",+ session: ctx.session,+ });++ const thirtyDaysAgo = new Date();+ thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);+ thirtyDaysAgo.setHours(0, 0, 0, 0);+ let billingPeriodStart: Date | null = null;++ const organization = await ctx.prisma.organization.findUnique({+ where: {+ id: input.orgId,+ },+ });+ if (!organization) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "Organization not found",+ });+ }+ const parsedOrg = parseDbOrg(organization);++ // For Stripe subscriptions, we can get usage from the Stripe Metered Billing API+ if (+ stripeClient &&+ parsedOrg.cloudConfig?.stripe?.customerId &&+ parsedOrg.cloudConfig?.stripe?.activeSubscriptionId+ ) {+ const subscription = await stripeClient.subscriptions.retrieve(+ parsedOrg.cloudConfig.stripe.activeSubscriptionId,+ );+ if (subscription)+ billingPeriodStart = new Date(+ subscription.current_period_start * 1000,+ );+ }++ const usage = await ctx.prisma.observation.count({+ where: {+ project: {+ orgId: input.orgId,+ },+ startTime: {+ gte: billingPeriodStart ?? thirtyDaysAgo,+ },+ },+ });++ return {+ countObservations: usage,+ billingPeriodStart,+ };+ }),+});diff --git a/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts b/web/src/ee/features/billing/server/stripeWebhookApiHandler.tsnew file mode 100644index 0000000000..55539e68ff--- /dev/null+++ b/web/src/ee/features/billing/server/stripeWebhookApiHandler.ts@@ -0,0 +1,231 @@+import {+ getOrgIdFromStripeClientReference,+ isStripeClientReferenceFromCurrentCloudRegion,+} from "@/src/ee/features/billing/stripeClientReference";+import { env } from "@/src/env.mjs";+import { type NextRequest, NextResponse } from "next/server";+import { prisma } from "@langfuse/shared/src/db";+import { stripeClient } from "@/src/ee/features/billing/utils/stripe";+import type Stripe from "stripe";+import { CloudConfigSchema, parseDbOrg } from "@langfuse/shared";+import { traceException } from "@langfuse/shared/src/server";++/*+ * Sign-up endpoint (email/password users), creates user in database.+ * SSO users are created by the NextAuth adapters.+ */+export async function stripeWebhookApiHandler(req: NextRequest) {+ if (req.method !== "POST")+ return NextResponse.json(+ { message: "Method not allowed" },+ { status: 405 },+ );++ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION || !stripeClient) {+ console.error("[Stripe Webhook] Endpoint only available in Langfuse Cloud");+ return NextResponse.json(+ { message: "Stripe webhook endpoint only available in Langfuse Cloud" },+ { status: 500 },+ );+ }+ if (!env.STRIPE_WEBHOOK_SIGNING_SECRET) {+ console.error("[Stripe Webhook] Stripe webhook signing key not found");+ return NextResponse.json(+ { message: "Stripe secret key not found" },+ { status: 500 },+ );+ }++ // check if the request is signed by stripe+ const sig = req.headers.get("stripe-signature");+ console.log("[Stripe Webhook] Signature", sig);+ if (!sig) {+ console.error("[Stripe Webhook] No signature");+ return NextResponse.json({ message: "No signature" }, { status: 400 });+ }+ let event: Stripe.Event;+ try {+ event = stripeClient.webhooks.constructEvent(+ await req.text(),+ sig,+ env.STRIPE_WEBHOOK_SIGNING_SECRET,+ );+ } catch (err) {+ console.error("[Stripe Webhook] Error verifying signature", err);+ return NextResponse.json(+ { message: `Webhook Error: ${err}` },+ { status: 400 },+ );+ }++ // Handle the event+ switch (event.type) {+ case "customer.subscription.created":+ // update the active product id on the organization linked to the subscription + customer and subscription id (if null or same)+ const subscription = event.data.object;+ console.log(+ "[Stripe Webhook] Start customer.subscription.created",+ subscription,+ );+ await handleSubscriptionChanged(subscription, "created");+ break;+ case "customer.subscription.updated":+ // update the active product id on the organization linked to the subscription + customer and subscription id (if null or same)+ const updatedSubscription = event.data.object;+ console.log(+ "[Stripe Webhook] Start customer.subscription.updated",+ updatedSubscription,+ );+ await handleSubscriptionChanged(updatedSubscription, "updated");+ break;+ case "customer.subscription.deleted":+ // remove the active product id on the organization linked to the subscription + subscription, keep customer id+ const deletedSubscription = event.data.object;+ console.log(+ "[Stripe Webhook] Start customer.subscription.deleted",+ deletedSubscription,+ );+ await handleSubscriptionChanged(deletedSubscription, "deleted");+ break;+ default:+ console.log(`Unhandled event type ${event.type}`);+ }++ return NextResponse.json({ received: true }, { status: 200 });+}++async function handleSubscriptionChanged(+ subscription: Stripe.Subscription,+ action: "created" | "deleted" | "updated",+) {+ const subscriptionId = subscription.id;++ // get the checkout session from the subscription to retrieve the client reference for this subscription+ const checkoutSessionsResponse = await stripeClient?.checkout.sessions.list({+ subscription: subscriptionId,+ limit: 1,+ });+ if (!checkoutSessionsResponse || checkoutSessionsResponse.data.length !== 1) {+ console.error("[Stripe Webhook] No checkout session found");+ return;+ }+ const checkoutSession = checkoutSessionsResponse.data[0];++ // the client reference is passed to the stripe checkout session via the pricing page+ const clientReference = checkoutSession.client_reference_id;+ if (!clientReference) {+ console.error("[Stripe Webhook] No client reference");+ return NextResponse.json(+ { message: "No client reference" },+ { status: 400 },+ );+ }+ if (!isStripeClientReferenceFromCurrentCloudRegion(clientReference)) {+ console.log(+ "[Stripe Webhook] Client reference not from current cloud region",+ );+ return;+ }+ const orgId = getOrgIdFromStripeClientReference(clientReference);++ // find the org with the customer ID+ const organization = await prisma.organization.findUnique({+ where: {+ id: orgId,+ },+ });+ if (!organization) {+ console.error("[Stripe Webhook] No organization not found");+ return;+ }+ const parsedOrg = parseDbOrg(organization);++ // assert that no other stripe customer id is already set on the org+ const customerId = subscription.customer;+ if (!customerId || typeof customerId !== "string") {+ console.error("[Stripe Webhook] Product ID not found");+ traceException("[Stripe Webhook] Product ID not found");+ return;+ }+ if (+ parsedOrg.cloudConfig?.stripe?.customerId &&+ parsedOrg.cloudConfig?.stripe?.customerId !== customerId+ ) {+ traceException("[Stripe Webhook] Another customer id already set on org");+ return;+ }++ // check subscription items+ console.log("subscription.items.data", subscription.items.data);++ if (!subscription.items.data || subscription.items.data.length !== 1) {+ console.error(+ "[Stripe Webhook] Subscription items not found or more than one",+ );+ return;+ }++ const subscriptionItem = subscription.items.data[0];+ const productId = subscriptionItem.price.product;++ if (!productId || typeof productId !== "string") {+ console.error("[Stripe Webhook] Product ID not found");+ traceException("[Stripe Webhook] Product ID not found");+ return;+ }++ // assert that no other product is already set on the org if this is not an update+ if (+ action !== "updated" &&+ parsedOrg.cloudConfig?.stripe?.activeProductId &&+ parsedOrg.cloudConfig?.stripe?.activeProductId !== productId+ ) {+ traceException(+ "[Stripe Webhook] Another active product id already set on (one of the) org with this active subscription id",+ );+ return;+ }++ // update the cloud config with the product ID+ if (action === "created" || action === "updated") {+ await prisma.organization.update({+ where: {+ id: parsedOrg.id,+ },+ data: {+ cloudConfig: {+ ...parsedOrg.cloudConfig,+ stripe: {+ ...parsedOrg.cloudConfig?.stripe,+ ...CloudConfigSchema.shape.stripe.parse({+ activeProductId: productId,+ activeSubscriptionId: subscriptionId,+ customerId: customerId,+ }),+ },+ },+ },+ });+ } else if (action === "deleted") {+ await prisma.organization.update({+ where: {+ id: parsedOrg.id,+ },+ data: {+ cloudConfig: {+ ...parsedOrg.cloudConfig,+ stripe: {+ ...parsedOrg.cloudConfig?.stripe,+ ...CloudConfigSchema.shape.stripe.parse({+ activeProductId: undefined,+ activeSubscriptionId: undefined,+ customerId: customerId,+ }),+ },+ },+ },+ });+ }++ return;+}diff --git a/web/src/ee/features/billing/stripeClientReference.ts b/web/src/ee/features/billing/stripeClientReference.tsnew file mode 100644index 0000000000..b35cdf5126--- /dev/null+++ b/web/src/ee/features/billing/stripeClientReference.ts@@ -0,0 +1,22 @@+import { env } from "@/src/env.mjs";++// used client-side to create a stripe customer reference+export const createStripeClientReference = (orgId: string) => {+ if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ console.error(+ "Returning null stripeCustomerReference, you cannot run the checkout page outside of Langfuse Cloud",+ );+ return null;+ }+ return `${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-${orgId}`;+};++// used server-side to check if the stripe customer reference is valid and parse the orgId+export const isStripeClientReferenceFromCurrentCloudRegion = (+ clientReference: string,+) =>+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&+ clientReference.startsWith(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);++export const getOrgIdFromStripeClientReference = (clientReference: string) =>+ clientReference.replace(`${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}-`, "");diff --git a/web/src/ee/features/billing/utils/stripe.ts b/web/src/ee/features/billing/utils/stripe.tsnew file mode 100644index 0000000000..82be2ae291--- /dev/null+++ b/web/src/ee/features/billing/utils/stripe.ts@@ -0,0 +1,6 @@+import { env } from "@/src/env.mjs";+import Stripe from "stripe";++export const stripeClient = env.STRIPE_SECRET_KEY+ ? new Stripe(env.STRIPE_SECRET_KEY)+ : undefined;diff --git a/web/src/ee/features/billing/utils/stripeProducts.ts b/web/src/ee/features/billing/utils/stripeProducts.tsnew file mode 100644index 0000000000..4041d98524--- /dev/null+++ b/web/src/ee/features/billing/utils/stripeProducts.ts@@ -0,0 +1,47 @@+import { env } from "@/src/env.mjs";+import { type Plan } from "@/src/features/entitlements/constants/plans";++type StripeProduct = {+ stripeProductId: string;+ mappedPlan: Plan;+ // include checkout if product can be subscribed to by new users+ checkout: {+ title: string;+ description: string;+ price: string;+ } | null;+};++// map of planid to plan name+export const stripeProducts: StripeProduct[] = [+ {+ stripeProductId:+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV"+ ? "prod_QgDNYKXcBfvUQ3" // test+ : "prod_P47h5SDEr9vJZk", // live+ mappedPlan: "cloud:pro",+ checkout: {+ title: "Pro",+ description:+ "For serious projects. Includes access to full history and higher usage.",+ price: "$59 / month + $10/100k observations",+ },+ },+ {+ stripeProductId:+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV"+ ? "prod_QgDOxTD64U6KDv" // test+ : "prod_PAo9J9pxepZQVe", // live+ mappedPlan: "cloud:team",+ checkout: {+ title: "Team",+ description:+ "Dedicated solutions and support for your team. Contact us for pricing.",+ price: "$499 / month + $10/100k observations",+ },+ },+];++export const mapStripeProductIdToPlan = (productId: string): Plan | null =>+ stripeProducts.find((product) => product.stripeProductId === productId)+ ?.mappedPlan ?? null;diff --git a/web/src/env.mjs b/web/src/env.mjsindex 4f7440d19c..9b10f09716 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -166,6 +166,8 @@ export const env = createEnv({.number().positive().default(60 * 10),+ STRIPE_SECRET_KEY: z.string().optional(),+ STRIPE_WEBHOOK_SIGNING_SECRET: z.string().optional(),},/**@@ -176,6 +178,8 @@ export const env = createEnv({* WARNING: They do not work when used in Docker builds as NEXT_PUBLIC variables are not runtime but compile-time.*/client: {+ // WARNING: Also add these to web/Dockerfile+// NEXT_PUBLIC_CLIENTVAR: z.string().min(1),NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.enum(["US", "EU", "STAGING", "DEV"])@@ -309,6 +313,8 @@ export const env = createEnv({process.env.LANGFUSE_ALLOWED_ORGANIZATION_CREATORS,LANGFUSE_INGESTION_BUFFER_TTL_SECONDS:process.env.LANGFUSE_INGESTION_BUFFER_TTL_SECONDS,+ STRIPE_SECRET_KEY: process.env.STRIPE_SECRET_KEY,+ STRIPE_WEBHOOK_SIGNING_SECRET: process.env.STRIPE_WEBHOOK_SIGNING_SECRET,},// Skip validation in Docker builds// DOCKER_BUILD is set in Dockerfilediff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.tsindex f6af206364..6b1b329665 100644--- a/web/src/features/audit-logs/auditLog.ts+++ b/web/src/features/audit-logs/auditLog.ts@@ -21,6 +21,7 @@ export type AuditableResource =| "posthogIntegration"| "llmApiKey"| "batchExport"+ | "stripeCheckoutSession"// legacy resources| "membership";diff --git a/web/src/features/entitlements/constants/entitlements.ts b/web/src/features/entitlements/constants/entitlements.tsindex a38e6e7e73..943b472f7f 100644--- a/web/src/features/entitlements/constants/entitlements.ts+++ b/web/src/features/entitlements/constants/entitlements.ts@@ -5,7 +5,7 @@ const entitlements = ["playground","model-based-evaluations","rbac-project-roles",- "cloud-usage-metering",+ "cloud-billing","integration-posthog","batch-export",] as const;@@ -15,7 +15,7 @@ export type Entitlement = (typeof entitlements)[number];const cloudAllPlansEntitlements: Entitlement[] = ["playground","model-based-evaluations",- "cloud-usage-metering",+ "cloud-billing","integration-posthog","batch-export",];diff --git a/web/src/features/entitlements/constants/plans.ts b/web/src/features/entitlements/constants/plans.tsindex 8ba4d9f710..cd1da760aa 100644--- a/web/src/features/entitlements/constants/plans.ts+++ b/web/src/features/entitlements/constants/plans.ts@@ -1,8 +1,14 @@-const plans = [- "oss",- "cloud:hobby",- "cloud:pro",- "cloud:team",- "self-hosted:enterprise",-] as const;-export type Plan = (typeof plans)[number];+export const planLabels = {+ oss: "OSS",+ "cloud:hobby": "Hobby",+ "cloud:pro": "Pro",+ "cloud:team": "Team",+ "self-hosted:enterprise": "Enterprise",+} as const;++export type Plan = keyof typeof planLabels;++export const plans = Object.keys(planLabels) as Plan[];++// This function is kept here to ensure consistency when updating plan names in the future.+export const isCloudPlan = (plan: Plan) => plan.startsWith("cloud");diff --git a/web/src/features/entitlements/server/getOrganizationPlan.ts b/web/src/features/entitlements/server/getOrganizationPlan.tsindex 2030636ac5..0f23b44aa5 100644--- a/web/src/features/entitlements/server/getOrganizationPlan.ts+++ b/web/src/features/entitlements/server/getOrganizationPlan.ts@@ -1,6 +1,7 @@+import { mapStripeProductIdToPlan } from "@/src/ee/features/billing/utils/stripeProducts";import { env } from "@/src/env.mjs";import { type Plan } from "@/src/features/entitlements/constants/plans";-import { type CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";+import { type CloudConfigSchema } from "@langfuse/shared";/*** Get the plan of the organization based on the cloud configuration. Used to add this plan to the organization object in JWT via NextAuth.@@ -8,18 +9,30 @@ import { type CloudConfigSchema } from "@/src/features/organizations/utils/cloudexport function getOrganizationPlan(cloudConfig?: CloudConfigSchema): Plan {if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {// in dev, grant team plan to all organizations- if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV") {- return "cloud:team";- }+ // if (process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "DEV") {+ // return "cloud:team";+ // }if (cloudConfig) {- switch (cloudConfig.plan) {- case "Hobby":- return "cloud:hobby";- case "Pro":- return "cloud:pro";- case "Team":- case "Enterprise":- return "cloud:team";+ // manual plan override+ if (cloudConfig.plan) {+ switch (cloudConfig.plan) {+ case "Hobby":+ return "cloud:hobby";+ case "Pro":+ return "cloud:pro";+ case "Team":+ case "Enterprise":+ return "cloud:team";+ }+ }+ // stripe plan via product id+ if (cloudConfig.stripe?.activeProductId) {+ const stripePlan = mapStripeProductIdToPlan(+ cloudConfig.stripe.activeProductId,+ );+ if (stripePlan) {+ return stripePlan;+ }}}return "cloud:hobby";diff --git a/web/src/features/organizations/components/ProjectOverview.tsx b/web/src/features/organizations/components/ProjectOverview.tsxindex 89a25384df..d4025ca1e2 100644--- a/web/src/features/organizations/components/ProjectOverview.tsx+++ b/web/src/features/organizations/components/ProjectOverview.tsx@@ -23,6 +23,10 @@ import {createOrganizationRoute,createProjectRoute,} from "@/src/features/setup/setupRoutes";+import {+ isCloudPlan,+ planLabels,+} from "@/src/features/entitlements/constants/plans";const SingleOrganizationProjectOverview = ({orgId,@@ -82,6 +86,14 @@ const SingleOrganizationProjectOverview = ({title={org.name}level={level}status={orgId === env.NEXT_PUBLIC_DEMO_ORG_ID ? "Demo Org" : undefined}+ label={+ isCloudPlan(org.plan)+ ? {+ text: planLabels[org.plan],+ href: `/organization/${org.id}/settings/billing`,+ }+ : undefined+ }actionButtons={<><Button asChild variant="ghost">diff --git a/web/src/features/pricing-page/PricingPage.tsx b/web/src/features/pricing-page/PricingPage.tsxdeleted file mode 100644index 5d56942ad1..0000000000--- a/web/src/features/pricing-page/PricingPage.tsx+++ /dev/null@@ -1,18 +0,0 @@-import { useQueryOrganization } from "@/src/features/organizations/hooks";-import Script from "next/script";--export function PricingPage(props: { className?: string }) {- const org = useQueryOrganization();- return (- <>- <Script async src="https://js.stripe.com/v3/pricing-table.js" />- <div className={props.className}>- <stripe-pricing-table- client-reference-id={org?.id}- pricing-table-id="prctbl_1OjTUyAWilt2EAVVMCMAMDgB"- publishable-key="pk_live_51MPW00AWilt2EAVVFWfPTQhgmLA0EeacLSzAs6e3vECCcMBvwcMse81XgXO6k1bdBHbPBdpOmrXE8P1gBrxE7yhH00RPHQ8SyG"- ></stripe-pricing-table>- </div>- </>- );-}diff --git a/web/src/features/rbac/components/MembershipInvitesPage.tsx b/web/src/features/rbac/components/MembershipInvitesPage.tsxindex 1a7b972f5a..57a9d65d41 100644--- a/web/src/features/rbac/components/MembershipInvitesPage.tsx+++ b/web/src/features/rbac/components/MembershipInvitesPage.tsx@@ -11,11 +11,11 @@ import { api } from "@/src/utils/api";import type { RouterOutput } from "@/src/utils/types";import { Trash } from "lucide-react";import { useQueryParams, withDefault, NumberParam } from "use-query-params";-import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";-import { type Role } from "@langfuse/shared";+import { type Organization, type Role } from "@langfuse/shared";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import Header from "@/src/components/layouts/header";+export type tmp = Organization;export type InvitesTableRow = {email: string;createdAt: Date;@@ -192,14 +192,7 @@ export function MembershipInvitesPage({};if (projectId ? !hasProjectViewAccess : !hasOrgViewAccess) {- return (- <Alert>- <AlertTitle>Access Denied</AlertTitle>- <AlertDescription>- You do not have permission to view invites of this organization.- </AlertDescription>- </Alert>- );+ return null;}if (totalCount === 0) return null;diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.tsindex 1b02e55901..b8a3f42ad1 100644--- a/web/src/features/rbac/constants/organizationAccessRights.ts+++ b/web/src/features/rbac/constants/organizationAccessRights.ts@@ -7,6 +7,7 @@ const organizationScopes = ["organization:delete","organizationMembers:read","organizationMembers:CUD",+ "langfuseCloudBilling:CRUD",] as const;// type string of all Resource:Action, e.g. "organizationMembers:read"@@ -20,6 +21,7 @@ export const organizationRoleAccessRights: Record<Role, OrganizationScope[]> = {"organization:delete","organizationMembers:CUD","organizationMembers:read",+ "langfuseCloudBilling:CRUD",],ADMIN: ["projects:create",diff --git a/web/src/features/usage-metering/OrganizationUsageChart.tsx b/web/src/features/usage-metering/OrganizationUsageChart.tsxdeleted file mode 100644index 390906c159..0000000000--- a/web/src/features/usage-metering/OrganizationUsageChart.tsx+++ /dev/null@@ -1,116 +0,0 @@-// Langfuse Cloud only--import { Button } from "@/src/components/ui/button";-import { api } from "@/src/utils/api";-import { Flex, MarkerBar, Metric, Text } from "@tremor/react";-import Link from "next/link";-import { PricingPage } from "@/src/features/pricing-page/PricingPage";-import {- Dialog,- DialogContent,- DialogHeader,- DialogTrigger,-} from "@/src/components/ui/dialog";-import Header from "@/src/components/layouts/header";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";-import { useQueryOrganization } from "@/src/features/organizations/hooks";-import { Card } from "@/src/components/ui/card";-import { numberFormatter, compactNumberFormatter } from "@/src/utils/numbers";-import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";--export const OrganizationUsageChart = () => {- const organization = useQueryOrganization();- const entitled = useHasOrgEntitlement("cloud-usage-metering");- const usage = api.usageMetering.last30d.useQuery(- {- orgId: organization!.id,- },- {- enabled: organization !== undefined && entitled,- trpc: {- context: {- skipBatch: true,- },- },- },- );- const capture = usePostHogClientCapture();- const planLimit =- organization?.cloudConfig?.monthlyObservationLimit ?? 50_000;- const plan = organization?.cloudConfig?.plan ?? "Hobby";-- if (!entitled) return null;-- return (- <div>- <Header title="Usage & Billing" level="h3" />- <Card className="p-4">- {usage.data !== undefined ? (- <>- <Text>Observations / last 30d</Text>- <Metric>{numberFormatter(usage.data, 0)}</Metric>- {plan === "Hobby" && (- <>- <Flex className="mt-4">- <Text>{`${numberFormatter((usage.data / planLimit) * 100)}%`}</Text>- <Text>Plan limit: {compactNumberFormatter(planLimit)}</Text>- </Flex>- <MarkerBar- value={Math.min((usage.data / planLimit) * 100, 100)}- className="mt-3"- />- </>- )}- </>- ) : (- "Loading (might take a moment) ..."- )}- </Card>- <div className="mt-4 flex flex-row items-center gap-2">- {plan === "Hobby" ? (- <Dialog- onOpenChange={(open) => {- if (open) {- capture("project_settings:pricing_dialog_opened");- }- }}- >- <DialogTrigger asChild>- <Button variant="secondary">Change plan</Button>- </DialogTrigger>- <DialogContent className="max-w-3xl">- <DialogHeader>- <Header- title="Select plan"- level="h3"- actionButtons={- <Button variant="secondary" asChild>- <Link href="https://langfuse.com/pricing" target="_blank">- Pricing page ↗- </Link>- </Button>- }- />- </DialogHeader>- <PricingPage className="mb-5 mt-5" />- </DialogContent>- </Dialog>- ) : (- <Button variant="secondary">- <Link href="https://billing.stripe.com/p/login/6oE9BXd4u8PR2aYaEE">- Billing settings- </Link>- </Button>- )}- <Button variant="secondary" asChild>- <Link href="https://langfuse.com/pricing" target="_blank">- Pricing page ↗- </Link>- </Button>- <div className="inline-block text-sm text-muted-foreground">- Current plan: {plan}- </div>- </div>- </div>- );-};diff --git a/web/src/features/usage-metering/README.md b/web/src/features/usage-metering/README.mddeleted file mode 100644index 1e9315bb5c..0000000000--- a/web/src/features/usage-metering/README.md+++ /dev/null@@ -1,3 +0,0 @@-# Usage Metering--This feature is used on Langfuse cloud to track project usage and bill customers accordingly.diff --git a/web/src/features/usage-metering/server/usageMeteringRouter.ts b/web/src/features/usage-metering/server/usageMeteringRouter.tsdeleted file mode 100644index bdf57b8622..0000000000--- a/web/src/features/usage-metering/server/usageMeteringRouter.ts+++ /dev/null@@ -1,46 +0,0 @@-import { hasEntitlement } from "@/src/features/entitlements/server/hasEntitlement";-import {- createTRPCRouter,- protectedOrganizationProcedure,-} from "@/src/server/api/trpc";-import { TRPCError } from "@trpc/server";-import * as z from "zod";--export const usageMeteringRouter = createTRPCRouter({- last30d: protectedOrganizationProcedure- .input(- z.object({- orgId: z.string(),- }),- )- .query(async ({ input, ctx }) => {- if (- !hasEntitlement({- entitlement: "cloud-usage-metering",- sessionUser: ctx.session.user,- orgId: input.orgId,- })- )- throw new TRPCError({- code: "UNAUTHORIZED",- message: "Missing cloud-usage-metering entitlement",- });-- const thirtyDaysAgo = new Date();- thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);- thirtyDaysAgo.setHours(0, 0, 0, 0);-- const usage = await ctx.prisma.observation.count({- where: {- project: {- orgId: input.orgId,- },- startTime: {- gte: thirtyDaysAgo,- },- },- });-- return usage;- }),-});diff --git a/web/src/pages/api/billing/README.md b/web/src/pages/api/billing/README.mdnew file mode 100644index 0000000000..b08bdacd49--- /dev/null+++ b/web/src/pages/api/billing/README.md@@ -0,0 +1 @@+These APIs are implemented via the NextJS App router in src/app/api/billing.diff --git a/web/src/pages/organization/[organizationId]/settings/index.tsx b/web/src/pages/organization/[organizationId]/settings/index.tsxindex 2dd9e91def..c92c3934f3 100644--- a/web/src/pages/organization/[organizationId]/settings/index.tsx+++ b/web/src/pages/organization/[organizationId]/settings/index.tsx@@ -3,18 +3,19 @@ import Header from "@/src/components/layouts/header";import { MembershipInvitesPage } from "@/src/features/rbac/components/MembershipInvitesPage";import { MembersTable } from "@/src/features/rbac/components/MembersTable";import { JSONView } from "@/src/components/ui/CodeJsonViewer";-import { env } from "@/src/env.mjs";import RenameOrganization from "@/src/features/organizations/components/RenameOrganization";import { useQueryOrganization } from "@/src/features/organizations/hooks";-import { OrganizationUsageChart } from "@/src/features/usage-metering/OrganizationUsageChart";import { useRouter } from "next/router";import { SettingsDangerZone } from "@/src/components/SettingsDangerZone";import { DeleteOrganizationButton } from "@/src/features/organizations/components/DeleteOrganizationButton";+import { BillingSettings } from "@/src/ee/features/billing/components/BillingSettings";+import { useHasOrgEntitlement } from "@/src/features/entitlements/hooks";const OrgSettingsPage = () => {const organization = useQueryOrganization();const router = useRouter();const { page } = router.query;+ const showBillingSettings = useHasOrgEntitlement("cloud-billing");if (!organization) return null;@@ -68,8 +69,8 @@ const OrgSettingsPage = () => {{title: "Billing",slug: "billing",- content: <OrganizationUsageChart />,- show: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined,+ content: <BillingSettings />,+ show: showBillingSettings,},{title: "Projects",diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex c04076b2c0..11722b80ad 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -8,7 +8,7 @@ import { apiKeysRouter } from "@/src/features/public-api/server/apiKeyRouter";import { membersRouter } from "@/src/features/rbac/server/membersRouter";import { userRouter } from "@/src/server/api/routers/users";import { datasetRouter } from "@/src/features/datasets/server/dataset-router";-import { usageMeteringRouter } from "@/src/features/usage-metering/server/usageMeteringRouter";+import { cloudBillingRouter } from "@/src/ee/features/billing/server/cloudBillingRouter";import { observationsRouter } from "@/src/server/api/routers/observations";import { sessionRouter } from "@/src/server/api/routers/sessions";import { promptRouter } from "@/src/features/prompts/server/routers/promptRouter";@@ -43,7 +43,7 @@ export const appRouter = createTRPCRouter({apiKeys: apiKeysRouter,members: membersRouter,datasets: datasetRouter,- usageMetering: usageMeteringRouter,+ cloudBilling: cloudBillingRouter,observations: observationsRouter,prompts: promptRouter,models: modelRouter,diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 984a323ba1..2156858227 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -29,7 +29,7 @@ import {loadSsoProviders,} from "@/src/ee/features/multi-tenant-sso/utils";import { z } from "zod";-import { CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";+import { CloudConfigSchema } from "@langfuse/shared";import {CustomSSOProvider,traceException,diff --git a/web/types/next-auth.d.ts b/web/types/next-auth.d.tsindex d2bf02640d..63fc40bbed 100644--- a/web/types/next-auth.d.ts+++ b/web/types/next-auth.d.ts@@ -6,7 +6,7 @@ import {type Role,} from "@langfuse/shared/src/db";import { type Flags } from "@/src/features/feature-flags/types";-import { type CloudConfigSchema } from "@/src/features/organizations/utils/cloudConfigSchema";+import { type CloudConfigSchema } from "@langfuse/shared";import { type Plan } from "@/src/features/entitlements/constants/plans";/**diff --git a/worker/package.json b/worker/package.jsonindex 0867f08859..dbdbcde533 100644--- a/worker/package.json+++ b/worker/package.json@@ -51,6 +51,7 @@"pino": "^9.2.0","pino-http": "^9.0.0","pino-pretty": "^10.3.1",+ "stripe": "^16.8.0","tiktoken": "^1.0.15","uuid": "^9.0.1","zod": "^3.23.8"diff --git a/worker/src/app.ts b/worker/src/app.tsindex f92226eb24..e4c3e17f2e 100644--- a/worker/src/app.ts+++ b/worker/src/app.ts@@ -17,6 +17,7 @@ import { onShutdown } from "./utils/shutdown";import helmet from "helmet";import { legacyIngestionExecutor } from "./queues/legacyIngestionQueue";+import { cloudUsageMeteringJobExecutor } from "./queues/cloudUsageMeteringQueue";const app = express();@@ -50,6 +51,10 @@ logger.info("Legacy Ingestion Executor started",legacyIngestionExecutor?.isRunning());+logger.info(+ "Cloud Usage Metering Job Executor started",+ cloudUsageMeteringJobExecutor?.isRunning()+);evalJobCreator?.on("failed", logQueueWorkerError);evalJobExecutor?.on("failed", logQueueWorkerError);@@ -57,6 +62,7 @@ batchExportJobExecutor?.on("failed", logQueueWorkerError);repeatQueueExecutor?.on("failed", logQueueWorkerError);ingestionQueueExecutor?.on("failed", logQueueWorkerError);legacyIngestionExecutor?.on("failed", logQueueWorkerError);+cloudUsageMeteringJobExecutor?.on("failed", logQueueWorkerError);process.on("SIGINT", () => onShutdown("SIGINT"));process.on("SIGTERM", () => onShutdown("SIGTERM"));diff --git a/worker/src/ee/cloudUsageMetering/constants.ts b/worker/src/ee/cloudUsageMetering/constants.tsnew file mode 100644index 0000000000..c8171d91e6--- /dev/null+++ b/worker/src/ee/cloudUsageMetering/constants.ts@@ -0,0 +1,6 @@+export const cloudUsageMeteringDbCronJobName = "cloud_usage_metering";++export enum CloudUsageMeteringDbCronJobStates {+ Queued = "queued",+ Processing = "processing",+}diff --git a/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.tsnew file mode 100644index 0000000000..f9af81dff0--- /dev/null+++ b/worker/src/ee/cloudUsageMetering/handleCloudUsageMeteringJob.ts@@ -0,0 +1,165 @@+import { parseDbOrg, Prisma } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import Stripe from "stripe";+import { env } from "../../env";+import logger from "../../logger";+import {+ cloudUsageMeteringDbCronJobName,+ CloudUsageMeteringDbCronJobStates,+} from "./constants";+import { cloudUsageMeteringQueue } from "../../queues/cloudUsageMeteringQueue";+import {+ QueueJobs,+ recordGauge,+ traceException,+} from "@langfuse/shared/src/server";+import { Job } from "bullmq";++const delayFromStartOfInterval = 3600000 + 5 * 60 * 1000; // 5 minutes after the end of the interval++export const handleCloudUsageMeteringJob = async (job: Job) => {+ if (!env.STRIPE_SECRET_KEY) {+ throw new Error("Stripe secret key not found");+ }++ const cron = await prisma.cronJobs.upsert({+ where: { name: cloudUsageMeteringDbCronJobName },+ create: {+ name: cloudUsageMeteringDbCronJobName,+ state: CloudUsageMeteringDbCronJobStates.Queued,+ lastRun: new Date(Date.now() - ((Date.now() % 3600000) + 3600000)), // beginning of the last full hour+ },+ update: {},+ });+ if (!cron.lastRun) {+ throw new Error("Cloud Usage Metering Cron Job last run not found");+ }+ if (cron.lastRun.getTime() % 3600000 !== 0) {+ throw new Error(+ "Cloud Usage Metering Cron Job last run is not on the full hour"+ );+ }+ if (cron.lastRun.getTime() + delayFromStartOfInterval > Date.now()) {+ logger.info(`Next Cloud Usage Metering Job is not due yet`);+ return;+ }++ if (cron.state === CloudUsageMeteringDbCronJobStates.Processing) {+ if (+ cron.jobStartedAt &&+ cron.jobStartedAt < new Date(Date.now() - 1200000)+ ) {+ logger.warn(+ "Last cloud usage metering job started at is older than 20 minutes, retrying job"+ );+ } else {+ logger.warn("Cloud Usage Metering Job already in progress");+ return;+ }+ }++ await prisma.cronJobs.update({+ where: { name: cloudUsageMeteringDbCronJobName },+ data: {+ state: CloudUsageMeteringDbCronJobStates.Processing,+ jobStartedAt: new Date(),+ },+ });++ // timing+ const meterIntervalStart = cron.lastRun;+ const meterIntervalEnd = new Date(cron.lastRun.getTime() + 3600000);+ logger.info(+ `Cloud Usage Metering Job running for interval ${meterIntervalStart.toISOString()} - ${meterIntervalEnd.toISOString()}`+ );++ // find all organizations which have a stripe org id set up+ const organizations = (+ await prisma.organization.findMany({+ where: {+ cloudConfig: {+ path: ["stripe", "customerId"],+ not: Prisma.DbNull,+ },+ },+ })+ ).map(parseDbOrg);+ logger.info(+ `Cloud Usage Metering Job for ${organizations.length} organizations`+ );++ // setup stripe client+ const stripe = new Stripe(env.STRIPE_SECRET_KEY);++ // for each org, calculate the meter and push to stripe+ let countProcessedOrgs = 0;+ let countProcessedObservations = 0;+ for (const org of organizations) {+ // update progress to prevent job from being stalled+ job.updateProgress(countProcessedOrgs / organizations.length);++ const stripeCustomerId = org.cloudConfig?.stripe?.customerId;+ if (!stripeCustomerId) {+ // should not happen+ traceException(`Stripe customer id not found for org ${org.id}`);+ logger.error(`Stripe customer id not found for org ${org.id}`);+ continue;+ }++ const countObservations = await prisma.observation.count({+ where: {+ project: {+ orgId: org.id,+ },+ createdAt: {+ gte: meterIntervalStart,+ lt: meterIntervalEnd,+ },+ },+ });+ logger.info(+ `Cloud Usage Metering Job for org ${org.id} - ${stripeCustomerId} stripe customer id - ${countObservations} observations`+ );++ await stripe.billing.meterEvents.create({+ event_name: "tracing_observations",+ timestamp: meterIntervalEnd.getTime() / 1000,+ payload: {+ stripe_customer_id: stripeCustomerId,+ value: countObservations.toString(), // value is a string in stripe+ },+ });++ countProcessedOrgs++;+ countProcessedObservations += countObservations;+ }++ recordGauge("cloud_usage_metering_processed_orgs", countProcessedOrgs, {+ unit: "organizations",+ });+ recordGauge(+ "cloud_usage_metering_processed_observations",+ countProcessedObservations,+ {+ unit: "observations",+ }+ );++ // update cron job+ await prisma.cronJobs.update({+ where: { name: cloudUsageMeteringDbCronJobName },+ data: {+ lastRun: meterIntervalEnd,+ state: CloudUsageMeteringDbCronJobStates.Queued,+ jobStartedAt: null,+ },+ });++ if (meterIntervalEnd.getTime() + delayFromStartOfInterval < Date.now()) {+ logger.info(`Enqueueing next Cloud Usage Metering Job to catch up `);+ recordGauge("cloud_usage_metering_scheduled_catchup_jobs", 1, {+ unit: "jobs",+ });+ await cloudUsageMeteringQueue?.add(QueueJobs.CloudUsageMeteringJob, {});+ }+};diff --git a/worker/src/env.ts b/worker/src/env.tsindex e94d286d00..1b907adaa1 100644--- a/worker/src/env.ts+++ b/worker/src/env.ts@@ -66,6 +66,7 @@ const EnvSchema = z.object({.number().positive().default(25),+ STRIPE_SECRET_KEY: z.string().optional(),});export const env = EnvSchema.parse(process.env);diff --git a/worker/src/queues/cloudUsageMeteringQueue.ts b/worker/src/queues/cloudUsageMeteringQueue.tsnew file mode 100644index 0000000000..a0bc106923--- /dev/null+++ b/worker/src/queues/cloudUsageMeteringQueue.ts@@ -0,0 +1,65 @@+import { Queue, Worker } from "bullmq";+import logger from "../logger";+import {+ redis,+ QueueName,+ QueueJobs,+ instrument,+} from "@langfuse/shared/src/server";+import { handleCloudUsageMeteringJob } from "../ee/cloudUsageMetering/handleCloudUsageMeteringJob";+import { env } from "../env";++export const cloudUsageMeteringQueue =+ redis && env.STRIPE_SECRET_KEY+ ? new Queue(QueueName.CloudUsageMeteringQueue, {+ connection: redis,+ })+ : null;++if (cloudUsageMeteringQueue) {+ cloudUsageMeteringQueue.add(+ QueueJobs.CloudUsageMeteringJob,+ {},+ {+ repeat: { pattern: "5 * * * *" },+ }+ );++ // add a job to the queue to start the job immediately in case we need to catch up+ cloudUsageMeteringQueue.add(QueueJobs.CloudUsageMeteringJob, {}, {});++ // log the jobs in the queue+ cloudUsageMeteringQueue.getJobCounts().then((counts) => {+ logger.info("Cloud Usage Metering Queue", counts);+ });+}++export const cloudUsageMeteringJobExecutor =+ redis && env.STRIPE_SECRET_KEY+ ? new Worker(+ QueueName.CloudUsageMeteringQueue,+ async (job) => {+ if (job.name === QueueJobs.CloudUsageMeteringJob) {+ return instrument(+ { name: "cloudUsageMeteringJobExecutor" },+ async () => {+ logger.info("Executing Cloud Usage Metering Job", job.data);+ try {+ return await handleCloudUsageMeteringJob(job);+ } catch (error) {+ logger.error(+ "Error executing Cloud Usage Metering Job",+ error+ );+ throw error;+ }+ }+ );+ }+ },+ {+ connection: redis,+ concurrency: 1,+ }+ )+ : null;diff --git a/worker/src/utils/shutdown.ts b/worker/src/utils/shutdown.tsindex 8c45cd8199..1242acb511 100644--- a/worker/src/utils/shutdown.ts+++ b/worker/src/utils/shutdown.ts@@ -10,6 +10,7 @@ import { ClickhouseWriter } from "../services/ClickhouseWriter";import { setSigtermReceived } from "../features/health";import { server } from "../index";import { legacyIngestionExecutor } from "../queues/legacyIngestionQueue";+import { cloudUsageMeteringJobExecutor } from "../queues/cloudUsageMeteringQueue";export const onShutdown: NodeJS.SignalsListener = async (signal) => {logger.info(`Received ${signal}, closing server...`);@@ -27,6 +28,7 @@ export const onShutdown: NodeJS.SignalsListener = async (signal) => {ingestionQueueExecutor,repeatQueueExecutor,legacyIngestionExecutor,+ cloudUsageMeteringJobExecutor,];await Promise.all(workers.map((worker) => worker?.close()));