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 rocketlane import source (#68568)

Tom Owers9094dff1ae13
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 3151a7a0e79e..271f508934fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -291,6 +291,7 @@ the row lists both.
| resend | HTTP | requests | ✅ |
| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| rippling | HTTP | requests | ✅ |
+| rocketlane | HTTP | requests | ✅ |
| rollbar | HTTP | requests | ✅ |
| rootly | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
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 445b8d736759..f0df77a93c67 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
@@ -2796,7 +2796,7 @@ class RocketChatSourceConfig(config.Config):
@config.config
class RocketlaneSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/canonical_descriptions.py
new file mode 100644
index 000000000000..81cf2ee653ad
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/canonical_descriptions.py
@@ -0,0 +1,102 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Rocketlane API docs (https://developer.rocketlane.com/reference).
+# Partial coverage is fine — uncovered columns fall back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "A Rocketlane project — a customer onboarding or professional-services engagement.",
+ "docs_url": "https://developer.rocketlane.com/reference/get-all-projects",
+ "columns": {
+ "projectId": "The unique, system-generated identifier of the project.",
+ "projectName": "The name of the project.",
+ "startDate": "The planned start date of the project (YYYY-MM-DD).",
+ "dueDate": "The planned completion date of the project (YYYY-MM-DD).",
+ "owner": "The team member responsible for managing the project.",
+ "status": "The current project status, as a value and label pair.",
+ "customer": "The customer company the project is delivered for.",
+ "teamMembers": "The project's members, invited customers, and champion.",
+ "financials": "Contract type and revenue metrics for the project.",
+ "archived": "Whether the project has been archived.",
+ "progressPercentage": "The completion percentage of the project, derived from its tasks.",
+ "createdAt": "When the project was created (epoch milliseconds).",
+ "updatedAt": "When the project was last modified (epoch milliseconds).",
+ },
+ },
+ "tasks": {
+ "description": "A Rocketlane task — a unit of work within a project, optionally grouped under a phase.",
+ "docs_url": "https://developer.rocketlane.com/reference/get-all-tasks",
+ "columns": {
+ "taskId": "The unique, system-generated identifier of the task.",
+ "taskName": "The name of the task.",
+ "taskDescription": "The HTML-formatted description of the task.",
+ "startDate": "The scheduled start date of the task (YYYY-MM-DD).",
+ "dueDate": "The scheduled completion date of the task (YYYY-MM-DD).",
+ "status": "The current task status, as a value and label pair.",
+ "progress": "The task progress as a percentage (0-100).",
+ "effortInMinutes": "The expected effort to complete the task, in minutes.",
+ "project": "The project the task belongs to.",
+ "phase": "The phase the task is grouped under.",
+ "assignees": "The team members or placeholders executing the task.",
+ "followers": "The team members tracking the task.",
+ "priority": "The task priority, as a value and label pair.",
+ "type": "Whether the record is a TASK or a MILESTONE.",
+ "archived": "Whether the task has been archived.",
+ "createdAt": "When the task was created (epoch milliseconds).",
+ "updatedAt": "When the task was last modified (epoch milliseconds).",
+ },
+ },
+ "time_entries": {
+ "description": "A Rocketlane time entry — logged work against a project, task, or ad-hoc activity.",
+ "docs_url": "https://developer.rocketlane.com/reference/get-all-time-entries",
+ "columns": {
+ "timeEntryId": "The unique, system-generated identifier of the time entry.",
+ "date": "The date the work occurred (YYYY-MM-DD).",
+ "minutes": "The duration of the logged work, in minutes.",
+ "activityName": "The name of the ad-hoc activity, when the entry is not tied to a task.",
+ "project": "The project the time was logged against.",
+ "task": "The task the time was logged against, if any.",
+ "user": "The team member who logged the time.",
+ "billable": "Whether the logged time is billable to the client.",
+ "status": "The approval state (NOT_SUBMITTED, SUBMITTED, APPROVED, REJECTED).",
+ "sourceType": "The origin of the entry (TASK, ADHOC, GOOGLE_CALENDAR, ...).",
+ "createdAt": "When the time entry was created (epoch milliseconds).",
+ "updatedAt": "When the time entry was last modified (epoch milliseconds).",
+ },
+ },
+ "users": {
+ "description": "A Rocketlane user — a team member, partner, or customer with access to the account.",
+ "docs_url": "https://developer.rocketlane.com/reference/get-all-users",
+ "columns": {
+ "userId": "The unique, system-generated identifier of the user.",
+ "email": "The user's email address.",
+ "firstName": "The user's first name.",
+ "lastName": "The user's last name.",
+ "type": "The user category (TEAM_MEMBER, PARTNER, CUSTOMER, EXTERNAL_PARTNER).",
+ "status": "The user state (INACTIVE, INVITED, ACTIVE, PASSIVE).",
+ "role": "The user's role, as a roleId and roleName pair.",
+ "company": "The company the user belongs to.",
+ "permission": "The user's permission level.",
+ "capacityInMinutes": "The user's allocated capacity, in minutes.",
+ "profilePictureUrl": "The URL of the user's profile image.",
+ "createdAt": "When the user was created (epoch milliseconds).",
+ "updatedAt": "When the user was last modified (epoch milliseconds).",
+ },
+ },
+ "fields": {
+ "description": "A Rocketlane custom field definition, attached to projects, tasks, or users.",
+ "docs_url": "https://developer.rocketlane.com/reference/get-all-fields",
+ "columns": {
+ "fieldId": "The unique, system-generated identifier of the field.",
+ "fieldLabel": "The display name of the custom field.",
+ "fieldType": "The field data type (TEXT, DATE, SINGLE_CHOICE, ...).",
+ "objectType": "The object the field attaches to (PROJECT, TASK, or USER).",
+ "fieldOptions": "The available choices for SINGLE_CHOICE and MULTIPLE_CHOICE fields.",
+ "enabled": "Whether the field is currently active.",
+ "private": "Whether the field is private or shared.",
+ "createdAt": "When the field was created (epoch milliseconds).",
+ "updatedAt": "When the field was last modified (epoch milliseconds).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/rocketlane.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/rocketlane.py
new file mode 100644
index 000000000000..aa390a1129c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/rocketlane.py
@@ -0,0 +1,158 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any, Optional
+
+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.rocketlane.settings import ROCKETLANE_ENDPOINTS
+
+ROCKETLANE_BASE_URL = "https://api.rocketlane.com/api/1.0"
+# The list endpoints cap `pageSize` at 100 (values above the cap fall back to 100), so 100 minimises
+# round trips.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap endpoint used to confirm an api-key is genuine. The key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/users"
+
+
+class RocketlaneRetryableError(Exception):
+ pass
+
+
+class RocketlaneResumeConfig:
+ # Opaque cursor for the next page. Rocketlane returns a `nextPageToken` alongside `hasMore`; a
+ # crashed full-refresh sync resumes from the last token it persisted. Note: Rocketlane tokens are
+ # only valid for ~15 minutes, so a long-stalled resume may need to restart from the first page —
+ # merge dedupes on the primary key either way.
+ page_token: Optional[str] = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ # Rocketlane expects the raw key in an `api-key` header — no "Bearer " prefix.
+ return {"api-key": api_key, "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((RocketlaneRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ page_token: Optional[str],
+ page_size: int,
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"pageSize": page_size}
+ # Omit `pageToken` on the first request; an empty token returns page 1.
+ if page_token:
+ params["pageToken"] = page_token
+
+ response = session.get(
+ f"{ROCKETLANE_BASE_URL}{path}",
+ params=params,
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+
+ # Rocketlane signals rate limiting with 429 (error code TOO_MANY_REQUEST); back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RocketlaneRetryableError(f"Rocketlane API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"Rocketlane API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RocketlaneResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = ROCKETLANE_ENDPOINTS[endpoint]
+ # `redact_values` masks the api-key in logged URLs and captured samples.
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page_token: Optional[str] = resume.page_token if resume else None
+ if resume and resume.page_token:
+ logger.debug(f"Rocketlane: resuming {endpoint} from saved page token")
+
+ while True:
+ data = _fetch_page(session, config.path, page_token, PAGE_SIZE, logger)
+
+ # `data` is always present in a well-formed list response; missing it means a malformed
+ # response, so fail loudly rather than silently advancing past lost rows.
+ rows = data["data"]
+ if rows:
+ yield rows
+
+ pagination = data.get("pagination") or {}
+ next_token = pagination.get("nextPageToken")
+ # Stop when the API says there are no more pages, when it stops handing back a cursor, or when
+ # a page comes back empty (guards against a server-side cursor bug looping forever).
+ if not pagination.get("hasMore") or not next_token or not rows:
+ break
+
+ page_token = next_token
+ # Save AFTER yielding so a crash re-fetches from the token pointing at the *next* page (the
+ # already-yielded pages are persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(RocketlaneResumeConfig(page_token=page_token))
+
+
+def rocketlane_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[RocketlaneResumeConfig],
+) -> SourceResponse:
+ config = ROCKETLANE_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=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 check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single list endpoint to validate the api-key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise. The api-key is account-wide, so one probe
+ validates access to every list endpoint.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{ROCKETLANE_BASE_URL}{path}", params={"pageSize": 1}, timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Rocketlane: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Rocketlane returned HTTP {response.status_code}"
+
+ return 200, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/settings.py
new file mode 100644
index 000000000000..f5e070325cf2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/settings.py
@@ -0,0 +1,40 @@
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class RocketlaneEndpointConfig:
+ name: str
+ path: str
+ # Each Rocketlane object type exposes its own system-generated identifier field
+ # (projectId, taskId, ...) rather than a shared `id`, so the primary key is per-endpoint.
+ primary_keys: list[str]
+ # A stable (never-rewritten) creation timestamp to partition by, where the object exposes one.
+ # Rocketlane timestamps are epoch milliseconds; only set this where the field is genuinely
+ # immutable — never `updatedAt`, which changes on every edit.
+ partition_key: Optional[str] = None
+
+
+# Rocketlane list endpoints that can be pulled without a parent id. Endpoints that require a
+# `projectId` query parameter (phases, spaces, ...) are intentionally excluded — they are per-parent
+# fan-outs, not account-level lists. All are full-refresh only: Rocketlane's list endpoints expose
+# per-field filters but no single documented `updated_after` cursor, so there is no genuine
+# incremental cursor to advance.
+ROCKETLANE_ENDPOINTS: dict[str, RocketlaneEndpointConfig] = {
+ "projects": RocketlaneEndpointConfig(
+ name="projects", path="/projects", primary_keys=["projectId"], partition_key="createdAt"
+ ),
+ "tasks": RocketlaneEndpointConfig(name="tasks", path="/tasks", primary_keys=["taskId"], partition_key="createdAt"),
+ "time_entries": RocketlaneEndpointConfig(
+ name="time_entries", path="/time-entries", primary_keys=["timeEntryId"], partition_key="createdAt"
+ ),
+ "users": RocketlaneEndpointConfig(name="users", path="/users", primary_keys=["userId"], partition_key="createdAt"),
+ "fields": RocketlaneEndpointConfig(
+ name="fields", path="/fields", primary_keys=["fieldId"], partition_key="createdAt"
+ ),
+}
+
+ENDPOINTS = tuple(ROCKETLANE_ENDPOINTS.keys())
+
+# Full refresh only — see the note above. Kept for parity with the incremental-capable sources.
+INCREMENTAL_FIELDS: dict[str, list] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/source.py
index 657ff3a46644..6520d3993647 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/source.py
@@ -1,19 +1,42 @@
-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.generated_configs import RocketlaneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.rocketlane import (
+ RocketlaneResumeConfig,
+ check_access,
+ rocketlane_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.settings import (
+ ENDPOINTS,
+ ROCKETLANE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RocketlaneSource(SimpleSource[RocketlaneSourceConfig]):
+class RocketlaneSource(ResumableSource[RocketlaneSourceConfig, RocketlaneResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ROCKETLANE
@@ -24,7 +47,95 @@ class RocketlaneSource(SimpleSource[RocketlaneSourceConfig]):
name=SchemaExternalDataSourceType.ROCKETLANE,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Rocketlane",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Rocketlane API key to pull your Rocketlane data into the PostHog Data warehouse.
+
+You can generate an API key under **Settings → API** in the [Rocketlane app](https://app.rocketlane.com/). This single key grants read access to your projects, tasks, time entries, users, and fields.
+""",
iconPath="/static/services/rocketlane.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/rocketlane",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked api-key surfaces as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.
+ # Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.rocketlane.com": "Your Rocketlane API key is invalid or has been revoked. Generate a new key under Settings → API, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.rocketlane.com": "Your Rocketlane API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: RocketlaneSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — Rocketlane's list endpoints expose per-field filters
+ # but no single server-side `updated_after` cursor, so there is nothing to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ 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: RocketlaneSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The api-key is account-wide, so a single probe validates access to every schema; there is
+ # no per-endpoint scope to check.
+ status, message = check_access(config.api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid Rocketlane API key"
+ return False, message or "Could not validate Rocketlane API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RocketlaneResumeConfig]:
+ return ResumableSourceManager[RocketlaneResumeConfig](inputs, RocketlaneResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RocketlaneSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RocketlaneResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ROCKETLANE_ENDPOINTS:
+ raise ValueError(f"Unknown Rocketlane schema '{inputs.schema_name}'")
+
+ return rocketlane_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/rocketlane/tests/test_rocketlane.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/tests/test_rocketlane.py
new file mode 100644
index 000000000000..4c23146b3dc7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/tests/test_rocketlane.py
@@ -0,0 +1,236 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane import rocketlane
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.rocketlane import (
+ RocketlaneResumeConfig,
+ RocketlaneRetryableError,
+ check_access,
+ get_rows,
+ rocketlane_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.settings import (
+ ENDPOINTS,
+ ROCKETLANE_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = rocketlane._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: RocketlaneResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[RocketlaneResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> RocketlaneResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: RocketlaneResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(rows: list[dict], has_more: bool, next_token: str | None) -> dict[str, Any]:
+ return {
+ "data": rows,
+ "pagination": {
+ "pageSize": 100,
+ "hasMore": has_more,
+ "totalRecordCount": len(rows),
+ "nextPageToken": next_token,
+ },
+ }
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str | None, dict],
+ endpoint: str = "projects",
+ ) -> list[dict]:
+ def fake_fetch(session: Any, path: str, page_token: str | None, page_size: int, logger: Any) -> dict:
+ return pages[page_token]
+
+ monkeypatch.setattr(rocketlane, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(rocketlane, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="rl-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_yields_rows_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(
+ manager, monkeypatch, {None: _page([{"projectId": 1}, {"projectId": 2}], has_more=False, next_token=None)}
+ )
+ assert rows == [{"projectId": 1}, {"projectId": 2}]
+ # No further pages, so no resume state is persisted.
+ assert manager.saved == []
+
+ def test_follows_cursor_until_has_more_is_false(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: _page([{"projectId": 1}], has_more=True, next_token="t2"),
+ "t2": _page([{"projectId": 2}], has_more=True, next_token="t3"),
+ "t3": _page([{"projectId": 3}], has_more=False, next_token=None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"projectId": 1}, {"projectId": 2}, {"projectId": 3}]
+
+ def test_stops_when_next_token_missing_even_if_has_more(self, monkeypatch: Any) -> None:
+ # A page advertising hasMore but no token cannot be followed — stop rather than loop.
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: _page([{"projectId": 1}], has_more=True, next_token=None)})
+ assert rows == [{"projectId": 1}]
+ assert manager.saved == []
+
+ def test_saves_next_token_after_yielding_each_batch(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ None: _page([{"projectId": 1}], has_more=True, next_token="t2"),
+ "t2": _page([{"projectId": 2}], has_more=False, next_token=None),
+ }
+ self._collect(manager, monkeypatch, pages)
+ # State is saved AFTER the first page is yielded (pointing at the next token), never for the last.
+ assert [s.page_token for s in manager.saved] == ["t2"]
+
+ def test_resumes_from_saved_token(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(RocketlaneResumeConfig(page_token="t2"))
+ pages: dict[str | None, dict] = {
+ # The first page (token None) must never be fetched on resume.
+ "t2": _page([{"projectId": 2}], has_more=True, next_token="t3"),
+ "t3": _page([{"projectId": 3}], has_more=False, next_token=None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"projectId": 2}, {"projectId": 3}]
+
+ def test_empty_page_does_not_yield_and_terminates(self, monkeypatch: Any) -> None:
+ # An empty page terminates the stream even if the API keeps advertising a cursor.
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {None: _page([], has_more=True, next_token="t2")})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: dict | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body or {}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(RocketlaneRetryableError):
+ _fetch_page_unwrapped(session, "/projects", None, 100, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/projects", None, 100, MagicMock())
+
+ def test_success_returns_json_body(self) -> None:
+ body = _page([{"projectId": 1}], has_more=False, next_token=None)
+ session = self._session_returning(200, body)
+ result = _fetch_page_unwrapped(session, "/projects", None, 100, MagicMock())
+ assert result == body
+
+ def test_first_request_omits_page_token(self) -> None:
+ session = self._session_returning(200, _page([], has_more=False, next_token=None))
+ _fetch_page_unwrapped(session, "/projects", None, 100, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"pageSize": 100}
+
+ def test_subsequent_request_includes_page_token(self) -> None:
+ session = self._session_returning(200, _page([], has_more=False, next_token=None))
+ _fetch_page_unwrapped(session, "/tasks", "abc", 100, MagicMock())
+ _, kwargs = session.get.call_args
+ assert kwargs["params"] == {"pageSize": 100, "pageToken": "abc"}
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session_for(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Rocketlane returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ session = self._session_for(response)
+ with patch.object(rocketlane, "make_tracked_session", lambda **kwargs: session):
+ assert check_access("rl-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ session = self._session_for(requests.ConnectionError("boom"))
+ with patch.object(rocketlane, "make_tracked_session", lambda **kwargs: session):
+ status, message = check_access("rl-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestRocketlaneSourceResponse:
+ @parameterized.expand(
+ [
+ ("projects", ["projectId"]),
+ ("tasks", ["taskId"]),
+ ("time_entries", ["timeEntryId"]),
+ ("users", ["userId"]),
+ ("fields", ["fieldId"]),
+ ]
+ )
+ def test_response_uses_endpoint_primary_key(self, endpoint: str, primary_keys: list[str]) -> None:
+ response = rocketlane_source(
+ api_key="rl-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ # Every endpoint exposes a stable `createdAt`, so all partition by datetime.
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+
+ def test_endpoint_keys_match_endpoints_tuple(self) -> None:
+ assert set(ROCKETLANE_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/tests/test_rocketlane_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/tests/test_rocketlane_source.py
new file mode 100644
index 000000000000..165742d1d845
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rocketlane/tests/test_rocketlane_source.py
@@ -0,0 +1,166 @@
+import pytest
+from unittest import mock
+
+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.generated_configs import RocketlaneSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.rocketlane import (
+ RocketlaneResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.source import RocketlaneSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestRocketlaneSource:
+ def setup_method(self) -> None:
+ self.source = RocketlaneSource()
+ self.team_id = 123
+ self.config = RocketlaneSourceConfig(api_key="rl-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ROCKETLANE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Rocketlane"
+ assert config.label == "Rocketlane"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/rocketlane"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret `api_key`; the base URL is hardcoded and the account is
+ # implicit in the key, so there is no non-secret field that retargets where the key is sent.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Rocketlane's list endpoints have no single server-side timestamp cursor, so every schema
+ # is full refresh.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tasks"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tasks"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ # Exercises the credential-free catalog path used by the posthog.com docs.
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.rocketlane.com/api/1.0/projects?pageSize=100",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://api.rocketlane.com/api/1.0/tasks?pageSize=100&pageToken=abc",
+ ),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.rocketlane.com/api/1.0/projects",
+ ),
+ ("read_timeout", "HTTPSConnectionPool(host='api.rocketlane.com', port=443): Read timed out."),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.rocketlane.com/api/1.0/users"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("valid", 200, True, None),
+ ("unauthorized", 401, False, "Invalid Rocketlane API key"),
+ ("forbidden", 403, False, "Invalid Rocketlane API key"),
+ ("server_error", 500, False, "Rocketlane returned HTTP 500"),
+ ("connection_error", 0, False, "Could not connect to Rocketlane: boom"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.source.check_access")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ message = (
+ "Rocketlane returned HTTP 500"
+ if status == 500
+ else ("Could not connect to Rocketlane: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.source.check_access")
+ def test_validate_credentials_probes_the_account_key(self, mock_check: mock.MagicMock) -> None:
+ # The api-key is account-wide, so validation probes the key, not a per-schema scope.
+ mock_check.return_value = (200, None)
+ self.source.validate_credentials(self.config, self.team_id, schema_name="tasks")
+ mock_check.assert_called_once_with("rl-key")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RocketlaneResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rocketlane.source.rocketlane_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_rocketlane_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "projects"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_rocketlane_source.assert_called_once()
+ kwargs = mock_rocketlane_source.call_args.kwargs
+ assert kwargs["api_key"] == "rl-key"
+ assert kwargs["endpoint"] == "projects"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Rocketlane schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)