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.

feat(data-warehouse): implement firecrawl import source (#70034)

Tom Owers7ec42526bba5
diff --git a/frontend/public/services/firecrawl.svg b/frontend/public/services/firecrawl.svg
new file mode 100644
index 000000000000..12a82742bc19
--- /dev/null
+++ b/frontend/public/services/firecrawl.svg
@@ -0,0 +1,3 @@
+<svg width="200" height="284" viewBox="0 0 200 284" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M166.862 90.7716C155.812 94.0514 147.483 101.471 141.383 109.53C140.073 111.26 137.343 109.96 137.863 107.841C149.543 59.8136 134.113 19.896 86.0157 0.247269C83.5758 -0.752669 81.0359 1.43719 81.6759 3.99704C103.555 91.8416 11.5294 84.432 23.1588 184.016C23.3588 185.726 21.4389 186.896 20.039 185.896C15.6792 182.766 10.8095 176.236 7.46963 171.647C6.48968 170.297 4.36978 170.677 3.9198 172.287C1.25994 181.906 0 190.965 0 199.965C0 234.963 17.9891 265.771 45.2177 283.63C46.7777 284.65 48.7776 283.19 48.2476 281.4C46.8477 276.7 46.0577 271.74 45.9977 266.611C45.9977 263.461 46.1977 260.241 46.6877 257.241C47.8276 249.702 50.4475 242.522 54.8473 235.983C69.9365 213.334 100.185 191.455 95.3552 161.747C95.0453 159.867 97.2651 158.627 98.6651 159.917C119.974 179.386 124.194 205.575 120.694 229.063C120.394 231.103 122.954 232.193 124.244 230.593C127.504 226.513 131.483 222.933 135.813 220.244C136.893 219.574 138.333 220.084 138.743 221.284C141.153 228.293 144.733 234.873 148.113 241.452C152.152 249.362 154.302 258.391 153.962 267.951C153.792 272.6 153.022 277.1 151.732 281.38C151.182 283.19 153.162 284.7 154.752 283.66C182.001 265.801 200 234.993 200 199.975C200 187.806 197.87 175.876 193.84 164.697C185.391 141.248 163.952 123.64 169.372 93.0815C169.632 91.6216 168.282 90.3517 166.862 90.7716Z" fill="#FA5D19" style="fill:#FA5D19;fill:color(display-p3 0.9816 0.3634 0.0984);fill-opacity:1;"/>
+</svg>
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 8b74ebf76f76..b09f125b3fc8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -169,6 +169,7 @@ the row lists both.
| financial_modelling | HTTP | requests | ✅ |
| finnhub | HTTP | requests | ✅ |
| finnworlds | HTTP | requests | ✅ |
+| firecrawl | HTTP | requests | ✅ |
| fleetio | HTTP | requests | ✅ |
| firehydrant | HTTP | requests | ✅ |
| flexmail | HTTP | requests | ✅ |
@@ -543,7 +544,6 @@ doesn't conflict with concurrent PRs.
- fintoc
- firebase
- firebolt
-- firecrawl
- fireworks_ai
- flexmail
- flexport
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/canonical_descriptions.py
new file mode 100644
index 000000000000..82643187d383
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Sourced from the public Firecrawl v2 API reference (https://docs.firecrawl.dev/api-reference).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "team_activity": {
+ "description": "Your team's job activity from the past 24 hours - one row per API job (scrape, crawl, search, etc.).",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/activity",
+ "columns": {
+ "id": "The job ID, used to fetch the full result from the matching retrieval endpoint.",
+ "endpoint": "The endpoint used for the job (scrape, crawl, batch_scrape, search, extract, map, agent, ...).",
+ "api_version": "The API version used for the request.",
+ "created_at": "When the job was created.",
+ "target": "The URL or query that was submitted.",
+ },
+ },
+ "credit_usage_historical": {
+ "description": "Credits used per billing period, month by month.",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/credit-usage-historical",
+ "columns": {
+ "startDate": "Start date of the billing period.",
+ "endDate": "End date of the billing period.",
+ "apiKey": "The API key the usage is attributed to, or null for the team total (the default).",
+ "totalCredits": "Total number of credits used in the billing period.",
+ },
+ },
+ "token_usage_historical": {
+ "description": "Tokens used per billing period, month by month.",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/token-usage-historical",
+ "columns": {
+ "startDate": "Start date of the billing period.",
+ "endDate": "End date of the billing period.",
+ "apiKey": "The API key the usage is attributed to, or null for the team total (the default).",
+ "totalTokens": "Total number of tokens used in the billing period.",
+ },
+ },
+ "active_crawls": {
+ "description": "Crawls that are currently in progress for your team.",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/crawl-active",
+ "columns": {
+ "id": "The unique identifier of the crawl.",
+ "teamId": "The ID of the team that owns the crawl.",
+ "url": "The origin URL of the crawl.",
+ "options": "The crawler options used for this crawl.",
+ },
+ },
+ "monitors": {
+ "description": "Change-detection monitors that periodically re-scrape targets and report what changed.",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/monitor-list",
+ "columns": {
+ "id": "The unique identifier of the monitor.",
+ "name": "The monitor's name.",
+ "status": "Monitor status (active, paused, deleted).",
+ "schedule": "The monitor's run schedule (cron expression and timezone).",
+ "nextRunAt": "When the monitor is next scheduled to run.",
+ "lastRunAt": "When the monitor last ran.",
+ "targets": "The scrape, crawl, or search targets the monitor watches.",
+ "retentionDays": "How many days of checks are retained.",
+ "estimatedCreditsPerMonth": "Upper-bound monthly credit estimate for the monitor.",
+ "createdAt": "When the monitor was created.",
+ "updatedAt": "When the monitor was last updated.",
+ },
+ },
+ "monitor_checks": {
+ "description": "Individual change-detection runs for a monitor, including credit cost and a page-change summary.",
+ "docs_url": "https://docs.firecrawl.dev/api-reference/endpoint/monitor-checks-list",
+ "columns": {
+ "id": "The unique identifier of the check.",
+ "monitorId": "The monitor this check belongs to.",
+ "status": "Check status (queued, running, completed, failed, partial, skipped_overlap).",
+ "trigger": "What triggered the check (scheduled or manual).",
+ "startedAt": "When the check started.",
+ "finishedAt": "When the check finished.",
+ "actualCredits": "Credits actually consumed by the check.",
+ "summary": "Page-change summary (totalPages, same, changed, new, removed, error).",
+ "createdAt": "When the check was created.",
+ "updatedAt": "When the check was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/docs/firecrawl.md b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/docs/firecrawl.md
new file mode 100644
index 000000000000..a9ec6e84408b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/docs/firecrawl.md
@@ -0,0 +1,54 @@
+---
+title: Linking Firecrawl as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Firecrawl
+beta: true
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+[Firecrawl](https://www.firecrawl.dev) is a web scraping and crawling API. This connector syncs your Firecrawl account's operational data - job activity, credit and token usage, active crawls, and change-detection monitors - into the PostHog Data warehouse, so you can track your scraping usage and spend alongside the rest of your data.
+
+## Prerequisites
+
+- A Firecrawl account.
+- A Firecrawl API key, which you can create in your [Firecrawl dashboard](https://www.firecrawl.dev/app/api-keys). A single key grants access to every table this connector syncs.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+Provide your Firecrawl **API key** (it starts with `fc-`). That's the only credential the connector needs.
+
+## Sync modes
+
+<SyncModes />
+
+Firecrawl's account endpoints don't expose a server-side "updated since" filter, so every Firecrawl table syncs with **full refresh** - each sync replaces the table with the current data from the API.
+
+One table is worth calling out: `team_activity` is a rolling log that Firecrawl only retains for the **last 24 hours**. Older activity can't be backfilled, so schedule frequent syncs if you want to accumulate a longer history of jobs in the warehouse.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+The `monitor_checks` table is disabled by default because it fans out one request per monitor - enable it in the table picker if you use Firecrawl monitors and want their individual check runs.
+
+## Troubleshooting
+
+- **Invalid API key:** if the connection fails to validate, confirm the key is active in your [Firecrawl dashboard](https://www.firecrawl.dev/app/api-keys) and that you pasted the full `fc-...` value.
+- **Empty `team_activity`:** the endpoint only returns the last 24 hours of jobs. If your account hasn't run any jobs in that window, the table will be empty until it does.
+- **Rate limits:** Firecrawl enforces plan-based rate and concurrency limits. The connector automatically backs off and retries when it's throttled.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/firecrawl.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/firecrawl.py
new file mode 100644
index 000000000000..092f4d97d0db
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/firecrawl.py
@@ -0,0 +1,265 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.settings import (
+ FIRECRAWL_BASE_URL,
+ FIRECRAWL_ENDPOINTS,
+ FirecrawlEndpointConfig,
+)
+
+# Both the cursor endpoint (activity) and the offset endpoints (monitors, monitor checks) cap page
+# size at 100. Ask for the maximum to minimize round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Hard stop so a misbehaving offset endpoint (one that never shrinks a page below PAGE_SIZE) can't
+# spin forever. 100 * 100_000 = 10M rows per resource, far above any realistic account.
+MAX_PAGE_ITERATIONS = 100_000
+
+
+class FirecrawlRetryableError(Exception):
+ pass
+
+
+class FirecrawlResumeConfig:
+ # team_activity cursor-pagination bookmark: the cursor for the next page to fetch.
+ cursor: str | None = None
+ # Offset for the offset-paginated endpoints (monitors, monitor_checks).
+ offset: int | None = None
+ # monitor_checks fan-out: the monitor whose checks we're currently paging. A stable ID bookmark
+ # (not a positional index) so monitors added/removed between a crash and the retry can't resume
+ # us into the wrong monitor. None for the non-fan-out endpoints.
+ monitor_id: str | None = None
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+@retry(
+ # ChunkedEncodingError is a mid-stream connection break (server truncated a chunked body); it's
+ # transient like ConnectionError/ReadTimeout but not a ConnectionError subclass, so list it.
+ retry=retry_if_exception_type(
+ (
+ FirecrawlRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ params: dict[str, Any] | None,
+ logger: FilteringBoundLogger,
+) -> dict:
+ response = session.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Plan-based rate/concurrency limits surface as 429; 5xx are transient. Back off and retry both.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise FirecrawlRetryableError(f"Firecrawl API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Firecrawl API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # credit-usage is a cheap, always-present team endpoint: a genuine key returns 200, an invalid or
+ # revoked one 401. We only confirm the token itself here (see FirecrawlSource.validate_credentials).
+ url = f"{FIRECRAWL_BASE_URL}/v2/team/credit-usage"
+ try:
+ # Redact the bearer token from tracked logs/samples in case Firecrawl reflects it back
+ # (redirect URL, error body, or a non-denylisted field).
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _fetch_single(
+ session: requests.Session, headers: dict[str, str], cfg: FirecrawlEndpointConfig, logger: FilteringBoundLogger
+) -> list[dict]:
+ """Unpaginated endpoints: one request, return the whole row array."""
+ data = _fetch(session, f"{FIRECRAWL_BASE_URL}{cfg.path}", headers, None, logger)
+ # Index (not .get) so a renamed/missing selector fails the sync loudly instead of silently
+ # replacing warehouse data with zero rows on a full refresh.
+ return data[cfg.data_selector] or []
+
+
+def _iter_cursor_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ cfg: FirecrawlEndpointConfig,
+ manager: ResumableSourceManager[FirecrawlResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict]]:
+ """Cursor-paginated endpoints (team activity). Yields one page of rows at a time."""
+ resume = manager.load_state() if manager.can_resume() else None
+ cursor = resume.cursor if resume else None
+ if cursor:
+ logger.debug(f"Firecrawl: resuming {cfg.name} from cursor")
+
+ url = f"{FIRECRAWL_BASE_URL}{cfg.path}"
+ for _ in range(MAX_PAGE_ITERATIONS):
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if cursor:
+ params["cursor"] = cursor
+ data = _fetch(session, url, headers, params, logger)
+
+ # Index (not .get) so a renamed/missing selector fails loudly rather than truncating the sync.
+ yield data[cfg.data_selector] or []
+
+ next_cursor = data.get("cursor")
+ if not data.get("has_more") or not next_cursor:
+ break
+ cursor = next_cursor
+ # Save AFTER yielding the page so a crash resumes at the next page rather than replaying the
+ # whole log; full-refresh keeps already-written rows on resume, and the primary key dedupes.
+ manager.save_state(FirecrawlResumeConfig(cursor=cursor))
+
+
+def _iter_offset_pages(
+ session: requests.Session,
+ headers: dict[str, str],
+ path: str,
+ data_selector: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[FirecrawlResumeConfig] | None = None,
+ monitor_id: str | None = None,
+ start_offset: int = 0,
+) -> Iterator[list[dict]]:
+ """Offset-paginated endpoints (monitors, monitor checks). Yields one page of rows at a time.
+
+ Termination is a short page (< PAGE_SIZE): these endpoints return no total or has_more flag, so
+ a full page means "there may be more". When a manager is supplied, saves the next offset (and the
+ fan-out monitor_id) after each page so a resume picks up mid-resource.
+ """
+ offset = start_offset
+ url = f"{FIRECRAWL_BASE_URL}{path}"
+ for _ in range(MAX_PAGE_ITERATIONS):
+ data = _fetch(session, url, headers, {"limit": PAGE_SIZE, "offset": offset}, logger)
+ # Index (not .get) so a renamed/missing selector fails loudly rather than truncating the sync.
+ items = data[data_selector] or []
+
+ yield items
+
+ if len(items) < PAGE_SIZE:
+ break
+ offset += PAGE_SIZE
+ if manager is not None:
+ manager.save_state(FirecrawlResumeConfig(offset=offset, monitor_id=monitor_id))
+
+
+def _iter_monitor_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:
+ monitor_ids: list[str] = []
+ for page in _iter_offset_pages(session, headers, FIRECRAWL_ENDPOINTS["monitors"].path, "data", logger):
+ # Index (not a guarded skip) so a monitor row missing its id fails loudly rather than
+ # silently dropping every check for that monitor.
+ monitor_ids.extend(item["id"] for item in page)
+ return monitor_ids
+
+
+def _iter_monitor_checks(
+ session: requests.Session,
+ headers: dict[str, str],
+ cfg: FirecrawlEndpointConfig,
+ manager: ResumableSourceManager[FirecrawlResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict]]:
+ """Fan out over every monitor, paging each monitor's checks. Each check id is a globally-unique
+ uuid, and every row also carries its `monitorId`, so the primary key stays unique table-wide."""
+ monitor_ids = _iter_monitor_ids(session, headers, logger)
+
+ resume = manager.load_state() if manager.can_resume() else None
+ remaining = monitor_ids
+ resume_offset = 0
+ if resume is not None and resume.monitor_id is not None and resume.monitor_id in monitor_ids:
+ remaining = monitor_ids[monitor_ids.index(resume.monitor_id) :]
+ resume_offset = resume.offset or 0
+ logger.debug(f"Firecrawl: resuming monitor_checks from monitor {resume.monitor_id}, offset {resume_offset}")
+
+ for index, monitor_id in enumerate(remaining):
+ path = cfg.path.replace("{monitor_id}", monitor_id)
+ start_offset = resume_offset if index == 0 else 0
+ yield from _iter_offset_pages(
+ session,
+ headers,
+ path,
+ cfg.data_selector,
+ logger,
+ manager=manager,
+ monitor_id=monitor_id,
+ start_offset=start_offset,
+ )
+ # Advance the bookmark to the next monitor so a crash between monitors resumes correctly.
+ if index + 1 < len(remaining):
+ manager.save_state(FirecrawlResumeConfig(offset=0, monitor_id=remaining[index + 1]))
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FirecrawlResumeConfig],
+) -> Iterator[list[dict]]:
+ cfg = FIRECRAWL_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive. Redact the bearer
+ # token from tracked logs/samples in case Firecrawl reflects it back in a URL or response body.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ if cfg.fan_out_over_monitors:
+ yield from _iter_monitor_checks(session, headers, cfg, resumable_source_manager, logger)
+ elif cfg.pagination == "cursor":
+ yield from _iter_cursor_pages(session, headers, cfg, resumable_source_manager, logger)
+ elif cfg.pagination == "offset":
+ yield from _iter_offset_pages(
+ session, headers, cfg.path, cfg.data_selector, logger, manager=resumable_source_manager
+ )
+ else:
+ yield _fetch_single(session, headers, cfg, logger)
+
+
+def firecrawl_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[FirecrawlResumeConfig],
+) -> SourceResponse:
+ cfg = FIRECRAWL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=cfg.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if cfg.partition_key else None,
+ partition_format=cfg.partition_format if cfg.partition_key else None,
+ partition_keys=[cfg.partition_key] if cfg.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/settings.py
new file mode 100644
index 000000000000..d9f9bc6e28b3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/settings.py
@@ -0,0 +1,97 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+FIRECRAWL_BASE_URL = "https://api.firecrawl.dev"
+
+PaginationMode = Literal["cursor", "offset", "none"]
+PartitionFormat = Literal["month", "week", "day", "hour"]
+
+
+@dataclass
+class FirecrawlEndpointConfig:
+ name: str
+ path: str
+ # Top-level key in the JSON body holding the row array (e.g. "data", "periods", "crawls").
+ data_selector: str
+ pagination: PaginationMode = "none"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable datetime field to partition by. Only ever a creation-style column (never updated_at),
+ # so partitions don't rewrite on every sync. None for endpoints without a stable timestamp.
+ partition_key: Optional[str] = None
+ partition_format: PartitionFormat = "week"
+ should_sync_default: bool = True
+ # monitor_checks fans out one offset-paginated request per monitor listed by /v2/monitor.
+ # When True, `path` is a template with a `{monitor_id}` placeholder.
+ fan_out_over_monitors: bool = False
+
+
+# Firecrawl exposes account-level operational data alongside its scrape/crawl action endpoints.
+# None of these list endpoints accept a server-side timestamp filter (verified against the public
+# v2 API reference), so every table is full-refresh only - see firecrawl.py for the rationale.
+FIRECRAWL_ENDPOINTS: dict[str, FirecrawlEndpointConfig] = {
+ # Rolling 24h job log. Cursor-paginated. Retains only the last 24 hours, so frequent syncs are
+ # needed to accumulate history and there is no way to backfill older activity.
+ "team_activity": FirecrawlEndpointConfig(
+ name="team_activity",
+ path="/v2/team/activity",
+ data_selector="data",
+ pagination="cursor",
+ primary_keys=["id"],
+ partition_key="created_at",
+ ),
+ # Month-by-month credit usage. Small unpaginated list; the current period's total keeps growing,
+ # so full refresh (replace) keeps it current.
+ "credit_usage_historical": FirecrawlEndpointConfig(
+ name="credit_usage_historical",
+ path="/v2/team/credit-usage/historical",
+ data_selector="periods",
+ pagination="none",
+ primary_keys=["startDate"],
+ ),
+ "token_usage_historical": FirecrawlEndpointConfig(
+ name="token_usage_historical",
+ path="/v2/team/token-usage/historical",
+ data_selector="periods",
+ pagination="none",
+ primary_keys=["startDate"],
+ ),
+ # Point-in-time snapshot of in-flight crawls; rows vanish as crawls finish, so full refresh only.
+ "active_crawls": FirecrawlEndpointConfig(
+ name="active_crawls",
+ path="/v2/crawl/active",
+ data_selector="crawls",
+ pagination="none",
+ primary_keys=["id"],
+ ),
+ # Change-detection monitors. Offset-paginated.
+ "monitors": FirecrawlEndpointConfig(
+ name="monitors",
+ path="/v2/monitor",
+ data_selector="data",
+ pagination="offset",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ ),
+ # Per-monitor change-detection runs. Fans out one offset-paginated request per monitor, so it's
+ # off by default to avoid the extra API cost on teams that don't need it.
+ "monitor_checks": FirecrawlEndpointConfig(
+ name="monitor_checks",
+ path="/v2/monitor/{monitor_id}/checks",
+ data_selector="data",
+ pagination="offset",
+ primary_keys=["id"],
+ partition_key="createdAt",
+ should_sync_default=False,
+ fan_out_over_monitors=True,
+ ),
+}
+
+ENDPOINTS = tuple(FIRECRAWL_ENDPOINTS.keys())
+
+# Every endpoint is full-refresh: Firecrawl has no server-side timestamp filter on any of these list
+# endpoints, so there is no genuine incremental cursor to advertise (a client-side "skip already-seen
+# rows" pass would still page the whole endpoint, which is not incremental). Kept as an explicit empty
+# mapping so `get_schemas` reads uniformly with the other sources.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/source.py
index a94168b1c5fa..ecc731ad2107 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/source.py
@@ -1,19 +1,47 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.firecrawl import (
+ FirecrawlResumeConfig,
+ firecrawl_source,
+ validate_credentials as validate_firecrawl_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.settings import (
+ ENDPOINTS,
+ FIRECRAWL_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FirecrawlSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+_ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "team_activity": "Job activity log. Firecrawl only retains the last 24 hours, so sync frequently to accumulate history - older activity cannot be backfilled.",
+ "monitor_checks": "Change-detection runs, one row per check across every monitor. Off by default: it fans out one request per monitor.",
+}
+
@SourceRegistry.register
-class FirecrawlSource(SimpleSource[FirecrawlSourceConfig]):
+class FirecrawlSource(ResumableSource[FirecrawlSourceConfig, FirecrawlResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog - safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FIRECRAWL
@@ -24,8 +52,94 @@ class FirecrawlSource(SimpleSource[FirecrawlSourceConfig]):
name=SchemaExternalDataSourceType.FIRECRAWL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Firecrawl",
- iconPath="/static/services/firecrawl.png",
- keywords=["scraping", "crawling", "web data", "firecrawl"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Firecrawl API key to pull your Firecrawl account activity and usage into the PostHog Data warehouse.
+
+You can create an API key in your [Firecrawl dashboard](https://www.firecrawl.dev/app/api-keys). A single key grants access to all of the tables below.""",
+ iconPath="/static/services/firecrawl.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/firecrawl",
+ keywords=["scraping", "crawling", "web data", "firecrawl"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="fc-...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked key surfaces as an HTTPError from raise_for_status(). Retrying can
+ # never satisfy a credential problem, so stop the sync. Match the stable status text plus
+ # base host, not the per-request path.
+ "401 Client Error: Unauthorized for url: https://api.firecrawl.dev": "Your Firecrawl API key is invalid or has been revoked. Create a new key in your Firecrawl dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.firecrawl.dev": "Your Firecrawl API key does not have access to this data. Check the key in your Firecrawl dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: FirecrawlSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = FIRECRAWL_ENDPOINTS[endpoint]
+ # Every endpoint is full-refresh: Firecrawl has no server-side timestamp filter to drive a
+ # genuine incremental sync (see settings.py).
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ description=_ENDPOINT_DESCRIPTIONS.get(endpoint),
+ detected_primary_keys=endpoint_config.primary_keys,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: FirecrawlSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # A Firecrawl key is all-or-nothing (no per-endpoint scopes), so the same token probe covers
+ # both source-create (schema_name=None) and the per-schema check.
+ if validate_firecrawl_credentials(config.api_key):
+ return True, None
+ return False, "Invalid Firecrawl API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FirecrawlResumeConfig]:
+ return ResumableSourceManager[FirecrawlResumeConfig](inputs, FirecrawlResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: FirecrawlSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FirecrawlResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return firecrawl_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl.py
new file mode 100644
index 000000000000..a5ee4818fbc5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl.py
@@ -0,0 +1,311 @@
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl import firecrawl
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.firecrawl import (
+ FirecrawlResumeConfig,
+ firecrawl_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.settings import FIRECRAWL_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: FirecrawlResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[FirecrawlResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> FirecrawlResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: FirecrawlResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(manager: _FakeResumableManager, endpoint: str) -> list[dict]:
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key="fc-test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(page)
+ return rows
+
+
+def _make_response(status_code: int, *, ok: bool | None = None, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = ok if ok is not None else status_code < 400
+ response.json.return_value = body if body is not None else {}
+ response.text = ""
+ return response
+
+
+class TestFetchRetryClassification:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502)])
+ def test_retryable_statuses_raise_and_retry(self, _name: str, status_code: int) -> None:
+ # 429 (plan rate/concurrency limit) and 5xx must retry rather than fail the sync outright.
+ session = MagicMock()
+ session.get.side_effect = [_make_response(status_code), _make_response(200, body={"data": []})]
+
+ with patch.object(firecrawl._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = firecrawl._fetch(session, "https://api.firecrawl.dev/v2/team/activity", {}, None, MagicMock())
+
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_immediately(self, _name: str, status_code: int) -> None:
+ # A 4xx credential/permission error can never be fixed by retrying, so it must surface at once.
+ response = _make_response(status_code)
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status_code} Client Error", response=cast(requests.Response, response)
+ )
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError):
+ firecrawl._fetch(session, "https://api.firecrawl.dev/v2/team/activity", {}, None, MagicMock())
+ assert session.get.call_count == 1
+
+ @parameterized.expand(
+ [
+ ("chunked", requests.exceptions.ChunkedEncodingError("Connection broken")),
+ ("read_timeout", requests.ReadTimeout("Read timed out.")),
+ ("connection", requests.ConnectionError("Connection reset by peer")),
+ ]
+ )
+ def test_transient_network_errors_are_retried(self, _name: str, transient: Exception) -> None:
+ session = MagicMock()
+ session.get.side_effect = [transient, _make_response(200, body={"data": []})]
+
+ with patch.object(firecrawl._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = firecrawl._fetch(session, "https://api.firecrawl.dev/v2/team/activity", {}, None, MagicMock())
+
+ assert result == {"data": []}
+ assert session.get.call_count == 2
+
+ def test_transient_error_reraised_after_five_attempts(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ReadTimeout("Read timed out.")
+
+ with patch.object(firecrawl._fetch.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(requests.ReadTimeout):
+ firecrawl._fetch(session, "https://api.firecrawl.dev/v2/team/activity", {}, None, MagicMock())
+ assert session.get.call_count == 5
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])
+ def test_status_maps_to_bool(self, _name: str, status_code: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _make_response(status_code)
+ with patch.object(firecrawl, "make_tracked_session", return_value=session):
+ assert validate_credentials("fc-test") is expected
+
+ def test_network_failure_is_false(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(firecrawl, "make_tracked_session", return_value=session):
+ assert validate_credentials("fc-test") is False
+
+
+class TestCursorPagination:
+ def _patch_fetch(self, monkeypatch: Any, pages_by_cursor: dict[Any, Any]) -> list[Any]:
+ seen_cursors: list[Any] = []
+
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ cursor = params.get("cursor") if params else None
+ seen_cursors.append(cursor)
+ return pages_by_cursor[cursor]
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ return seen_cursors
+
+ def test_follows_cursor_until_has_more_false(self, monkeypatch: Any) -> None:
+ pages = {
+ None: {"data": [{"id": "a"}], "cursor": "c1", "has_more": True},
+ "c1": {"data": [{"id": "b"}], "cursor": "c2", "has_more": True},
+ "c2": {"data": [{"id": "c"}], "cursor": None, "has_more": False},
+ }
+ seen = self._patch_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager()
+
+ rows = _collect(manager, "team_activity")
+
+ assert [r["id"] for r in rows] == ["a", "b", "c"]
+ assert seen == [None, "c1", "c2"]
+ # State is saved only for the pages that had a next cursor, and points at the NEXT page.
+ assert [s.cursor for s in manager.saved] == ["c1", "c2"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ pages = {
+ "c1": {"data": [{"id": "b"}], "cursor": None, "has_more": False},
+ }
+ seen = self._patch_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager(FirecrawlResumeConfig(cursor="c1"))
+
+ rows = _collect(manager, "team_activity")
+
+ assert [r["id"] for r in rows] == ["b"]
+ assert seen == ["c1"] # never re-fetched the already-processed first page
+
+ def test_stops_when_cursor_missing_even_if_has_more_true(self, monkeypatch: Any) -> None:
+ # Guard against an infinite loop if the API ever returns has_more=true with a null cursor.
+ pages = {None: {"data": [{"id": "a"}], "cursor": None, "has_more": True}}
+ self._patch_fetch(monkeypatch, pages)
+ rows = _collect(_FakeResumableManager(), "team_activity")
+ assert [r["id"] for r in rows] == ["a"]
+
+
+class TestOffsetPagination:
+ def _patch_fetch(self, monkeypatch: Any, pages_by_offset: dict[int, list[dict]]) -> list[int]:
+ seen_offsets: list[int] = []
+
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ offset = params["offset"]
+ seen_offsets.append(offset)
+ return {"data": pages_by_offset.get(offset, [])}
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ return seen_offsets
+
+ def test_pages_until_short_page(self, monkeypatch: Any) -> None:
+ full_page = [{"id": str(i)} for i in range(firecrawl.PAGE_SIZE)]
+ pages = {0: full_page, firecrawl.PAGE_SIZE: [{"id": "last"}]}
+ seen = self._patch_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager()
+
+ rows = _collect(manager, "monitors")
+
+ assert len(rows) == firecrawl.PAGE_SIZE + 1
+ assert seen == [0, firecrawl.PAGE_SIZE] # stopped after the short second page
+ assert [s.offset for s in manager.saved] == [firecrawl.PAGE_SIZE]
+
+ def test_single_short_page_does_not_advance(self, monkeypatch: Any) -> None:
+ seen = self._patch_fetch(monkeypatch, {0: [{"id": "x"}]})
+ manager = _FakeResumableManager()
+ rows = _collect(manager, "monitors")
+ assert [r["id"] for r in rows] == ["x"]
+ assert seen == [0]
+ assert manager.saved == []
+
+
+class TestUnpaginated:
+ @pytest.mark.parametrize(
+ "endpoint,selector",
+ [
+ ("credit_usage_historical", "periods"),
+ ("token_usage_historical", "periods"),
+ ("active_crawls", "crawls"),
+ ],
+ )
+ def test_single_request_reads_the_endpoint_selector(self, endpoint: str, selector: str, monkeypatch: Any) -> None:
+ calls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ calls.append(url)
+ return {selector: [{"id": "1"}, {"id": "2"}]}
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ rows = _collect(_FakeResumableManager(), endpoint)
+ assert rows == [{"id": "1"}, {"id": "2"}]
+ assert len(calls) == 1 # unpaginated: exactly one request
+
+
+class TestMonitorChecksFanOut:
+ def test_config_is_opt_in_fan_out(self) -> None:
+ cfg = FIRECRAWL_ENDPOINTS["monitor_checks"]
+ assert cfg.fan_out_over_monitors is True
+ assert cfg.should_sync_default is False
+ assert "{monitor_id}" in cfg.path
+
+ def test_fans_out_over_every_monitor(self, monkeypatch: Any) -> None:
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ if url.endswith("/v2/monitor"):
+ return {"data": [{"id": "m1"}, {"id": "m2"}]}
+ if "m1" in url:
+ return {"data": [{"id": "chk1", "monitorId": "m1"}]}
+ if "m2" in url:
+ return {"data": [{"id": "chk2", "monitorId": "m2"}]}
+ raise AssertionError(f"unexpected url {url}")
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ rows = _collect(_FakeResumableManager(), "monitor_checks")
+ assert rows == [
+ {"id": "chk1", "monitorId": "m1"},
+ {"id": "chk2", "monitorId": "m2"},
+ ]
+
+ def test_resumes_from_saved_monitor(self, monkeypatch: Any) -> None:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ fetched.append(url)
+ if url.endswith("/v2/monitor"):
+ return {"data": [{"id": "m1"}, {"id": "m2"}]}
+ return {"data": [{"id": "chk2", "monitorId": "m2"}]}
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ manager = _FakeResumableManager(FirecrawlResumeConfig(monitor_id="m2", offset=0))
+ rows = _collect(manager, "monitor_checks")
+
+ assert rows == [{"id": "chk2", "monitorId": "m2"}]
+ # m1's checks are never fetched - we resumed straight to m2.
+ assert not any("m1/checks" in url for url in fetched)
+
+ def test_unknown_saved_monitor_restarts_from_first(self, monkeypatch: Any) -> None:
+ def fake_fetch(session: Any, url: str, headers: Any, params: Any, logger: Any) -> dict:
+ if url.endswith("/v2/monitor"):
+ return {"data": [{"id": "m1"}]}
+ return {"data": [{"id": "chk1", "monitorId": "m1"}]}
+
+ monkeypatch.setattr(firecrawl, "_fetch", fake_fetch)
+ manager = _FakeResumableManager(FirecrawlResumeConfig(monitor_id="DELETED", offset=40))
+ rows = _collect(manager, "monitor_checks")
+ assert rows == [{"id": "chk1", "monitorId": "m1"}]
+
+
+class TestSourceResponseShape:
+ @parameterized.expand(
+ [
+ ("team_activity", ["id"], "created_at", "week"),
+ ("credit_usage_historical", ["startDate"], None, None),
+ ("token_usage_historical", ["startDate"], None, None),
+ ("active_crawls", ["id"], None, None),
+ ("monitors", ["id"], "createdAt", "week"),
+ ("monitor_checks", ["id"], "createdAt", "week"),
+ ]
+ )
+ def test_primary_keys_and_partitioning(
+ self, endpoint: str, expected_pk: list[str], partition_key: str | None, partition_format: str | None
+ ) -> None:
+ # Locks the primary key + a STABLE (creation-time) partition field per endpoint. A non-unique
+ # key or an updated_at partition would rewrite partitions every sync and accumulate duplicates.
+ response = firecrawl_source(
+ api_key="fc-test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pk
+ assert response.sort_mode == "asc"
+ if partition_key is None:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+ else:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.partition_format == partition_format
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl_source.py
new file mode 100644
index 000000000000..82048474ad01
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/firecrawl/tests/test_firecrawl_source.py
@@ -0,0 +1,119 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.firecrawl import FirecrawlResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.source import FirecrawlSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import FirecrawlSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> FirecrawlSourceConfig:
+ return FirecrawlSourceConfig(api_key="fc-test")
+
+
+class TestFirecrawlSourceConfig:
+ def test_source_type(self) -> None:
+ assert FirecrawlSource().source_type == ExternalDataSourceType.FIRECRAWL
+
+ def test_api_key_field_is_a_required_secret(self) -> None:
+ # A non-secret / non-password api_key field would render in plaintext and leak the credential.
+ fields = {f.name: f for f in FirecrawlSource().get_source_config.fields}
+ api_key = fields["api_key"]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.required is True
+ assert api_key.secret is True
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+
+ def test_released_as_alpha(self) -> None:
+ assert FirecrawlSource().get_source_config.releaseStatus == ReleaseStatus.ALPHA
+
+
+class TestFirecrawlGetSchemas:
+ def test_every_endpoint_is_full_refresh_only(self) -> None:
+ # Firecrawl has no server-side timestamp filter, so advertising incremental/append would be a
+ # false promise: every sync would still page the whole endpoint.
+ schemas = FirecrawlSource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ for schema in schemas:
+ assert schema.supports_incremental is False, schema.name
+ assert schema.supports_append is False, schema.name
+ assert schema.incremental_fields == []
+
+ def test_monitor_checks_is_off_by_default(self) -> None:
+ # It fans out one request per monitor, so it must not auto-enable on connect.
+ schemas = {s.name: s for s in FirecrawlSource().get_schemas(_config(), team_id=1)}
+ assert schemas["monitor_checks"].should_sync_default is False
+ assert schemas["team_activity"].should_sync_default is True
+
+ def test_names_filter_is_applied(self) -> None:
+ schemas = FirecrawlSource().get_schemas(_config(), team_id=1, names=["team_activity"])
+ assert [s.name for s in schemas] == ["team_activity"]
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # lists_tables_without_credentials must stay True (static catalog) or the docs table vanishes.
+ source = FirecrawlSource()
+ assert source.lists_tables_without_credentials is True
+ tables = source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+
+class TestFirecrawlValidateCredentials:
+ @parameterized.expand([("valid", True), ("invalid", False)])
+ def test_maps_token_probe_to_result(self, _name: str, probe_result: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.source.validate_firecrawl_credentials",
+ return_value=probe_result,
+ ):
+ ok, error = FirecrawlSource().validate_credentials(_config(), team_id=1)
+ assert ok is probe_result
+ assert (error is None) is probe_result
+
+
+class TestFirecrawlNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.firecrawl.dev/v2/team/activity"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.firecrawl.dev/v2/monitor"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ errors = FirecrawlSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.firecrawl.dev/v2/monitor"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.firecrawl.dev/v2/team/activity"),
+ ("read_timeout", "HTTPSConnectionPool(host='api.firecrawl.dev', port=443): Read timed out."),
+ ]
+ )
+ def test_transient_errors_stay_retryable(self, _name: str, observed: str) -> None:
+ errors = FirecrawlSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestFirecrawlResumableWiring:
+ def test_manager_is_bound_to_resume_config(self) -> None:
+ # A wrong data class would deserialize saved Redis state into the wrong shape on resume.
+ inputs = MagicMock()
+ manager = FirecrawlSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is FirecrawlResumeConfig
+
+ def test_source_for_pipeline_plumbs_api_key_and_endpoint(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "team_activity"
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.firecrawl.source.firecrawl_source"
+ ) as mock_source:
+ FirecrawlSource().source_for_pipeline(_config(), manager, inputs)
+ _, kwargs = mock_source.call_args
+ assert kwargs["api_key"] == "fc-test"
+ assert kwargs["endpoint"] == "team_activity"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 76778db75b67..26588273c596 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1329,7 +1329,7 @@ class FireboltSourceConfig(config.Config):
@config.config
class FirecrawlSourceConfig(config.Config):
- pass
+ api_key: str
@config.config