🪢 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(billing): CHB billing integration UI flow (#15464)
Steffen Schmitz8a5733db46d3
diff --git a/web/src/__tests__/server/unit/cloudBillingRouter.servertest.ts b/web/src/__tests__/server/unit/cloudBillingRouter.servertest.tsnew file mode 100644index 0000000000..6c7a4f5e1b--- /dev/null+++ b/web/src/__tests__/server/unit/cloudBillingRouter.servertest.ts@@ -0,0 +1,157 @@+import type { Session } from "next-auth";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ resolveBillingService: vi.fn(),+ throwIfNoEntitlement: vi.fn(),+ throwIfNoOrganizationAccess: vi.fn(),+ auditLog: vi.fn(),+ isCloudBillingEnabled: vi.fn(() => true),+}));++vi.mock("@/src/ee/features/billing/server/resolveBillingService", () => ({+ resolveBillingService: mocks.resolveBillingService,+}));++vi.mock("@/src/features/entitlements/server/hasEntitlement", () => ({+ throwIfNoEntitlement: mocks.throwIfNoEntitlement,+}));++vi.mock("@/src/features/rbac/utils/checkOrganizationAccess", () => ({+ throwIfNoOrganizationAccess: mocks.throwIfNoOrganizationAccess,+}));++vi.mock("@/src/features/audit-logs/auditLog", () => ({+ auditLog: mocks.auditLog,+}));++vi.mock("@/src/ee/features/billing/utils/isCloudBilling", () => ({+ isCloudBillingEnabled: mocks.isCloudBillingEnabled,+}));++import { cloudBillingRouter } from "@/src/ee/features/billing/server/cloudBillingRouter";+import { logger } from "@langfuse/shared/src/server";++/** Metadata payloads passed to `logger.error`, where the labels land. */+const loggedErrors = () =>+ vi+ .mocked(logger.error)+ .mock.calls.map((call) => (call as unknown[])[1] as unknown);++const ORG_ID = "org-1";++const caller = () => {+ const session = {+ expires: "1",+ user: {+ id: "user-1",+ name: "Demo User",+ email: "[email protected]",+ admin: false,+ organizations: [{ id: ORG_ID, name: "Org", role: "OWNER", projects: [] }],+ },+ } as unknown as Session;++ return cloudBillingRouter.createCaller({+ session,+ headers: {},+ prisma: {} as never,+ } as never);+};++/** Minimal stand-in for the resolved provider service. */+const serviceMock = () => ({+ createCheckoutSession: vi.fn().mockResolvedValue("https://checkout.example"),+ getCustomerPortalUrl: vi.fn(),+ getInvoices: vi.fn(),+});++describe("cloudBillingRouter provider dispatch", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(logger, "error").mockImplementation((() => {}) as never);+ mocks.isCloudBillingEnabled.mockReturnValue(true);+ });++ describe("createStripeCheckoutSession", () => {+ it("forwards opId to the resolved service", async () => {+ // The CHB path keys its checkout request's idempotency key on opId, so a+ // dropped opId sends a concurrent retry to CHB unkeyed: two CH+ // organizations get created, one loses the atomic claim, and the user+ // sees a spurious CONFLICT while a CH organization is orphaned.+ const service = serviceMock();+ mocks.resolveBillingService.mockResolvedValue({+ billingProvider: "clickhouse",+ service,+ });++ await caller().createStripeCheckoutSession({+ orgId: ORG_ID,+ stripeProductId: "prod_core",+ opId: "op-1",+ });++ expect(service.createCheckoutSession).toHaveBeenCalledWith(+ ORG_ID,+ "prod_core",+ "op-1",+ );+ });+ });++ describe("provider-agnostic error labels", () => {+ // `withErrorHandling` masks every 5xx message before it reaches the client,+ // so the label is an on-call surface, not a user-facing one: it lands in the+ // middleware's `logger.error` payload. ChbApiError extends Error, not+ // TRPCError, so a CHB REST failure does reach that wrapper.+ it.each([+ ["getInvoices" as const, "getInvoices" as const],+ ["getStripeCustomerPortalUrl" as const, "getCustomerPortalUrl" as const],+ ])(+ "labels a CHB failure in %s as ClickHouse Billing",+ async (procedure, method) => {+ const service = serviceMock();+ service[method].mockRejectedValue(new Error("CHB request failed"));+ mocks.resolveBillingService.mockResolvedValue({+ billingProvider: "clickhouse",+ service,+ });++ await expect(caller()[procedure]({ orgId: ORG_ID })).rejects.toThrow();++ expect(loggedErrors()).toEqual(+ expect.arrayContaining([+ // The procedure's own log line names the provider that failed.+ expect.objectContaining({ billingProvider: "clickhouse" }),+ expect.objectContaining({+ error: expect.objectContaining({+ message: "ClickHouse Billing error: CHB request failed",+ }),+ }),+ ]),+ );+ },+ );++ it("still labels a Stripe failure as Stripe", async () => {+ const service = serviceMock();+ service.getInvoices.mockRejectedValue(new Error("upstream unavailable"));+ mocks.resolveBillingService.mockResolvedValue({+ billingProvider: "stripe",+ service,+ });++ await expect(caller().getInvoices({ orgId: ORG_ID })).rejects.toThrow();++ expect(loggedErrors()).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ error: expect.objectContaining({+ message: "Stripe error: upstream unavailable",+ }),+ }),+ ]),+ );+ });+ });+});diff --git a/web/src/__tests__/server/unit/resolveBillingService.servertest.ts b/web/src/__tests__/server/unit/resolveBillingService.servertest.tsnew file mode 100644index 0000000000..99b1db3fe6--- /dev/null+++ b/web/src/__tests__/server/unit/resolveBillingService.servertest.ts@@ -0,0 +1,142 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ env: {+ LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE: null as Date | null,+ },+ getChbApiClient: vi.fn(),+ createBillingServiceFromContext: vi.fn(),+ findOrg: vi.fn(),+}));++vi.mock("@/src/env.mjs", () => ({ env: mocks.env }));++vi.mock("@/src/ee/features/billing/server/chb/chbApiClient", () => ({+ getChbApiClient: mocks.getChbApiClient,+}));++vi.mock("@/src/ee/features/billing/server/stripe/stripeBillingService", () => ({+ createBillingServiceFromContext: mocks.createBillingServiceFromContext,+}));++import { resolveBillingService } from "@/src/ee/features/billing/server/resolveBillingService";+import { ChbBillingService } from "@/src/ee/features/billing/server/chb/chbBillingService";+import { logger } from "@langfuse/shared/src/server";++vi.spyOn(logger, "error").mockImplementation((() => {}) as never);++const ORG_ID = "org-1";+const CHB_ORG_ID = "3f7c1b0a-2d5e-4c8b-9a1f-8e6d4c2b1a09";++const ctxWithOrg = (cloudConfig: unknown) =>+ ({+ prisma: { organization: { findUnique: mocks.findOrg } },+ session: { user: { id: "user-1" } },+ cloudConfig,+ }) as never;++const STRIPE_SERVICE = { provider: "stripe-service" };++describe("resolveBillingService", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE = null;+ mocks.createBillingServiceFromContext.mockReturnValue(STRIPE_SERVICE);+ mocks.getChbApiClient.mockReturnValue({ client: true });+ mocks.findOrg.mockResolvedValue({+ id: ORG_ID,+ name: "Org",+ cloudConfig: {},+ });+ });++ it("serves an org carrying CHB state with the CHB service", async () => {+ mocks.findOrg.mockResolvedValue({+ id: ORG_ID,+ name: "Org",+ cloudConfig: { clickhouse: { organizationId: CHB_ORG_ID } },+ });++ const { billingProvider, service } = await resolveBillingService(+ ctxWithOrg({}),+ ORG_ID,+ );++ expect(billingProvider).toBe("clickhouse");+ expect(service).toBeInstanceOf(ChbBillingService);+ });++ it("errors instead of falling back for a CHB org when the CHB env is missing", async () => {+ // Sticky CHB org: Stripe cannot serve it, so a half-configured deployment is+ // a config error, not a fallback.+ mocks.getChbApiClient.mockReturnValue(null);+ mocks.findOrg.mockResolvedValue({+ id: ORG_ID,+ name: "Org",+ cloudConfig: { clickhouse: { organizationId: CHB_ORG_ID } },+ });++ await expect(+ resolveBillingService(ctxWithOrg({}), ORG_ID),+ ).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });+ expect(mocks.createBillingServiceFromContext).not.toHaveBeenCalled();+ });++ it("routes a never-billed org to CHB once the cutoff has passed", async () => {+ // Regression guard for the cutoff plumbing: the shared resolver takes the+ // cutoff as an argument, so forgetting to pass it silently pins every new+ // org to Stripe.+ mocks.env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE = new Date(+ "2020-01-01T00:00:00Z",+ );++ const { billingProvider } = await resolveBillingService(+ ctxWithOrg({}),+ ORG_ID,+ );++ expect(billingProvider).toBe("clickhouse");+ });++ it("fails closed to Stripe when the cutoff is set but the CHB env is incomplete", async () => {+ mocks.env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE = new Date(+ "2020-01-01T00:00:00Z",+ );+ mocks.getChbApiClient.mockReturnValue(null);++ const { billingProvider, service } = await resolveBillingService(+ ctxWithOrg({}),+ ORG_ID,+ );++ expect(billingProvider).toBe("stripe");+ expect(service).toBe(STRIPE_SERVICE);+ });++ it("keeps an existing Stripe customer on Stripe after the cutoff", async () => {+ mocks.env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE = new Date(+ "2020-01-01T00:00:00Z",+ );+ mocks.findOrg.mockResolvedValue({+ id: ORG_ID,+ name: "Org",+ cloudConfig: { stripe: { customerId: "cus_1" } },+ });++ const { billingProvider, service } = await resolveBillingService(+ ctxWithOrg({}),+ ORG_ID,+ );++ expect(billingProvider).toBe("stripe");+ expect(service).toBe(STRIPE_SERVICE);+ });++ it("errors when the organization does not exist", async () => {+ mocks.findOrg.mockResolvedValue(null);++ await expect(+ resolveBillingService(ctxWithOrg({}), ORG_ID),+ ).rejects.toMatchObject({ code: "INTERNAL_SERVER_ERROR" });+ });+});diff --git a/web/src/ee/features/billing/components/BillingActionButtons.tsx b/web/src/ee/features/billing/components/BillingActionButtons.tsxindex 906d444b76..25da2831da 100644--- a/web/src/ee/features/billing/components/BillingActionButtons.tsx+++ b/web/src/ee/features/billing/components/BillingActionButtons.tsx@@ -11,21 +11,22 @@ import { useBillingInformation } from "./useBillingInformation";import { StripeCancellationButton } from "./StripeCancellationButton";export const BillingActionButtons = () => {- const { organization, hasValidPaymentMethod, isLoading } =- useBillingInformation();+ const {+ organization,+ hasActiveSubscription,+ hasValidPaymentMethod,+ isLoading,+ } = useBillingInformation();const { setOpen } = useSupportDrawer();const { setOpen: setMigrationPanelOpen } = useV4MigrationPanel();// Show pricing page buttonconst shouldDisableChangePlan = useMemo(() => {- if (!organization?.cloudConfig?.stripe?.activeSubscriptionId) {+ if (!hasActiveSubscription) {return false; // always show for hobby plan users}return !hasValidPaymentMethod;- }, [- organization?.cloudConfig?.stripe?.activeSubscriptionId,- hasValidPaymentMethod,- ]);+ }, [hasActiveSubscription, hasValidPaymentMethod]);// Do not show checkout or customer portal if manual plan is set in cloud configif (organization?.cloudConfig?.plan) {@@ -55,7 +56,7 @@ export const BillingActionButtons = () => {{/* Always show – also for people who are currently on hobby plan */}<BillingSwitchPlanDialog disabled={shouldDisableChangePlan} />- {organization?.cloudConfig?.stripe?.activeSubscriptionId && (+ {organization && hasActiveSubscription && (<><StripeCustomerPortalButtonorgId={organization.id}@@ -74,14 +75,11 @@ export const BillingActionButtons = () => {</Link></Button></div>- {organization?.cloudConfig?.stripe?.activeSubscriptionId &&- !hasValidPaymentMethod &&- !isLoading && (- <p className="text-sm text-red-600">- You do not have a valid payment method. Please Update Billing- Details.- </p>- )}+ {hasActiveSubscription && !hasValidPaymentMethod && !isLoading && (+ <p className="text-sm text-red-600">+ You do not have a valid payment method. Please Update Billing Details.+ </p>+ )}</div>);};diff --git a/web/src/ee/features/billing/components/BillingDiscountView.tsx b/web/src/ee/features/billing/components/BillingDiscountView.tsxindex 9bd338f0f2..dbc773a998 100644--- a/web/src/ee/features/billing/components/BillingDiscountView.tsx+++ b/web/src/ee/features/billing/components/BillingDiscountView.tsx@@ -4,7 +4,7 @@ import { useBillingInformation } from "@/src/ee/features/billing/components/useBimport { BillingDiscountCodeButton } from "@/src/ee/features/billing/components/BillingDiscountCodeButton";export const BillingDiscountView = () => {- const { organization } = useBillingInformation();+ const { organization, billingProvider } = useBillingInformation();const shouldRenderComponent = Boolean(organization?.cloudConfig?.stripe?.customerId,@@ -31,6 +31,11 @@ export const BillingDiscountView = () => {}};+ // No promotion-code API on the ClickHouse Billing path yet+ if (billingProvider === "clickhouse") {+ return null;+ }+// Hide promotion code view and button when user is on Hobby Plan// Hobby plan users don't have an active subscription IDif (!organization?.cloudConfig?.stripe?.activeSubscriptionId) {diff --git a/web/src/ee/features/billing/components/BillingInvoiceTable.tsx b/web/src/ee/features/billing/components/BillingInvoiceTable.tsxindex 431a308e62..0d469ea5ff 100644--- a/web/src/ee/features/billing/components/BillingInvoiceTable.tsx+++ b/web/src/ee/features/billing/components/BillingInvoiceTable.tsx@@ -32,9 +32,15 @@ type InvoiceRow = {export function BillingInvoiceTable() {const { organization } = useBillingInformation();const isCloudBillingAvailable = useIsCloudBillingAvailable();- const shouldShowTable =- isCloudBillingAvailable &&- Boolean(organization?.cloudConfig?.stripe?.customerId);+ // Provider-agnostic: getInvoices dispatches to whichever provider bills the+ // org, so the gate is "does this org have a billing identity at all", not+ // "does it have a Stripe customer". A CHB org never populates+ // stripe.customerId and would otherwise never see its invoice history.+ const hasBillingIdentity = Boolean(+ organization?.cloudConfig?.stripe?.customerId ??+ organization?.cloudConfig?.clickhouse?.organizationId,+ );+ const shouldShowTable = isCloudBillingAvailable && hasBillingIdentity;const [virtualTotal, setVirtualTotal] = useState(9999);const [paginationState, setPaginationState] = useState<{diff --git a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsxindex 3e85dae913..b94c53be9f 100644--- a/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx+++ b/web/src/ee/features/billing/components/BillingSwitchPlanDialog.tsx@@ -44,6 +44,7 @@ export const BillingSwitchPlanDialog = ({scheduledPlanSwitch,isLegacySubscription,hasValidPaymentMethod,+ currentProductId,} = useBillingInformation();const capture = usePostHogClientCapture();@@ -89,8 +90,6 @@ export const BillingSwitchPlanDialog = ({{stripeProducts.filter((product) => Boolean(product.checkout)).map((product) => {- const currentProductId =- organization?.cloudConfig?.stripe?.activeProductId;const isThisUpgrade = currentProductId? isUpgrade(currentProductId, product.stripeProductId): true;@@ -112,14 +111,12 @@ export const BillingSwitchPlanDialog = ({<span className="ml-1">Starts next period</span>)}{scheduledPlanSwitch &&- organization?.cloudConfig?.stripe?.activeProductId ===- product.stripeProductId && (+ currentProductId === product.stripeProductId && (<span className="ml-1">(Until next period)</span>)}{!scheduledPlanSwitch &&cancellation?.isCancelled &&- organization?.cloudConfig?.stripe?.activeProductId ===- product.stripeProductId && (+ currentProductId === product.stripeProductId && (<span className="ml-1">(Until next period)</span>)}</div>@@ -164,7 +161,7 @@ export const BillingSwitchPlanDialog = ({Learn more about plan →</Link>{/* The default behavior the user is on a paid plan.*/}- {organization?.cloudConfig?.stripe?.activeProductId ? (+ {currentProductId ? (// Change plan view<div className="mt-2 space-y-2">{isCurrentPlan && (@@ -278,8 +275,7 @@ export const BillingSwitchPlanDialog = ({}}}disabled={- organization?.cloudConfig?.stripe- ?.activeProductId === product.stripeProductId+ currentProductId === product.stripeProductId}loading={processingPlanId === product.stripeProductIddiff --git a/web/src/ee/features/billing/components/useBillingInformation.tsx b/web/src/ee/features/billing/components/useBillingInformation.tsxindex 411523658f..7fe5d947ba 100644--- a/web/src/ee/features/billing/components/useBillingInformation.tsx+++ b/web/src/ee/features/billing/components/useBillingInformation.tsx@@ -2,8 +2,9 @@ import { useMemo } from "react";import { useQueryOrganization } from "@/src/features/organizations/hooks";import { formatLocalIsoDate } from "@/src/components/LocalIsoDate";-import { type Plan, planLabels } from "@langfuse/shared";+import { type BillingProvider, type Plan, planLabels } from "@langfuse/shared";import { stripeProducts } from "@/src/ee/features/billing/utils/stripeCatalogue";+import { mapChbPlanCodeToStripeProductId } from "@/src/ee/features/billing/utils/chbCatalogue";import { api } from "@/src/utils/api";export type BillingCancellationInfo = {@@ -31,6 +32,14 @@ export type UseBillingInformationResult = {isLegacySubscription: boolean;hasActiveSubscription: boolean;hasValidPaymentMethod: boolean;+ billingProvider: BillingProvider;+ /**+ * Stripe product id of the current paid plan, provider-agnostic: the real+ * product id for Stripe orgs, the mapped equivalent for CHB orgs. The plan+ * dialog keys its cards on Stripe product ids until plan-code-first inputs+ * ship.+ */+ currentProductId: string | null;};export const useBillingInformation = (): UseBillingInformationResult => {@@ -93,6 +102,19 @@ export const useBillingInformation = (): UseBillingInformationResult => {}}, [subscriptionInfo]);+ // Server-resolved provider once loaded; before that, derive from the+ // session org's cloudConfig so gating does not flicker for CHB orgs.+ const billingProvider: BillingProvider =+ subscriptionInfo?.billingProvider ??+ (organization?.cloudConfig?.clickhouse?.organizationId+ ? "clickhouse"+ : "stripe");++ const chbPlanCode = organization?.cloudConfig?.clickhouse?.planCode;+ const currentProductId =+ organization?.cloudConfig?.stripe?.activeProductId ??+ (chbPlanCode ? mapChbPlanCodeToStripeProductId(chbPlanCode) : null);+return {isLoading: isLoadingSubscriptionInfo,organization,@@ -103,8 +125,11 @@ export const useBillingInformation = (): UseBillingInformationResult => {organization?.cloudConfig?.stripe?.isLegacySubscription,),hasActiveSubscription: Boolean(- organization?.cloudConfig?.stripe?.activeSubscriptionId,+ organization?.cloudConfig?.stripe?.activeSubscriptionId ??+ organization?.cloudConfig?.clickhouse?.bundleId,),hasValidPaymentMethod: subscriptionInfo?.hasValidPaymentMethod ?? false,+ billingProvider,+ currentProductId,};};diff --git a/web/src/ee/features/billing/server/chb/chbBillingService.ts b/web/src/ee/features/billing/server/chb/chbBillingService.tsindex 5446b574c6..122e2eb4fd 100644--- a/web/src/ee/features/billing/server/chb/chbBillingService.ts+++ b/web/src/ee/features/billing/server/chb/chbBillingService.ts@@ -16,6 +16,7 @@ import {type ChbBundle,ChbPaymentRequiredError,} from "./chbApiClient";+import { backfillChbProjectEvents } from "./chbProjectEvents";import {isChbUpgrade,mapChbPlanCodeToStripeProductId,@@ -249,6 +250,13 @@ export class ChbBillingService {"Cannot initialize ClickHouse Billing checkout for a Stripe-billed organization",});}+ if (parsedOrg.cloudConfig?.clickhouse?.bundleId) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message:+ "Organization already has an active bundle; use changePlan instead of checkout",+ });+ }const planCode = mapStripeProductIdToChbPlanCode(stripeProductId);if (!planCode) {@@ -386,6 +394,26 @@ export class ChbBillingService {},});+ // Persisting the CH organization id above is the first moment CHB can+ // attribute a project to this org, and project events are suppressed until+ // then, so the projects the org already has have never been sent. Mirror+ // them once. Only the first checkout reaches this line -- a retry against+ // an org that already has a CH organization returned above -- so there is+ // no second backfill resending the same list.+ //+ // Not awaited: best-effort by design (it swallows its own failures and+ // reports them through langfuse.billing_events.emit_failed), and the user+ // is waiting on a redirect to the payment page.+ backfillChbProjectEvents({ orgId }).catch((error) => {+ // The backfill already reports its own per-project failures; reaching+ // here means it rejected unexpectedly, which must still not surface as+ // an unhandled rejection.+ logger.error(+ `chbBillingService.checkout.backfill.failed for org ${orgId}`,+ error,+ );+ });+return session.url;}diff --git a/web/src/ee/features/billing/server/cloudBillingRouter.ts b/web/src/ee/features/billing/server/cloudBillingRouter.tsindex 8fed1f5f6c..b036191690 100644--- a/web/src/ee/features/billing/server/cloudBillingRouter.ts+++ b/web/src/ee/features/billing/server/cloudBillingRouter.ts@@ -10,9 +10,28 @@ import { TRPCError } from "@trpc/server";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";import { auditLog } from "@/src/features/audit-logs/auditLog";import { logger } from "@langfuse/shared/src/server";-import { createBillingServiceFromContext } from "./stripe/stripeBillingService";+import { type BillingProvider } from "@langfuse/shared";+import { resolveBillingService } from "./resolveBillingService";import { isCloudBillingEnabled } from "../utils/isCloudBilling";+const PROVIDER_LABEL: Record<BillingProvider, string> = {+ stripe: "Stripe",+ clickhouse: "ClickHouse Billing",+};++/**+ * Names the provider that actually failed. Both procedures below can dispatch+ * to either provider, so a hardcoded "Stripe error:" would point on-call at+ * the wrong system for a CHB REST failure.+ */+const billingErrorMessage = (+ billingProvider: BillingProvider,+ error: unknown,+) => {+ const label = PROVIDER_LABEL[billingProvider];+ return `${label} error: ${error instanceof Error ? error.message : `Unknown ${label} error`}`;+};+export const cloudBillingRouter = createTRPCRouter({getSubscriptionInfo: protectedOrganizationProcedure.input(@@ -44,13 +63,16 @@ export const cloudBillingRouter = createTRPCRouter({scheduledChange: null,billingPeriod: null,hasValidPaymentMethod: false,+ billingProvider: "stripe" as const,};}- const res = await createBillingServiceFromContext(+ const { billingProvider, service } = await resolveBillingService(ctx,- ).getSubscriptionInfo(input.orgId);- return res;+ input.orgId,+ );+ const res = await service.getSubscriptionInfo(input.orgId);+ return { ...res, billingProvider };}),createStripeCheckoutSession: protectedOrganizationProcedure.input(@@ -80,10 +102,16 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);- const url = await stripeBillingService.createCheckoutSession(+ const { service } = await resolveBillingService(ctx, input.orgId);++ // opId is forwarded: the CHB path keys its checkout request on it, so+ // dropping it would send a concurrent retry to CHB with no idempotency+ // key and orphan a CH organization. Stripe stays byte-identical because+ // its createCheckoutSession ignores the argument.+ const url = await service.createCheckoutSession(input.orgId,input.stripeProductId,+ input.opId,);auditLog({@@ -124,9 +152,11 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- await stripeBillingService.changePlan(input.orgId, input.stripeProductId);+ // opId is intentionally not forwarded: the Stripe path never received+ // it here, and §4.2 keeps Stripe behavior byte-identical.+ await service.changePlan(input.orgId, input.stripeProductId);}),cancelStripeSubscription: protectedOrganizationProcedure.input(@@ -155,9 +185,9 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- await stripeBillingService.cancel(input.orgId, input.opId);+ await service.cancel(input.orgId, input.opId);return { ok: true } as const;}),@@ -188,9 +218,9 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- await stripeBillingService.reactivate(input.orgId, input.opId);+ await service.reactivate(input.orgId, input.opId);return { ok: true } as const;}),@@ -216,12 +246,9 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- await stripeBillingService.clearPlanSwitchSchedule(- input.orgId,- input.opId,- );+ await service.clearPlanSwitchSchedule(input.orgId, input.opId);return { ok: true } as const;}),@@ -252,13 +279,18 @@ export const cloudBillingRouter = createTRPCRouter({return null;}+ // Resolved outside the try so the catch can label the failure with the+ // provider that actually failed. `ChbApiError` extends `Error`, not+ // `TRPCError`, so a CHB REST failure reaches the wrapper below.+ let billingProvider: BillingProvider = "stripe";try {- return await createBillingServiceFromContext(ctx).getCustomerPortalUrl(- input.orgId,- );+ const resolved = await resolveBillingService(ctx, input.orgId);+ billingProvider = resolved.billingProvider;+ return await resolved.service.getCustomerPortalUrl(input.orgId);} catch (error) {logger.error("cloudBilling.getStripeCustomerPortalUrl:error", {orgId: input.orgId,+ billingProvider,error,});if (error instanceof TRPCError) {@@ -266,7 +298,7 @@ export const cloudBillingRouter = createTRPCRouter({}throw new TRPCError({code: "INTERNAL_SERVER_ERROR",- message: `Stripe error: ${error instanceof Error ? error.message : "Unknown Stripe error"}`,+ message: billingErrorMessage(billingProvider, error),cause: error as Error,});}@@ -300,18 +332,19 @@ export const cloudBillingRouter = createTRPCRouter({return { invoices: [], hasMore: false, cursors: {} };}+ let billingProvider: BillingProvider = "stripe";try {- return await createBillingServiceFromContext(ctx).getInvoices(- input.orgId,- {- limit: input.limit,- startingAfter: input.startingAfter,- endingBefore: input.endingBefore,- },- );+ const resolved = await resolveBillingService(ctx, input.orgId);+ billingProvider = resolved.billingProvider;+ return await resolved.service.getInvoices(input.orgId, {+ limit: input.limit,+ startingAfter: input.startingAfter,+ endingBefore: input.endingBefore,+ });} catch (error) {logger.error("cloudBilling.getInvoices:error", {orgId: input.orgId,+ billingProvider,error,});if (error instanceof TRPCError) {@@ -319,7 +352,7 @@ export const cloudBillingRouter = createTRPCRouter({}throw new TRPCError({code: "INTERNAL_SERVER_ERROR",- message: `Stripe error: ${error instanceof Error ? error.message : "Unknown Stripe error"}`,+ message: billingErrorMessage(billingProvider, error),cause: error as Error,});}@@ -352,9 +385,9 @@ export const cloudBillingRouter = createTRPCRouter({return null;}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- return await stripeBillingService.getUsage(input.orgId);+ return await service.getUsage(input.orgId);}),applyPromotionCode: protectedOrganizationProcedure.input(@@ -384,9 +417,9 @@ export const cloudBillingRouter = createTRPCRouter({});}- const stripeBillingService = createBillingServiceFromContext(ctx);+ const { service } = await resolveBillingService(ctx, input.orgId);- const result = await stripeBillingService.applyPromotionCode(+ const result = await service.applyPromotionCode(input.orgId,input.code,input.opId,diff --git a/web/src/ee/features/billing/server/resolveBillingService.ts b/web/src/ee/features/billing/server/resolveBillingService.tsnew file mode 100644index 0000000000..55215403f2--- /dev/null+++ b/web/src/ee/features/billing/server/resolveBillingService.ts@@ -0,0 +1,97 @@+import { TRPCError } from "@trpc/server";++import { env } from "@/src/env.mjs";+import { type OrgAuthedContext } from "@/src/server/api/trpc";+import {+ type BillingProvider,+ getBillingProvider,+ parseDbOrg,+} from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";++import { getChbApiClient } from "./chb/chbApiClient";+import { ChbBillingService } from "./chb/chbBillingService";+import { createBillingServiceFromContext } from "./stripe/stripeBillingService";++export type CloudBillingService =+ | ReturnType<typeof createBillingServiceFromContext>+ | ChbBillingService;++/**+ * Provider-dispatching billing service factory.+ *+ * Resolves the org's billing provider via the shared `getBillingProvider`+ * and returns the matching service — the untouched Stripe `BillingService`+ * for Stripe orgs, `ChbBillingService` for CHB orgs. The ten+ * `cloudBillingRouter` procedures keep their names, inputs, and output+ * shapes, so the tRPC contract does not change.+ *+ * Fail-closed guard: when the CHB cutoff is set but the CHB REST env is+ * incomplete, cutoff-routed orgs (no CHB state yet) fall back to Stripe —+ * never a half-configured CHB flow. Orgs already carrying CHB state cannot be+ * served by Stripe and error instead.+ *+ * This dispatch is also the structural interlock that keeps Stripe checkout+ * unreachable for any org holding a `cloudConfig.clickhouse` block: such+ * orgs always resolve to the CHB service.+ */+export const resolveBillingService = async (+ ctx: OrgAuthedContext,+ orgId: string,+): Promise<{+ billingProvider: BillingProvider;+ service: CloudBillingService;+}> => {+ const org = await ctx.prisma.organization.findUnique({+ where: { id: orgId },+ });+ if (!org) {+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Organization not found",+ });+ }+ const parsedOrg = parseDbOrg(org);+ // The cutoff is injected rather than read inside the resolver: the shared+ // module is exported from the client-safe barrel, so web passes the value from+ // its own validated env schema.+ const cutoff = env.LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE;+ const billingProvider = getBillingProvider(parsedOrg, { cutoff });++ if (billingProvider === "clickhouse") {+ // Shared process-wide, so every billing request reuses one Auth0 token+ // cache rather than minting a token per request.+ const client = getChbApiClient();+ if (!client) {+ if (parsedOrg.cloudConfig?.clickhouse?.organizationId) {+ // Sticky CHB org: Stripe cannot serve it, this is a config error+ logger.error(+ `resolveBillingService: org ${orgId} is CHB-billed but the CHB REST env is not configured`,+ );+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "ClickHouse Billing is not configured on this deployment",+ });+ }+ // Cutoff-routed org without CHB state: fail closed to Stripe+ if (cutoff) {+ logger.error(+ "resolveBillingService: LANGFUSE_CLOUD_BILLING_CHB_CUTOFF_DATE is set but the CHB REST env is incomplete — treating the cutoff as unset (fail closed to Stripe)",+ );+ }+ return {+ billingProvider: "stripe",+ service: createBillingServiceFromContext(ctx),+ };+ }+ return {+ billingProvider: "clickhouse",+ service: new ChbBillingService(client, ctx),+ };+ }++ return {+ billingProvider: "stripe",+ service: createBillingServiceFromContext(ctx),+ };+};diff --git a/web/src/ee/features/billing/server/stripe/stripeBillingService.ts b/web/src/ee/features/billing/server/stripe/stripeBillingService.tsindex cda43bedac..09970eef9b 100644--- a/web/src/ee/features/billing/server/stripe/stripeBillingService.ts+++ b/web/src/ee/features/billing/server/stripe/stripeBillingService.ts@@ -616,9 +616,18 @@ class BillingService {** @param orgId Organization id* @param stripeProductId Stripe Product id for the subscription plan+ * @param _opId Unused here, and deliberately so: Stripe checkout session+ * creation sends no idempotency key today and this keeps that unchanged. The+ * parameter exists only so `cloudBillingRouter` can forward `opId` across the+ * provider union, where the ClickHouse Billing path does key its request on+ * it.* @returns Redirect URL to Stripe Checkout*/- async createCheckoutSession(orgId: string, stripeProductId: string) {+ async createCheckoutSession(+ orgId: string,+ stripeProductId: string,+ _opId?: string,+ ) {return await instrumentAsync({ name: "stripe.checkout.create", spanKind: SpanKind.CLIENT },async (span) => {diff --git a/web/src/features/organizations/server/organizationRouter.ts b/web/src/features/organizations/server/organizationRouter.tsindex 590b708520..adf9e7e1d2 100644--- a/web/src/features/organizations/server/organizationRouter.ts+++ b/web/src/features/organizations/server/organizationRouter.ts@@ -16,7 +16,7 @@ import {getLastTraceTimestampsByProjects,redis,} from "@langfuse/shared/src/server";-import { createBillingServiceFromContext } from "@/src/ee/features/billing/server/stripe/stripeBillingService";+import { resolveBillingService } from "@/src/ee/features/billing/server/resolveBillingService";import { isCloudBillingEnabled } from "@/src/ee/features/billing/utils/isCloudBilling";import { shouldAutoEnableV4 } from "@/src/features/events/lib/v4Rollout";import { buildAdminOrgContext } from "@/src/features/organizations/server/adminOrgContext";@@ -397,17 +397,17 @@ export const organizationsRouter = createTRPCRouter({});}- // Attempt to cancel Stripe subscription immediately (Cloud only) before deleting org+ // Attempt to cancel the billing subscription immediately (Cloud only) before deleting orgif (isCloudBillingEnabled()) {try {- const stripeBillingService = createBillingServiceFromContext(ctx);- await stripeBillingService.cancelImmediatelyAndInvoice(input.orgId);+ const { service } = await resolveBillingService(ctx, input.orgId);+ await service.cancelImmediatelyAndInvoice(input.orgId);} catch (e) {// If billing cancellation fails for reasons other than no subscription, abort deletionthrow new TRPCError({code: "INTERNAL_SERVER_ERROR",message:- "Failed to cancel Stripe subscription prior to organization deletion",+ "Failed to cancel billing subscription prior to organization deletion",cause: e as Error,});}