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 the browse ai import source (#108618)

Tom Owers79fc586ef1da
diff --git a/frontend/public/services/browse_ai.png b/frontend/public/services/browse_ai.png
new file mode 100644
index 000000000000..e443f6c70075
Binary files /dev/null and b/frontend/public/services/browse_ai.png differ
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 f0f171a89413..2469cd9e3597 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -136,6 +136,7 @@ the row lists both.
| breezometer | HTTP | requests | ✅ |
| brevo | HTTP | requests | ✅ |
| brex | HTTP | requests | ✅ |
+| browse_ai | HTTP + Webhook | requests + `rest_source.RESTClient` | ✅ |
| browser_use | HTTP | requests | ✅ |
| browserbase | HTTP | requests | ✅ |
| bugherd | HTTP | requests + `rest_source.RESTClient` | ✅ |
@@ -948,7 +949,6 @@ doesn't conflict with concurrent PRs.
- braintrust
- branch
- breezy_hr
-- browse_ai
- buffer
- buildium
- buy_me_a_coffee
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/browse_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/browse_ai.py
new file mode 100644
index 000000000000..abe4b0ccf708
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/browse_ai.py
@@ -0,0 +1,287 @@
+import secrets
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import TYPE_CHECKING, Any
+from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
+from uuid import UUID
+
+from asgiref.sync import async_to_sync
+from requests import Response
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.settings import (
+ AUTH_ERROR,
+ BASE_URL,
+ ENDPOINTS,
+ PERMISSION_ERROR,
+ BrowseAIEndpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
+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.rest_source import rest_api_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+
+if TYPE_CHECKING:
+ import pyarrow as pa
+
+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+
+
+@frozen
+class BrowseAIResumeConfig:
+ paginator_state: dict[str, Any] | None = None
+
+
+class BrowseAIPagePaginator(PageNumberPaginator):
+ def __init__(self, pagination_path: str) -> None:
+ super().__init__(base_page=1, stop_after_empty_page=False)
+ self.pagination_path = pagination_path
+
+ def update_state(self, response: Response, data: list[Any] | None = None) -> None:
+ pagination = response.json()
+ for key in self.pagination_path.split("."):
+ pagination = pagination[key]
+ has_more = pagination["hasMore"]
+ if not isinstance(has_more, bool):
+ raise ValueError("Browse AI returned an invalid hasMore value")
+ super().update_state(response, data)
+ self._has_next_page = has_more
+
+
+def normalize_row(row: dict[str, Any]) -> dict[str, Any]:
+ row = dict(row)
+ if isinstance(row.get("createdAt"), int | float):
+ row["createdAt"] = datetime.fromtimestamp(row["createdAt"] / 1000, tz=UTC)
+ return row
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ client = RESTClient(base_url=BASE_URL, auth=BearerTokenAuth(api_key), request_timeout=30)
+ try:
+ next(
+ client.paginate(
+ "robots", paginator=SinglePagePaginator(), data_selector="robots.items", data_selector_required=True
+ )
+ )
+ except HTTPError as error:
+ if error.response is not None and error.response.status_code in (401, 403):
+ return False, AUTH_ERROR if error.response.status_code == 401 else PERMISSION_ERROR
+ raise
+ return True, None
+
+
+def endpoint_config(endpoint: BrowseAIEndpoint) -> Endpoint:
+ return {
+ "path": endpoint.path,
+ "data_selector": endpoint.data_selector,
+ "data_selector_required": True,
+ "paginator": BrowseAIPagePaginator(endpoint.pagination_path)
+ if endpoint.pagination_path
+ else SinglePagePaginator(),
+ }
+
+
+def browse_ai_source(
+ api_key: str,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[BrowseAIResumeConfig],
+ webhook_manager: "WebhookSourceManager",
+) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Browse AI schema: {inputs.schema_name}")
+ endpoint = ENDPOINTS[inputs.schema_name]
+ webhook_enabled = endpoint.name == "tasks" and async_to_sync(webhook_manager.webhook_enabled)()
+
+ def rows() -> Iterator[list[dict[str, Any]]]:
+ resume = manager.load_state() if manager.can_resume() else None
+ client: ClientConfig = {
+ "base_url": BASE_URL,
+ "auth": {"type": "bearer", "token": api_key},
+ "request_timeout": 30,
+ }
+
+ def save_state(state: dict[str, Any] | None) -> None:
+ manager.save_state(BrowseAIResumeConfig(paginator_state=state))
+
+ initial = resume.paginator_state if resume else None
+ if endpoint.fanout:
+ resource = build_dependent_resource(
+ endpoint_configs=ENDPOINTS,
+ child_endpoint=endpoint.name,
+ fanout=endpoint.fanout,
+ client_config=client,
+ path_format_values={},
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra=endpoint_config(ENDPOINTS["robots"]),
+ child_endpoint_extra=endpoint_config(endpoint),
+ child_params_extra=endpoint.params,
+ page_size_param=None,
+ resume_hook=save_state,
+ initial_paginator_state=initial,
+ )
+ else:
+ resource = rest_api_resource(
+ {
+ "client": client,
+ "resources": [
+ {"name": endpoint.name, "endpoint": endpoint_config(endpoint), "table_format": "delta"}
+ ],
+ },
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_state,
+ initial_paginator_state=initial,
+ )
+ for page in resource:
+ yield [normalize_row(row) for row in page]
+
+ return SourceResponse(
+ name=endpoint.name,
+ items=(lambda: webhook_manager.get_items(table_transformer=webhook_table)) if webhook_enabled else rows,
+ primary_keys=list(endpoint.primary_keys),
+ partition_keys=[endpoint.partition_key],
+ partition_mode="datetime",
+ partition_format="month",
+ sort_mode=None,
+ supports_resume=not webhook_enabled and endpoint.fanout is not None,
+ )
+
+
+def webhook_table(table: "pa.Table") -> "pa.Table":
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import ( # noqa: PLC0415 - keep Arrow conversion off the source registry import path
+ table_from_py_list,
+ )
+
+ latest: dict[tuple[str, str], dict[str, Any]] = {}
+ for row in table.to_pylist():
+ task = row["task"]
+ key = (task["robotId"], task["id"])
+ previous = latest.get(key)
+ if previous is None or (task.get("finishedAt") or 0) >= (previous.get("finishedAt") or 0):
+ latest[key] = task
+ return table_from_py_list([normalize_row(task) for task in latest.values()])
+
+
+class BrowseAIWebhooks:
+ def __init__(self, api_key: str) -> None:
+ self.api_key = api_key
+ # Webhook listings contain callback tokens that are not known before the response arrives.
+ self.client = RESTClient(base_url=BASE_URL, auth=BearerTokenAuth(api_key), request_timeout=30, capture=False)
+
+ def _robots(self) -> list[dict[str, Any]]:
+ return next(
+ self.client.paginate(
+ "robots", paginator=SinglePagePaginator(), data_selector="robots.items", data_selector_required=True
+ )
+ )
+
+ def _path(self, robot_id: str) -> str:
+ return f"robots/{UUID(robot_id)}/webhooks"
+
+ def _hooks(self, robot_id: str) -> list[dict[str, Any]]:
+ return next(
+ self.client.paginate(
+ self._path(robot_id),
+ paginator=SinglePagePaginator(),
+ data_selector="webhooks.items",
+ data_selector_required=True,
+ )
+ )
+
+ @staticmethod
+ def _matches(url: str, webhook_url: str) -> bool:
+ parsed = urlsplit(url)
+ expected = urlsplit(webhook_url)
+ return (parsed.scheme, parsed.netloc, parsed.path) == (expected.scheme, expected.netloc, expected.path)
+
+ def create(self, webhook_url: str) -> WebhookCreationResult:
+ robots = self._robots()
+ if not robots:
+ return WebhookCreationResult(success=False, error="Create a Browse AI robot before enabling webhooks.")
+ existing = {robot["id"]: self._hooks(robot["id"]) for robot in robots}
+ tokens = {
+ token
+ for hooks in existing.values()
+ for hook in hooks
+ if self._matches(hook["url"], webhook_url) and hook["webhookEvent"] == "taskFinished"
+ for token in parse_qs(urlsplit(hook["url"]).query).get("token", [])
+ }
+ if len(tokens) > 1:
+ return WebhookCreationResult(
+ success=False, error="Delete the existing Browse AI webhooks and reconnect them."
+ )
+ token = next(iter(tokens), secrets.token_urlsafe(32))
+ parsed = urlsplit(webhook_url)
+ query = parse_qs(parsed.query)
+ query["token"] = [token]
+ signed_url = urlunsplit(parsed._replace(query=urlencode(query, doseq=True)))
+ with make_tracked_session(redact_values=(self.api_key, token)) as session:
+ session.auth = BearerTokenAuth(self.api_key)
+ for robot in robots:
+ if any(
+ hook["url"] == signed_url and hook["webhookEvent"] == "taskFinished"
+ for hook in existing[robot["id"]]
+ ):
+ continue
+ response = session.post(
+ f"{BASE_URL}/{self._path(robot['id'])}",
+ json={"hookUrl": signed_url, "eventType": "taskFinished"},
+ timeout=30,
+ )
+ response.raise_for_status()
+ return WebhookCreationResult(success=True, extra_inputs={"webhook_token": token})
+
+ def info(self, webhook_url: str) -> ExternalWebhookInfo:
+ robots = self._robots()
+ matches = {
+ robot["id"]: [
+ hook
+ for hook in self._hooks(robot["id"])
+ if self._matches(hook["url"], webhook_url)
+ and hook["webhookEvent"] == "taskFinished"
+ and parse_qs(urlsplit(hook["url"]).query).get("token")
+ ]
+ for robot in robots
+ }
+ exists = any(matches.values())
+ return ExternalWebhookInfo(
+ exists=exists,
+ url=webhook_url if exists else None,
+ enabled_events=["taskFinished"] if exists else [],
+ status="active" if robots and all(matches.values()) else "incomplete",
+ )
+
+ def delete(self, webhook_url: str) -> WebhookDeletionResult:
+ with make_tracked_session(redact_values=(self.api_key,)) as session:
+ session.auth = BearerTokenAuth(self.api_key)
+ for robot in self._robots():
+ for hook in self._hooks(robot["id"]):
+ if not self._matches(hook["url"], webhook_url):
+ continue
+ response = session.delete(f"{BASE_URL}/{self._path(robot['id'])}/{UUID(hook['id'])}", timeout=30)
+ if response.status_code != 404:
+ response.raise_for_status()
+ return WebhookDeletionResult(success=True)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/canonical_descriptions.py
new file mode 100644
index 000000000000..183c94e707d7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/canonical_descriptions.py
@@ -0,0 +1,57 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "robots": {
+ "description": "Trained robots that extract website data or monitor pages for changes.",
+ "docs_url": "https://docs.browse.ai/api",
+ "columns": {
+ "id": "Robot identifier.",
+ "name": "Robot name.",
+ "createdAt": "When the robot was created, converted from Unix milliseconds to UTC.",
+ "inputParameters": "Inputs accepted by the robot when starting a task.",
+ },
+ },
+ "tasks": {
+ "description": "Robot executions with their status and captured data. Large results can be represented by temporary download links.",
+ "docs_url": "https://docs.browse.ai/api",
+ "columns": {
+ "id": "Task identifier.",
+ "robotId": "Robot that executed the task.",
+ "createdAt": "When the task was created, converted from Unix milliseconds to UTC.",
+ "finishedAt": "Task completion time in Unix milliseconds, or null while running.",
+ "status": "Whether the task succeeded, failed, or is still running.",
+ "capturedTexts": "Named text values extracted by the robot.",
+ "capturedLists": "Named lists of rows extracted by the robot.",
+ "capturedScreenshots": "Screenshots captured during the task.",
+ "capturedDataTemporaryUrl": "Expiring download link used when captured data exceeds 100 KB.",
+ "robotBulkRunId": "Bulk run that started the task, when applicable.",
+ "runByTaskMonitorId": "Monitor that started the task, when applicable.",
+ },
+ },
+ "monitors": {
+ "description": "Scheduled robot runs with their inputs, notification settings, and active or paused status.",
+ "docs_url": "https://docs.browse.ai/api",
+ "columns": {
+ "id": "Monitor identifier.",
+ "robotId": "Robot whose monitor list contains this row.",
+ "createdAt": "When the monitor was created, converted from Unix milliseconds to UTC.",
+ "status": "Whether the monitor is active or paused.",
+ "pausedReason": "Reason the monitor was paused.",
+ "inputParameters": "Inputs supplied to scheduled runs.",
+ },
+ },
+ "bulk_runs": {
+ "description": "Groups of tasks started together with execution status and success and failure counts.",
+ "docs_url": "https://docs.browse.ai/api",
+ "columns": {
+ "id": "Bulk run identifier.",
+ "robotId": "Robot used for the bulk run.",
+ "createdAt": "When the bulk run was created, converted from Unix milliseconds to UTC.",
+ "tasksCount": "Number of tasks in the bulk run.",
+ "successfulTasks": "Number of tasks that succeeded.",
+ "failedTasks": "Number of tasks that failed.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/settings.py
new file mode 100644
index 000000000000..dcf0ad2287eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/settings.py
@@ -0,0 +1,70 @@
+from dataclasses import field
+from typing import Any
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField
+
+BASE_URL = "https://api.browse.ai/v2"
+AUTH_ERROR = "Your Browse AI API key is invalid or expired. Generate a new key and reconnect."
+PERMISSION_ERROR = "Your Browse AI API key cannot access this resource. Check the key's permissions and reconnect."
+
+
+@frozen
+class BrowseAIEndpoint:
+ name: str
+ path: str
+ data_selector: str
+ primary_keys: tuple[str, ...]
+ pagination_path: str | None = None
+ params: dict[str, Any] = field(default_factory=dict)
+ partition_key: str = "createdAt"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ page_size: int = 10
+ fanout: DependentEndpointConfig | None = None
+
+
+def robot_fanout() -> DependentEndpointConfig:
+ return DependentEndpointConfig(
+ parent_name="robots",
+ resolve_param="robot_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "robotId"},
+ )
+
+
+ENDPOINTS = {
+ "robots": BrowseAIEndpoint(name="robots", path="robots", data_selector="robots.items", primary_keys=("id",)),
+ "tasks": BrowseAIEndpoint(
+ name="tasks",
+ path="robots/{robot_id}/tasks",
+ data_selector="result.robotTasks.items",
+ primary_keys=("robotId", "id"),
+ pagination_path="result.robotTasks",
+ params={"pageSize": 10, "sort": "createdAt", "includeRetried": "true"},
+ fanout=robot_fanout(),
+ ),
+ "monitors": BrowseAIEndpoint(
+ name="monitors",
+ path="robots/{robot_id}/monitors",
+ data_selector="monitors.items",
+ primary_keys=("robotId", "id"),
+ fanout=robot_fanout(),
+ ),
+ "bulk_runs": BrowseAIEndpoint(
+ name="bulk_runs",
+ path="robots/{robot_id}/bulk-runs",
+ data_selector="result.items",
+ primary_keys=("robotId", "id"),
+ pagination_path="result",
+ fanout=robot_fanout(),
+ ),
+}
+
+# Creation-time filtering needs a live-account check before it can safely advance a task watermark.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/source.py
index 5cc050d00f63..dc34f5e51f57 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/source.py
@@ -1,8 +1,45 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.browse_ai import (
+ BrowseAIResumeConfig,
+ BrowseAIWebhooks,
+ browse_ai_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.settings import (
+ AUTH_ERROR,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PERMISSION_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.browseai import (
BrowseAISourceConfig,
)
@@ -10,7 +47,12 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BrowseAISource(SimpleSource[BrowseAISourceConfig]):
+class BrowseAISource(ResumableSource[BrowseAISourceConfig, BrowseAIResumeConfig], WebhookSource[BrowseAISourceConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://docs.browse.ai/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BROWSEAI
@@ -22,7 +64,155 @@ class BrowseAISource(SimpleSource[BrowseAISourceConfig]):
category=DataWarehouseSourceCategory.ANALYTICS,
label="Browse AI",
iconPath="/static/services/browse_ai.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/browse-ai",
keywords=["web scraping", "data extraction", "monitoring", "automation"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption="Enter an API key from your [Browse AI dashboard](https://dashboard.browse.ai/api). "
+ "Task results remain nested. Results above 100 KB may contain temporary download links instead of captured data.",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ placeholder="",
+ required=True,
+ secret=True,
+ )
+ ],
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="webhook_token",
+ label="Webhook token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ placeholder="",
+ required=True,
+ secret=True,
+ )
+ ],
+ ),
+ webhookSetupCaption="Connect webhooks again after adding robots to Browse AI. Each connection registers task completion events on your current robots.",
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_schemas(
+ self,
+ config: BrowseAISourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, supports_webhooks={"tasks"})
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.canonical_descriptions import ( # noqa: PLC0415 - load descriptions only when enrichment needs them
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def validate_credentials(
+ self,
+ config: BrowseAISourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name not in ENDPOINTS:
+ return False, f"Unknown Browse AI schema: {schema_name}"
+ return validate_credentials(config.api_key)
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.browse.ai": AUTH_ERROR,
+ "403 Client Error: Forbidden for url: https://api.browse.ai": PERMISSION_ERROR,
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BrowseAIResumeConfig]:
+ return ResumableSourceManager(inputs, BrowseAIResumeConfig)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def source_for_pipeline(
+ self,
+ config: BrowseAISourceConfig,
+ resumable_source_manager: ResumableSourceManager[BrowseAIResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return browse_ai_source(
+ config.api_key, inputs, resumable_source_manager, self.get_webhook_source_manager(inputs)
+ )
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return {"tasks": "task"}
+
+ def create_webhook(
+ self,
+ config: BrowseAISourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> WebhookCreationResult:
+ return BrowseAIWebhooks(config.api_key).create(webhook_url)
+
+ def delete_webhook(
+ self,
+ config: BrowseAISourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> WebhookDeletionResult:
+ return BrowseAIWebhooks(config.api_key).delete(webhook_url)
+
+ def get_external_webhook_info(
+ self,
+ config: BrowseAISourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> ExternalWebhookInfo:
+ return BrowseAIWebhooks(config.api_key).info(webhook_url)
+
+ @property
+ def webhook_template(self) -> HogFunctionTemplateDC:
+ return HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-browse-ai",
+ name="Browse AI warehouse source webhook",
+ description="Receive Browse AI task completion events for data warehouse ingestion",
+ icon_url="/static/services/browse_ai.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""
+if (request.method != 'POST') {
+ return {'httpResponse': {'status': 405, 'body': 'Method not allowed'}}
+}
+if (empty(inputs.webhook_token) or request.query.token != inputs.webhook_token) {
+ return {'httpResponse': {'status': 401, 'body': 'Invalid webhook token'}}
+}
+if (request.body.event not in ['task.finishedSuccessfully', 'task.finishedWithError', 'task.capturedDataChanged']) {
+ return {'httpResponse': {'status': 200, 'body': 'Event ignored'}}
+}
+if (empty(request.body.task.id) or empty(request.body.task.robotId)) {
+ return {'httpResponse': {'status': 400, 'body': 'Missing task identifiers'}}
+}
+let schemaId := inputs.schema_mapping?.task
+if (not empty(schemaId)) {
+ produceToWarehouseWebhooks({'task': request.body.task}, schemaId)
+}
+""",
+ inputs_schema=[
+ {"type": "string", "key": "webhook_token", "label": "Webhook token", "required": True, "secret": True},
+ {"type": "json", "key": "schema_mapping", "label": "Schema mapping", "required": True, "hidden": True},
+ {"type": "string", "key": "source_id", "label": "Source ID", "required": True, "hidden": True},
+ ],
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai.py
new file mode 100644
index 000000000000..258c77610387
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai.py
@@ -0,0 +1,235 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import AsyncMock, Mock, patch
+
+import pyarrow as pa
+import requests_mock
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.browse_ai import (
+ BrowseAIResumeConfig,
+ browse_ai_source,
+ validate_credentials,
+ webhook_table,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.settings import BASE_URL
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClient,
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+
+
+def sync_items(response: SourceResponse) -> Iterable[Any]:
+ items = response.items()
+ assert isinstance(items, Iterable)
+ return items
+
+
+def inputs() -> SourceInputs:
+ return SourceInputs(
+ schema_name="tasks",
+ schema_id="schema",
+ source_id="source",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job",
+ logger=Mock(),
+ reset_pipeline=False,
+ )
+
+
+def manager() -> Mock:
+ return Mock(can_resume=Mock(return_value=False))
+
+
+def webhook_manager() -> Mock:
+ return Mock(webhook_enabled=AsyncMock(return_value=False))
+
+
+def task_page(items: list[dict[str, Any]], has_more: bool) -> dict[str, Any]:
+ return {"result": {"robotTasks": {"items": items, "hasMore": has_more}}}
+
+
[email protected]("endpoint,envelope", [("tasks", "result.robotTasks"), ("bulk_runs", "result")])
+def test_pages_fan_out_and_resume_after_yield(
+ inputs: SourceInputs,
+ manager: Mock,
+ webhook_manager: Mock,
+ endpoint: str,
+ envelope: str,
+) -> None:
+ inputs.schema_name = endpoint
+ inputs.db_incremental_field_last_value = 9999999999999
+ child_path = "tasks" if endpoint == "tasks" else "bulk-runs"
+
+ def page(identifier: str, more: bool) -> dict[str, Any]:
+ body: dict[str, Any] = {
+ "items": [{"id": identifier, "createdAt": 1700000000123, "capturedLists": {"products": [{"price": "10"}]}}],
+ "hasMore": more,
+ }
+ for key in reversed(envelope.split(".")):
+ body = {key: body}
+ return body
+
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": "r1"}, {"id": "r2"}]}})
+ http.get(
+ f"{BASE_URL}/robots/r1/{child_path}", [{"json": page("same-id", True)}, {"json": page("second", False)}]
+ )
+ http.get(f"{BASE_URL}/robots/r2/{child_path}", json=page("same-id", False))
+ response = browse_ai_source("fake-key", inputs, manager, webhook_manager)
+ rows = iter(sync_items(response))
+ first = next(rows)
+ manager.save_state.assert_not_called()
+ second = next(rows)
+ saved = manager.save_state.call_args.args[0].paginator_state
+ assert saved == {"completed": [], "current": f"robots/r1/{child_path}", "child_state": {"page": 2}}
+ remaining = list(rows)
+ assert [first[0]["id"], second[0]["id"], remaining[0][0]["id"]] == ["same-id", "second", "same-id"]
+ assert first[0]["createdAt"] == datetime.fromtimestamp(1700000000.123, UTC)
+ assert first[0]["capturedLists"] == {"products": [{"price": "10"}]}
+ assert [first[0]["robotId"], remaining[0][0]["robotId"]] == ["r1", "r2"]
+ assert response.primary_keys == ["robotId", "id"]
+ assert [request.qs["page"] for request in http.request_history[1:]] == [["1"], ["2"], ["1"]]
+ for request in http.request_history:
+ assert request.headers["Authorization"] == "Bearer fake-key"
+ assert "fromdate" not in request.qs
+ if endpoint == "tasks":
+ assert all(request.qs["pagesize"] == ["10"] for request in http.request_history[1:])
+ assert all(request.qs["sort"] == ["createdat"] for request in http.request_history[1:])
+ else:
+ assert all("pagesize" not in request.qs for request in http.request_history)
+
+
+def test_resume_skips_completed_robot_and_resumes_child_page(
+ inputs: SourceInputs, manager: Mock, webhook_manager: Mock
+) -> None:
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = BrowseAIResumeConfig(
+ paginator_state={
+ "completed": ["robots/r1/tasks"],
+ "current": "robots/r2/tasks",
+ "child_state": {"page": 3},
+ }
+ )
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": "r1"}, {"id": "r2"}, {"id": "r3"}]}})
+ http.get(f"{BASE_URL}/robots/r2/tasks", json=task_page([{"id": "last"}], False))
+ http.get(f"{BASE_URL}/robots/r3/tasks", json=task_page([], False))
+ assert list(sync_items(browse_ai_source("fake-key", inputs, manager, webhook_manager))) == [
+ [{"id": "last", "robotId": "r2"}]
+ ]
+ assert [request.qs.get("page") for request in http.request_history] == [None, ["3"], ["1"]]
+ assert manager.save_state.call_args.args[0].paginator_state["completed"] == [
+ "robots/r1/tasks",
+ "robots/r2/tasks",
+ "robots/r3/tasks",
+ ]
+
+
[email protected]("endpoint", ["robots", "monitors"])
+def test_unpaginated_lists_and_empty_results(
+ inputs: SourceInputs, manager: Mock, webhook_manager: Mock, endpoint: str
+) -> None:
+ inputs.schema_name = endpoint
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": "r1"}]}})
+ if endpoint == "monitors":
+ http.get(f"{BASE_URL}/robots/r1/monitors", json={"monitors": {"items": []}})
+ rows = list(sync_items(browse_ai_source("fake-key", inputs, manager, webhook_manager)))
+ assert rows == ([[{"id": "r1"}]] if endpoint == "robots" else [])
+ assert all(request.qs == {} for request in http.request_history)
+
+
[email protected]("body", [{"unexpected": []}, {"result": {"robotTasks": {"items": [], "hasMore": "false"}}}])
+def test_malformed_response_fails_instead_of_erasing_table(
+ inputs: SourceInputs, manager: Mock, webhook_manager: Mock, body: dict[str, Any]
+) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": "r1"}]}})
+ http.get(f"{BASE_URL}/robots/r1/tasks", json=body)
+ with pytest.raises(ValueError):
+ list(sync_items(browse_ai_source("fake-key", inputs, manager, webhook_manager)))
+
+
+ "status,expected", [(200, (True, None)), (401, (False, "invalid or expired")), (403, (False, "permissions"))]
+)
+def test_credential_status_messages(status: int, expected: tuple[bool, str | None]) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", status_code=status, json={"robots": {"items": []}})
+ success, message = validate_credentials("fake-key")
+ expected_success, expected_message = expected
+ assert success == expected_success
+ if expected_message is None:
+ assert message is None
+ else:
+ assert message is not None
+ assert expected_message in message
+
+
+ "status,error_type,attempts",
+ [(401, HTTPError, 1), (403, HTTPError, 1), (429, RESTClientRetryableError, 5), (503, RESTClientRetryableError, 5)],
+)
+def test_http_failure_classification(status: int, error_type: type[Exception], attempts: int) -> None:
+ with requests_mock.Mocker() as http, patch.object(RESTClient._send_request.retry, "sleep"): # type: ignore[attr-defined]
+ http.get(f"{BASE_URL}/robots", status_code=status, json={"messageCode": "test_error"})
+ with pytest.raises(error_type):
+ validate_credentials("fake-key") if status not in (401, 403) else next(
+ RESTClient(base_url=BASE_URL).paginate("robots")
+ )
+ assert http.call_count == attempts
+
+
+def test_webhook_rows_deduplicate_by_robot_and_keep_latest_result() -> None:
+ rows = [
+ {
+ "task": {
+ "id": "same",
+ "robotId": robot,
+ "createdAt": 1700000000123,
+ "finishedAt": finished,
+ "capturedTexts": {"value": value},
+ }
+ }
+ for robot, finished, value in [("r1", 30, "new"), ("r1", 20, "old"), ("r2", 10, "other")]
+ ]
+ result = webhook_table(pa.Table.from_pylist(rows)).to_pylist()
+ assert [(row["robotId"], row["finishedAt"]) for row in result] == [("r1", 30), ("r2", 10)]
+ assert result[0]["createdAt"] == datetime.fromtimestamp(1700000000.123, UTC)
+
+
+def test_webhook_mode_uses_buffer_without_polling(inputs: SourceInputs, manager: Mock, webhook_manager: Mock) -> None:
+ webhook_manager.webhook_enabled.return_value = True
+ response = browse_ai_source("fake-key", inputs, manager, webhook_manager)
+ assert response.items() is webhook_manager.get_items.return_value
+ manager.can_resume.assert_not_called()
+ assert not response.supports_resume
+
+
+def test_empty_intermediate_page_advances(inputs: SourceInputs, manager: Mock, webhook_manager: Mock) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": "r1"}]}})
+ http.get(
+ f"{BASE_URL}/robots/r1/tasks",
+ [
+ {"json": task_page([], True)},
+ {"json": task_page([{"id": "t1"}], False)},
+ ],
+ )
+ assert list(sync_items(browse_ai_source("fake-key", inputs, manager, webhook_manager))) == [
+ [{"id": "t1", "robotId": "r1"}]
+ ]
+ assert [request.qs["page"] for request in http.request_history[1:]] == [["1"], ["2"]]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai_source.py
new file mode 100644
index 000000000000..6ff4050bb801
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/browse_ai/tests/test_browse_ai_source.py
@@ -0,0 +1,155 @@
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import Mock
+
+import requests_mock
+
+from posthog.cdp.validation import compile_hog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.settings import BASE_URL
+from products.warehouse_sources.backend.temporal.data_imports.sources.browse_ai.source import BrowseAISource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.browseai import (
+ BrowseAISourceConfig,
+)
+
+from common.hogvm.python.execute import execute_bytecode
+
+ROBOT = "00000000-0000-4000-8000-000000000001"
+SECOND_ROBOT = "00000000-0000-4000-8000-000000000002"
+HOOK = "00000000-0000-4000-8000-000000000003"
+CALLBACK = "https://example.com/webhook/warehouse"
+
+
+def test_invalid_schema_is_rejected_without_http() -> None:
+ source = BrowseAISource()
+ config = BrowseAISourceConfig(api_key="fake-key")
+ assert source.validate_credentials(config, 1, "missing") == (False, "Unknown Browse AI schema: missing")
+ with pytest.raises(ValueError, match="Unknown Browse AI schema"):
+ source.source_for_pipeline(config, Mock(), Mock(schema_name="missing"))
+
+
+def test_webhooks_create_idempotently_across_robots_and_delete_only_this_callback() -> None:
+ source = BrowseAISource()
+ config = BrowseAISourceConfig(api_key="fake-key")
+ hooks: dict[str, list[dict[str, Any]]] = {ROBOT: [], SECOND_ROBOT: []}
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": ROBOT}, {"id": SECOND_ROBOT}]}})
+ for robot in hooks:
+ path = f"{BASE_URL}/robots/{robot}/webhooks"
+
+ def list_hooks(request: Any, context: Any, robot_id: str = robot) -> dict[str, Any]:
+ return {"webhooks": {"items": hooks[robot_id]}}
+
+ def create_hook(request: Any, context: Any, robot_id: str = robot) -> dict[str, Any]:
+ payload = request.json()
+ hooks[robot_id].append({"id": HOOK, "url": payload["hookUrl"], "webhookEvent": payload["eventType"]})
+ return {"result": hooks[robot_id][-1]}
+
+ http.get(path, json=list_hooks)
+ http.post(path, json=create_hook)
+ http.delete(f"{path}/{HOOK}", status_code=204)
+
+ created = source.create_webhook(config, CALLBACK, 1)
+ assert created.success
+ token = created.extra_inputs["webhook_token"]
+ assert len(token) >= 32
+ assert all(parse_qs(urlsplit(items[0]["url"]).query)["token"] == [token] for items in hooks.values())
+ again = source.create_webhook(config, CALLBACK, 1)
+ assert again.extra_inputs == created.extra_inputs
+ assert len([request for request in http.request_history if request.method == "POST"]) == 2
+ info = source.get_external_webhook_info(config, CALLBACK, 1)
+ assert info.exists and info.status == "active"
+ hooks[ROBOT].append(
+ {"id": "leave-alone", "url": "https://example.com/another-webhook", "webhookEvent": "taskFinished"}
+ )
+ assert source.delete_webhook(config, CALLBACK, 1).success
+ deletes = [request.url for request in http.request_history if request.method == "DELETE"]
+ assert len(deletes) == 2
+ assert all(url.endswith(HOOK) for url in deletes)
+
+
[email protected]("robot_ids", [[], [ROBOT]])
+def test_webhook_status_reports_missing_or_incomplete_subscriptions(robot_ids: list[str]) -> None:
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": value} for value in robot_ids]}})
+ http.get(f"{BASE_URL}/robots/{ROBOT}/webhooks", json={"webhooks": {"items": []}})
+ source = BrowseAISource()
+ config = BrowseAISourceConfig(api_key="fake-key")
+ info = source.get_external_webhook_info(config, CALLBACK, 1)
+ assert not info.exists
+ assert info.status == "incomplete"
+ if not robot_ids:
+ result = source.create_webhook(config, CALLBACK, 1)
+ assert not result.success
+ assert result.error == "Create a Browse AI robot before enabling webhooks."
+
+
[email protected](scope="module")
+def webhook_bytecode() -> list[Any]:
+ template = BrowseAISource().webhook_template
+ return compile_hog(template.code, template.type)
+
+
+ "method,token,event,task,mapped,status,deliver",
+ [
+ ("POST", "fake-token", "task.finishedSuccessfully", {"id": "t1", "robotId": ROBOT}, True, None, True),
+ ("POST", "fake-token", "task.finishedWithError", {"id": "t1", "robotId": ROBOT}, True, None, True),
+ ("POST", "wrong", "task.finishedSuccessfully", {"id": "t1", "robotId": ROBOT}, True, 401, False),
+ ("POST", None, "task.finishedSuccessfully", {"id": "t1", "robotId": ROBOT}, True, 401, False),
+ ("GET", "fake-token", "task.finishedSuccessfully", {"id": "t1", "robotId": ROBOT}, True, 405, False),
+ ("POST", "fake-token", "unknown", {"id": "t1", "robotId": ROBOT}, True, 200, False),
+ ("POST", "fake-token", "task.finishedSuccessfully", {}, True, 400, False),
+ ("POST", "fake-token", "task.finishedSuccessfully", {"id": "t1", "robotId": ROBOT}, False, None, False),
+ ],
+)
+def test_webhook_authentication_and_routing(
+ webhook_bytecode: list[Any],
+ method: str,
+ token: str | None,
+ event: str,
+ task: dict[str, Any],
+ mapped: bool,
+ status: int | None,
+ deliver: bool,
+) -> None:
+ produce = Mock()
+ result = execute_bytecode(
+ webhook_bytecode,
+ {
+ "request": {"method": method, "query": {"token": token}, "body": {"event": event, "task": task}},
+ "inputs": {
+ "webhook_token": "fake-token",
+ "schema_mapping": {BrowseAISource().webhook_resource_map["tasks"]: "schema-1"} if mapped else {},
+ },
+ },
+ functions={"produceToWarehouseWebhooks": produce},
+ )
+ if status:
+ assert result.result["httpResponse"]["status"] == status
+ if deliver:
+ produce.assert_called_once_with({"task": task}, "schema-1")
+ else:
+ produce.assert_not_called()
+
+
+def test_conflicting_webhook_tokens_fail_without_creating_more_hooks() -> None:
+ with requests_mock.Mocker() as http:
+ http.get(f"{BASE_URL}/robots", json={"robots": {"items": [{"id": ROBOT}]}})
+ http.get(
+ f"{BASE_URL}/robots/{ROBOT}/webhooks",
+ json={
+ "webhooks": {
+ "items": [
+ {"id": str(index), "url": f"{CALLBACK}?token=fake-{index}", "webhookEvent": "taskFinished"}
+ for index in range(2)
+ ]
+ }
+ },
+ )
+ result = BrowseAISource().create_webhook(BrowseAISourceConfig(api_key="fake-key"), CALLBACK, 1)
+ assert not result.success
+ assert result.error == "Delete the existing Browse AI webhooks and reconnect them."
+ assert all(request.method == "GET" for request in http.request_history)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/browseai.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/browseai.py
index bbede694bdaf..45aeb6e1bb17 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/browseai.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/browseai.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class BrowseAISourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
index b331f2da209d..dbb182bc9b6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
@@ -54,7 +54,6 @@ SOURCES_WITHOUT_AN_ICON_FILE = {
"Appwrite",
"Backblaze",
"Baseten",
- "BrowseAI",
"BrowserUse",
"Cohere",
"DenoDeploy",