Skip to content

: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.

refactor(heatmaps): extract render_page from the screenshot loop (#114213)

Jordan Mryyan44a5889ed711
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.py
index b69f4a745ce1..8ce68946d551 100644
--- a/products/web_analytics/backend/api/heatmaps_api.py
+++ b/products/web_analytics/backend/api/heatmaps_api.py
@@ -74,6 +74,7 @@ from products.web_analytics.backend.api.heatmaps_utils import (
MAX_TARGET_WIDTHS,
PREWARM_PREVIEW_WIDTH,
PREWARM_TTL,
+ capture_image_within_limits,
heatmaps_flag_enabled,
)
from products.web_analytics.backend.heatmap_preflight import BlockedBy, Framing, preflight_page
@@ -86,9 +87,6 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import (
STALE_PROCESSING_THRESHOLD = timedelta(minutes=10)
-MAX_CAPTURE_IMAGE_WIDTH = 4000
-MAX_CAPTURE_IMAGE_HEIGHT = 30000
-MAX_CAPTURE_IMAGE_PIXELS = 50_000_000
MAX_CAPTURE_TOTAL_BYTES = 60 * 1024 * 1024
HEATMAPS_COHORT_FILTER_FLAG = "heatmaps-cohort-filter"
@@ -157,11 +155,7 @@ def _reject_oversized_capture_image(image_bytes: bytes) -> None:
width, height = im.size
except Exception:
raise ValidationError(code="invalid_image", detail="Uploaded media must be a valid image")
- if (
- width > MAX_CAPTURE_IMAGE_WIDTH
- or height > MAX_CAPTURE_IMAGE_HEIGHT
- or width * height > MAX_CAPTURE_IMAGE_PIXELS
- ):
+ if not capture_image_within_limits(width, height):
raise ValidationError(code="image_too_large", detail="Screenshot dimensions are too large to process")
diff --git a/products/web_analytics/backend/api/heatmaps_utils.py b/products/web_analytics/backend/api/heatmaps_utils.py
index 9e5f34c9e9bb..e94ef2dbae43 100644
--- a/products/web_analytics/backend/api/heatmaps_utils.py
+++ b/products/web_analytics/backend/api/heatmaps_utils.py
@@ -10,6 +10,19 @@ MAX_TARGET_WIDTHS = 16
PREWARM_PREVIEW_WIDTH = 1024
PREWARM_TTL = timedelta(minutes=15)
+MAX_CAPTURE_IMAGE_WIDTH = 4000
+MAX_CAPTURE_IMAGE_HEIGHT = 30000
+MAX_CAPTURE_IMAGE_PIXELS = 50_000_000
+
+
+def capture_image_within_limits(width: int, height: int) -> bool:
+ return (
+ width <= MAX_CAPTURE_IMAGE_WIDTH
+ and height <= MAX_CAPTURE_IMAGE_HEIGHT
+ and width * height <= MAX_CAPTURE_IMAGE_PIXELS
+ )
+
+
# The Pillow formats a stored snapshot can hold: Browserless renders JPEG, and the toolbar capture
# endpoint accepts JPEG or PNG. Image.open without formats= tries every format Pillow can parse.
HEATMAP_SNAPSHOT_IMAGE_FORMATS = ("JPEG", "PNG")
diff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.py
index c0613448de10..7259cb563bc9 100644
--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py
@@ -423,6 +423,9 @@ def _browserless_screenshot(
width: int,
block_consent_modals: bool,
cookies: list[dict[str, object]] | None = None,
+ *,
+ priority: Priority = Priority.NORMAL,
+ source: str = "heatmap_screenshot",
) -> tuple[bytes, int | None]:
# 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.
@@ -457,15 +460,15 @@ def _browserless_screenshot(
width_bucket = _width_bucket(width)
started = time.monotonic()
try:
- # NORMAL, not BATCH: somebody is waiting on this render. Background consumers of the same
- # fleet ask as BATCH and are shed first, which is what leaves headroom for this call.
+ # NORMAL by default: somebody is waiting on this render. Background callers such as the daily
+ # history capture pass BATCH and are shed first, which is what leaves headroom for this call.
response = browserless_request(
"POST",
endpoint_url,
token=settings.HEATMAP_BROWSERLESS_TOKEN,
- source="heatmap_screenshot",
+ source=source,
endpoint="screenshot",
- priority=Priority.NORMAL,
+ priority=priority,
json=body,
timeout=timeout,
)
@@ -604,9 +607,6 @@ def _generate_screenshots(screenshot: SavedHeatmap) -> int:
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", cause="not_configured")
# Skip widths already rendered, so promoting a prewarm only renders the still-missing widths.
already_rendered = _rendered_widths(screenshot, widths)
pending = [w for w in widths if w not in already_rendered]
@@ -620,34 +620,51 @@ def _generate_browserless_screenshots(screenshot: SavedHeatmap, widths: list[int
)
count = 0
for w in pending:
- config = TeamHeatmapConfig.objects.filter(team_id=screenshot.team_id).first()
- secret = config.screenshot_secret if config else None
- allowed_hostnames = config.allowed_hostnames if config else []
- reason = screenshot_credential_delivery_reason(secret, screenshot.url, allowed_hostnames)
- HEATMAP_SCREENSHOT_CREDENTIAL_DELIVERY.labels(reason=reason).inc()
- cookies = heatmap_screenshot_cookies(secret, screenshot.url, allowed_hostnames)
- image_data, page_status = _browserless_screenshot(
- endpoint_url, screenshot.url, w, screenshot.block_consent_modals, cookies
- )
- if page_status is not None and not 200 <= page_status < 300:
- guidance = (
- "Screenshot cookie delivery is disabled on this installation. Contact your PostHog administrator."
- if reason == "delivery_disabled"
- else "The screenshot cookie was configured. Check the page and your bot protection rule before retrying."
- if cookies
- else "No screenshot cookie was sent. If bot protection blocks this page, ask a project admin to "
- "approve its HTTPS hostname and configure a screenshot cookie in project settings under Heatmaps."
- )
- raise PageHttpStatusError(
- f"{_host_of(screenshot.url)} returned {page_status} when we loaded the page, so the capture "
- f"is a picture of that response. {guidance}",
- cause="page_http_status",
- )
+ image_data = render_page(screenshot.team_id, screenshot.url, w, screenshot.block_consent_modals)
_persist_snapshot(screenshot, w, image_data)
count += 1
return count
+def render_page(
+ team_id: int,
+ page_url: str,
+ width: int,
+ block_consent_modals: bool,
+ *,
+ priority: Priority = Priority.NORMAL,
+ source: str = "heatmap_screenshot",
+) -> bytes:
+ endpoint_url = _build_browserless_screenshot_url()
+ if not endpoint_url:
+ raise BrowserlessPermanentError("Browserless screenshot URL is not configured", cause="not_configured")
+ config = TeamHeatmapConfig.objects.filter(team_id=team_id).first()
+ secret = config.screenshot_secret if config else None
+ allowed_hostnames = config.allowed_hostnames if config else []
+ reason = screenshot_credential_delivery_reason(secret, page_url, allowed_hostnames)
+ HEATMAP_SCREENSHOT_CREDENTIAL_DELIVERY.labels(reason=reason).inc()
+ cookies = heatmap_screenshot_cookies(secret, page_url, allowed_hostnames)
+ image_data, page_status = _browserless_screenshot(
+ endpoint_url, page_url, width, block_consent_modals, cookies, priority=priority, source=source
+ )
+ if page_status is not None and not 200 <= page_status < 300:
+ guidance = (
+ "Screenshot cookie delivery is disabled on this installation. Contact your PostHog administrator."
+ if reason == "delivery_disabled"
+ else "The screenshot cookie was configured. Check the page and your bot protection rule before retrying."
+ if cookies
+ else "No screenshot cookie was sent. If bot protection blocks this page, ask a project admin to "
+ "approve its HTTPS hostname and configure a screenshot cookie in project settings under Heatmaps."
+ )
+ raise PageHttpStatusError(
+ f"{_host_of(page_url)} returned {page_status} when we loaded the page, so the capture "
+ f"is a picture of that response. {guidance}",
+ status_code=page_status,
+ cause="page_http_status",
+ )
+ return image_data
+
+
def _host_of(url: str) -> str:
return urlsplit(url).hostname or "The page"
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshots.py b/products/web_analytics/backend/test/test_heatmap_screenshots.py
index 499efc64e414..a10e29fd15d9 100644
--- a/products/web_analytics/backend/test/test_heatmap_screenshots.py
+++ b/products/web_analytics/backend/test/test_heatmap_screenshots.py
@@ -628,7 +628,7 @@ class TestHeatmapToolbarCapture(APIBaseTest):
self.assertEqual(resp.status_code, 400)
self.assertFalse(SavedHeatmap.objects.filter(team=self.team).exists())
- @patch("products.web_analytics.backend.api.heatmaps_api.MAX_CAPTURE_IMAGE_PIXELS", 100)
+ @patch("products.web_analytics.backend.api.heatmaps_utils.MAX_CAPTURE_IMAGE_PIXELS", 100)
def test_capture_rejects_oversized_dimensions(self, _mock_task: MagicMock) -> None:
resp = self._capture()
self.assertEqual(resp.status_code, 400)