:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(heatmaps): render screenshots on Browserless behind a flag (#60780)
Fernando Gomes4af4450a36c5
diff --git a/.env.example b/.env.exampleindex c697e2a10cf6..69c5e107b9fa 100644--- a/.env.example+++ b/.env.example@@ -33,3 +33,11 @@ ELEVENLABS_API_KEY=# ELEVENLABS_STT_MODEL_ID=scribe_v1# ELEVENLABS_VOICE_ID=21m00Tcm4TlvDq8ikWAM# ELEVENLABS_TTS_MODEL_ID=eleven_turbo_v2_5++HEATMAP_BROWSERLESS_URL=+HEATMAP_BROWSERLESS_TOKEN=+# HEATMAP_BROWSERLESS_TIMEOUT_MS=180000+# HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000+# HEATMAP_BROWSERLESS_BLOCK_ADS=false+# HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS=true+# In prod, also enable the "heatmap-browserless-cloud" feature flag to ramp rollout (DEBUG bypasses it).diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e24148e4700a..3b7e1038c774 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4479,7 +4479,7 @@ snapshots:scenes-app-data-pipelines-event-filtering--build-filter-from-scratch--light:hash: v1.k794b7964.f105335dd0a0a1d35dfb8f64bdeaa899ab3fcc2e9270b756971e8e9994fed7f9.0CcuVu8fn4Q5znDCFtt9YU7jqC5G9TQIneWamQaTiGcscenes-app-data-pipelines-event-filtering--deep-nested-tree--dark:- hash: v1.k794b7964.6fc0e1db4f51a831da4beb697a704c135542325b74de3dacdd84407ba0becc94.ywtC0KoCU_guvC94nGN_S3uvrPGHqnpCvaz7cJ0ylOI+ hash: v1.k794b7964.4befd3c924faa500b517c71037908f64c622b011220cec6f80ee9ac50107b071.p0MZfjGNbH-9JLdM_jJ_Dy3ToVXPxDG80ATisgoY6L0scenes-app-data-pipelines-event-filtering--deep-nested-tree--light:hash: v1.k794b7964.5bde36ae570efab7508c99591bd39dae56a7bbf3511760e4114ea066e5faca62.JWrN6DgRZUASJYK7k5zFKPjOTsxTYyzSBSGuuQE46hYscenes-app-data-pipelines-event-filtering--disabled-with-conditions--dark:@@ -4875,7 +4875,7 @@ snapshots:scenes-app-insights-funnels--funnel-left-to-right-breakdown-edit--light:hash: v1.k794b7964.414326f685dca45885b93d728ae8a75c7d8b600af35d76c9512a74a27e453006.IyZ8qHUwOv6qsBYvdUR1ZsK1Md_GNFCftDGvNZj78BQscenes-app-insights-funnels--funnel-left-to-right-edit--dark:- hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.xupnP9sdcp25xPBOMzrhSHwtRpKPLKHaqLDBncapvQA+ hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.gaL7vRk-pWoOUkiPi-NGCd1W72x-M5l9jk5Qu-UcjwIscenes-app-insights-funnels--funnel-left-to-right-edit--light:hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.3gc3UBg-8GVo4HkNBH7UrogK2q1uh9pXPDjTdYGT8ncscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--medium--dark:@@ -4887,7 +4887,7 @@ snapshots:scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--superwide--light:hash: v1.k794b7964.c95c5a49f7a20b7fcb1041dd26c73ee87c9a906cb229247a44fd4633bbdc9173.StrJ2VBA5acLqvnsiO2CS_o6qadxeaeO6ST8lxf5UdIscenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:- hash: v1.k794b7964.c47bdb853ef9b6becfb675e2ca0bdbdb0c1b4385cf2442d50dd92752d90f7906.URrKOLP9uUjbKWcui2yOA7hm_JsXsbkAlOcWJshoQrI+ hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.O7SwG4Drfr3z02hcLNC1LsLsGWddouhybBp4xZaUE-Ascenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.KSiw8WpvjWXIDh87ExL4cPnopVJlTXvzU8N8ruh6Hi8scenes-app-insights-funnels--funnel-time-to-convert--dark:diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.tsindex 6c2588806ce3..c463351b1916 100644--- a/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/heatmapLogic.ts@@ -177,9 +177,12 @@ export const heatmapLogic = kea<heatmapLogicType>([pollScreenshotStatus: async ({ id, width }, breakpoint) => {let attempts = 0actions.setGeneratingScreenshot(true)- const maxAttempts = 60+ // Multi-width renders open one Browserless session per width and can take a few minutes,+ // so poll for up to 5 minutes before giving up (the backend marks failures sooner).+ const pollIntervalMs = 2000+ const maxAttempts = (5 * 60 * 1000) / pollIntervalMswhile (attempts < maxAttempts) {- await breakpoint(2000)+ await breakpoint(pollIntervalMs)try {const contentResponse = await api.heatmapScreenshots.getContent(id)if (contentResponse.success) {@@ -218,7 +221,7 @@ export const heatmapLogic = kea<heatmapLogicType>([if (attempts >= maxAttempts) {actions.setGeneratingScreenshot(false)- actions.setScreenshotError('Screenshot generation timed out')+ actions.setScreenshotError('Screenshot is still generating — refresh to check, or try fewer widths.')}},regenerateScreenshot: async () => {diff --git a/posthog/settings/integrations.py b/posthog/settings/integrations.pyindex 47e366facbe7..d2aa0a76dcf9 100644--- a/posthog/settings/integrations.py+++ b/posthog/settings/integrations.py@@ -120,3 +120,13 @@ PANDADOC_API_KEY = get_from_env("PANDADOC_API_KEY", "")PANDADOC_WEBHOOK_SECRET = get_from_env("PANDADOC_WEBHOOK_SECRET", "")PANDADOC_BAA_TEMPLATE_ID = get_from_env("PANDADOC_BAA_TEMPLATE_ID", "")PANDADOC_DPA_TEMPLATE_ID = get_from_env("PANDADOC_DPA_TEMPLATE_ID", "")++HEATMAP_BROWSERLESS_URL = get_from_env("HEATMAP_BROWSERLESS_URL", "")+HEATMAP_BROWSERLESS_TOKEN = get_from_env("HEATMAP_BROWSERLESS_TOKEN", "")+# Browserless /screenshot session cap (ms); must stay under the plan's max-timeout.+HEATMAP_BROWSERLESS_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_TIMEOUT_MS", 180000, type_cast=int)+HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS = get_from_env("HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS", 30000, type_cast=int)+HEATMAP_BROWSERLESS_BLOCK_ADS = get_from_env("HEATMAP_BROWSERLESS_BLOCK_ADS", False, type_cast=str_to_bool)+HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS = get_from_env(+ "HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS", True, type_cast=str_to_bool+)diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex 411f6e2f5334..676f363d2959 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -37,7 +37,7 @@ from posthog.rate_limit import (from posthog.security.url_validation import is_url_allowedfrom posthog.utils import relative_date_parse_with_delta_mapping-from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS+from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS, MAX_TARGET_WIDTHSfrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmapfrom products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot@@ -649,7 +649,14 @@ _URL_PATTERN_CHARS = set("*+?^${}()|[]\\")class SavedHeatmapRequestSerializer(serializers.ModelSerializer):widths = serializers.ListField(- child=serializers.IntegerField(min_value=100, max_value=3000), required=False, allow_empty=False+ child=serializers.IntegerField(min_value=100, max_value=3000),+ required=False,+ allow_empty=False,+ max_length=MAX_TARGET_WIDTHS,+ help_text=(+ "Viewport widths (px, 100-3000) to render the heatmap screenshot at — one render per width. "+ f"Defaults to {DEFAULT_TARGET_WIDTHS} when omitted. At most {MAX_TARGET_WIDTHS} widths."+ ),)def validate_url(self, value: str) -> str:diff --git a/products/web_analytics/backend/api/heatmaps_utils.py b/products/web_analytics/backend/api/heatmaps_utils.pyindex 7a185c87c1f8..1505834d3768 100644--- a/products/web_analytics/backend/api/heatmaps_utils.py+++ b/products/web_analytics/backend/api/heatmaps_utils.py@@ -1 +1,4 @@DEFAULT_TARGET_WIDTHS = [320, 375, 425, 768, 1024, 1440, 1920]+# Each width is one screenshot render (one Browserless session on the cloud path), so cap how many a+# single heatmap can fan out to.+MAX_TARGET_WIDTHS = 16diff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.pyindex 81b58d51a93e..4df19b87415d 100644--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py@@ -1,26 +1,56 @@import os+import re+import time+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit+from django.conf import settings++import requestsimport structlogimport posthoganalytics-from celery import shared_task+from celery import Task, shared_task+from celery.exceptions import SoftTimeLimitExceededfrom playwright.sync_api import (+ Browser,Page,+ Playwright,ProxySettings,TimeoutError as PlaywrightTimeoutError,sync_playwright,)from posthog.exceptions_capture import capture_exception+from posthog.ph_client import ph_scoped_capturefrom posthog.security.url_validation import is_url_allowed, should_block_urlfrom posthog.tasks.utils import CeleryQueue-from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS+from products.web_analytics.backend.api.heatmaps_utils import DEFAULT_TARGET_WIDTHS, MAX_TARGET_WIDTHSfrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmaplogger = structlog.get_logger(__name__)TMP_DIR = "/tmp"+HEATMAP_BROWSERLESS_FLAG = "heatmap-browserless-cloud"++# Reclaim a hung worker rather than letting a stuck render hold an EXPORTS slot for the full retry budget.+HEATMAP_SCREENSHOT_SOFT_TIME_LIMIT = 600 # seconds+HEATMAP_SCREENSHOT_TIME_LIMIT = HEATMAP_SCREENSHOT_SOFT_TIME_LIMIT + 30+# Reject implausibly large Browserless responses before they reach worker memory / Postgres.+HEATMAP_SCREENSHOT_MAX_BYTES = 20 * 1024 * 1024+++class BrowserlessError(Exception):+ """Base class for Browserless /screenshot failures."""+++class BrowserlessTransientError(BrowserlessError):+ """A failure that may succeed on retry (5xx, timeout, empty/blank render)."""+++class BrowserlessPermanentError(BrowserlessError):+ """A failure that will not be fixed by retrying (4xx, misconfiguration, oversized output)."""+def _dismiss_cookie_banners(page: Page) -> None:# Try to click obvious accept/allow buttons (generic + Cookiebot)@@ -164,15 +194,73 @@ def _scroll_page(page: Page) -> None:pass+def _capture_mode_usage(+ screenshot: SavedHeatmap,+ use_browserless: bool,+ *,+ success: bool,+ width_count: int | None = None,+ duration_seconds: float | None = None,+ error_type: str | None = None,+) -> None:+ # ph_scoped_capture (not posthoganalytics.capture) — events from Celery tasks are otherwise+ # silently lost; no-ops off PostHog Cloud. Telemetry must never fail the task, so swallow errors.+ team = screenshot.team+ try:+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=str(team.uuid),+ event="heatmap screenshot generated",+ properties={+ "mode": "browserless" if use_browserless else "local",+ "success": success,+ "width_count": width_count,+ "duration_seconds": duration_seconds,+ "error_type": error_type,+ "team_id": team.id,+ "screenshot_id": str(screenshot.id),+ },+ groups={"organization": str(team.organization_id), "project": str(team.id)},+ )+ except Exception:+ logger.warning("heatmap_screenshot.usage_capture_failed", screenshot_id=screenshot.id, exc_info=True)+++def _record_failure(screenshot: SavedHeatmap, use_browserless: bool, e: Exception) -> None:+ screenshot.status = SavedHeatmap.Status.FAILED+ screenshot.exception = str(e)+ screenshot.save(update_fields=["status", "exception"])++ _capture_mode_usage(screenshot, use_browserless, success=False, error_type=type(e).__name__)++ logger.exception(+ "heatmap_screenshot.failed",+ screenshot_id=screenshot.id,+ team_id=screenshot.team_id,+ url=screenshot.url,+ exception=str(e),+ exc_info=True,+ )++ capture_exception(+ e,+ additional_properties={+ "celery_task": "heatmap_screenshot",+ "team_id": screenshot.team_id,+ "screenshot_id": screenshot.id,+ },+ )++@shared_task(+ bind=True,ignore_result=True,queue=CeleryQueue.EXPORTS.value,- autoretry_for=(Exception,),- retry_backoff=2,- retry_backoff_max=60,max_retries=3,+ soft_time_limit=HEATMAP_SCREENSHOT_SOFT_TIME_LIMIT,+ time_limit=HEATMAP_SCREENSHOT_TIME_LIMIT,)-def generate_heatmap_screenshot(screenshot_id: str) -> None:+def generate_heatmap_screenshot(self: Task, screenshot_id: str) -> None:try:screenshot = SavedHeatmap.objects.select_related("team", "created_by").get(id=screenshot_id)except SavedHeatmap.DoesNotExist:@@ -183,6 +271,7 @@ def generate_heatmap_screenshot(screenshot_id: str) -> None:posthoganalytics.tag("team_id", screenshot.team_id)posthoganalytics.tag("screenshot_id", screenshot.id)+ use_browserless = Falsetry:ok, err = is_url_allowed(screenshot.url)if not ok:@@ -198,130 +287,320 @@ def generate_heatmap_screenshot(screenshot_id: str) -> None:)return- _generate_screenshots(screenshot)+ use_browserless = _use_browserless_for_screenshot(screenshot)+ posthoganalytics.tag("use_browserless", use_browserless)++ started_at = time.monotonic()+ width_count = _generate_screenshots(screenshot, use_browserless)+ duration_seconds = round(time.monotonic() - started_at, 2)screenshot.status = SavedHeatmap.Status.COMPLETEDscreenshot.save()+ _capture_mode_usage(+ screenshot,+ use_browserless,+ success=True,+ width_count=width_count,+ duration_seconds=duration_seconds,+ )+logger.info("heatmap_screenshot.completed",screenshot_id=screenshot.id,team_id=screenshot.team_id,url=screenshot.url,+ mode="browserless" if use_browserless else "local",+ duration_seconds=duration_seconds,)+ except (BrowserlessPermanentError, SoftTimeLimitExceeded) as e:+ # Won't succeed on retry (bad request / config / oversized output / timed out) — fail now.+ _record_failure(screenshot, use_browserless, e)+ raiseexcept Exception as e:- screenshot.status = SavedHeatmap.Status.FAILED- screenshot.exception = str(e)- screenshot.save(update_fields=["status", "exception"])-- logger.exception(- "heatmap_screenshot.failed",+ # Transient cloud failure or a local render error: retry with backoff, but only record+ # FAILED + emit the failure event once retries are exhausted, so a blip doesn't flap the+ # status or inflate the failure metric.+ if self.request.called_directly or self.request.retries >= self.max_retries:+ _record_failure(screenshot, use_browserless, e)+ raise+ logger.warning(+ "heatmap_screenshot.retrying",screenshot_id=screenshot.id,- team_id=screenshot.team_id,- url=screenshot.url,+ retries=self.request.retries,exception=str(e),- exc_info=True,)+ raise self.retry(exc=e, countdown=min(2 ** (self.request.retries + 1), 60))+++def _build_browserless_screenshot_url() -> str | None:+ # Read settings at call time (not import) so override_settings works in tests.+ # Strip whitespace + any inline comment a bash-sourced .env left in the value.+ base_url = settings.HEATMAP_BROWSERLESS_URL.split("#", 1)[0].strip()+ parsed = urlsplit(base_url) if base_url else None+ host = parsed.hostname if parsed else None+ if not parsed or not host:+ return None+ # Preserve a non-default port so self-hosted / local Browserless (e.g. wss://host:3000/chromium) works.+ netloc = f"{host}:{parsed.port}" if parsed.port else host+ params = {"token": settings.HEATMAP_BROWSERLESS_TOKEN, "timeout": str(settings.HEATMAP_BROWSERLESS_TIMEOUT_MS)}+ return f"https://{netloc}/screenshot?{urlencode(params)}"+++def _redact_browserless_url(url: str) -> str:+ # Strip userinfo and the token value so the URL is safe to put in errors/logs.+ parts = urlsplit(url)+ safe_query = urlencode(+ [(k, "REDACTED" if k == "token" else v) for k, v in parse_qsl(parts.query, keep_blank_values=True)]+ )+ netloc = parts.hostname or ""+ if parts.port:+ netloc = f"{netloc}:{parts.port}"+ return urlunsplit(parts._replace(netloc=netloc, query=safe_query))+++_TOKEN_QS_RE = re.compile(r"(token=)[^&\s\"']+")+++def _sanitize_browserless_error(message: str) -> str:+ # Scrub the token (raw value + any `token=...` in an echoed URL) while keeping the error reason.+ token = settings.HEATMAP_BROWSERLESS_TOKEN+ if token:+ message = message.replace(token, "REDACTED")+ return _TOKEN_QS_RE.sub(r"\1REDACTED", message)+++def _is_permanent_status(status: int) -> bool:+ # 4xx won't be fixed by retrying, except request-timeout / rate-limit which are worth a retry.+ return 400 <= status < 500 and status not in (408, 429)+++def _validate_screenshot_response(response: requests.Response, endpoint_url: str) -> bytes:+ # A 200 from Browserless isn't necessarily a usable JPEG: bestAttempt can return a blank/partial+ # render, and errors can come back as a 200 with a JSON/text body. Reject anything that isn't a+ # sane image before it's stored and served as image/jpeg.+ content = response.content+ if len(content) > HEATMAP_SCREENSHOT_MAX_BYTES:+ raise BrowserlessPermanentError(+ f"Browserless screenshot too large ({len(content)} bytes) for {_redact_browserless_url(endpoint_url)}"+ )+ if not content:+ raise BrowserlessTransientError(+ f"Browserless returned an empty body for {_redact_browserless_url(endpoint_url)}"+ )+ content_type = response.headers.get("content-type", "")+ if not content_type.startswith("image/"):+ raise BrowserlessTransientError(+ f"Browserless returned non-image content-type {content_type!r} for "+ f"{_redact_browserless_url(endpoint_url)}: {_sanitize_browserless_error(response.text[:200])}"+ )+ if not content.startswith(b"\xff\xd8\xff"): # JPEG start-of-image marker+ raise BrowserlessTransientError(+ f"Browserless returned a non-JPEG body for {_redact_browserless_url(endpoint_url)}"+ )+ return content+++def _browserless_screenshot(endpoint_url: str, page_url: str, width: int) -> bytes:+ # Render one width via the Browserless /screenshot REST API. viewport.width sets the captured width;+ # scrollPage triggers lazy-loaded content and blockConsentModals dismisses cookie banners server-side.+ body: dict[str, object] = {+ "url": page_url,+ "options": {"fullPage": True, "type": "jpeg", "quality": 70},+ "viewport": {+ "width": int(width),+ "height": 800,+ "deviceScaleFactor": 1,+ "isMobile": width < 500,+ "hasTouch": width < 500,+ },+ "gotoOptions": {"waitUntil": "networkidle2", "timeout": 30_000},+ "scrollPage": True,+ "blockConsentModals": settings.HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS,+ "bestAttempt": True,+ }+ if settings.HEATMAP_BROWSERLESS_BLOCK_ADS:+ body["blockAds"] = True- capture_exception(- e,- additional_properties={- "celery_task": "heatmap_screenshot",- "team_id": screenshot.team_id,- "screenshot_id": screenshot.id,- },+ timeout = (+ settings.HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS / 1000,+ settings.HEATMAP_BROWSERLESS_TIMEOUT_MS / 1000 + 30,+ )+ try:+ response = requests.post(endpoint_url, json=body, timeout=timeout)+ except Exception as e:+ # The endpoint URL carries the token; scrub it before it reaches logs / SavedHeatmap.exception.+ raise BrowserlessTransientError(+ f"Browserless screenshot request failed for {_redact_browserless_url(endpoint_url)}: "+ f"{_sanitize_browserless_error(str(e))}"+ ) from None+ if response.status_code != 200:+ message = (+ f"Browserless screenshot failed ({response.status_code}) for "+ f"{_redact_browserless_url(endpoint_url)}: {_sanitize_browserless_error(response.text[:500])}"+ )+ if _is_permanent_status(response.status_code):+ raise BrowserlessPermanentError(message)+ raise BrowserlessTransientError(message)+ return _validate_screenshot_response(response, endpoint_url)+++def _use_browserless_for_screenshot(screenshot: SavedHeatmap) -> bool:+ # Gated per team in prod; in local dev (DEBUG) the env var alone is the switch. Fail closed to+ # the local launch on any flag-eval error.+ if not settings.HEATMAP_BROWSERLESS_URL:+ return False+ if settings.DEBUG:+ return True++ team = screenshot.team+ org_id = str(team.organization_id)+ project_id = str(team.id)+ try:+ return bool(+ posthoganalytics.feature_enabled(+ HEATMAP_BROWSERLESS_FLAG,+ project_id, # bucket per team so a whole team flips together, not per user+ groups={"organization": org_id, "project": project_id},+ group_properties={"organization": {"id": org_id}, "project": {"id": project_id}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,)- raise+ )+ except Exception:+ return False+++def _launch_local_browser(p: Playwright) -> Browser:+ launch_args = [+ "--force-device-scale-factor=1",+ "--disable-dev-shm-usage",+ "--no-sandbox",+ "--disable-gpu",+ ]+ proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")+ proxy_config = ProxySettings(server=proxy_url) if proxy_url else None+ return p.chromium.launch(+ headless=True, # TIP: for debugging, set to False+ args=launch_args,+ proxy=proxy_config,+ )+++def _render_width(browser: Browser, width: int, url: str) -> bytes:+ ctx = browser.new_context(+ viewport={"width": int(width), "height": 800},+ device_scale_factor=1, # keep 1:1 CSS px -> bitmap px+ is_mobile=(width < 500), # trigger mobile layout on small widths+ has_touch=(width < 500), # some sites key on touch capability+ user_agent=(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) "+ "AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/115.0.0.0 "+ "Mobile/15E148 Safari/604.1"+ if width < 500+ else None+ ),+ )+ try:+ page = ctx.new_page()+ # The local --no-sandbox Chromium is on our network, so per-request SSRF interception stays.+ _block_internal_requests(page)++ # Start navigation and try to wait for DOM ready, but only up to 5s+ dom_ready = True+ try:+ page.goto(url, wait_until="domcontentloaded", timeout=5_000)+ except PlaywrightTimeoutError:+ dom_ready = False+ # Navigation may still continue in the background; we just won't block on it.++ # Small settle: if DOM was ready, give JS time to render (SPAs). Otherwise, brief paint time.+ page.wait_for_timeout(3000 if dom_ready else 1000)++ # Try to clear overlays/cookie banners if present+ _dismiss_cookie_banners(page)+ page.wait_for_timeout(500)+ # Scroll to bottom and back to top to trigger lazy-loaded content+ _scroll_page(page)-def _generate_screenshots(screenshot: SavedHeatmap) -> None:- # Determine target widths+ # Hide scrollbars so they don't appear in the exported image+ try:+ page.add_style_tag(+ content="*::-webkit-scrollbar { display: none !important; } html, body { scrollbar-width: none !important; }"+ )+ except Exception:+ pass++ return page.screenshot(full_page=True, type="jpeg", quality=70)+ finally:+ ctx.close()+++def _close_browser_quietly(browser: Browser) -> None:+ # Closing an already-torn-down browser can itself raise; swallow so it can't mask the render error.+ try:+ browser.close()+ except Exception:+ logger.warning("heatmap_screenshot.browser_close_failed", exc_info=True)+++def _resolve_widths(screenshot: SavedHeatmap) -> list[int]:target_widths = screenshot.target_widths or DEFAULT_TARGET_WIDTHS- # Deduplicate and keep order- seen = set()+ seen: set[int] = set()widths: list[int] = []for w in target_widths:if isinstance(w, int) and 100 <= w <= 3000 and w not in seen:widths.append(w)seen.add(w)-if not widths:- widths = [1024]-- # Collect screenshots in-memory first to avoid Django ORM calls inside Playwright's async context+ return [1024]+ # Backstop the per-width render fan-out for heatmaps created before the serializer cap (or via the+ # regenerate path), so one heatmap can't spawn an unbounded number of Browserless sessions.+ return widths[:MAX_TARGET_WIDTHS]+++def _persist_snapshot(screenshot: SavedHeatmap, width: int, image_data: bytes) -> None:+ snapshot, _ = HeatmapSnapshot.objects.get_or_create(heatmap=screenshot, width=width)+ snapshot.content = image_data+ snapshot.content_location = None+ snapshot.save()+++def _generate_screenshots(screenshot: SavedHeatmap, use_browserless: bool) -> int:+ widths = _resolve_widths(screenshot)+ if use_browserless:+ return _generate_browserless_screenshots(screenshot, widths)+ return _generate_local_screenshots(screenshot, widths)+++def _generate_browserless_screenshots(screenshot: SavedHeatmap, widths: list[int]) -> int:+ # REST /screenshot: one request per width (viewport.width sets the captured width). Persist and+ # release each image as it arrives so worker memory holds one full-page JPEG at a time.+ endpoint_url = _build_browserless_screenshot_url()+ if not endpoint_url:+ raise BrowserlessPermanentError("Browserless screenshot URL is not configured")+ count = 0+ for w in widths:+ image_data = _browserless_screenshot(endpoint_url, screenshot.url, w)+ _persist_snapshot(screenshot, w, image_data)+ count += 1+ return count+++def _generate_local_screenshots(screenshot: SavedHeatmap, widths: list[int]) -> int:+ # Local Chromium: one launch renders every width. ORM must run after the Playwright block — calls+ # inside `with sync_playwright()` raise SynchronousOnlyOperation (its event-loop context).snapshot_bytes: list[tuple[int, bytes]] = []with sync_playwright() as p:- launch_args = [- "--force-device-scale-factor=1",- "--disable-dev-shm-usage",- "--no-sandbox",- "--disable-gpu",- ]- proxy_url = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")- proxy_config = ProxySettings(server=proxy_url) if proxy_url else None-- browser = p.chromium.launch(- headless=True, # TIP: for debugging, set to False- args=launch_args,- proxy=proxy_config,- )+ browser = _launch_local_browser(p)try:for w in widths:- ctx = browser.new_context(- viewport={"width": int(w), "height": 800},- device_scale_factor=1, # keep 1:1 CSS px -> bitmap px- is_mobile=(w < 500), # trigger mobile layout on small widths- has_touch=(w < 500), # some sites key on touch capability- user_agent=(- "Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) "- "AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/115.0.0.0 "- "Mobile/15E148 Safari/604.1"- if w < 500- else None- ),- )- page = ctx.new_page()- _block_internal_requests(page)-- # Start navigation and try to wait for DOM ready, but only up to 5s- dom_ready = True- try:- page.goto(screenshot.url, wait_until="domcontentloaded", timeout=5_000)- except PlaywrightTimeoutError:- dom_ready = False- # Navigation may still continue in the background; we just won't block on it.-- # Small settle: if DOM was ready, give JS time to render (SPAs). Otherwise, brief paint time.- page.wait_for_timeout(3000 if dom_ready else 1000)-- # Try to clear overlays/cookie banners if present- _dismiss_cookie_banners(page)- page.wait_for_timeout(500)-- # Scroll to bottom and back to top to trigger lazy-loaded content- _scroll_page(page)-- # Hide scrollbars so they don't appear in the exported image- try:- page.add_style_tag(- content="*::-webkit-scrollbar { display: none !important; } html, body { scrollbar-width: none !important; }"- )- except Exception:- pass-- # Take full-page screenshot without resizing viewport- # (resizing viewport causes elements with vh units to expand)- image_data: bytes = page.screenshot(full_page=True, type="jpeg", quality=70)- snapshot_bytes.append((w, image_data))-- ctx.close()+ snapshot_bytes.append((w, _render_width(browser, w, screenshot.url)))finally:- browser.close()+ _close_browser_quietly(browser)- # Persist captured images with ORM after Playwright context (back in pure sync context)for w, image_data in snapshot_bytes:- snapshot, _ = HeatmapSnapshot.objects.get_or_create(heatmap=screenshot, width=w)- snapshot.content = image_data- snapshot.content_location = None- snapshot.save()+ _persist_snapshot(screenshot, w, image_data)+ return len(snapshot_bytes)diff --git a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.pyindex 104574df77a9..3ad0fa560db3 100644--- a/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py+++ b/products/web_analytics/backend/tasks/test/test_heatmap_screenshot.py@@ -1,11 +1,75 @@+from contextlib import contextmanager+from typing import Any+from posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.test import SimpleTestCase, override_settings++from parameterized import parameterized++from products.web_analytics.backend.api.heatmaps_utils import MAX_TARGET_WIDTHSfrom products.web_analytics.backend.models import HeatmapSnapshot, SavedHeatmap-from products.web_analytics.backend.tasks.heatmap_screenshot import generate_heatmap_screenshot+from products.web_analytics.backend.tasks.heatmap_screenshot import (+ HEATMAP_BROWSERLESS_FLAG,+ BrowserlessError,+ BrowserlessPermanentError,+ _browserless_screenshot,+ _build_browserless_screenshot_url,+ _redact_browserless_url,+ _resolve_widths,+ _sanitize_browserless_error,+ _use_browserless_for_screenshot,+ generate_heatmap_screenshot,+)++BROWSERLESS_SETTINGS = {+ "HEATMAP_BROWSERLESS_URL": "wss://production-sfo.browserless.io/chromium",+ "HEATMAP_BROWSERLESS_TOKEN": "secret-token",+ "HEATMAP_BROWSERLESS_TIMEOUT_MS": 180000,+ "HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS": 30000,+}+++def _jpeg(suffix: bytes = b"") -> bytes:+ # Minimal bytes that pass the JPEG start-of-image magic-byte check.+ return b"\xff\xd8\xff" + suffix+++def _make_response(+ content: bytes | None = None,+ status: int = 200,+ text: str = "",+ content_type: str = "image/jpeg",+) -> MagicMock:+ resp = MagicMock()+ resp.status_code = status+ resp.content = _jpeg() if content is None else content+ resp.text = text+ resp.headers = {"content-type": content_type}+ return respclass TestHeatmapScreenshotTask(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Stub ph_scoped_capture so tests don't spin up a real PostHog client, and record the events.+ self.captured_events: list[dict] = []++ @contextmanager+ def _fake_scoped_capture():+ def _capture(**kwargs: object) -> None:+ self.captured_events.append(kwargs)++ yield _capture++ patcher = patch(+ "products.web_analytics.backend.tasks.heatmap_screenshot.ph_scoped_capture",+ _fake_scoped_capture,+ )+ patcher.start()+ self.addCleanup(patcher.stop)+@patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")def test_generates_multiple_width_snapshots_and_marks_completed(self, mock_sync_playwright: MagicMock) -> None:# Arrange Playwright mocks@@ -47,9 +111,20 @@ class TestHeatmapScreenshotTask(APIBaseTest):assert snaps[1].content == b"jpeg768"assert snaps[2].content == b"jpeg1024"- # Ensure we cleaned up the browser+ # One launch renders every width locally+ mock_p.chromium.launch.assert_called_once()mock_browser.close.assert_called_once()+ # A mode-usage event is captured for the local path+ assert len(self.captured_events) == 1+ event = self.captured_events[0]+ assert event["event"] == "heatmap screenshot generated"+ assert event["properties"]["mode"] == "local"+ assert event["properties"]["success"] is True+ assert event["properties"]["width_count"] == 3+ assert event["properties"]["duration_seconds"] is not None+ assert event["groups"]["project"] == str(self.team.id)+@patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")def test_failure_marks_failed_and_records_exception(self, mock_sync_playwright: MagicMock) -> None:# Arrange: make playwright crash when entering context@@ -73,3 +148,411 @@ class TestHeatmapScreenshotTask(APIBaseTest):heatmap.refresh_from_db()assert heatmap.status == SavedHeatmap.Status.FAILEDassert "boom" in (heatmap.exception or "")++ # A failure mode-usage event is captured+ assert self.captured_events[-1]["properties"]["success"] is False+ assert self.captured_events[-1]["properties"]["mode"] == "local"+ assert self.captured_events[-1]["properties"]["error_type"] == "RuntimeError"++ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")+ def test_local_path_installs_request_interception(self, mock_sync_playwright: MagicMock) -> None:+ mock_p = MagicMock()+ mock_browser = MagicMock()+ mock_context = MagicMock()+ mock_page = MagicMock()+ mock_sync_playwright.return_value.__enter__.return_value = mock_p+ mock_p.chromium.launch.return_value = mock_browser+ mock_browser.new_context.return_value = mock_context+ mock_context.new_page.return_value = mock_page+ mock_page.evaluate.return_value = 1200+ mock_page.screenshot.side_effect = [b"jpeg1024"]++ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[1024],+ status=SavedHeatmap.Status.PROCESSING,+ )++ generate_heatmap_screenshot(heatmap.id)++ mock_p.chromium.launch.assert_called_once()+ mock_page.route.assert_called()++ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")+ def test_snapshots_persisted_only_after_browser_closed(self, mock_sync_playwright: MagicMock) -> None:+ # Regression: Django ORM calls inside `with sync_playwright()` run in its greenlet/event-loop+ # context and raise SynchronousOnlyOperation, so persistence must happen after browser.close().+ # Mocks can't reproduce that async context, so assert the call ordering instead.+ order: list[str] = []+ mock_p = MagicMock()+ mock_browser = MagicMock()+ mock_context = MagicMock()+ mock_page = MagicMock()+ mock_sync_playwright.return_value.__enter__.return_value = mock_p+ mock_p.chromium.launch.return_value = mock_browser+ mock_browser.new_context.return_value = mock_context+ mock_context.new_page.return_value = mock_page+ mock_page.evaluate.return_value = 1200+ mock_page.screenshot.side_effect = [b"jpeg320", b"jpeg768"]+ mock_browser.close.side_effect = lambda: order.append("browser_close")++ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[320, 768],+ status=SavedHeatmap.Status.PROCESSING,+ )++ real_get_or_create = HeatmapSnapshot.objects.get_or_create++ def recording_get_or_create(*args: Any, **kwargs: Any) -> Any:+ order.append("persist")+ return real_get_or_create(*args, **kwargs)++ with patch.object(HeatmapSnapshot.objects, "get_or_create", side_effect=recording_get_or_create):+ generate_heatmap_screenshot(heatmap.id)++ # The browser must be closed before any snapshot is persisted+ assert order, "expected snapshots to be persisted"+ assert order[0] == "browser_close", f"snapshots persisted inside the Playwright context: {order}"++ @override_settings(**BROWSERLESS_SETTINGS)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot._use_browserless_for_screenshot", return_value=True)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_cloud_path_uses_rest_screenshot_api(+ self, mock_requests: MagicMock, mock_sync_playwright: MagicMock, mock_use_browserless: MagicMock+ ) -> None:+ mock_requests.post.return_value = _make_response(_jpeg(b"1024"))++ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[1024],+ status=SavedHeatmap.Status.PROCESSING,+ )++ generate_heatmap_screenshot(heatmap.id)++ # The REST path never touches local Playwright+ mock_sync_playwright.assert_not_called()++ mock_requests.post.assert_called_once()+ endpoint = mock_requests.post.call_args.args[0]+ assert "/screenshot" in endpoint+ assert "token=secret-token" in endpoint+ body = mock_requests.post.call_args.kwargs["json"]+ assert body["url"] == "https://example.com"+ assert body["viewport"]["width"] == 1024++ heatmap.refresh_from_db()+ assert heatmap.status == SavedHeatmap.Status.COMPLETED+ snaps = {s.width: s.content for s in HeatmapSnapshot.objects.filter(heatmap=heatmap)}+ assert snaps == {1024: _jpeg(b"1024")}++ # The mode-usage event reflects the browserless path+ assert self.captured_events[-1]["properties"]["mode"] == "browserless"+ assert self.captured_events[-1]["properties"]["success"] is True++ @override_settings(**BROWSERLESS_SETTINGS)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot._use_browserless_for_screenshot", return_value=True)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_cloud_path_one_request_per_width(+ self, mock_requests: MagicMock, mock_sync_playwright: MagicMock, mock_use_browserless: MagicMock+ ) -> None:+ mock_requests.post.side_effect = [+ _make_response(_jpeg(b"320")),+ _make_response(_jpeg(b"768")),+ _make_response(_jpeg(b"1024")),+ ]++ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[320, 768, 1024],+ status=SavedHeatmap.Status.PROCESSING,+ )++ generate_heatmap_screenshot(heatmap.id)++ # One /screenshot request per width, each carrying its own viewport width+ assert mock_requests.post.call_count == 3+ mock_sync_playwright.assert_not_called()+ bodies = [call.kwargs["json"] for call in mock_requests.post.call_args_list]+ assert [body["viewport"]["width"] for body in bodies] == [320, 768, 1024]+ # Narrow widths render as a touch/mobile viewport+ assert bodies[0]["viewport"]["isMobile"] is True+ assert bodies[2]["viewport"]["isMobile"] is False++ heatmap.refresh_from_db()+ assert heatmap.status == SavedHeatmap.Status.COMPLETED+ # Each width's bytes land on the matching row (the width→image mapping must be preserved)+ snaps = {s.width: s.content for s in HeatmapSnapshot.objects.filter(heatmap=heatmap)}+ assert snaps == {320: _jpeg(b"320"), 768: _jpeg(b"768"), 1024: _jpeg(b"1024")}++ @override_settings(**BROWSERLESS_SETTINGS)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot._use_browserless_for_screenshot", return_value=True)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_cloud_path_failure_on_later_width_marks_failed_and_keeps_earlier_widths(+ self, mock_requests: MagicMock, mock_use_browserless: MagicMock+ ) -> None:+ # First width succeeds, second width's request fails+ mock_requests.post.side_effect = [_make_response(_jpeg(b"320")), Exception("boom on second width")]++ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[320, 768],+ status=SavedHeatmap.Status.PROCESSING,+ )++ with self.assertRaises(BrowserlessError):+ generate_heatmap_screenshot(heatmap.id)++ heatmap.refresh_from_db()+ assert heatmap.status == SavedHeatmap.Status.FAILED+ # The cloud path persists each width as it renders, so the earlier success is kept and the+ # failed width is simply absent (bounded worker memory > all-or-nothing persistence).+ snaps = {s.width: s.content for s in HeatmapSnapshot.objects.filter(heatmap=heatmap)}+ assert snaps == {320: _jpeg(b"320")}+ assert self.captured_events[-1]["properties"]["mode"] == "browserless"+ assert self.captured_events[-1]["properties"]["success"] is False++ @override_settings(**BROWSERLESS_SETTINGS)+ @patch(+ "products.web_analytics.backend.tasks.heatmap_screenshot._use_browserless_for_screenshot",+ return_value=False,+ )+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.sync_playwright")+ def test_flag_off_uses_local_even_when_url_set(+ self, mock_sync_playwright: MagicMock, mock_use_browserless: MagicMock+ ) -> None:+ mock_p = MagicMock()+ mock_browser = MagicMock()+ mock_context = MagicMock()+ mock_page = MagicMock()+ mock_sync_playwright.return_value.__enter__.return_value = mock_p+ mock_p.chromium.launch.return_value = mock_browser+ mock_browser.new_context.return_value = mock_context+ mock_context.new_page.return_value = mock_page+ mock_page.evaluate.return_value = 1200+ mock_page.screenshot.side_effect = [b"jpeg1024"]++ heatmap = self._make_heatmap()+ generate_heatmap_screenshot(heatmap.id)++ # Browserless configured (URL set) but flag off → local launch, and interception installed+ mock_p.chromium.launch.assert_called_once()+ mock_page.route.assert_called()++ def _make_heatmap(self) -> SavedHeatmap:+ return SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=[1024],+ status=SavedHeatmap.Status.PROCESSING,+ )++ @override_settings(HEATMAP_BROWSERLESS_URL="")+ def test_use_browserless_false_when_url_unset(self) -> None:+ assert _use_browserless_for_screenshot(self._make_heatmap()) is False++ def test_resolve_widths_caps_render_fan_out(self) -> None:+ # A heatmap created before the serializer cap (or via regenerate) can carry an unbounded+ # widths list; the worker must still bound the per-width render fan-out.+ heatmap = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com",+ created_by=self.user,+ target_widths=list(range(100, 100 + 5 * (MAX_TARGET_WIDTHS + 50), 5)), # well over the cap+ status=SavedHeatmap.Status.PROCESSING,+ )+ widths = _resolve_widths(heatmap)+ assert len(widths) == MAX_TARGET_WIDTHS++ @override_settings(HEATMAP_BROWSERLESS_URL="wss://host/chromium", DEBUG=True)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.posthoganalytics.feature_enabled")+ def test_use_browserless_true_in_debug_without_consulting_flag(self, mock_feature_enabled: MagicMock) -> None:+ assert _use_browserless_for_screenshot(self._make_heatmap()) is True+ mock_feature_enabled.assert_not_called()++ @override_settings(HEATMAP_BROWSERLESS_URL="wss://host/chromium", DEBUG=False)+ @patch(+ "products.web_analytics.backend.tasks.heatmap_screenshot.posthoganalytics.feature_enabled",+ return_value=True,+ )+ def test_use_browserless_consults_flag_with_team_groups_in_prod(self, mock_feature_enabled: MagicMock) -> None:+ assert _use_browserless_for_screenshot(self._make_heatmap()) is True+ mock_feature_enabled.assert_called_once()+ args, kwargs = mock_feature_enabled.call_args+ assert args[0] == HEATMAP_BROWSERLESS_FLAG+ # The distinct_id (2nd positional) is the per-team bucketing key — a whole team flips together+ assert args[1] == str(self.team.id)+ assert kwargs["groups"]["project"] == str(self.team.id)+ assert kwargs["groups"]["organization"] == str(self.team.organization_id)+ assert kwargs["send_feature_flag_events"] is False+ assert kwargs["only_evaluate_locally"] is False++ @override_settings(HEATMAP_BROWSERLESS_URL="wss://host/chromium", DEBUG=False)+ @patch(+ "products.web_analytics.backend.tasks.heatmap_screenshot.posthoganalytics.feature_enabled",+ side_effect=Exception("flags service down"),+ )+ def test_use_browserless_fails_closed_on_flag_error(self, mock_feature_enabled: MagicMock) -> None:+ assert _use_browserless_for_screenshot(self._make_heatmap()) is False+++# Pure-function tests for the Browserless REST helper — no DB, so they run on SimpleTestCase.+class TestBrowserlessScreenshotRequest(SimpleTestCase):+ @parameterized.expand([("desktop", 1024, False), ("mobile", 320, True)])+ @override_settings(+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,+ HEATMAP_BROWSERLESS_BLOCK_ADS=False,+ HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS=True,+ )+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_posts_full_page_body_with_viewport_width(+ self, _name: str, width: int, is_mobile: bool, mock_requests: MagicMock+ ) -> None:+ mock_requests.post.return_value = _make_response(_jpeg(b"img"))++ content = _browserless_screenshot("https://host/screenshot?token=t", "https://example.com", width)++ assert content == _jpeg(b"img")+ body = mock_requests.post.call_args.kwargs["json"]+ assert body["url"] == "https://example.com"+ assert body["viewport"]["width"] == width+ assert body["viewport"]["isMobile"] is is_mobile+ assert body["options"]["fullPage"] is True+ assert body["options"]["type"] == "jpeg"+ assert body["scrollPage"] is True+ assert body["blockConsentModals"] is True+ assert "blockAds" not in body+ # (connect, read) timeout tuple wired from settings+ assert mock_requests.post.call_args.kwargs["timeout"] == (30.0, 210.0)++ @override_settings(+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,+ HEATMAP_BROWSERLESS_BLOCK_ADS=True,+ )+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_block_ads_added_to_body_when_enabled(self, mock_requests: MagicMock) -> None:+ mock_requests.post.return_value = _make_response()+ _browserless_screenshot("https://host/screenshot?token=t", "https://example.com", 1024)+ assert mock_requests.post.call_args.kwargs["json"]["blockAds"] is True++ @parameterized.expand(["non_200", "request_raises"])+ @override_settings(+ HEATMAP_BROWSERLESS_TOKEN="secret-token",+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000,+ )+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_failure_redacts_token(self, mode: str, mock_requests: MagicMock) -> None:+ endpoint = "https://host/screenshot?token=secret-token&timeout=180000"+ if mode == "non_200":+ mock_requests.post.return_value = _make_response(b"", status=401, text="Unauthorized token=secret-token")+ else:+ mock_requests.post.side_effect = Exception("ECONNREFUSED https://host/screenshot?token=secret-token")++ with self.assertRaises(BrowserlessError) as ctx:+ _browserless_screenshot(endpoint, "https://example.com", 1024)++ message = str(ctx.exception)+ # The token must never reach the (API-readable) persisted exception+ assert "secret-token" not in message+ assert "REDACTED" in message++ @parameterized.expand(+ [+ ("empty_body", b"", "image/jpeg"),+ ("non_image_content_type", b'{"error":"nope"}', "application/json"),+ ("non_jpeg_body", b"\x89PNG\r\n", "image/png"),+ ]+ )+ @override_settings(HEATMAP_BROWSERLESS_TIMEOUT_MS=180000, HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_rejects_invalid_200_body(+ self, _name: str, content: bytes, content_type: str, mock_requests: MagicMock+ ) -> None:+ # A 200 that isn't a real JPEG must not be stored and served as image/jpeg.+ mock_requests.post.return_value = _make_response(content, content_type=content_type)+ with self.assertRaises(BrowserlessError):+ _browserless_screenshot("https://host/screenshot?token=t", "https://example.com", 1024)++ @override_settings(HEATMAP_BROWSERLESS_TIMEOUT_MS=180000, HEATMAP_BROWSERLESS_CONNECT_TIMEOUT_MS=30000)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.HEATMAP_SCREENSHOT_MAX_BYTES", 8)+ @patch("products.web_analytics.backend.tasks.heatmap_screenshot.requests")+ def test_rejects_oversized_body_as_permanent(self, mock_requests: MagicMock) -> None:+ mock_requests.post.return_value = _make_response(_jpeg(b"way over the cap"))+ with self.assertRaises(BrowserlessPermanentError):+ _browserless_screenshot("https://host/screenshot?token=t", "https://example.com", 1024)+++# Pure-function tests for the Browserless URL helpers — no DB, so they run on SimpleTestCase.+class TestBrowserlessUrlHelpers(SimpleTestCase):+ @override_settings(HEATMAP_BROWSERLESS_URL="")+ def test_build_screenshot_url_returns_none_when_unset(self) -> None:+ assert _build_browserless_screenshot_url() is None++ @override_settings(+ HEATMAP_BROWSERLESS_URL="wss://production-sfo.browserless.io/chromium",+ HEATMAP_BROWSERLESS_TOKEN="t",+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ )+ def test_build_screenshot_url_builds_https_endpoint(self) -> None:+ url = _build_browserless_screenshot_url()+ assert url is not None+ assert url.startswith("https://production-sfo.browserless.io/screenshot?")+ assert "token=t" in url+ assert "timeout=180000" in url++ @override_settings(+ HEATMAP_BROWSERLESS_URL="wss://localhost:3000/chromium",+ HEATMAP_BROWSERLESS_TOKEN="t",+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ )+ def test_build_screenshot_url_preserves_non_default_port(self) -> None:+ # Self-hosted / local Browserless runs on a non-443 port; dropping it would post to the wrong host.+ url = _build_browserless_screenshot_url()+ assert url is not None+ assert url.startswith("https://localhost:3000/screenshot?")++ @override_settings(+ HEATMAP_BROWSERLESS_URL="wss://production-sfo.browserless.io/chromium # region nearest your worker",+ HEATMAP_BROWSERLESS_TOKEN="t",+ HEATMAP_BROWSERLESS_TIMEOUT_MS=180000,+ )+ def test_build_screenshot_url_strips_inline_comment_and_whitespace(self) -> None:+ # A bash-sourced .env keeps the inline comment in the value; we must not let it become a fragment.+ url = _build_browserless_screenshot_url()+ assert url is not None+ assert url.startswith("https://production-sfo.browserless.io/screenshot?")+ assert "#" not in url+ assert "region" not in url++ def test_redact_browserless_url_strips_token_and_userinfo(self) -> None:+ redacted = _redact_browserless_url("https://user:pass@host:3000/screenshot?token=supersecret&timeout=1000")+ assert "supersecret" not in redacted+ assert "pass" not in redacted+ assert "token=REDACTED" in redacted+ assert "timeout=1000" in redacted++ @override_settings(HEATMAP_BROWSERLESS_TOKEN="supersecret")+ def test_sanitize_browserless_error_scrubs_token_but_keeps_reason(self) -> None:+ msg = "Unexpected server response: 401 at https://host/screenshot?token=supersecret&timeout=180000"+ sanitized = _sanitize_browserless_error(msg)+ assert "supersecret" not in sanitized+ assert "token=REDACTED" in sanitized+ # The real failure reason is preserved so the error is debuggable+ assert "401" in sanitized