Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. π₯
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Nick: MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM for preview
Nicolasbb789a58a4ed
diff --git a/apps/api/src/controllers/v2/browser.ts b/apps/api/src/controllers/v2/browser.tsindex 43030ea2c..82c046726 100644--- a/apps/api/src/controllers/v2/browser.ts+++ b/apps/api/src/controllers/v2/browser.ts@@ -10,6 +10,9 @@ import {listBrowserSessions,updateBrowserSessionActivity,updateBrowserSessionStatus,+ getActiveBrowserSessionCount,+ invalidateActiveBrowserSessionCount,+ MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM,} from "../../lib/browser-sessions";import { RequestWithAuth } from "./types";@@ -181,6 +184,19 @@ export async function browserCreateController(logger.info("Creating browser session", { ttl, activityTtl });+ // 0. Enforce per-team active session limit+ const activeCount = await getActiveBrowserSessionCount(req.auth.team_id);+ if (activeCount >= MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM) {+ logger.warn("Active browser session limit reached", {+ activeCount,+ limit: MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM,+ });+ return res.status(429).json({+ success: false,+ error: `You have reached the maximum number of active browser sessions (${MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM}). Please destroy existing sessions before creating new ones.`,+ });+ }+// 1. Create a browser session via the browser servicelet svcResponse: BrowserServiceCreateResponse;try {@@ -232,6 +248,9 @@ export async function browserCreateController(});}+ // Invalidate cached count so next check reflects the new session+ invalidateActiveBrowserSessionCount(req.auth.team_id).catch(() => {});+logger.info("Browser session created", {sessionId,browserId: svcResponse.sessionId,@@ -398,6 +417,9 @@ export async function browserDeleteController(// Mark destroyed in Supabaseawait updateBrowserSessionStatus(session.id, "destroyed");+ // Invalidate cached count so next check reflects the destroyed session+ invalidateActiveBrowserSessionCount(session.team_id).catch(() => {});+logger.info("Browser session destroyed", { sessionDurationMs });return res.status(200).json({@@ -489,6 +511,9 @@ export async function browserWebhookDestroyedController(await updateBrowserSessionStatus(session.id, "destroyed");+ // Invalidate cached count so the team can create new sessions immediately+ invalidateActiveBrowserSessionCount(session.team_id).catch(() => {});+logger.info("Session marked as destroyed via webhook", { sessionId: session.id, browserId });return res.status(200).json({ ok: true });diff --git a/apps/api/src/lib/browser-sessions.ts b/apps/api/src/lib/browser-sessions.tsindex 3b54fd46b..f9b4c6706 100644--- a/apps/api/src/lib/browser-sessions.ts+++ b/apps/api/src/lib/browser-sessions.ts@@ -1,8 +1,16 @@import { supabase_service } from "../services/supabase";+import { getValue, setValue, deleteKey } from "../services/redis";import { logger as _logger } from "./logger";const logger = _logger.child({ module: "browser-sessions" });+export const MAX_ACTIVE_BROWSER_SESSIONS_PER_TEAM = 20;+const ACTIVE_COUNT_CACHE_TTL_SECONDS = 300;++function activeBrowserCountKey(teamId: string): string {+ return `browser_sessions:active_count:${teamId}`;+}+type BrowserSessionStatus = "active" | "destroyed" | "error";export interface BrowserSessionRow {@@ -136,3 +144,61 @@ export async function updateBrowserSessionStatus(logger.warn("Failed to update browser session status", { error, id });}}++// ---------------------------------------------------------------------------+// Active session count (cached)+// ---------------------------------------------------------------------------++async function countActiveBrowserSessionsFromDb(teamId: string): Promise<number> {+ const { count, error } = await supabase_service+ .from(TABLE)+ .select("*", { count: "exact", head: true })+ .eq("team_id", teamId)+ .eq("status", "active");++ if (error) {+ logger.error("Failed to count active browser sessions", { error, teamId });+ throw new Error(`Failed to count active browser sessions: ${error.message}`);+ }++ return count ?? 0;+}++/**+ * Returns the number of active browser sessions for a team.+ * Uses a Redis cache with a short TTL to avoid hitting the DB on every request.+ */+export async function getActiveBrowserSessionCount(teamId: string): Promise<number> {+ const cacheKey = activeBrowserCountKey(teamId);++ try {+ const cached = await getValue(cacheKey);+ if (cached !== null) {+ return parseInt(cached, 10);+ }+ } catch {+ // Redis down β fall through to DB+ }++ const count = await countActiveBrowserSessionsFromDb(teamId);++ try {+ await setValue(cacheKey, String(count), ACTIVE_COUNT_CACHE_TTL_SECONDS);+ } catch {+ // Redis down β non-fatal+ }++ return count;+}++/**+ * Invalidate the cached active session count for a team.+ * Call after creating or destroying a session.+ */+export async function invalidateActiveBrowserSessionCount(teamId: string): Promise<void> {+ try {+ await deleteKey(activeBrowserCountKey(teamId));+ } catch {+ // Redis down β non-fatal+ }+}