: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(egress): add a firecrawl client for outbound page scraping (#86726)
Adam Bowkerf7265c0ab5a3
diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 33ce84361eb6..ae7dcb576594 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -12,7 +12,7 @@ Three lanes, one per subpackage:This is _outbound_ egress — what PostHog sends.It is unrelated to `posthog.rate_limit`, which throttles _inbound_ DRF requests from clients.-All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`, `logodev/`), supplying a budget policy, a metric set + parser, and a transport subclass.+All three lanes are **domain-generic** and domain-free; each third-party API is an incarnation under its own subpackage (`github/`, `logodev/`, `firecrawl/`), supplying a budget policy, a metric set + parser, and a transport subclass.Adding a new outbound API is another `<domain>/` folder, not a change to the mechanisms.## Rate limiting@@ -55,6 +55,12 @@ logo.dev publishes no rate-limit numbers, so the budgets are static operator ceiEvery logo.dev call runs on a sheddable lane — the icon id is user-controlled, so nothing in this domain runs `CRITICAL`.Icon bytes are never stored server-side (logo.dev licenses that separately), so steady-state traffic is deduped only by browser caching (`posthog/cdp/services/icons.py` sets `Cache-Control`) and tracks unique (user, icon) first views per day — raise the settings if that outgrows the defaults.+Firecrawl (`firecrawl/`) meters per account and bills a credit per call, and an instance holds a single API key, so it follows the same shape: one `firecrawl` domain, one instance-wide budget under a constant scope.+Firecrawl's per-plan limits are not discoverable from the running process, so the budgets are operator ceilings on spend read from settings at acquire time: `FIRECRAWL_EGRESS_PER_MINUTE_BUDGET` (default 60) smooths a burst of concurrent callers, and `FIRECRAWL_EGRESS_HOURLY_BUDGET` (default 1,000) caps what a runaway caller can spend before anyone notices.+One scrape is one credit, so those numbers cap a bill as much as a rate; they are sized for traffic of roughly one scrape per event a person triggers, and are meant to be raised in settings as that grows.+Every Firecrawl call runs on a sheddable lane: what gets scraped is derived from user-supplied input and callers can do without the scrape, so nothing in this domain runs `CRITICAL`.+`FIRECRAWL_API_KEY` authenticates every call as a bearer token; an instance without one makes no request at all (`FirecrawlNotConfigured`).+### Priority lanesPriority (`CRITICAL` / `NORMAL` / `BATCH`) controls how sheddable a call is when the budget gets tight.@@ -104,6 +110,9 @@ Response handling — what to do on a 403/429 — stays with the caller: `raise_The model-coupled `GitHubIntegrationBase.api_request` layers the installation-token lifecycle (proactive refresh, 401 refresh-retry, rate-limit raising, per-instance `source` attribution) on top — hold an integration, call that; hold a bare token, call `github_request`.Raw `requests` calls against `api.github.com` are blocked by the `github-api-calls-go-through-egress` semgrep rule (`.semgrep/devex-rules/`), so new callers land on one of these two paths by construction.+Firecrawl callers go through `firecrawl/client.py` rather than `firecrawl_request` directly: `scrape(url, source=...)` returns a typed `FirecrawlScrape` (markdown, summary, plus the page title, description, status code and credits used) and raises `FirecrawlScrapeFailed` when Firecrawl answers with anything but a successful scrape, including the 200 responses that carry `success: false`.+Only `POST /v2/scrape` is wired up, and the client reads `FIRECRAWL_API_KEY` from settings so the transport stays token-agnostic like the others.+Slack Web API calls use `SlackWebClient` (and `SlackAsyncWebClient` where needed) from `slack/` sorequest volume, method, status, source, and workspace are recorded consistently. Slack applies Web APIlimits per method, workspace, and app, with additional special limits such as per-channel message@@ -143,10 +152,12 @@ The headers are already on the response, so it needs no request restructuring## Adding a new egress domain-Add a `<domain>/` subpackage with three small adapters (see `github/`):+Add a `<domain>/` subpackage with three small adapters (see `github/`, or `firecrawl/` for a smaller one):- `limiter.py` — register a budget with `register_policy("<domain>", provider)` and a thin gate that builds the `{domain}:{scope}:{id}` key.- `observability.py` — an observability adapter (metric set, response parser, endpoint normalizer) and the recorders.- `transport.py` — an `EgressClient` subclass filling the domain hooks (headers, gate, recorders, normalizer, budget-exhausted error), exposed as a `<domain>_request` helper.+A domain whose callers all hit the same few endpoints can add a fourth module, a typed client over the transport (see `firecrawl/client.py`), so call sites don't hand-build request bodies or re-parse the same response shape.+Keep the identity in the external API's id space, keep the subpackage free of `posthog.models` imports, and remember the limiter is non-blocking — the caller owns the back-off.diff --git a/posthog/egress/firecrawl/__init__.py b/posthog/egress/firecrawl/__init__.pynew file mode 100644index 000000000000..49e4f9f16f0d--- /dev/null+++ b/posthog/egress/firecrawl/__init__.py@@ -0,0 +1,20 @@+from posthog.egress.firecrawl.client import (+ DEFAULT_SCRAPE_FORMATS,+ FirecrawlNotConfigured,+ FirecrawlScrape,+ FirecrawlScrapeFailed,+ ScrapeFormat,+ scrape,+)+from posthog.egress.firecrawl.transport import FirecrawlEgressBudgetExhausted, firecrawl_request++__all__ = [+ "DEFAULT_SCRAPE_FORMATS",+ "FirecrawlEgressBudgetExhausted",+ "FirecrawlNotConfigured",+ "FirecrawlScrape",+ "FirecrawlScrapeFailed",+ "ScrapeFormat",+ "firecrawl_request",+ "scrape",+]diff --git a/posthog/egress/firecrawl/client.py b/posthog/egress/firecrawl/client.pynew file mode 100644index 000000000000..ca643e271217--- /dev/null+++ b/posthog/egress/firecrawl/client.py@@ -0,0 +1,132 @@+"""Typed client for the one Firecrawl endpoint PostHog calls: a single-page scrape.++Firecrawl fetches and renders a page server-side and returns the extracted formats plus page+metadata. Only ``POST /v2/scrape`` is wired up; crawl, map and search are separate products with+their own credit cost and are not exposed until something needs them.+"""++from collections.abc import Mapping, Sequence+from typing import Literal, cast++from django.conf import settings++from posthog.dataclasses import frozen+from posthog.egress.firecrawl.transport import firecrawl_request+from posthog.egress.limiter.policies import Priority++FIRECRAWL_API_BASE = "https://api.firecrawl.dev"+SCRAPE_ENDPOINT = "/v2/scrape"++# The formats we have a use for. Firecrawl offers more (branding, screenshots, JSON extraction,+# change tracking); add them here when a caller needs one, so the request body stays a checked shape.+#+# Formats are not equal in cost. Firecrawl runs an LLM pass for some of them, and the credit price+# hides it: one scrape of the same page measured 1.1s for markdown alone, 3.7s adding summary, and+# 15.6s adding branding, all billed as a single credit. Weigh a new format against the caller's+# latency budget rather than its price.+ScrapeFormat = Literal["markdown", "summary"]++DEFAULT_SCRAPE_FORMATS: tuple[ScrapeFormat, ...] = ("markdown", "summary")++# Firecrawl renders the page before answering, which takes seconds, so the read timeout is generous+# while the connect timeout stays short: a connection that will not open is never worth waiting on.+DEFAULT_SCRAPE_TIMEOUT: tuple[float, float] = (5.0, 45.0)+++class FirecrawlNotConfigured(Exception):+ """No Firecrawl API key is configured on this instance, so no call was made. Self-hosted+ deployments run without one, so callers must treat this as a normal degraded path."""+++class FirecrawlScrapeFailed(Exception):+ """Firecrawl was reached but did not return a usable scrape (HTTP error, ``success: false``,+ or a body that does not match the documented shape)."""+++@frozen+class FirecrawlScrape:+ """One scraped page. Every extracted field is optional: Firecrawl returns only the formats that+ were requested, and a page can render without a title or description."""++ url: str+ markdown: str | None = None+ summary: str | None = None+ title: str | None = None+ description: str | None = None+ status_code: int | None = None+ credits_used: int | None = None+++def _as_str(value: object) -> str | None:+ return value if isinstance(value, str) else None+++def _as_int(value: object) -> int | None:+ return value if isinstance(value, int) and not isinstance(value, bool) else None+++def _as_mapping(value: object) -> Mapping[str, object] | None:+ # An isinstance check cannot narrow the key type, but these mappings come from a parsed JSON+ # body, where every key is a string by construction.+ return cast(Mapping[str, object], value) if isinstance(value, Mapping) else None+++def scrape(+ url: str,+ *,+ source: str,+ formats: Sequence[ScrapeFormat] = DEFAULT_SCRAPE_FORMATS,+ only_main_content: bool = True,+ priority: Priority = Priority.NORMAL,+ timeout: float | tuple[float, float] = DEFAULT_SCRAPE_TIMEOUT,+) -> FirecrawlScrape:+ """Scrape one page through Firecrawl. Costs one credit per call regardless of how many formats+ are requested.++ Raises :class:`FirecrawlNotConfigured` when the instance has no API key,+ :class:`FirecrawlScrapeFailed` when Firecrawl answers with anything but a successful scrape, and+ :class:`~posthog.egress.firecrawl.transport.FirecrawlEgressBudgetExhausted` when our own egress+ budget sheds the call.+ """+ api_key = settings.FIRECRAWL_API_KEY+ if not api_key:+ raise FirecrawlNotConfigured("No FIRECRAWL_API_KEY configured")++ response = firecrawl_request(+ "POST",+ f"{FIRECRAWL_API_BASE}{SCRAPE_ENDPOINT}",+ api_key=api_key,+ source=source,+ endpoint=SCRAPE_ENDPOINT,+ priority=priority,+ timeout=timeout,+ json={"url": url, "formats": list(formats), "onlyMainContent": only_main_content},+ )++ if not response.ok:+ # The body can carry the scraped page, so keep it out of the exception that gets logged.+ raise FirecrawlScrapeFailed(f"Firecrawl scrape of {url} returned HTTP {response.status_code}")++ try:+ payload: object = response.json()+ except ValueError as exc:+ raise FirecrawlScrapeFailed(f"Firecrawl scrape of {url} returned a non-JSON body") from exc++ payload_mapping = _as_mapping(payload)+ if payload_mapping is None or payload_mapping.get("success") is not True:+ raise FirecrawlScrapeFailed(f"Firecrawl scrape of {url} was unsuccessful")++ data = _as_mapping(payload_mapping.get("data"))+ if data is None:+ raise FirecrawlScrapeFailed(f"Firecrawl scrape of {url} returned no data")++ metadata = _as_mapping(data.get("metadata")) or {}+ return FirecrawlScrape(+ url=url,+ markdown=_as_str(data.get("markdown")),+ summary=_as_str(data.get("summary")),+ title=_as_str(metadata.get("title")),+ description=_as_str(metadata.get("description")),+ status_code=_as_int(metadata.get("statusCode")),+ credits_used=_as_int(metadata.get("creditsUsed")),+ )diff --git a/posthog/egress/firecrawl/limiter.py b/posthog/egress/firecrawl/limiter.pynew file mode 100644index 000000000000..c537eba3a617--- /dev/null+++ b/posthog/egress/firecrawl/limiter.py@@ -0,0 +1,59 @@+"""Firecrawl egress budget.++Firecrawl meters per account and bills credits per call, and a PostHog instance holds a single+Firecrawl API key, so the whole instance draws from one shared budget under a constant scope.+Firecrawl's per-plan request limits are not discoverable from the running process, so the defaults+below are operator ceilings on spend rather than observed provider limits: they exist to stop a+retry loop or a burst of sign-ups from spending a plan's credits, not to mirror Firecrawl's own+limit. Raise them in settings when real traffic outgrows them.++Importing this module registers the policy as a side effect, so import it (directly or via+``consume_firecrawl_sync``) before using a ``firecrawl:...`` limiter key.+"""++from django.conf import settings++from posthog.egress.limiter.outbound import get_outbound_rate_limiter+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy++FIRECRAWL_DOMAIN = "firecrawl"++# One Firecrawl account per instance, so a constant id carries the instance-wide shared budget.+_ACCOUNT_SCOPE_ID = "default"++# Same reserved-floor ladder as the other egress domains: BATCH is denied first as the budget fills,+# then NORMAL. Nothing in this domain runs CRITICAL, because the scraped URL is derived from+# user-supplied input and a never-shed lane would make the budget advisory.+_RESERVE: dict[Priority, float] = {Priority.BATCH: 0.30, Priority.NORMAL: 0.10}++# Operator ceilings on credit spend, not observed provider limits. Each scrape costs a credit, so+# the per-minute rate smooths a burst of concurrent sign-ups and the hourly rate caps what a runaway+# caller can spend before someone notices.+_DEFAULT_PER_MINUTE_BUDGET = 60+_DEFAULT_HOURLY_BUDGET = 1_000+++# Registered as a provider so the budgets are read at acquire time, which means a settings override applies+# without a process restart, matching the other egress domains.+def _firecrawl_policy(key: str) -> RatePolicy:+ per_minute = int(getattr(settings, "FIRECRAWL_EGRESS_PER_MINUTE_BUDGET", _DEFAULT_PER_MINUTE_BUDGET))+ hourly = int(getattr(settings, "FIRECRAWL_EGRESS_HOURLY_BUDGET", _DEFAULT_HOURLY_BUDGET))+ return RatePolicy(+ limits=((per_minute, 60.0), (hourly, 3600.0)),+ in_memory_divider=4,+ reserve=_RESERVE,+ )+++register_policy(FIRECRAWL_DOMAIN, _firecrawl_policy)+++def firecrawl_account_key() -> str:+ """Limiter key for the instance's single Firecrawl account, which is the unit Firecrawl meters."""+ return f"{FIRECRAWL_DOMAIN}:account:{_ACCOUNT_SCOPE_ID}"+++def consume_firecrawl_sync(n: int = 1, *, priority: Priority = Priority.NORMAL, source: str = "unknown") -> bool:+ """Reserve ``n`` requests against the instance's Firecrawl budget. Returns False when the budget+ (or this ``priority``'s reserved floor) is exhausted, so degrade gracefully rather than calling out."""+ return get_outbound_rate_limiter().consume_sync(firecrawl_account_key(), n, priority=priority, source=source)diff --git a/posthog/egress/firecrawl/observability.py b/posthog/egress/firecrawl/observability.pynew file mode 100644index 000000000000..37c72f638892--- /dev/null+++ b/posthog/egress/firecrawl/observability.py@@ -0,0 +1,98 @@+"""Firecrawl egress telemetry.++Every Firecrawl call funnels through these recorders so request volume lands on one metric set+whichever subsystem made the call, attributed by the ``source`` label. Firecrawl meters each+endpoint separately, so the gauges' ``resource`` is the endpoint the observed headers describe.+"""++from collections.abc import Mapping++import requests+from prometheus_client import Counter, Gauge++from posthog.egress.observability.observability import (+ EgressMetrics,+ EgressObservability,+ RateLimitSnapshot,+ default_normalize_endpoint,+ register_egress_observability,+)++FIRECRAWL_DOMAIN = "firecrawl"++_metrics = EgressMetrics(+ request_counter=Counter(+ "firecrawl_api_requests",+ "Number of Firecrawl API requests made through the Firecrawl egress client.",+ labelnames=["account", "method", "endpoint", "status_code", "source"],+ ),+ remaining_gauge=Gauge(+ "firecrawl_api_rate_limit_remaining",+ "Most recently observed Firecrawl rate limit remaining count by endpoint.",+ labelnames=["account", "resource"],+ ),+ limit_gauge=Gauge(+ "firecrawl_api_rate_limit_limit",+ "Most recently observed Firecrawl rate limit by endpoint.",+ labelnames=["account", "resource"],+ ),+ reset_gauge=Gauge(+ "firecrawl_api_rate_limit_reset_timestamp_seconds",+ "Most recently observed Firecrawl rate limit reset timestamp by endpoint "+ "(unset: Firecrawl does not document the encoding of its reset header).",+ labelnames=["account", "resource"],+ ),+)+++def _float_header(headers: Mapping[str, str] | None, name: str) -> float | None:+ if headers is None:+ return None+ value = headers.get(name)+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _parse_firecrawl_rate_limit(response: requests.Response) -> RateLimitSnapshot:+ """Read Firecrawl's rate-limit headers when the response carries them. ``reset_at`` is left unset+ because Firecrawl does not document whether its reset header is an epoch or a number of seconds,+ and a gauge that could be either is worse than an unset one."""+ headers = response.headers if isinstance(response.headers, Mapping) else None+ request = getattr(response, "request", None)+ url = getattr(request, "url", None)+ return RateLimitSnapshot(+ resource=default_normalize_endpoint(url if isinstance(url, str) else None),+ remaining=_float_header(headers, "X-RateLimit-Remaining"),+ limit=_float_header(headers, "X-RateLimit-Limit"),+ )+++firecrawl_egress = EgressObservability(FIRECRAWL_DOMAIN, _metrics, _parse_firecrawl_rate_limit)+register_egress_observability(firecrawl_egress)+++def record_firecrawl_api_response(+ response: requests.Response,+ *,+ source: str,+ method: str | None = None,+ endpoint: str | None = None,+) -> None:+ """Record one Firecrawl API response. The scope is always the instance's single account,+ because Firecrawl meters per API key and each instance holds exactly one."""+ firecrawl_egress.record_response(response, source=source, scope="default", method=method, endpoint=endpoint)+++def record_firecrawl_api_exception(+ *,+ source: str,+ method: str,+ endpoint: str | None = None,+ url: str | None = None,+) -> None:+ """Record a request that raised before a response (timeout, connection error)."""+ firecrawl_egress.record_exception(source=source, scope="default", method=method, endpoint=endpoint, url=url)diff --git a/posthog/egress/firecrawl/transport.py b/posthog/egress/firecrawl/transport.pynew file mode 100644index 000000000000..ebd305140a40--- /dev/null+++ b/posthog/egress/firecrawl/transport.py@@ -0,0 +1,80 @@+"""Firecrawl incarnation of the egress transport.++``firecrawl_request`` is the one way to call Firecrawl from anywhere in the codebase: it gates on+the instance's shared account budget and records telemetry by construction. It stays token-agnostic+like the other incarnations, so the caller owns where the API key comes from:+:mod:`posthog.egress.firecrawl.client` reads it from settings.+"""++from typing import Any++import requests++from posthog.egress.firecrawl.limiter import consume_firecrawl_sync+from posthog.egress.firecrawl.observability import record_firecrawl_api_exception, record_firecrawl_api_response+from posthog.egress.limiter.policies import Priority+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient++# The whole instance shares one Firecrawl account, so every call carries the same scope.+_ACCOUNT_SCOPE = "default"+++class FirecrawlEgressBudgetExhausted(EgressBudgetExhausted):+ """A sheddable (BATCH/NORMAL) Firecrawl call was shed by our egress limiter before it was sent.+ Callers that can degrade (e.g. opening a session without scraped company context) catch this."""+++class FirecrawlClient(EgressClient):+ """The Firecrawl incarnation of :class:`EgressClient`. Stateless, so one shared instance serves+ every caller; wire it through :func:`firecrawl_request`."""++ def _standard_headers(self) -> dict[str, str]:+ return {"Accept": "application/json", "Content-Type": "application/json"}++ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return consume_firecrawl_sync(priority=priority, source=source)++ def _record_response(+ self, response: requests.Response, *, source: str, scope: str | None, method: str, endpoint: str | None+ ) -> None:+ record_firecrawl_api_response(response, source=source, method=method, endpoint=endpoint)++ def _record_exception(self, *, source: str, scope: str | None, method: str, url: str, endpoint: str | None) -> None:+ record_firecrawl_api_exception(source=source, method=method, url=url, endpoint=endpoint)++ def _budget_exhausted_error(self, scope: str) -> FirecrawlEgressBudgetExhausted:+ return FirecrawlEgressBudgetExhausted("Firecrawl egress budget exhausted; degrading")+++# Stateless, so one shared instance serves the whole process.+_firecrawl_client = FirecrawlClient()+++def firecrawl_request(+ method: str,+ url: str,+ *,+ api_key: str,+ source: str,+ endpoint: str,+ priority: Priority = Priority.NORMAL,+ timeout: float | tuple[float, float] | None = None,+ **kwargs: Any,+) -> requests.Response:+ """Make a gated, recorded Firecrawl request. ``source`` attributes the call to a subsystem.++ The default lane is sheddable: what we scrape is derived from user-supplied input, and every+ caller so far can do without the scrape, so Firecrawl traffic must not be able to consume the+ whole budget the way a CRITICAL lane would.+ """+ return _firecrawl_client.request(+ method,+ url,+ source=source,+ headers={"Authorization": f"Bearer {api_key}"},+ scope=_ACCOUNT_SCOPE,+ priority=priority,+ endpoint=endpoint,+ timeout=timeout,+ **kwargs,+ )diff --git a/posthog/egress/test/test_firecrawl.py b/posthog/egress/test/test_firecrawl.pynew file mode 100644index 000000000000..814aaa7f0695--- /dev/null+++ b/posthog/egress/test/test_firecrawl.py@@ -0,0 +1,117 @@+import json+from collections.abc import Iterator+from contextlib import contextmanager++from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase, override_settings++import requests+from parameterized import parameterized++from posthog.egress.firecrawl.client import FirecrawlNotConfigured, FirecrawlScrapeFailed, scrape+from posthog.egress.firecrawl.limiter import consume_firecrawl_sync, firecrawl_account_key+from posthog.egress.limiter.policies import Priority, resolve_policy++_FAKE_API_KEY = "fake-key-for-tests"++_SUCCESSFUL_SCRAPE = {+ "success": True,+ "data": {+ "markdown": "# Example",+ "summary": "Example builds widgets.",+ "metadata": {+ "title": "Example",+ "description": "Widgets for everyone.",+ "statusCode": 200,+ "creditsUsed": 1,+ },+ },+}+++def _response(status: int, body: str) -> requests.Response:+ response = requests.models.Response()+ response.status_code = status+ response._content = body.encode()+ return response+++@contextmanager+def _firecrawl_answers(response: requests.Response) -> Iterator[tuple[MagicMock, MagicMock]]:+ """Yield the patched sender and limiter gate. The gate is patched so these tests never draw on+ the shared budget counter, which would couple them to each other's ordering."""+ with (+ patch("posthog.egress.firecrawl.transport.consume_firecrawl_sync", return_value=True) as consume,+ patch("requests.request", return_value=response) as request,+ ):+ yield request, consume+++@override_settings(FIRECRAWL_API_KEY=_FAKE_API_KEY)+class TestFirecrawlEgress(SimpleTestCase):+ def test_scrape_sends_the_request_shape_firecrawl_documents(self) -> None:+ # Firecrawl reads camelCase body keys and ignores unknown ones, so a snake_case slip would+ # silently scrape whole-page boilerplate instead of the main content, with no error to notice.+ with _firecrawl_answers(_response(200, json.dumps(_SUCCESSFUL_SCRAPE))) as (request, _consume):+ scrape("https://example.com", source="test", formats=["summary"])++ assert request.call_args.args == ("POST", "https://api.firecrawl.dev/v2/scrape")+ kwargs = request.call_args.kwargs+ assert kwargs["headers"]["Authorization"] == f"Bearer {_FAKE_API_KEY}"+ assert kwargs["json"] == {"url": "https://example.com", "formats": ["summary"], "onlyMainContent": True}++ def test_scrape_maps_the_documented_response_onto_the_result(self) -> None:+ # title, description and creditsUsed live under `metadata`, not alongside the formats, so+ # reading them from the wrong level hands callers a result that is silently all None.+ with _firecrawl_answers(_response(200, json.dumps(_SUCCESSFUL_SCRAPE))):+ result = scrape("https://example.com", source="test")++ assert result.markdown == "# Example"+ assert result.summary == "Example builds widgets."+ assert result.title == "Example"+ assert result.description == "Widgets for everyone."+ assert result.status_code == 200+ assert result.credits_used == 1++ @parameterized.expand(+ [+ ("http_error", 402, json.dumps({"error": "Insufficient credits"})),+ ("unsuccessful_body", 200, json.dumps({"success": False, "error": "unreachable"})),+ ("missing_data", 200, json.dumps({"success": True})),+ ("non_json_body", 200, "<html>gateway timeout</html>"),+ ]+ )+ def test_scrape_raises_rather_than_returning_an_empty_result(self, _name: str, status: int, body: str) -> None:+ # Firecrawl answers 200 with `success: false` for pages it could not fetch, so a caller that+ # only checked the HTTP status would treat a failed scrape as a page with no content.+ with _firecrawl_answers(_response(status, body)), self.assertRaises(FirecrawlScrapeFailed):+ scrape("https://example.com", source="test")++ @override_settings(FIRECRAWL_API_KEY="")+ def test_scrape_without_a_configured_key_never_calls_out(self) -> None:+ # Instances run without a key; sending `Bearer ` would spend a request to be told 401.+ with patch("requests.request") as request:+ with self.assertRaises(FirecrawlNotConfigured):+ scrape("https://example.com", source="test")+ request.assert_not_called()++ def test_scrape_defaults_to_a_sheddable_lane(self) -> None:+ # The scraped URL comes from user-influenced input, so this traffic must stay deniable as the+ # shared budget fills. CRITICAL is never shed, which would make the budget advisory.+ with _firecrawl_answers(_response(200, json.dumps(_SUCCESSFUL_SCRAPE))) as (_request, consume):+ scrape("https://example.com", source="test")++ assert consume.call_args.kwargs["priority"] is Priority.NORMAL++ def test_policy_is_registered_for_the_account_key(self) -> None:+ # consume raises for a domain with no registered policy, so this catches the registration side+ # effect being lost (e.g. an import shuffle dropping the register_policy call).+ assert firecrawl_account_key() == "firecrawl:account:default"+ assert consume_firecrawl_sync(source="test") is True++ @override_settings(FIRECRAWL_EGRESS_PER_MINUTE_BUDGET=7, FIRECRAWL_EGRESS_HOURLY_BUDGET=11)+ def test_budgets_come_from_the_settings_they_are_named_after(self) -> None:+ # The policy reads settings through getattr defaults, which would swallow a renamed or+ # misspelled setting and quietly pin the budget to the code default forever.+ assert resolve_policy(firecrawl_account_key()).limits == ((7, 60.0), (11, 3600.0))diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 380f8c143e86..4b546a41f669 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -1076,6 +1076,13 @@ LOGO_DEV_TOKEN = get_from_env("LOGO_DEV_TOKEN", "")LOGO_DEV_PUBLISHABLE_KEY = get_from_env("LOGO_DEV_PUBLISHABLE_KEY", LOGO_DEV_TOKEN)LOGO_DEV_SECRET_KEY = get_from_env("LOGO_DEV_SECRET_KEY", "")+####+# Firecrawl (outbound page scraping, see posthog/egress/firecrawl/)+FIRECRAWL_API_KEY = get_from_env("FIRECRAWL_API_KEY", "")+# Operator ceilings on credit spend rather than Firecrawl's own limits, which the process can't see.+FIRECRAWL_EGRESS_PER_MINUTE_BUDGET = get_from_env("FIRECRAWL_EGRESS_PER_MINUTE_BUDGET", 60, type_cast=int)+FIRECRAWL_EGRESS_HOURLY_BUDGET = get_from_env("FIRECRAWL_EGRESS_HOURLY_BUDGET", 1000, type_cast=int)+##### Feature flag billing analytics# Used to track feature flag requests for billing purposes.