:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the Lovable source (#89088)
Tom Owersfd3b7b9a49cb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 99b8f094f93e..5b19d176af98 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -435,6 +435,7 @@ the row lists both.| logz_io | HTTP | requests | ✅ || loop_returns | HTTP | requests + `rest_source.RESTClient` | ✅ || loops | HTTP | requests + `rest_source.RESTClient` | ✅ |+| lovable | HTTP | requests + `rest_source.RESTClient` | ✅ || luma | HTTP | requests | ✅ || mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ || marketo | HTTP | requests | ✅ |@@ -1159,7 +1160,6 @@ doesn't conflict with concurrent PRs.- logrocket- lokalise- looker-- lovable- m3ter- mailtrap- mantlediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lovable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lovable.pyindex 43edafa6ec9f..278f73d62679 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lovable.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/lovable.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass LovableSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/canonical_descriptions.pynew file mode 100644index 000000000000..abcc5f4f5cb1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/canonical_descriptions.py@@ -0,0 +1,138 @@+"""Canonical, documentation-sourced descriptions for Lovable endpoints and columns.++Sourced from the Lovable API v1 reference (https://api.lovable.dev/v1/docs). Keyed by the resource+names in `settings.py` `LOVABLE_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced+Lovable table. Columns absent here fall back to LLM enrichment.+"""++from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://api.lovable.dev/v1/docs"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Workspaces": {+ "description": "A Lovable workspace the API key's owner belongs to, and the container for its projects, members, and credits.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Workspace ID.",+ "name": "Workspace display name.",+ "description": "Workspace description.",+ "plan": "Plan tier: free, pro, business, or enterprise.",+ "num_projects": "Number of projects in the workspace.",+ "image_url": "Workspace image URL.",+ "membership": "The API key owner's membership in this workspace.",+ "created_at": "When the workspace was created.",+ "updated_at": "When the workspace was last updated.",+ },+ },+ "Projects": {+ "description": "An app built in Lovable, listed per workspace.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Project ID.",+ "workspace_id": "Workspace the project belongs to.",+ "user_id": "Project owner user ID.",+ "name": "Project slug.",+ "display_name": "Human-readable project name.",+ "description": "Description supplied by the caller on create or update.",+ "generated_description": "AI-written summary of what the project does. Absent until the agent has completed a response for the project.",+ "project_type": "Project type: project or library.",+ "tech_stack": "Project tech stack.",+ "status": "Provisioning status of the project scaffold, not agent build progress: in_progress, completed, or failed.",+ "visibility": "Project visibility: draft, private, workspace_view, or public.",+ "is_published": "Whether the project is published.",+ "publish_visibility": "Published visibility: public or private.",+ "url": "Published project URL.",+ "folder_id": "Folder the project belongs to, if any.",+ "latest_screenshot_url": "URL of the latest screenshot.",+ "og_image_url": "Open Graph image URL.",+ "last_edited_at": "When the project was last edited.",+ "created_at": "When the project was created.",+ "updated_at": "When the project was last updated.",+ },+ },+ "WorkspaceMembers": {+ "description": "A member of a Lovable workspace, including pending invites.",+ "docs_url": _DOCS_URL,+ "columns": {+ "workspace_id": "Workspace the membership belongs to.",+ "user_id": "Stable identifier for the entry: the user ID for active members, the membership row ID for pending invites.",+ "display_name": "User display name as stored on the membership.",+ "email": "Member email as stored on the membership. For pending invites this is the invited email.",+ "role": "Workspace role: owner, admin, member, viewer, or collaborator.",+ "monthly_credit_limit": "Explicit monthly credit cap for this member. Absent when the workspace default applies.",+ "invited_at": "When the user was invited.",+ "joined_at": "When the user accepted the invitation. Absent on pending invites.",+ },+ },+ "WorkspaceCreditHistory": {+ "description": "One entry in a workspace's credit ledger: a grant, expiry, adjustment, or conversion.",+ "docs_url": _DOCS_URL,+ "columns": {+ "workspace_id": "Workspace the entry belongs to.",+ "id": "Stable ledger entry ID.",+ "credits_change": "Signed change in Lovable credits: positive for grants, negative for expiries and debits.",+ "event_type": "What happened to the credits.",+ "grant_type": "Credit bucket this entry affected.",+ "label": "Human-readable summary of the entry.",+ "occurred_at": "When the entry occurred.",+ },+ },+ "ProjectCollaborators": {+ "description": "A user with direct access to one project, whether or not they are a member of its workspace.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Project the access grant belongs to.",+ "workspace_id": "Workspace the project belongs to.",+ "user_id": "User ID of the collaborator.",+ "display_name": "Display name, falling back to the email when the user has not set one.",+ "email": "Email address of the collaborator.",+ "access_level": "Access level: owner, admin, write, or read.",+ "is_workspace_member": "Whether the collaborator is a member of the project's workspace. False marks an ad-hoc collaborator with no broader workspace access.",+ "is_internal": "Whether the collaborator is internal to the workspace, by membership or by a workspace-verified email domain.",+ "invited_by": "User ID of the inviter. Empty for the project owner.",+ "invited_at": "When the user was invited to the project. Null for the project owner.",+ "accepted_at": "When the user accepted the project invitation. Null while the invite is pending.",+ },+ },+ "ProjectSecurityScans": {+ "description": "One security scan invocation against a project.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Project that was scanned.",+ "workspace_id": "Workspace the project belongs to.",+ "scan_id": "Unique scan invocation ID.",+ "status": "Scan status: running, completed, or failed.",+ "trigger_source": "What triggered the scan, such as workflow, user, ui_auto, or workspace_scheduled.",+ "triggered_by": "Actor that triggered the scan.",+ "requested_scanners": "Scanners requested for this invocation.",+ "commit_sha": "Project commit at scan start.",+ "started_at": "When the scan started.",+ "finished_at": "When the scan finished.",+ },+ },+ "ProjectPiiLabels": {+ "description": "A piece of personal data Lovable's scanners detected in a project.",+ "docs_url": _DOCS_URL,+ "columns": {+ "project_id": "Project the label belongs to.",+ "workspace_id": "Workspace the project belongs to.",+ "id": "PII label ID.",+ "source": "Where the PII was detected: chat, upload, cloud_storage, or cloud_sql.",+ "info_type": "DLP info type, such as EMAIL_ADDRESS.",+ "likelihood": "DLP likelihood: VERY_UNLIKELY, UNLIKELY, POSSIBLE, LIKELY, or VERY_LIKELY.",+ "sensitivity": "Sensitivity bucket: low, mid, or high.",+ "status": "Label status: open, ignored, or fixed.",+ "quote": "Masked sample of the detected value.",+ "scan_id": "Scan run that recorded the label.",+ "chat_message_id": "Trajectory event ID, for chat-source labels.",+ "chat_upload_id": "Uploaded file ID, for upload-source labels.",+ "connector_id": "Connector ID, for connector labels.",+ "sql_location": "Database location, for cloud_sql labels.",+ "storage_path": "Cloud storage object path, for cloud_storage labels.",+ "found_at": "When the label was recorded.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/lovable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/lovable.pynew file mode 100644index 000000000000..7f8c2065717f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/lovable.py@@ -0,0 +1,282 @@+from collections.abc import Iterator+from typing import Any, Optional++from requests.exceptions import HTTPError++from posthog.dataclasses import frozen++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.auth import APIKeyAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponseCursorPaginator,+ 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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.settings import (+ LOVABLE_API_BASE_URL,+ LOVABLE_ENDPOINTS,+ LovableEndpointConfig,+)++API_KEY_HEADER = "Lovable-API-Key"++# Bounded connect/read timeout so a host that accepts the TCP connection but never responds can't+# hold an import worker indefinitely.+REQUEST_TIMEOUT_SECONDS = 30.0+++@frozen+class LovableResumeConfig:+ """Where a resumed attempt picks the fan-out back up.++ `workspace_id`/`project_id` name the parent the checkpoint belongs to (both null for the+ account-scoped endpoint). A set `cursor` means "continue that parent's pages here"; a null one+ means the parent finished, so the walk restarts at the parent after it.+ """++ workspace_id: Optional[str] = None+ project_id: Optional[str] = None+ cursor: Optional[str] = None+++@frozen+class _ParentRef:+ workspace_id: Optional[str] = None+ project_id: Optional[str] = None+++def _client(api_key: str) -> RESTClient:+ return RESTClient(+ base_url=LOVABLE_API_BASE_URL,+ headers={"Accept": "application/json"},+ auth=APIKeyAuth(api_key=api_key, name=API_KEY_HEADER, location="header"),+ # Lovable-API-Key is a custom header, which `requests` does not strip on a cross-origin+ # redirect, so pin every request to the API host instead of replaying the key elsewhere.+ allowed_hosts=[],+ allow_redirects=False,+ request_timeout=REQUEST_TIMEOUT_SECONDS,+ # capture=False: workspace, project, member, and PII-label rows carry names, emails, and+ # free-text security-finding content the generic scrubber's name-based denylist won't catch.+ capture=False,+ )+++def _paginator() -> JSONResponseCursorPaginator:+ return JSONResponseCursorPaginator(cursor_path="pagination.next_cursor", cursor_param="cursor")+++def _path(api_version: str, config: LovableEndpointConfig, parent: _ParentRef) -> str:+ return f"/{api_version}{config.path}".format(+ workspace_id=parent.workspace_id or "",+ project_id=parent.project_id or "",+ )+++def _params(config: LovableEndpointConfig, parent: _ParentRef) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": config.page_size, **config.params}+ if config.parent_id_param and parent.workspace_id:+ params[config.parent_id_param] = parent.workspace_id+ return params+++def _iter_rows(client: RESTClient, path: str, params: dict[str, Any]) -> Iterator[dict[str, Any]]:+ for page in client.paginate(path=path, params=params, paginator=_paginator(), data_selector="data"):+ yield from page+++def _iter_parents(client: RESTClient, api_version: str, config: LovableEndpointConfig) -> Iterator[_ParentRef]:+ if config.scope == "account":+ yield _ParentRef()+ return++ workspaces = LOVABLE_ENDPOINTS["Workspaces"]+ for workspace in _iter_rows(+ client, _path(api_version, workspaces, _ParentRef()), _params(workspaces, _ParentRef())+ ):+ workspace_id = workspace.get("id")+ if not workspace_id:+ continue+ if config.scope == "workspace":+ yield _ParentRef(workspace_id=workspace_id)+ continue++ projects = LOVABLE_ENDPOINTS["Projects"]+ workspace_ref = _ParentRef(workspace_id=workspace_id)+ for project in _iter_rows(+ client, _path(api_version, projects, workspace_ref), _params(projects, workspace_ref)+ ):+ project_id = project.get("id")+ if project_id:+ yield _ParentRef(workspace_id=workspace_id, project_id=project_id)+++def resume_position(parents: list[_ParentRef], resume: Optional[LovableResumeConfig]) -> tuple[int, Optional[str]]:+ """Index into `parents` to restart at, and the cursor to seed its first request with.++ Falls back to a full walk when the checkpointed parent is gone from the listing, because+ re-reading rows beats resuming past a parent that no longer lines up.+ """+ if resume is None:+ return 0, None++ checkpoint = _ParentRef(workspace_id=resume.workspace_id, project_id=resume.project_id)+ if checkpoint not in parents:+ return 0, None++ index = parents.index(checkpoint)+ return (index, resume.cursor) if resume.cursor else (index + 1, None)+++def _with_parent_ids(row: dict[str, Any], parent: _ParentRef) -> dict[str, Any]:+ """Stamp the fan-out parent onto a child row.++ Child endpoints identify rows only within their parent (a collaborator carries a `user_id`, not+ the project), so the parent id is what makes the primary key unique across the whole table.+ """+ if parent.workspace_id:+ row.setdefault("workspace_id", parent.workspace_id)+ if parent.project_id:+ row.setdefault("project_id", parent.project_id)+ return row+++def _iter_endpoint(+ client: RESTClient,+ api_version: str,+ config: LovableEndpointConfig,+ resumable_source_manager: ResumableSourceManager[LovableResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ parents = list(_iter_parents(client, api_version, config))+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index, cursor = resume_position(parents, resume)++ for index in range(start_index, len(parents)):+ parent = parents[index]++ def save_checkpoint(state: Optional[dict[str, Any]], parent: _ParentRef = parent) -> None:+ next_cursor = state.get("cursor") if state else None+ resumable_source_manager.save_state(+ LovableResumeConfig(+ workspace_id=parent.workspace_id,+ project_id=parent.project_id,+ cursor=str(next_cursor) if next_cursor else None,+ )+ )++ for page in client.paginate(+ path=_path(api_version, config, parent),+ params=_params(config, parent),+ paginator=_paginator(),+ data_selector="data",+ resume_hook=save_checkpoint,+ initial_paginator_state={"cursor": cursor} if index == start_index and cursor else None,+ ):+ if page:+ yield [_with_parent_ids(row, parent) for row in page]++ cursor = None++ # Leaving the final checkpoint behind would let a later attempt on the same job resume past+ # every parent and sync nothing.+ resumable_source_manager.clear_state()+++def lovable_source(+ api_key: str,+ api_version: str,+ endpoint: str,+ resumable_source_manager: ResumableSourceManager[LovableResumeConfig],+) -> SourceResponse:+ config = LOVABLE_ENDPOINTS[endpoint]+ client = _client(api_key)++ return SourceResponse(+ name=endpoint,+ items=lambda: _iter_endpoint(client, api_version, config, resumable_source_manager),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:+ is_valid, status_code = validate_via_probe(+ # capture=False: the probe's response body carries the caller's real account/workspace+ # details, which the generic scrubber's name-based denylist won't catch.+ lambda: make_tracked_session(redact_values=(api_key,), capture=False),+ f"{LOVABLE_API_BASE_URL}/{api_version}/me",+ headers={API_KEY_HEADER: api_key},+ # The key rides a custom header, which `requests` replays across a cross-origin redirect.+ allow_redirects=False,+ )+ if is_valid:+ return True, None+ if status_code == 401:+ return False, "Invalid Lovable API key. Create a new key in Lovable and reconnect."+ return False, "Could not connect to Lovable. Check the API key and try again."+++def _probe_status(client: RESTClient, path: str, params: dict[str, Any]) -> int | None:+ """Status of a single-row GET, or `None` when no response came back at all."""+ try:+ for _ in client.paginate(path=path, params=params, paginator=SinglePagePaginator(), data_selector="data"):+ break+ except HTTPError as error:+ return error.response.status_code if error.response is not None else None+ except Exception:+ return None+ return 200+++def _first_id(client: RESTClient, api_version: str, config: LovableEndpointConfig, parent: _ParentRef) -> str | None:+ try:+ for row in _iter_rows(client, _path(api_version, config, parent), {**_params(config, parent), "limit": 1}):+ row_id = row.get("id")+ if row_id:+ return str(row_id)+ except Exception:+ return None+ return None+++def check_endpoint_permissions(api_key: str, api_version: str, endpoints: list[str]) -> dict[str, str | None]:+ """Per-table reason the key can't read it, or `None` when it can.++ Most tables sit behind a Lovable plan tier and answer 402 below it, so probing turns a table+ that could only ever fail into one the schema picker shows as unavailable and leaves off.+ """+ client = _client(api_key)+ workspaces = LOVABLE_ENDPOINTS["Workspaces"]+ workspace_id = _first_id(client, api_version, workspaces, _ParentRef())+ # A saved schema whose endpoint left the catalog must not fail the whole schema picker.+ known = {name: LOVABLE_ENDPOINTS[name] for name in endpoints if name in LOVABLE_ENDPOINTS}+ project_id: str | None = None+ if workspace_id and any(config.scope == "project" for config in known.values()):+ project_id = _first_id(+ client, api_version, LOVABLE_ENDPOINTS["Projects"], _ParentRef(workspace_id=workspace_id)+ )++ permissions: dict[str, str | None] = dict.fromkeys(endpoints)+ for name, config in known.items():+ parent = _ParentRef(workspace_id=workspace_id, project_id=project_id)+ # No workspace or project to probe against means nothing to report, because an empty+ # account is not a permission problem.+ if (config.scope == "workspace" and not workspace_id) or (config.scope == "project" and not project_id):+ permissions[name] = None+ continue++ status = _probe_status(client, _path(api_version, config, parent), {**_params(config, parent), "limit": 1})+ if status == 402:+ plan = config.minimum_plan or "paid"+ permissions[name] = f"This table needs Lovable's {plan} plan or higher."+ elif status == 403:+ permissions[name] = "This Lovable API key does not have permission to read this table."+ else:+ permissions[name] = None+ return permissionsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/settings.pynew file mode 100644index 000000000000..ac09cedebb16--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/settings.py@@ -0,0 +1,105 @@+from dataclasses import field+from typing import Any, Literal++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField++# Where an endpoint's rows live: directly on the account, under one workspace, or under one+# project. Anything but "account" is fanned out over the parents discovered at sync time.+EndpointScope = Literal["account", "workspace", "project"]++LOVABLE_API_BASE_URL = "https://api.lovable.dev"++# Version segment prefixed onto every endpoint path. Lovable also serves a `/v1beta` channel for+# preview endpoints (audit logs, message exports); this source only calls the GA one.+LOVABLE_API_VERSION_V1 = "v1"+++@frozen+class LovableEndpointConfig:+ name: str+ path: str+ scope: EndpointScope+ primary_keys: list[str]+ # Query param carrying the parent id, for endpoints that take it that way instead of in the+ # path. Only `/projects` does, which is workspace-scoped via `?workspace_id=`.+ parent_id_param: str | None = None+ partition_key: str | None = None+ page_size: int = 100+ params: dict[str, Any] = field(default_factory=dict)+ # Lowest Lovable plan that may call the endpoint. Below it the API answers 402, so this is the+ # reason surfaced per table in the schema picker rather than a sync that can only ever fail.+ minimum_plan: str | None = None+++LOVABLE_ENDPOINTS: dict[str, LovableEndpointConfig] = {+ "Workspaces": LovableEndpointConfig(+ name="Workspaces",+ path="/workspaces",+ scope="account",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "Projects": LovableEndpointConfig(+ name="Projects",+ path="/projects",+ scope="workspace",+ parent_id_param="workspace_id",+ primary_keys=["id"],+ partition_key="created_at",+ # Both filters default to a narrowed set, so a table synced without them would silently+ # miss personal drafts and unpublished projects.+ params={"visibility": "all", "publish_status": "any"},+ ),+ "WorkspaceMembers": LovableEndpointConfig(+ name="WorkspaceMembers",+ path="/workspaces/{workspace_id}/members",+ scope="workspace",+ primary_keys=["workspace_id", "user_id"],+ partition_key="invited_at",+ page_size=50,+ # `status` defaults to "active", which drops every pending invite.+ params={"status": "all"},+ minimum_plan="Enterprise",+ ),+ "WorkspaceCreditHistory": LovableEndpointConfig(+ name="WorkspaceCreditHistory",+ path="/workspaces/{workspace_id}/billing/credit-history",+ scope="workspace",+ primary_keys=["workspace_id", "id"],+ partition_key="occurred_at",+ minimum_plan="Enterprise",+ ),+ "ProjectCollaborators": LovableEndpointConfig(+ name="ProjectCollaborators",+ path="/projects/{project_id}/collaborators",+ scope="project",+ primary_keys=["project_id", "user_id"],+ # `invited_at` is the only timestamp and it is null for the project owner, so there is no+ # stable column to partition on.+ minimum_plan="Enterprise",+ ),+ "ProjectSecurityScans": LovableEndpointConfig(+ name="ProjectSecurityScans",+ path="/projects/{project_id}/security-scans",+ scope="project",+ primary_keys=["project_id", "scan_id"],+ partition_key="started_at",+ minimum_plan="Business",+ ),+ "ProjectPiiLabels": LovableEndpointConfig(+ name="ProjectPiiLabels",+ path="/projects/{project_id}/pii-labels",+ scope="project",+ primary_keys=["project_id", "id"],+ partition_key="found_at",+ minimum_plan="Enterprise",+ ),+}++ENDPOINTS = tuple(LOVABLE_ENDPOINTS.keys())++# Every v1 list endpoint paginates by opaque cursor with no timestamp filter, so none of these+# tables can sync incrementally. A run either walks the collection or it skips rows.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/source.pyindex a7d6186097e7..e26f6fbb9256 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/source.py@@ -1,32 +1,134 @@-from typing import cast+from typing import Optional, castfrom 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.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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lovable import (LovableSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.lovable import (+ LovableResumeConfig,+ check_endpoint_permissions,+ lovable_source,+ validate_credentials as validate_lovable_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LOVABLE_API_VERSION_V1,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LovableSource(SimpleSource[LovableSourceConfig]):+class LovableSource(ResumableSource[LovableSourceConfig, LovableResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ supported_versions = (LOVABLE_API_VERSION_V1,)+ default_version = LOVABLE_API_VERSION_V1+ api_docs_url = "https://api.lovable.dev/v1/docs"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LOVABLE+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Lovable API key is invalid or has been revoked. Create a new key in Lovable and reconnect.",+ "402 Client Error": "This table needs a higher Lovable plan. Turn it off in the sync settings, or upgrade the workspace in Lovable.",+ "403 Client Error": "Your Lovable API key does not have permission to read this data. Use a key from an account with access, or turn this table off in the sync settings.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: LovableSourceConfig,+ 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)++ def validate_credentials(+ self,+ config: LovableSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_lovable_credentials(config.api_key, self.resolve_api_version(api_version))++ def get_endpoint_permissions(+ self, config: LovableSourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None+ ) -> dict[str, str | None]:+ return check_endpoint_permissions(config.api_key, self.resolve_api_version(api_version), endpoints)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LovableResumeConfig]:+ return ResumableSourceManager[LovableResumeConfig](inputs, LovableResumeConfig)++ def source_for_pipeline(+ self,+ config: LovableSourceConfig,+ resumable_source_manager: ResumableSourceManager[LovableResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return lovable_source(+ api_key=config.api_key,+ api_version=self.resolve_api_version(inputs.api_version),+ endpoint=inputs.schema_name,+ resumable_source_manager=resumable_source_manager,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.LOVABLE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Lovable",+ caption=(+ "Connect your Lovable account with an API key to sync workspaces, projects, "+ "members, credit history, and security findings. Member, collaborator, credit, and "+ "PII tables need Lovable's Enterprise plan, and security scans need Business or higher."+ ),+ keywords=["app builder"],+ docsUrl="https://posthog.com/docs/cdp/sources/lovable",iconPath="/static/services/lovable.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="lov_...",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable.pynew file mode 100644index 000000000000..90e4fd6c4eb5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable.py@@ -0,0 +1,337 @@+import json+from typing import Any++from unittest import mock++import requests+from parameterized import parameterized+from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.lovable import (+ LovableResumeConfig,+ _ParentRef,+ check_endpoint_permissions,+ lovable_source,+ resume_position,+ validate_credentials,+)++CLIENT_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client."+ "make_tracked_session"+)+PROBE_SESSION_PATCH = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.lovable.lovable.make_tracked_session"+)+++def _page(rows: list[dict[str, Any]], next_cursor: str | None = None, status_code: int = 200) -> Response:+ response = Response()+ response.status_code = status_code+ response._content = json.dumps(+ {"data": rows, "pagination": {"has_more": next_cursor is not None, "next_cursor": next_cursor}}+ ).encode()+ return response+++def _error(status_code: int, error_type: str = "payment_required") -> Response:+ response = Response()+ response.status_code = status_code+ response.url = "https://api.lovable.dev/v1/workspaces"+ response._content = json.dumps(+ {"status": status_code, "type": error_type, "title": "Nope", "request_id": "req-1"}+ ).encode()+ return response+++def _wire(session: mock.MagicMock, responses: list[Response]) -> list[str]:+ """Point a mocked session at `responses` and record the URL of every request it sends."""+ real_session = requests.Session()+ urls: list[str] = []+ session.headers = {}++ def _prepare(request: Any) -> Any:+ prepared = real_session.prepare_request(request)+ urls.append(prepared.url or "")+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return urls+++def _manager(resume_state: LovableResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _rows(source_response: Any) -> list[dict[str, Any]]:+ return [row for page in source_response.items() for row in page]+++def _run(endpoint: str, manager: mock.MagicMock | None = None) -> Any:+ return lovable_source(+ api_key="lov_key",+ api_version="v1",+ endpoint=endpoint,+ resumable_source_manager=manager or _manager(),+ )+++class TestLovableSourceTransport:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_account_endpoint_follows_the_cursor(self, mock_session: mock.MagicMock) -> None:+ urls = _wire(+ mock_session.return_value,+ [_page([{"id": "ws-1"}], next_cursor="c1"), _page([{"id": "ws-2"}])],+ )++ rows = _rows(_run("Workspaces"))++ assert [row["id"] for row in rows] == ["ws-1", "ws-2"]+ assert urls[0] == "https://api.lovable.dev/v1/workspaces?limit=100"+ assert "cursor=c1" in urls[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_workspace_endpoint_binds_the_workspace_into_the_path_and_the_row(+ self, mock_session: mock.MagicMock+ ) -> None:+ urls = _wire(+ mock_session.return_value,+ [+ _page([{"id": "ws-1"}, {"id": "ws-2"}]),+ _page([{"user_id": "u-1", "workspace_id": "ws-1"}]),+ _page([{"user_id": "u-2", "workspace_id": "ws-2"}]),+ ],+ )++ rows = _rows(_run("WorkspaceMembers"))++ assert [(row["workspace_id"], row["user_id"]) for row in rows] == [("ws-1", "u-1"), ("ws-2", "u-2")]+ assert urls[1].startswith("https://api.lovable.dev/v1/workspaces/ws-1/members?")+ assert urls[2].startswith("https://api.lovable.dev/v1/workspaces/ws-2/members?")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_members_request_asks_for_pending_invites_and_the_endpoint_page_size(+ self, mock_session: mock.MagicMock+ ) -> None:+ urls = _wire(mock_session.return_value, [_page([{"id": "ws-1"}]), _page([{"user_id": "u-1"}])])++ _rows(_run("WorkspaceMembers"))++ assert "status=all" in urls[1]+ assert "limit=50" in urls[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_projects_pass_the_workspace_as_a_query_param_with_unnarrowed_filters(+ self, mock_session: mock.MagicMock+ ) -> None:+ urls = _wire(mock_session.return_value, [_page([{"id": "ws-1"}]), _page([{"id": "p-1"}])])++ rows = _rows(_run("Projects"))++ assert [row["id"] for row in rows] == ["p-1"]+ assert urls[1].startswith("https://api.lovable.dev/v1/projects?")+ assert "workspace_id=ws-1" in urls[1]+ assert "visibility=all" in urls[1]+ assert "publish_status=any" in urls[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_project_endpoint_fans_out_through_workspaces_and_stamps_both_parents(+ self, mock_session: mock.MagicMock+ ) -> None:+ urls = _wire(+ mock_session.return_value,+ [+ _page([{"id": "ws-1"}]),+ _page([{"id": "p-1"}, {"id": "p-2"}]),+ _page([{"user_id": "u-1"}]),+ _page([{"user_id": "u-2"}]),+ ],+ )++ rows = _rows(_run("ProjectCollaborators"))++ assert [(row["workspace_id"], row["project_id"], row["user_id"]) for row in rows] == [+ ("ws-1", "p-1", "u-1"),+ ("ws-1", "p-2", "u-2"),+ ]+ assert urls[2].startswith("https://api.lovable.dev/v1/projects/p-1/collaborators?")+ assert urls[3].startswith("https://api.lovable.dev/v1/projects/p-2/collaborators?")++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_parents_without_an_id_are_skipped(self, mock_session: mock.MagicMock) -> None:+ _wire(+ mock_session.return_value,+ [_page([{"name": "no id here"}, {"id": "ws-2"}]), _page([{"user_id": "u-1"}])],+ )++ rows = _rows(_run("WorkspaceMembers"))++ assert [row["workspace_id"] for row in rows] == ["ws-2"]++ @parameterized.expand(+ [+ ("Workspaces", ["id"], "created_at"),+ ("Projects", ["id"], "created_at"),+ ("WorkspaceMembers", ["workspace_id", "user_id"], "invited_at"),+ ("WorkspaceCreditHistory", ["workspace_id", "id"], "occurred_at"),+ ("ProjectCollaborators", ["project_id", "user_id"], None),+ ("ProjectSecurityScans", ["project_id", "scan_id"], "started_at"),+ ("ProjectPiiLabels", ["project_id", "id"], "found_at"),+ ]+ )+ def test_primary_keys_and_partitioning_per_endpoint(+ self, endpoint: str, primary_keys: list[str], partition_key: str | None+ ) -> None:+ response = _run(endpoint)++ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == ([partition_key] if partition_key else None)+ assert response.partition_mode == ("datetime" if partition_key else None)+++class TestLovableResume:+ @parameterized.expand(+ [+ ("no_saved_state", None, 0, None),+ ("cursor_resumes_that_parent", LovableResumeConfig(workspace_id="ws-2", cursor="c9"), 1, "c9"),+ ("finished_parent_moves_on", LovableResumeConfig(workspace_id="ws-2"), 2, None),+ ("unknown_parent_restarts", LovableResumeConfig(workspace_id="gone", cursor="c9"), 0, None),+ ]+ )+ def test_resume_position(+ self, _name: str, resume: LovableResumeConfig | None, expected_index: int, expected_cursor: str | None+ ) -> None:+ parents = [_ParentRef(workspace_id="ws-1"), _ParentRef(workspace_id="ws-2"), _ParentRef(workspace_id="ws-3")]++ assert resume_position(parents, resume) == (expected_index, expected_cursor)++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoint_records_the_parent_and_next_cursor_then_marks_it_finished(+ self, mock_session: mock.MagicMock+ ) -> None:+ _wire(+ mock_session.return_value,+ [+ _page([{"id": "ws-1"}]),+ _page([{"user_id": "u-1"}], next_cursor="c1"),+ _page([{"user_id": "u-2"}]),+ ],+ )+ manager = _manager()++ _rows(_run("WorkspaceMembers", manager))++ assert [call.args[0] for call in manager.save_state.call_args_list] == [+ LovableResumeConfig(workspace_id="ws-1", cursor="c1"),+ LovableResumeConfig(workspace_id="ws-1", cursor=None),+ ]+ manager.clear_state.assert_called_once()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumed_run_seeds_the_cursor_and_skips_earlier_parents(self, mock_session: mock.MagicMock) -> None:+ urls = _wire(+ mock_session.return_value,+ [_page([{"id": "ws-1"}, {"id": "ws-2"}]), _page([{"user_id": "u-2"}])],+ )++ rows = _rows(_run("WorkspaceMembers", _manager(LovableResumeConfig(workspace_id="ws-2", cursor="c9"))))++ assert [row["user_id"] for row in rows] == ["u-2"]+ assert urls[1].startswith("https://api.lovable.dev/v1/workspaces/ws-2/members?")+ assert "cursor=c9" in urls[1]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_finished_parent_checkpoint_yields_nothing_more(self, mock_session: mock.MagicMock) -> None:+ _wire(mock_session.return_value, [_page([{"id": "ws-1"}])])++ rows = _rows(_run("WorkspaceMembers", _manager(LovableResumeConfig(workspace_id="ws-1"))))++ assert rows == []+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("valid", 200, True, None),+ ("bad_key", 401, False, "Invalid Lovable API key. Create a new key in Lovable and reconnect."),+ ("server_error", 500, False, "Could not connect to Lovable. Check the API key and try again."),+ ]+ )+ @mock.patch(PROBE_SESSION_PATCH)+ def test_status_maps_to_message(+ self,+ _name: str,+ status_code: int,+ expected_valid: bool,+ expected_message: str | None,+ mock_session: mock.MagicMock,+ ) -> None:+ response = Response()+ response.status_code = status_code+ mock_session.return_value.get.return_value = response++ assert validate_credentials("lov_key", "v1") == (expected_valid, expected_message)+ assert mock_session.return_value.get.call_args.args[0] == "https://api.lovable.dev/v1/me"++ @mock.patch(PROBE_SESSION_PATCH)+ def test_transport_failure_is_not_valid(self, mock_session: mock.MagicMock) -> None:+ mock_session.return_value.get.side_effect = requests.ConnectionError("nope")++ is_valid, message = validate_credentials("lov_key", "v1")++ assert is_valid is False+ assert message == "Could not connect to Lovable. Check the API key and try again."+++class TestCheckEndpointPermissions:+ @parameterized.expand(+ [+ ("plan_gated", _error(402), "This table needs Lovable's Enterprise plan or higher."),+ (+ "forbidden",+ _error(403, "forbidden"),+ "This Lovable API key does not have permission to read this table.",+ ),+ ("readable", _page([{"user_id": "u-1"}]), None),+ # An unexpected status is not a denial, so the table must not be disabled over it.+ ("unexpected_status", _error(404, "not_found"), None),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_probe_status_maps_to_a_reason(+ self, _name: str, probe_response: Response, expected_reason: str | None, mock_session: mock.MagicMock+ ) -> None:+ _wire(mock_session.return_value, [_page([{"id": "ws-1"}]), probe_response])++ assert check_endpoint_permissions("lov_key", "v1", ["WorkspaceMembers"]) == {+ "WorkspaceMembers": expected_reason+ }++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_account_with_no_workspaces_reports_no_reason(self, mock_session: mock.MagicMock) -> None:+ _wire(mock_session.return_value, [_page([])])++ assert check_endpoint_permissions("lov_key", "v1", ["WorkspaceMembers"]) == {"WorkspaceMembers": None}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_endpoint_missing_from_the_catalog_reports_no_reason(self, mock_session: mock.MagicMock) -> None:+ _wire(mock_session.return_value, [_page([{"id": "ws-1"}])])++ assert check_endpoint_permissions("lov_key", "v1", ["RetiredTable"]) == {"RetiredTable": None}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_project_scoped_table_probes_a_project(self, mock_session: mock.MagicMock) -> None:+ urls = _wire(+ mock_session.return_value,+ [_page([{"id": "ws-1"}]), _page([{"id": "p-1"}]), _error(402)],+ )++ permissions = check_endpoint_permissions("lov_key", "v1", ["ProjectSecurityScans"])++ assert permissions == {"ProjectSecurityScans": "This table needs Lovable's Business plan or higher."}+ assert urls[2].startswith("https://api.lovable.dev/v1/projects/p-1/security-scans?")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable_source.pynew file mode 100644index 000000000000..be5df1f80e11--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lovable/tests/test_lovable_source.py@@ -0,0 +1,106 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.lovable import (+ LovableSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.lovable import LovableResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.lovable.source import LovableSource++SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.lovable.source"+++class TestLovableSource:+ def setup_method(self) -> None:+ self.source = LovableSource()+ self.config = LovableSourceConfig(api_key="lov_key")++ def test_source_config_is_released_with_an_api_key_field(self) -> None:+ config = self.source.get_source_config++ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.iconPath == "/static/services/lovable.png"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.fields is not None+ assert [field.name for field in config.fields] == ["api_key"]+ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ # No v1 list endpoint takes a timestamp filter, so nothing here can sync incrementally.+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)+ assert all(schema.incremental_fields == [] for schema in schemas)++ @parameterized.expand(+ [+ ("401", "401 Client Error: Unauthorized for url: https://api.lovable.dev/v1/workspaces"),+ ("402", "402 Client Error: Payment Required for url: https://api.lovable.dev/v1/workspaces/ws-1/members"),+ ("403", "403 Client Error: Forbidden for url: https://api.lovable.dev/v1/projects/p-1/pii-labels"),+ ]+ )+ def test_non_retryable_errors_match_permanent_failures(self, _name: str, observed_error: str) -> None:+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.lovable.dev/v1/workspaces"),+ ("server_error", "HTTP 503 for https://api.lovable.dev/v1/workspaces"),+ ("timeout", "Request timed out (ConnectTimeout) for https://api.lovable.dev/v1/workspaces"),+ ]+ )+ def test_non_retryable_errors_do_not_match_transient_failures(self, _name: str, other_error: str) -> None:+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_resumable_manager_is_bound_to_the_resume_config(self) -> None:+ inputs = mock.MagicMock()+ inputs.team_id = 1+ inputs.job_id = "job-1"++ manager = self.source.get_resumable_source_manager(inputs)++ assert manager._data_class is LovableResumeConfig++ @mock.patch(f"{SOURCE_MODULE}.lovable_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_lovable_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Projects"+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_lovable_source.call_args.kwargs+ assert kwargs == {+ "api_key": "lov_key",+ "api_version": "v1",+ "endpoint": "Projects",+ "resumable_source_manager": manager,+ }++ @mock.patch(f"{SOURCE_MODULE}.validate_lovable_credentials", return_value=(True, None))+ def test_validate_credentials_resolves_the_api_version(self, mock_validate: mock.MagicMock) -> None:+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)+ assert mock_validate.call_args.args == ("lov_key", "v1")++ @mock.patch(f"{SOURCE_MODULE}.check_endpoint_permissions", return_value={"Projects": None})+ def test_endpoint_permissions_delegate_to_the_probe(self, mock_check: mock.MagicMock) -> None:+ assert self.source.get_endpoint_permissions(self.config, team_id=1, endpoints=["Projects"]) == {+ "Projects": None+ }+ assert mock_check.call_args.args == ("lov_key", "v1", ["Projects"])