Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(cloud): push orgs as tenants to plain (#6986)

Marc Klingen1dbefb099425
diff --git a/.env.prod.example b/.env.prod.example
index c932dd210e..f8891c8724 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -251,6 +251,8 @@ OTEL_SERVICE_NAME="langfuse"
# Plain Chat
# NEXT_PUBLIC_PLAIN_APP_ID=
# PLAIN_AUTHENTICATION_SECRET=
+# PLAIN_API_KEY=
+# PLAIN_CARDS_API_TOKEN=
# Admin API
# ADMIN_API_KEY=
diff --git a/web/src/env.mjs b/web/src/env.mjs
index cb77f4f21a..329a4eb9d9 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -276,6 +276,8 @@ export const env = createEnv({
.positive()
.default(50_000),
PLAIN_AUTHENTICATION_SECRET: z.string().optional(),
+ PLAIN_API_KEY: z.string().optional(),
+ PLAIN_CARDS_API_TOKEN: z.string().optional(),
// UI customization - comma-separated list of visible product modules
LANGFUSE_UI_VISIBLE_PRODUCT_MODULES: z.string().optional(),
@@ -475,6 +477,8 @@ export const env = createEnv({
// Other
NEXT_PUBLIC_PLAIN_APP_ID: process.env.NEXT_PUBLIC_PLAIN_APP_ID,
PLAIN_AUTHENTICATION_SECRET: process.env.PLAIN_AUTHENTICATION_SECRET,
+ PLAIN_API_KEY: process.env.PLAIN_API_KEY,
+ PLAIN_CARDS_API_TOKEN: process.env.PLAIN_CARDS_API_TOKEN,
// clickhouse
CLICKHOUSE_URL: process.env.CLICKHOUSE_URL,
CLICKHOUSE_CLUSTER_NAME: process.env.CLICKHOUSE_CLUSTER_NAME,
diff --git a/web/src/features/support-chat/PlainChat.tsx b/web/src/features/support-chat/PlainChat.tsx
index 898e7dd78f..4c12fb327d 100644
--- a/web/src/features/support-chat/PlainChat.tsx
+++ b/web/src/features/support-chat/PlainChat.tsx
@@ -1,6 +1,8 @@
import { env } from "@/src/env.mjs";
+import { api } from "@/src/utils/api";
import { type Plan } from "@langfuse/shared";
-import { useEffect, useRef } from "react";
+import { useSession } from "next-auth/react";
+import { useEffect, useRef, useState } from "react";
declare global {
interface Window {
@@ -14,6 +16,16 @@ let isWidgetLoaded = false;
const PlainChat = () => {
const scriptRef = useRef<HTMLScriptElement | null>(null);
+ const updatePlainDataMut = api.plain.updatePlainData.useMutation({
+ onError: () => {}, // Don't show default error toast
+ });
+ const session = useSession();
+ const [isWidgetLoadedState, setIsWidgetLoadedState] = useState(false);
+
+ const updateIsWidgetLoaded = (value: boolean) => {
+ setIsWidgetLoadedState(value); // for use in useEffect
+ isWidgetLoaded = value; // for use in global functions
+ };
useEffect(() => {
if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return;
@@ -58,7 +70,7 @@ const PlainChat = () => {
});
// Mark widget as loaded and process queued metadata updates
- isWidgetLoaded = true;
+ updateIsWidgetLoaded(true);
for (const metadataUpdate of metadataQueue) {
try {
metadataUpdate();
@@ -84,8 +96,25 @@ const PlainChat = () => {
}
};
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ // Update Plain.com data when user is authenticated and chat is loaded
+ // Trigger not be authenticated to prevent trigger on every auth session refresh (status=loading)
+ const isNotUnauthenticated = session.status !== "unauthenticated";
+
+ useEffect(() => {
+ if (
+ isNotUnauthenticated &&
+ isWidgetLoaded &&
+ session.status === "authenticated" &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ) {
+ updatePlainDataMut.mutate();
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isNotUnauthenticated, isWidgetLoadedState]);
+
return null;
};
@@ -172,12 +201,6 @@ export const chatSetThreadDetails = (p: { orgId?: string; plan?: Plan }) => {
externalId: `cloud_${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}_org_${p.orgId}`,
},
}),
- ...(p.plan && {
- tierIdentifier: {
- externalId: p.plan,
- },
- }),
- // project_id: `cloud_${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}_project_${project?.id}`,
},
});
}
diff --git a/web/src/features/support-chat/trpc/plain.ts b/web/src/features/support-chat/trpc/plain.ts
new file mode 100644
index 0000000000..08fa0ef91c
--- /dev/null
+++ b/web/src/features/support-chat/trpc/plain.ts
@@ -0,0 +1,157 @@
+import { createTRPCRouter, protectedProcedure } from "@/src/server/api/trpc";
+import { TRPCError } from "@trpc/server";
+import { env } from "@/src/env.mjs";
+import { logger } from "@langfuse/shared/src/server";
+import { type CustomerTenantMembershipPartsFragment } from "@team-plain/typescript-sdk";
+import { PlainClient } from "@team-plain/typescript-sdk";
+
+const plainClient = env.PLAIN_API_KEY
+ ? new PlainClient({
+ apiKey: env.PLAIN_API_KEY,
+ })
+ : null;
+
+export const plainRouter = createTRPCRouter({
+ updatePlainData: protectedProcedure.mutation(async ({ ctx }) => {
+ try {
+ const { session } = ctx;
+ const user = session.user;
+ const email = user.email;
+
+ const CLOUD_REGION = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ if (!CLOUD_REGION) {
+ return;
+ }
+
+ if (!email) {
+ logger.error("User email is required for Plain.com profile update");
+ return;
+ }
+
+ if (!plainClient) {
+ logger.error("Plain.com client not configured");
+ return;
+ }
+
+ // Upsert customer in Plain.com
+ const plainCustomer = await plainClient.upsertCustomer({
+ identifier: {
+ emailAddress: email,
+ },
+ onCreate: {
+ email: {
+ email: email,
+ isVerified: true,
+ },
+ fullName: user.name ?? "",
+ },
+ onUpdate: {
+ email: {
+ email: email,
+ isVerified: true,
+ },
+ },
+ });
+ const plainCustomerId = plainCustomer.data?.customer.id;
+ if (!plainCustomerId) {
+ logger.error(
+ "Failed to upsert customer in Plain.com",
+ plainCustomer.error,
+ );
+ return;
+ }
+
+ // Upsert tenants in Plain.com
+ const tenantIdentifier = (orgId: string) =>
+ `cloud_${CLOUD_REGION}_org_${orgId}`;
+ const isTenantInRegion = (plainTenantId: string) =>
+ plainTenantId.startsWith(`cloud_${CLOUD_REGION}_org_`);
+ const tenantPromises = user.organizations.map(async (org) => {
+ await plainClient.upsertTenant({
+ identifier: {
+ externalId: tenantIdentifier(org.id),
+ },
+ name: `${CLOUD_REGION} - ${org.name}`,
+ externalId: tenantIdentifier(org.id),
+ });
+ await plainClient.updateTenantTier({
+ tenantIdentifier: {
+ externalId: tenantIdentifier(org.id),
+ },
+ tierIdentifier: {
+ externalId: org.plan,
+ },
+ });
+ });
+
+ await Promise.all(tenantPromises);
+
+ // Associate user with tenants
+ // Fetch all pages of customer tenant memberships
+ let plainCustomerTenantMemberships: CustomerTenantMembershipPartsFragment[] =
+ [];
+ let after: string | undefined = undefined;
+ const pageSize = 100;
+ while (true) {
+ const response = await plainClient.getCustomerTenantMemberships({
+ customerId: plainCustomerId,
+ first: pageSize,
+ after,
+ });
+ if (response.data?.tenantMemberships) {
+ plainCustomerTenantMemberships.push(
+ ...response.data.tenantMemberships,
+ );
+ }
+ const pageInfo = response.data?.pageInfo;
+ if (pageInfo?.hasNextPage && pageInfo.endCursor) {
+ after = pageInfo.endCursor;
+ } else {
+ break;
+ }
+ }
+ // Remove tenants from this region that are not in the user's organizations anymore
+ const tenantIdsOfUserInRegion = plainCustomerTenantMemberships
+ .map((tenant) => tenant.tenant.externalId)
+ .filter((id) => isTenantInRegion(id));
+ const tenantIdsOfUserInRegionToRemove = tenantIdsOfUserInRegion.filter(
+ (tenantId) =>
+ !user.organizations
+ .map((org) => tenantIdentifier(org.id))
+ .includes(tenantId),
+ );
+ if (tenantIdsOfUserInRegionToRemove.length > 0) {
+ await plainClient.removeCustomerFromTenants({
+ customerIdentifier: {
+ emailAddress: email,
+ },
+ tenantIdentifiers: tenantIdsOfUserInRegionToRemove.map((id) => ({
+ externalId: id,
+ })),
+ });
+ }
+ // Add user to tenants
+ const tenantIdsOfUserInRegionToAdd = user.organizations
+ .map((org) => tenantIdentifier(org.id))
+ .filter((tenantId) => !tenantIdsOfUserInRegion.includes(tenantId));
+ if (tenantIdsOfUserInRegionToAdd.length > 0) {
+ await plainClient.addCustomerToTenants({
+ customerIdentifier: {
+ emailAddress: email,
+ },
+ tenantIdentifiers: tenantIdsOfUserInRegionToAdd.map((tenantId) => ({
+ externalId: tenantId,
+ })),
+ });
+ }
+ } catch (error) {
+ logger.error("Failed to update Plain.com profiles", error);
+
+ throw new TRPCError({
+ code: "INTERNAL_SERVER_ERROR",
+ message: "Failed to update Plain.com profiles",
+ cause: error,
+ });
+ }
+ }),
+});
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index aa1b8bbadc..1aae8e306f 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -38,6 +38,7 @@ import { tableRouter } from "@/src/features/table/server/tableRouter";
import { cloudStatusRouter } from "@/src/features/cloud-status-notification/server/cloud-status-router";
import { dashboardWidgetRouter } from "./routers/dashboardWidgets";
import { TableViewPresetsRouter } from "@/src/server/api/routers/tableViewPresets";
+import { plainRouter } from "@/src/features/support-chat/trpc/plain";
/**
* This is the primary router for your server.
@@ -84,6 +85,7 @@ export const appRouter = createTRPCRouter({
cloudStatus: cloudStatusRouter,
dashboardWidgets: dashboardWidgetRouter,
TableViewPresets: TableViewPresetsRouter,
+ plain: plainRouter,
});
// export type definition of API