πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
replay limits (#1023)
Goldflagc0a531e9a82f
diff --git a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx b/client/src/app/[site]/replay/components/EnableSessionReplay.tsxindex f6e43d78a..e84707721 100644--- a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx+++ b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx@@ -8,6 +8,7 @@ import { updateSiteConfig } from "../../../../api/admin/endpoints";import { useGetSite } from "../../../../api/admin/hooks/useSites";import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";import { Button } from "../../../../components/ui/button";+import { planIncludesReplay } from "../../../../lib/subscription/planUtils";import { useStripeSubscription } from "../../../../lib/subscription/useStripeSubscription";import { IS_CLOUD } from "../../../../lib/const";@@ -18,7 +19,7 @@ export function EnableSessionReplay() {const { data: siteMetadata, isLoading, refetch } = useGetSite(siteId);const { data: subscription } = useStripeSubscription();- const canEnableReplay = !IS_CLOUD || (!!subscription?.planName.includes("pro") && !(subscription?.isTrial && (subscription?.eventLimit ?? 0) >= 500_000));+ const canEnableReplay = !IS_CLOUD || planIncludesReplay(subscription);if (isLoading || siteMetadata?.sessionReplay || !canEnableReplay) return null;@@ -32,7 +33,9 @@ export function EnableSessionReplay() {</AlertTitle><AlertDescription className="text-sm text-neutral-700/80 dark:text-neutral-300/80"><div className="mb-2">- {t("Session replay will make the analytics script")} <b>{t("8x larger")}</b> {t("and the client will send significantly more and larger payloads.")} <b>{t("Only enable this if you will actually use it.")}</b>+ {t("Session replay will make the analytics script")} <b>{t("8x larger")}</b>{" "}+ {t("and the client will send significantly more and larger payloads.")}{" "}+ <b>{t("Only enable this if you will actually use it.")}</b></div><Buttonsize="sm"diff --git a/client/src/components/SiteSettings/TrackingTab.tsx b/client/src/components/SiteSettings/TrackingTab.tsxindex e14a9fff7..188292131 100644--- a/client/src/components/SiteSettings/TrackingTab.tsx+++ b/client/src/components/SiteSettings/TrackingTab.tsx@@ -9,6 +9,7 @@ import { Switch } from "@/components/ui/switch";import { updateSiteConfig, SiteResponse } from "@/api/admin/endpoints";import { useGetSitesFromOrg } from "@/api/admin/hooks/useSites";+import { planIncludesReplay } from "@/lib/subscription/planUtils";import { useStripeSubscription } from "@/lib/subscription/useStripeSubscription";import { Badge } from "@/components/ui/badge";import { IS_CLOUD } from "@/lib/const";@@ -80,10 +81,7 @@ export function TrackingTab({ siteMetadata, disabled = false }: TrackingTabPropsconst { data: subscription, isLoading: isSubscriptionLoading } = useStripeSubscription();- const sessionReplayDisabled =- (!subscription?.planName.includes("pro") ||- (!!subscription?.isTrial && (subscription?.eventLimit ?? 0) >= 500_000)) &&- IS_CLOUD;+ const sessionReplayDisabled = !planIncludesReplay(subscription) && IS_CLOUD;const standardFeaturesDisabled =!subscription?.planName.includes("custom") &&@@ -93,7 +91,10 @@ export function TrackingTab({ siteMetadata, disabled = false }: TrackingTabPropsIS_CLOUD;const analyticsToggles: ToggleConfig[] = [- ...(!isMobileSite && !subscription?.planName?.startsWith("appsumo") && !isSubscriptionLoading+ // Hide the replay toggle for AppSumo tiers without replays (1-3); tiers 4-6 include them+ ...(!isMobileSite &&+ !isSubscriptionLoading &&+ (!subscription?.planName?.startsWith("appsumo") || planIncludesReplay(subscription))? [{id: "sessionReplay",diff --git a/client/src/lib/subscription/planUtils.tsx b/client/src/lib/subscription/planUtils.tsxindex e8cef019e..30961d6ed 100644--- a/client/src/lib/subscription/planUtils.tsx+++ b/client/src/lib/subscription/planUtils.tsx@@ -41,6 +41,19 @@ export function findPriceForTier(return selectedPlan;}+// Whether a plan includes session replay: Pro plans (excluding large trials),+// AppSumo tiers 4-6, and custom (enterprise) plans. Mirrors the server-side+// subscriptionIncludesReplay rule.+export function planIncludesReplay(+ subscription: { planName: string; isTrial?: boolean; eventLimit?: number } | null | undefined+): boolean {+ if (!subscription) return false;+ if (subscription.planName === "custom") return true;+ if (/^appsumo-[456]$/.test(subscription.planName)) return true;+ const isLargeTrial = !!subscription.isTrial && (subscription.eventLimit ?? 0) >= 500_000;+ return subscription.planName.includes("pro") && !isLargeTrial;+}+// Format event tier for displayexport function formatEventTier(tier: number | string): string {if (typeof tier === "string") {diff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.tsindex b9e56ba61..4a701df2e 100644--- a/server/src/api/sessionReplay/recordSessionReplay.ts+++ b/server/src/api/sessionReplay/recordSessionReplay.ts@@ -54,11 +54,11 @@ export async function recordSessionReplay(return reply.status(200).send("Site over monthly limit, event not tracked");}- // Check if the site's plan includes session replay (e.g. it may have been- // enabled before a downgrade from Pro)+ // Check if the site can record replays: the plan may not include them (e.g. enabled+ // before a downgrade from Pro) or the monthly replay quota may be exhaustedif (usageService.isSiteWithoutReplay(Number(siteId))) {- logger.info(`[SessionReplay] Skipping event for site ${siteId} - plan does not include session replay`);- return reply.status(200).send({ success: true, message: "Session replay not included in plan" });+ logger.info(`[SessionReplay] Skipping event for site ${siteId} - replay not available for plan or quota`);+ return reply.status(200).send({ success: true, message: "Session replay not available for plan or quota" });}const body = recordSessionReplaySchema.parse(request.body) as RecordSessionReplayRequest;diff --git a/server/src/lib/const.ts b/server/src/lib/const.tsindex 1dbdb5628..b2785f2e4 100644--- a/server/src/lib/const.ts+++ b/server/src/lib/const.ts@@ -30,13 +30,23 @@ export const STANDARD_API_RATE_LIMIT = 20; // 20 req/minexport const PRO_API_RATE_LIMIT = 200; // 200 req/minexport const APPSUMO_SITE_LIMITS: Record<string, number | null> = {- "1": 3, "2": 10, "3": 25, "4": 50, "5": 100, "6": null,+ "1": 3,+ "2": 10,+ "3": 25,+ "4": 50,+ "5": 100,+ "6": null,};export const APPSUMO_MEMBER_LIMITS: Record<string, number | null> = {- "1": 1, "2": 3, "3": 10, "4": 25, "5": 50, "6": null,+ "1": 1,+ "2": 3,+ "3": 10,+ "4": 25,+ "5": 50,+ "6": null,};-// AppSumo tier limits (lifetime plans with standard features, no replays)+// AppSumo tier limits (lifetime plans with standard features)export const APPSUMO_TIER_LIMITS = {"1": 20_000,"2": 100_000,@@ -46,6 +56,16 @@ export const APPSUMO_TIER_LIMITS = {"6": 2_000_000,} as const;+// Monthly session replay limits per AppSumo tier (0 = replays not included)+export const APPSUMO_REPLAY_LIMITS: Record<string, number> = {+ "1": 0,+ "2": 0,+ "3": 0,+ "4": 500,+ "5": 1_000,+ "6": 2_000,+};+// Define a type for the plan objectsexport interface StripePlan {priceId: string;diff --git a/server/src/lib/subscriptionUtils.ts b/server/src/lib/subscriptionUtils.tsindex 8cbbd1eda..8b6bc1aed 100644--- a/server/src/lib/subscriptionUtils.ts+++ b/server/src/lib/subscriptionUtils.ts@@ -3,7 +3,13 @@ import { DateTime } from "luxon";import Stripe from "stripe";import { db } from "../db/postgres/postgres.js";import { organization } from "../db/postgres/schema.js";-import { APPSUMO_TIER_LIMITS, DEFAULT_EVENT_LIMIT, getStripePrices, StripePlan } from "./const.js";+import {+ APPSUMO_REPLAY_LIMITS,+ APPSUMO_TIER_LIMITS,+ DEFAULT_EVENT_LIMIT,+ getStripePrices,+ StripePlan,+} from "./const.js";import { stripe } from "./stripe.js";import { logger } from "./logger/logger.js";@@ -11,6 +17,7 @@ export interface AppSumoSubscriptionInfo {source: "appsumo";tier: string;eventLimit: number;+ replayLimit: number;periodStart: string;planName: string;status: "active";@@ -24,6 +31,7 @@ export interface StripeSubscriptionInfo {priceId: string;planName: string;eventLimit: number;+ replayLimit: number;periodStart: string;currentPeriodEnd: Date;status: string;@@ -97,6 +105,7 @@ export async function getAppSumoSubscription(organizationId: string): Promise<Apsource: "appsumo",tier,eventLimit,+ replayLimit: APPSUMO_REPLAY_LIMITS[tier] ?? 0,periodStart: getStartOfMonth(),planName: `appsumo-${tier}`,status: "active",@@ -139,7 +148,7 @@ export async function getOverrideSubscription(organizationId: string): Promise<Osource: "override",planName: org.planOverride,eventLimit,- replayLimit: 0, // AppSumo doesn't include replays+ replayLimit: APPSUMO_REPLAY_LIMITS[tier] ?? 0,periodStart: getStartOfMonth(),status: "active",interval: "lifetime",@@ -387,6 +396,7 @@ function buildStripeSubscriptionInfo(subscription: Stripe.Subscription): StripeSpriceId,planName: "Unknown Plan",eventLimit: 0,+ replayLimit: 0,periodStart: getStartOfMonth(),currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),status: subscription.status,@@ -411,6 +421,7 @@ function buildStripeSubscriptionInfo(subscription: Stripe.Subscription): StripeSpriceId,planName: planDetails.name,eventLimit: planDetails.limits.events,+ replayLimit: planDetails.limits.replays,periodStart,currentPeriodEnd: new Date(subscriptionItem.current_period_end * 1000),status: subscription.status,@@ -531,11 +542,12 @@ export async function getBestSubscriptionFromStripeSub(/*** Whether a subscription's plan includes session replay.*- * Replays are a Pro feature (see pricing page / PRO_FEATURES). This mirrors the- * client-side gate in EnableSessionReplay/TrackingTab, including the exclusion of- * large (>=500k event) trials. The per-plan `limits.replays` numbers in const.ts are- * a volume quota, not an entitlement β basic/standard plans carry them but do not- * include the feature.+ * Replays are a Pro feature (see pricing page / PRO_FEATURES), plus AppSumo tiers+ * with a nonzero replay limit (4-6). This mirrors the client-side gate in+ * EnableSessionReplay/TrackingTab, including the exclusion of large (>=500k event)+ * trials. For Stripe plans the `limits.replays` numbers in const.ts are a volume+ * quota, not an entitlement β basic/standard plans carry them but do not include+ * the feature.*/export function subscriptionIncludesReplay(subscription: SubscriptionInfo): boolean {switch (subscription.source) {@@ -543,17 +555,40 @@ export function subscriptionIncludesReplay(subscription: SubscriptionInfo): bool// Bespoke enterprise plans include everything in Proreturn true;case "override":- return subscription.planName.includes("pro");+ // AppSumo tier overrides carry the tier's replay entitlement;+ // Stripe-plan overrides follow the same pro-only rule as real Stripe plans+ return subscription.planName.startsWith("appsumo")+ ? subscription.replayLimit > 0+ : subscription.planName.includes("pro");case "stripe": {const isLargeTrial = subscription.status === "trialing" && subscription.eventLimit >= 500_000;return subscription.planName.includes("pro") && !isLargeTrial;}case "appsumo":+ return subscription.replayLimit > 0;case "free":return false;}}+/**+ * Monthly session replay quota for a subscription. Only meaningful when+ * subscriptionIncludesReplay is true; 0 otherwise.+ */+export function getReplayLimit(subscription: SubscriptionInfo): number {+ switch (subscription.source) {+ case "custom":+ // Bespoke enterprise plans have no replay cap+ return Infinity;+ case "stripe":+ case "override":+ case "appsumo":+ return subscription.replayLimit;+ case "free":+ return 0;+ }+}+function freeSubscription(): FreeSubscriptionInfo {return {source: "free",diff --git a/server/src/services/usageService.ts b/server/src/services/usageService.tsindex a479b91f3..45ee594e7 100644--- a/server/src/services/usageService.ts+++ b/server/src/services/usageService.ts@@ -12,6 +12,7 @@ import { createServiceLogger } from "../lib/logger/logger.js";import {getAllStripeSubscriptionsByCustomer,getBestSubscriptionFromStripeSub,+ getReplayLimit,stripeSubscriptionInfoFromSnapshot,subscriptionIncludesReplay,SubscriptionInfo,@@ -21,7 +22,8 @@ type UsageUpdateCallback = () => void;class UsageService {private sitesOverLimit = new Set<number>();- // Sites whose organization's plan does not include session replay. Empty until the+ // Sites that should not record session replays right now: their organization's plan+ // doesn't include replays, or its monthly replay quota is exhausted. Empty until the// usage cron runs (and always empty when self-hosted), so enforcement fails open.private sitesWithoutReplay = new Set<number>();private usageCheckTask: cron.ScheduledTask | null = null;@@ -220,6 +222,45 @@ class UsageService {}}+ /**+ * Gets monthly session replay counts for all sites in a single query (for current month).+ * The metadata table is a ReplacingMergeTree keyed by (site_id, session_id), so uniq+ * dedupes the multiple rows written per session before merges run.+ * Returns a map of site_id -> replay count; empty on failure so quota enforcement fails open.+ */+ private async getAllSiteReplayCounts(): Promise<Map<number, number>> {+ try {+ const periodStart = this.getStartOfMonth();++ const result = await clickhouse.query({+ query: `+ SELECT+ site_id,+ uniq(session_id) as count+ FROM session_replay_metadata+ WHERE start_time >= toDate({periodStart:String})+ GROUP BY site_id+ `,+ format: "JSONEachRow",+ query_params: {+ periodStart: periodStart,+ },+ });++ const rows = await processResults<{ site_id: number; count: string }>(result);++ const replayCountMap = new Map<number, number>();+ for (const row of rows) {+ replayCountMap.set(row.site_id, parseInt(String(row.count), 10));+ }++ return replayCountMap;+ } catch (error) {+ this.logger.error(error as Error, "Error querying ClickHouse for replay counts");+ return new Map();+ }+ }+/*** Updates monthly event usage for all organizations*/@@ -242,15 +283,19 @@ class UsageService {// Step 1: Get all sites with their organization IDsconst allSites = await this.getAllSites();- // Step 2: Get event counts for all sites in a single query (current month)- const eventCountMap = await this.getAllSiteEventCounts();+ // Step 2: Get event and replay counts for all sites (current month, one query each)+ const [eventCountMap, replayCountMap] = await Promise.all([+ this.getAllSiteEventCounts(),+ this.getAllSiteReplayCounts(),+ ]);- // Step 3: Build a map of organizationId -> { siteIds, eventCount }- const orgDataMap = new Map<string, { siteIds: number[]; eventCount: number }>();+ // Step 3: Build a map of organizationId -> { siteIds, eventCount, replayCount }+ const orgDataMap = new Map<string, { siteIds: number[]; eventCount: number; replayCount: number }>();for (const site of allSites) {- const orgData = orgDataMap.get(site.organizationId) || { siteIds: [], eventCount: 0 };+ const orgData = orgDataMap.get(site.organizationId) || { siteIds: [], eventCount: 0, replayCount: 0 };orgData.siteIds.push(site.siteId);orgData.eventCount += eventCountMap.get(site.siteId) || 0;+ orgData.replayCount += replayCountMap.get(site.siteId) || 0;orgDataMap.set(site.organizationId, orgData);}@@ -285,7 +330,9 @@ class UsageService {const subscription = await this.getOrganizationSubscriptionInfo(orgData, stripeSubscriptions);const eventLimit = subscription.eventLimit;const isOverLimit = eventCount > eventLimit;- const includesReplay = subscriptionIncludesReplay(subscription);++ const replayCount = orgStats?.replayCount || 0;+ const replayBlocked = !subscriptionIncludesReplay(subscription) || replayCount >= getReplayLimit(subscription);let sendApproaching = false;if (!alreadyNotifiedApproaching && !isOverLimit && Number.isFinite(eventLimit) && daysRemaining >= 2) {@@ -362,13 +409,14 @@ class UsageService {}}- // Track sites whose plan doesn't include session replay so ingest/config- // endpoints can stop recording for them (e.g. after a downgrade from Pro)+ // Track sites that shouldn't record session replays β plan doesn't include+ // them (e.g. after a downgrade from Pro) or the monthly quota is exhausted β+ // so ingest/config endpoints can stop recording for themfor (const siteId of siteIds) {- if (includesReplay) {- this.sitesWithoutReplay.delete(siteId);- } else {+ if (replayBlocked) {this.sitesWithoutReplay.add(siteId);+ } else {+ this.sitesWithoutReplay.delete(siteId);}}