: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 platform_sh import source (#70721)
Tom Owersc74c317dfb7e
diff --git a/frontend/public/services/platform_sh.svg b/frontend/public/services/platform_sh.svgnew file mode 100644index 000000000000..c466b3291fff--- /dev/null+++ b/frontend/public/services/platform_sh.svg@@ -0,0 +1,4 @@+<svg width="48" height="48" viewBox="0 0 47 48" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M23.4042 12.5467C29.7829 12.5467 34.9402 17.7147 34.9402 24.0827H46.4762C46.4762 11.336 36.1456 1 23.3882 1C10.6309 1 0.310913 11.3253 0.310913 24.0773H11.8469C11.8736 17.6987 17.0416 12.5413 23.4042 12.5413V12.5467Z" fill="#2E062F"/>+<path d="M27.3122 34.93C31.7602 33.3247 34.9335 29.074 34.9335 24.082H11.8668C11.8668 29.074 15.0455 33.3354 19.4882 34.93V35.1274H3.14685C7.05618 42.29 14.6668 47.1487 23.4135 47.1487C32.1602 47.1487 39.7548 42.29 43.6802 35.1274H27.3122V34.93Z" fill="#2E062F"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 3101f7eae9c1..5575c1f0bce2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -336,6 +336,7 @@ the row lists both.| pipeliner | HTTP | requests | ✅ || plain | HTTP | requests | ✅ || planhat | HTTP | requests | ✅ |+| platform_sh | HTTP | requests | ✅ || plausible | HTTP | requests | ✅ || polar | HTTP | requests | ✅ || plaid | HTTP | requests | ✅ |@@ -797,7 +798,6 @@ doesn't conflict with concurrent PRs.- pivotal_tracker- piwik- planetscale-- platform_sh- plunk- podiumdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 12abbcd031df..784335a3eebd 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@@ -3188,7 +3188,8 @@ class PlanhatSourceConfig(config.Config):@config.configclass PlatformShSourceConfig(config.Config):- pass+ api_token: str+ platform: Literal["platform_sh", "upsun"] = config.value(default="platform_sh")@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/canonical_descriptions.pynew file mode 100644index 000000000000..9cd6828325f3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/canonical_descriptions.py@@ -0,0 +1,122 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "An organization groups projects, members, and billing under one account on Platform.sh or Upsun.",+ "docs_url": "https://api.platform.sh/docs/#tag/Organizations",+ "columns": {+ "id": "Unique identifier (ULID) for the organization.",+ "owner_id": "User ID of the organization's owner.",+ "namespace": "Namespace the organization belongs to (e.g. platformsh, upsun).",+ "name": "Machine name of the organization, used in URLs and CLI commands.",+ "label": "Human-readable display name of the organization.",+ "country": "Country the organization is registered in.",+ "capabilities": "Capability flags enabled for the organization.",+ "vendor": "Vendor the organization belongs to.",+ "status": "Current status of the organization (e.g. active, restricted).",+ "created_at": "When the organization was created.",+ "updated_at": "When the organization was last updated.",+ },+ },+ "projects": {+ "description": "A project is a hosted application with its own Git repository, environments, and plan, belonging to an organization.",+ "docs_url": "https://api.platform.sh/docs/#tag/Project",+ "columns": {+ "id": "Unique identifier for the project, used in API routes and CLI commands.",+ "organization_id": "ID of the organization the project belongs to.",+ "subscription_id": "ID of the billing subscription backing the project.",+ "region": "Region the project is hosted in (e.g. eu-5.platform.sh).",+ "title": "Human-readable title of the project.",+ "plan": "Plan size the project runs on.",+ "default_branch": "Name of the project's default (production) branch.",+ "status": "Current status of the project (e.g. active, suspended, deleted).",+ "timezone": "Timezone used for the project's crons and maintenance windows.",+ "created_at": "When the project was created.",+ "updated_at": "When the project was last updated.",+ },+ },+ "environments": {+ "description": "An environment is a running instance of a project tied to a Git branch, such as production or a preview branch.",+ "docs_url": "https://api.platform.sh/docs/#tag/Environment",+ "columns": {+ "id": "Environment identifier within its project (the branch name).",+ "project_id": "ID of the project the environment belongs to (injected from the parent project).",+ "name": "Name of the environment's Git branch.",+ "machine_name": "Unique machine name used in the environment's URLs.",+ "title": "Human-readable title of the environment.",+ "type": "Environment type: production, staging, or development.",+ "parent": "Name of the parent environment this one was branched from.",+ "status": "Current status of the environment (e.g. active, inactive, dirty, deleting).",+ "is_main": "Whether this is the project's main (production) environment.",+ "is_pr": "Whether the environment was created for a pull request.",+ "default_domain": "Default domain attached to the environment, if any.",+ "edge_hostname": "Hostname the environment's routes resolve to.",+ "deployment_target": "Deployment target for the environment (e.g. local, dedicated).",+ "last_active_at": "When the environment last had activity.",+ "last_backup_at": "When the environment was last backed up.",+ "created_at": "When the environment was created.",+ "updated_at": "When the environment was last updated.",+ },+ },+ "activities": {+ "description": "An activity is an entry in a project's audit/deploy log: pushes, deploys, crons, backups, and other operations, with their state, result, and timings. The API prunes expired activities, so incremental sync is what preserves history.",+ "docs_url": "https://api.platform.sh/docs/#tag/Activity",+ "columns": {+ "id": "Unique identifier for the activity.",+ "project_id": "ID of the project the activity belongs to (injected from the parent project).",+ "project": "ID of the project the activity belongs to, as returned by the API.",+ "type": "Activity type (e.g. environment.push, environment.deploy, environment.cron, environment.backup).",+ "state": "Current state of the activity: pending, in_progress, complete, cancelled, or scheduled.",+ "result": "Result of the activity once finished: success or failure.",+ "environments": "IDs of the environments the activity applies to.",+ "parameters": "Input parameters the activity was created with.",+ "payload": "Type-specific payload describing the activity's subject (e.g. commits, environment).",+ "description": "Human-readable HTML description of the activity.",+ "text": "Human-readable plain-text description of the activity.",+ "completion_percent": "Progress of the activity, 0-100.",+ "timings": "Timing breakdown of the activity's execution.",+ "commands": "Commands executed by the activity, if any.",+ "started_at": "When the activity started executing.",+ "completed_at": "When the activity finished.",+ "cancelled_at": "When the activity was cancelled, if it was.",+ "expires_at": "When the activity expires and is pruned from the API.",+ "created_at": "When the activity was created.",+ "updated_at": "When the activity was last updated.",+ },+ },+ "subscriptions": {+ "description": "A subscription is the billing record backing a project: its plan, allowances, and status within an organization.",+ "docs_url": "https://api.platform.sh/docs/#tag/Subscriptions",+ "columns": {+ "id": "Unique identifier for the subscription.",+ "organization_id": "ID of the organization the subscription belongs to (injected from the parent organization).",+ "project_id": "ID of the project the subscription pays for.",+ "project_title": "Title of the project the subscription pays for.",+ "project_region": "Region the project is hosted in.",+ "plan": "Plan the subscription is on.",+ "environments": "Number of environments included in the plan.",+ "storage": "Storage allowance included in the plan, in MiB.",+ "user_licenses": "Number of user licenses included in the plan.",+ "status": "Current status of the subscription (e.g. active, suspended, deleted).",+ "is_trial_plan": "Whether the subscription is on a trial plan.",+ "owner": "User ID of the subscription's owner.",+ "created_at": "When the subscription was created.",+ "updated_at": "When the subscription was last updated.",+ },+ },+ "members": {+ "description": "A member is a user's membership in an organization, with their permissions and owner flag.",+ "docs_url": "https://api.platform.sh/docs/#tag/Organization-Members",+ "columns": {+ "id": "Unique identifier for the membership.",+ "organization_id": "ID of the organization the membership belongs to.",+ "user_id": "ID of the user the membership grants access to.",+ "permissions": "Permissions granted to the member within the organization.",+ "owner": "Whether the member is the organization's owner.",+ "created_at": "When the membership was created.",+ "updated_at": "When the membership was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/platform_sh.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/platform_sh.pynew file mode 100644index 000000000000..064758f33f27--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/platform_sh.py@@ -0,0 +1,503 @@+"""Platform.sh (Upsun) transport layer.++Platform.sh's REST API is a HAL-style JSON surface behind a short-lived OAuth2 bearer token. The+user supplies a long-lived API token (created in the Console), which we exchange for a ~15-minute+access token via `POST {auth_host}/oauth2/token` with HTTP basic auth `platform-api-user:` and+`grant_type=api_token` (verified against the live auth endpoints for both brands). The client+re-exchanges proactively before expiry and once reactively on a 401 mid-run.++Two brand host pairs exist for the same API: api.platform.sh + auth.api.platform.sh (Platform.sh)+and api.upsun.com + auth.upsun.com (Upsun). The user picks the brand in the source form.++Organization-level lists return an `{"items": [...], "_links": {...}}` envelope with cursor+pagination (`page[size]`, `_links.next.href`). Project-scoped lists return bare JSON arrays; the+activities feed is newest-first and pages backwards through history via `count` + `starts_at`+(params absent from the OpenAPI spec but used by the official Platform.sh PHP client and CLI, which+page by setting `starts_at` to the oldest `created_at` seen and dedupe by id).++Fan-out: organizations -> projects/subscriptions/members, and organizations -> projects ->+environments/activities. Resume state checkpoints the current organizations page URL after all its+children are processed; a resumed run re-fans that page and merge dedupes on the primary key.+"""++import time+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any+from urllib.parse import urlencode, urljoin, urlparse++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.platform_sh.settings import (+ PLATFORM_SH_ENDPOINTS,+ PlatformShEndpointConfig,+)++API_HOSTS = {+ "platform_sh": "https://api.platform.sh",+ "upsun": "https://api.upsun.com",+}+AUTH_HOSTS = {+ "platform_sh": "https://auth.api.platform.sh",+ "upsun": "https://auth.upsun.com",+}++# Access tokens are issued for ~900s; refresh this many seconds early so a request never rides an+# about-to-expire token across a slow response.+TOKEN_REFRESH_MARGIN_SECONDS = 60+REQUEST_TIMEOUT_SECONDS = 60++AUTH_FAILED_MESSAGE = "Platform.sh authentication failed"+++class PlatformShResumeConfig:+ # Next URL to fetch. For the top-level organizations table it's the next page URL; for fan-out+ # tables it's the current organizations page URL (resume re-fans that page and its children,+ # merge dedupes on the primary key).+ next_url: str | None = None+++class PlatformShRetryableError(Exception):+ pass+++class PlatformShAuthenticationError(Exception):+ """Raised when the token exchange rejects the API token. Matched by+ `get_non_retryable_errors` — retrying can never satisfy a credential problem."""+++class PlatformShUntrustedURLError(Exception):+ """Raised when a next-page/resume URL points off the configured API host. We attach the bearer+ token to every request, so following an off-host URL would leak it; refuse instead."""+++class PlatformShPageCapExceededError(Exception):+ """Raised when a fan-out parent exceeds the per-parent page cap. Failing loudly beats silently+ writing an incomplete table that later runs would never backfill."""+++class PlatformShClient:+ """Authenticated GET client: exchanges the API token for a bearer token, refreshes it before+ expiry and once reactively on 401, and pins every URL to the configured API host."""++ def __init__(self, api_token: str, platform: str, logger: FilteringBoundLogger) -> None:+ if platform not in API_HOSTS:+ raise ValueError(f"Platform.sh: unknown platform {platform!r}; expected one of {sorted(API_HOSTS)}")+ self.api_base = API_HOSTS[platform]+ self._parsed_base = urlparse(self.api_base)+ self._token_url = f"{AUTH_HOSTS[platform]}/oauth2/token"+ self._api_token = api_token+ self._logger = logger+ self._access_token: str | None = None+ self._token_deadline = 0.0+ # capture=False: environment responses carry `http_access.basic_auth` and activity+ # responses carry raw `log` output — secrets we strip client-side in `_clean_rows`, which+ # runs after HTTP sample capture would have recorded the raw body. Requests stay metered+ # and logged; only the opt-in body capture is excluded.+ self._session = make_tracked_session(redact_values=(api_token,), capture=False)++ def validate_url(self, url: str) -> str:+ """Reject a URL whose scheme or host differs from the configured API base.++ Next-page URLs come from remote `_links` payloads (and persisted resume state), and we send+ the bearer token with them. Pinning the scheme and host stops a tampered link from+ forwarding the token to an attacker-controlled server.+ """+ parsed = urlparse(url)+ if parsed.scheme != self._parsed_base.scheme or parsed.netloc != self._parsed_base.netloc:+ raise PlatformShUntrustedURLError(f"Platform.sh: refusing to follow off-host URL: {url}")+ return url++ @retry(+ retry=retry_if_exception_type((PlatformShRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def _exchange_token(self) -> None:+ # allow_redirects=False: requests preserves the POST body on 307/308 redirects, so+ # following one would re-send the long-lived API token to whatever host the redirect+ # names — the body isn't covered by requests' cross-host Authorization stripping.+ response = self._session.post(+ self._token_url,+ auth=("platform-api-user", ""),+ data={"grant_type": "api_token", "api_token": self._api_token},+ timeout=REQUEST_TIMEOUT_SECONDS,+ allow_redirects=False,+ )+ if 300 <= response.status_code < 400:+ raise PlatformShUntrustedURLError(+ f"Platform.sh: token endpoint responded with a redirect (status={response.status_code}); "+ "refusing to re-send the API token"+ )+ if response.status_code == 429 or response.status_code >= 500:+ raise PlatformShRetryableError(+ f"Platform.sh token exchange error (retryable): status={response.status_code}"+ )+ if not response.ok:+ # 400/401 from the auth server means the API token itself was rejected.+ raise PlatformShAuthenticationError(+ f"{AUTH_FAILED_MESSAGE}: the API token was rejected by {self._token_url} "+ f"(status={response.status_code})"+ )+ payload = response.json()+ self._access_token = payload["access_token"]+ self._token_deadline = time.monotonic() + float(payload.get("expires_in", 900)) - TOKEN_REFRESH_MARGIN_SECONDS+ # Rebuild the session so the fresh bearer token is masked from tracked logs, same as the+ # long-lived API token; capture stays off (see __init__).+ self._session = make_tracked_session(redact_values=(self._api_token, self._access_token), capture=False)++ def _ensure_token(self) -> str:+ if self._access_token is None or time.monotonic() >= self._token_deadline:+ self._exchange_token()+ assert self._access_token is not None+ return self._access_token++ def _headers(self) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {self._ensure_token()}",+ "Accept": "application/json",+ "User-Agent": "PostHog",+ }++ @retry(+ retry=retry_if_exception_type(+ (+ PlatformShRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def get(self, url: str) -> requests.Response:+ response = self._session.get(url, headers=self._headers(), timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 401:+ # The bearer token expires after ~15 minutes; re-exchange once and retry. A second 401+ # means the credential itself is broken and falls through to raise_for_status below.+ self._exchange_token()+ response = self._session.get(url, headers=self._headers(), timeout=REQUEST_TIMEOUT_SECONDS)++ # Rate limits aren't publicly documented; honor 429 and transient 5xx with backoff.+ if response.status_code == 429 or response.status_code >= 500:+ raise PlatformShRetryableError(+ f"Platform.sh API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ self._logger.error(f"Platform.sh API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def _build_url(api_base: str, path: str, page_size: int | None, page_size_param: str = "page[size]") -> str:+ url = f"{api_base}{path}"+ if page_size is not None:+ return f"{url}?{urlencode({page_size_param: page_size})}"+ return url+++def _next_link(body: dict[str, Any], current_url: str, client: PlatformShClient) -> str | None:+ """Return the absolute, host-pinned URL of `_links.next.href`, if any. HAL links are typically+ relative ("/organizations?page[after]=..."), so resolve against the current request URL."""+ href = ((body.get("_links") or {}).get("next") or {}).get("href")+ if not href:+ return None+ return client.validate_url(urljoin(current_url, href))+++def _iter_envelope_pages(+ client: PlatformShClient,+ url: str,+ max_pages: int | None = None,+ page_cap_context: dict[str, Any] | None = None,+) -> Iterator[tuple[list[dict[str, Any]], str]]:+ """Yield (items, page_url) for each page of an `{"items": [...], "_links": {...}}` list,+ following the `_links.next` cursor. When `max_pages` is set and more pages remain, raise+ rather than truncate: a silently short table would stay incomplete on every later run."""+ page_count = 0+ while True:+ body = client.get(url).json()+ items = body.get("items") if isinstance(body, dict) else None+ if not items:+ return+ next_url = _next_link(body, url, client)+ yield items, url+ page_count += 1+ if not next_url:+ return+ if max_pages is not None and page_count >= max_pages:+ raise PlatformShPageCapExceededError(+ f"Platform.sh: page cap of {max_pages} reached with more pages remaining; "+ f"raise max_pages_per_parent to sync this parent fully. context={page_cap_context or {}}"+ )+ url = next_url+++def _strip_keys_recursive(value: Any, keys: list[str]) -> Any:+ """Return `value` with every dict entry whose key is in `keys` removed, at any depth.+ Credential blocks (environment `http_access.basic_auth`) can appear nested inside activity+ payloads at varying depths, so strip by key name rather than a fixed path."""+ if isinstance(value, dict):+ return {k: _strip_keys_recursive(v, keys) for k, v in value.items() if k not in keys}+ if isinstance(value, list):+ return [_strip_keys_recursive(item, keys) for item in value]+ return value+++def _clean_rows(rows: list[dict[str, Any]], config: PlatformShEndpointConfig) -> list[dict[str, Any]]:+ if not config.drop_keys and not config.strip_keys_recursive:+ return rows+ cleaned: list[dict[str, Any]] = []+ for row in rows:+ if isinstance(row, dict):+ if config.drop_keys:+ row = {k: v for k, v in row.items() if k not in config.drop_keys}+ if config.strip_keys_recursive:+ row = _strip_keys_recursive(row, config.strip_keys_recursive)+ cleaned.append(row)+ return cleaned+++def _inject_parent_fields(+ rows: list[dict[str, Any]], parent: dict[str, Any], field_map: dict[str, str] | None+) -> list[dict[str, Any]]:+ """Copy the mapped parent fields onto each child row. Direct access on the parent fields: the+ injected columns feed the child's composite primary key, so a parent missing one is a broken+ response that must fail loudly, not corrupt the key with None."""+ if not field_map:+ return rows+ injected = {child_column: parent[parent_field] for parent_field, child_column in field_map.items()}+ return [{**row, **injected} for row in rows]+++def _coerce_datetime(value: Any) -> datetime:+ """Normalize a watermark or row timestamp to an aware UTC datetime for comparison."""+ if isinstance(value, datetime):+ parsed = value+ elif isinstance(value, date):+ parsed = datetime(value.year, value.month, value.day)+ elif isinstance(value, str):+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ else:+ raise ValueError(f"Platform.sh: cannot interpret {value!r} as a datetime")+ if parsed.tzinfo is None:+ parsed = parsed.replace(tzinfo=UTC)+ return parsed+++def _iter_project_activities(+ client: PlatformShClient,+ project_id: str,+ logger: FilteringBoundLogger,+ config: PlatformShEndpointConfig,+ cutoff: datetime | None,+) -> Iterator[list[dict[str, Any]]]:+ """Walk one project's activity feed newest-first, paging backwards with `starts_at` (oldest+ `created_at` seen, mirroring the official CLI's ActivityLoader) and deduping by id. With a+ watermark set, stop once a page crosses below it — the server has no lower-bound filter, so+ the cutoff has to be client-side or every incremental sync would re-walk full history."""+ base_url = f"{client.api_base}{config.path.format(project_id=project_id)}"+ seen_ids: set[str] = set()+ starts_at: str | None = None+ page_count = 0++ while True:+ params: dict[str, Any] = {}+ if config.page_size is not None:+ params["count"] = config.page_size+ if starts_at is not None:+ params["starts_at"] = starts_at+ url = f"{base_url}?{urlencode(params)}" if params else base_url++ rows = client.get(url).json()+ if not isinstance(rows, list) or not rows:+ return+ # `starts_at` bounds pages by "created before"; ties at the boundary can re-return rows we+ # already have, so dedupe by id and stop when a page brings nothing new (feed exhausted).+ new_rows = [row for row in rows if row["id"] not in seen_ids]+ if not new_rows:+ return+ seen_ids.update(row["id"] for row in new_rows)++ if cutoff is not None:+ fresh = [row for row in new_rows if _coerce_datetime(row["created_at"]) >= cutoff]+ if fresh:+ yield fresh+ if len(fresh) < len(new_rows):+ # The page crossed the watermark; everything older was synced by a previous run.+ return+ else:+ yield new_rows++ page_count += 1+ if page_count >= config.max_pages_per_parent:+ raise PlatformShPageCapExceededError(+ f"Platform.sh: activity page cap of {config.max_pages_per_parent} reached for "+ f"project {project_id} with more history remaining; raise max_pages_per_parent."+ )+ starts_at = min(row["created_at"] for row in new_rows)+++def _iter_project_children(+ client: PlatformShClient,+ project: dict[str, Any],+ logger: FilteringBoundLogger,+ config: PlatformShEndpointConfig,+ cutoff: datetime | None,+) -> Iterator[list[dict[str, Any]]]:+ project_id = project["id"]+ if config.name == "activities":+ raw_batches: Iterator[list[dict[str, Any]]] = _iter_project_activities(+ client, project_id, logger, config, cutoff+ )+ else:+ # Environments: a single unpaginated bare-array GET per project.+ url = f"{client.api_base}{config.path.format(project_id=project_id)}"+ data = client.get(url).json()+ raw_batches = iter([data] if isinstance(data, list) and data else [])++ for batch in raw_batches:+ yield _clean_rows(_inject_parent_fields(batch, project, config.include_parent_fields), config)+++def get_rows(+ api_token: str,+ platform: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PlatformShResumeConfig],+ should_use_incremental_field: bool = False,+ incremental_field: str | None = None,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = PLATFORM_SH_ENDPOINTS[endpoint]+ client = PlatformShClient(api_token, platform, logger)++ cutoff: datetime | None = None+ if (+ config.name == "activities"+ and should_use_incremental_field+ # `created_at` is the only advertised cursor; honor the user's schema setting rather than+ # silently applying a cutoff to a field we weren't asked to use.+ and incremental_field == "created_at"+ and db_incremental_field_last_value is not None+ ):+ cutoff = _coerce_datetime(db_incremental_field_last_value)+ logger.debug(f"Platform.sh: syncing {endpoint} incrementally from {cutoff.isoformat()}")++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ orgs_url = _build_url(client.api_base, "/organizations", PLATFORM_SH_ENDPOINTS["organizations"].page_size)+ if resume is not None and resume.next_url:+ orgs_url = client.validate_url(resume.next_url)+ logger.debug(f"Platform.sh: resuming {endpoint} from organizations page: {orgs_url}")++ if endpoint == "organizations":+ while True:+ body = client.get(orgs_url).json()+ items = body.get("items") if isinstance(body, dict) else None+ if not items:+ return+ next_url = _next_link(body, orgs_url, client)+ yield _clean_rows(items, config)+ if not next_url:+ return+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it+ # (merge dedupes on the primary key).+ resumable_source_manager.save_state(PlatformShResumeConfig(next_url=next_url))+ orgs_url = next_url++ # Fan-out tables: walk the organizations list and emit child rows per org (and, for+ # project-scoped tables, per project). Checkpoint the org page URL after all of its children+ # are processed; a resumed run re-fans that page and merge dedupes.+ for orgs, org_page_url in _iter_envelope_pages(client, orgs_url):+ for org in orgs:+ if config.fan_out_parent == "organizations":+ child_url = _build_url(client.api_base, config.path.format(organization_id=org["id"]), config.page_size)+ for child_items, _ in _iter_envelope_pages(+ client,+ child_url,+ max_pages=config.max_pages_per_parent,+ page_cap_context={"organization_id": org["id"], "endpoint": endpoint},+ ):+ yield _clean_rows(_inject_parent_fields(child_items, org, config.include_parent_fields), config)+ else: # children of projects (environments, activities)+ projects_config = PLATFORM_SH_ENDPOINTS["projects"]+ projects_url = _build_url(+ client.api_base,+ projects_config.path.format(organization_id=org["id"]),+ projects_config.page_size,+ )+ for projects, _ in _iter_envelope_pages(+ client,+ projects_url,+ max_pages=projects_config.max_pages_per_parent,+ page_cap_context={"organization_id": org["id"], "endpoint": endpoint},+ ):+ for project in projects:+ yield from _iter_project_children(client, project, logger, config, cutoff)+ resumable_source_manager.save_state(PlatformShResumeConfig(next_url=org_page_url))+++def validate_credentials(api_token: str, platform: str, logger: FilteringBoundLogger) -> tuple[bool, str | None]:+ """Exchange the API token and probe one cheap authenticated call. The token grants the same+ access as the user account (no granular scopes), so one probe confirms the whole credential."""+ try:+ client = PlatformShClient(api_token, platform, logger)+ client.get(_build_url(client.api_base, "/organizations", 1))+ return True, None+ except PlatformShAuthenticationError:+ return False, "Invalid Platform.sh API token"+ except Exception as e:+ return False, f"Could not connect to Platform.sh: {e}"+++def platform_sh_source(+ api_token: str,+ platform: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PlatformShResumeConfig],+ should_use_incremental_field: bool = False,+ incremental_field: str | None = None,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ endpoint_config = PLATFORM_SH_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ platform=platform,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Activities arrive newest-first across a per-project fan-out, so `desc` is the honest+ # mode: the pipeline only finalizes the incremental watermark after a fully successful+ # sync, which is required here because rows do not arrive in one global ascending stream.+ # (`db_incremental_field_earliest_value` — desc mid-run backfill scrolling à la Stripe —+ # is deliberately unused: the resumable manager checkpoints fan-out progress instead.)+ sort_mode=endpoint_config.sort_mode,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/settings.pynew file mode 100644index 000000000000..d5892a0eb34f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/settings.py@@ -0,0 +1,145 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Endpoint catalog for Platform.sh / Upsun. Two API surfaces feed these tables:+#+# - Organization-level lists (/organizations, /organizations/{id}/projects, .../members,+# .../subscriptions) return an `{"items": [...], "_links": {...}}` envelope with cursor+# pagination (`page[size]` 1-100, `_links.next.href`).+# - Project-scoped lists (/projects/{id}/environments, /projects/{id}/activities) return a bare+# JSON array. Environments are unpaginated; activities page backwards through history with the+# `count` + `starts_at` params (undocumented in the OpenAPI spec but used by the official+# Platform.sh PHP client and CLI).+#+# Only `activities` syncs incrementally: it's the one unbounded, append-heavy table, and the API+# prunes expired activities server-side, so a full refresh would drop history the API no longer+# returns. Everything else is a small list where full refresh is cheap and correct. The org+# project list documents a server-side `filter[updated_at]`, but we haven't verified against the+# live API that it actually filters (it needs real credentials), so projects ship as full refresh+# until that's confirmed.+++@dataclass+class PlatformShEndpointConfig:+ name: str+ # Path template appended to the API base. Fan-out children carry a placeholder filled from the+ # parent: {organization_id} for org-scoped tables, {project_id} for project-scoped tables.+ path: str+ # Primary key columns for upsert dedup. Fan-out children whose id is only unique within their+ # parent (environments are named per project) key on the injected parent id too so the key+ # stays unique table-wide.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field to partition by. Never a mutable field (`updated_at`) — partitions+ # must not rewrite on every sync.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Order rows actually arrive in. Activities are returned newest-first (verified against the+ # official client's backward-paging behavior); the envelope lists don't document a default+ # order, but they're all full refresh so no watermark ever depends on it.+ sort_mode: Literal["asc", "desc"] = "asc"+ should_sync_default: bool = True+ # Fan-out: the endpoint whose rows seed this child's path ("organizations" or "projects").+ fan_out_parent: Optional[str] = None+ # True when the response is the `{"items": [...], "_links": {...}}` envelope with cursor+ # pagination; False for project-scoped endpoints that return a bare JSON array.+ response_envelope: bool = True+ # Send `page[size]` on envelope requests / `count` on the activities feed. None for+ # unpaginated bare lists (environments).+ page_size: Optional[int] = 100+ # Parent fields copied onto each child row, mapped parent_field -> child_column. Only set for+ # children whose own API response omits the parent context (subscriptions carry no+ # organization_id; environments/activities get project_id injected so the composite key never+ # depends on a field the OpenAPI spec doesn't guarantee).+ include_parent_fields: Optional[dict[str, str]] = None+ # Hard cap on pages fetched per parent in a fan-out, bounding a runaway paginator. Hitting it+ # fails loudly rather than silently truncating the table.+ max_pages_per_parent: int = 100+ # Top-level row fields dropped before persisting. Activities carry `log` (raw build/deploy+ # output, unbounded and prone to echoing secrets) which doesn't belong in a warehouse row.+ drop_keys: list[str] = field(default_factory=list)+ # Dict keys removed recursively at any depth. Environments expose `http_access.basic_auth`+ # (plaintext credentials) and activity payloads can embed whole environment objects carrying+ # the same block, so we strip by key name rather than a fixed path.+ strip_keys_recursive: list[str] = field(default_factory=list)+ # Per-source default for the incremental re-read window (seconds). Activities mutate after+ # creation (state/result/timings fill in as they run), so each incremental sync re-reads a+ # trailing day to pick up completions instead of freezing rows at first-imported state.+ default_incremental_lookback_seconds: Optional[int] = None+++PLATFORM_SH_ENDPOINTS: dict[str, PlatformShEndpointConfig] = {+ "organizations": PlatformShEndpointConfig(+ name="organizations",+ path="/organizations",+ ),+ "projects": PlatformShEndpointConfig(+ name="projects",+ # Project ids are platform-wide unique (the /projects/{id} routes resolve without an org+ # scope), and rows natively carry organization_id, so no composite key or injection needed.+ path="/organizations/{organization_id}/projects",+ fan_out_parent="organizations",+ ),+ "environments": PlatformShEndpointConfig(+ name="environments",+ # An environment id is its branch name — unique only within its project — so key on the+ # injected project id too. Injecting (rather than relying on the row's own `project`+ # field) keeps the key independent of a field the OpenAPI spec doesn't list.+ path="/projects/{project_id}/environments",+ primary_keys=["project_id", "id"],+ fan_out_parent="projects",+ response_envelope=False,+ page_size=None,+ include_parent_fields={"id": "project_id"},+ strip_keys_recursive=["basic_auth"],+ ),+ "activities": PlatformShEndpointConfig(+ name="activities",+ # The project audit/deploy log: pushes, deploys, crons, backups — type, state, result,+ # timings. Newest-first; paged backwards via `starts_at`; expired activities are pruned+ # server-side, so incremental sync with merge is what preserves history in the warehouse.+ path="/projects/{project_id}/activities",+ primary_keys=["project_id", "id"],+ incremental_fields=[+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ sort_mode="desc", # newest-first feed; watermark is finalized only after a full sync+ fan_out_parent="projects",+ response_envelope=False,+ include_parent_fields={"id": "project_id"},+ drop_keys=["log"],+ strip_keys_recursive=["basic_auth"],+ # 200 pages x 100 activities bounds a runaway walk at 20k activities per project while+ # clearing any plausible retained history (the API prunes expired activities).+ max_pages_per_parent=200,+ default_incremental_lookback_seconds=86400,+ ),+ "subscriptions": PlatformShEndpointConfig(+ name="subscriptions",+ # Billing view of each project: plan, environment/storage/user allowances, status.+ # Subscription ids are platform-wide unique but rows carry no organization_id, so inject it.+ path="/organizations/{organization_id}/subscriptions",+ fan_out_parent="organizations",+ include_parent_fields={"id": "organization_id"},+ ),+ "members": PlatformShEndpointConfig(+ name="members",+ # Membership rows carry organization_id and user_id natively; the membership id is scoped+ # to its organization, so key on both.+ path="/organizations/{organization_id}/members",+ primary_keys=["organization_id", "id"],+ fan_out_parent="organizations",+ ),+}++ENDPOINTS = tuple(PLATFORM_SH_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PLATFORM_SH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/source.pyindex 355dfc876508..989fabafb524 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/source.py@@ -1,19 +1,50 @@-from typing import cast+from typing import Optional, cast++import structlogfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)-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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PlatformShSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.platform_sh import (+ AUTH_FAILED_MESSAGE,+ PlatformShResumeConfig,+ platform_sh_source,+ validate_credentials as validate_platform_sh_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PLATFORM_SH_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+logger = structlog.get_logger(__name__)+@SourceRegistry.register-class PlatformShSource(SimpleSource[PlatformShSourceConfig]):+class PlatformShSource(ResumableSource[PlatformShSourceConfig, PlatformShResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PLATFORMSH@@ -24,8 +55,119 @@ class PlatformShSource(SimpleSource[PlatformShSourceConfig]):name=SchemaExternalDataSourceType.PLATFORM_SH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Platform.sh",- iconPath="/static/services/platform_sh.png",- keywords=["paas", "deployments", "hosting", "devops"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Platform.sh (or Upsun) API token to sync your organizations, projects, environments, and deploy activity into the PostHog Data warehouse.++Create an API token in the Console under **My profile > API tokens** ([Platform.sh](https://docs.platform.sh/administration/cli/api-tokens.html) / [Upsun](https://docs.upsun.com/administration/cli/api-tokens.html)). The token has the same access as your user account, so no extra scopes are needed. Pick the API endpoint matching the product you use — a Platform.sh token does not work against the Upsun API, and vice versa.+""",+ iconPath="/static/services/platform_sh.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/platform-sh",+ keywords=["paas", "upsun", "deployments", "hosting", "devops"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="platform",+ label="API endpoint",+ required=True,+ defaultValue="platform_sh",+ options=[+ SourceFieldSelectConfigOption(label="Platform.sh (api.platform.sh)", value="platform_sh"),+ SourceFieldSelectConfigOption(label="Upsun (api.upsun.com)", value="upsun"),+ ],+ ),+ ],+ ),+ )++ @property+ def connection_host_fields(self) -> list[str]:+ # `platform` selects which vendor host the stored API token is sent to; switching brands+ # must re-require the token (a Platform.sh token is invalid on Upsun anyway).+ return ["platform"]++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.canonical_descriptions import ( # noqa: PLC0415 — lazy sibling import, matching every other source+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ invalid_token_message = (+ "Your Platform.sh API token is invalid or has been revoked. "+ "Create a new API token in the Console and reconnect."+ )+ forbidden_message = (+ "Your Platform.sh API token does not have access to this resource. "+ "Use a token for a user with access to the organizations you want to sync."+ )+ return {+ # Raised by the token exchange when the auth server rejects the API token.+ AUTH_FAILED_MESSAGE: invalid_token_message,+ # A 401 that survives one token re-exchange, on either brand host.+ "401 Client Error: Unauthorized for url: https://api.platform.sh": invalid_token_message,+ "401 Client Error: Unauthorized for url: https://api.upsun.com": invalid_token_message,+ "403 Client Error: Forbidden for url: https://api.platform.sh": forbidden_message,+ "403 Client Error: Forbidden for url: https://api.upsun.com": forbidden_message,+ }++ def get_schemas(+ self,+ config: PlatformShSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = []+ for endpoint in ENDPOINTS:+ endpoint_config = PLATFORM_SH_ENDPOINTS[endpoint]+ supports_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ schemas.append(+ SourceSchema(+ name=endpoint,+ supports_incremental=supports_incremental,+ supports_append=supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,+ )+ )+ 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: PlatformShSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_platform_sh_credentials(config.api_token, config.platform, logger)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PlatformShResumeConfig]:+ return ResumableSourceManager[PlatformShResumeConfig](inputs, PlatformShResumeConfig)++ def source_for_pipeline(+ self,+ config: PlatformShSourceConfig,+ resumable_source_manager: ResumableSourceManager[PlatformShResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return platform_sh_source(+ api_token=config.api_token,+ platform=config.platform,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ incremental_field=inputs.incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh.pynew file mode 100644index 000000000000..0480480a5d65--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh.py@@ -0,0 +1,354 @@+from typing import Any++import pytest+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh import platform_sh+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.platform_sh import (+ AUTH_FAILED_MESSAGE,+ PlatformShAuthenticationError,+ PlatformShClient,+ PlatformShResumeConfig,+ PlatformShUntrustedURLError,+ get_rows,+ platform_sh_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.settings import PLATFORM_SH_ENDPOINTS++API = "https://api.platform.sh"+++def _resp(data: Any, status: int = 200) -> mock.Mock:+ response = mock.Mock(spec=requests.Response)+ response.status_code = status+ response.ok = status < 400+ response.text = ""+ response.json.return_value = data+ return response+++def _token_resp(access_token: str = "bearer-1") -> mock.Mock:+ return _resp({"access_token": access_token, "expires_in": 900, "token_type": "bearer"})+++def _envelope(items: list[dict[str, Any]], next_href: str | None = None) -> dict[str, Any]:+ body: dict[str, Any] = {"items": items}+ if next_href:+ body["_links"] = {"next": {"href": next_href}}+ return body+++def _manager(resume: PlatformShResumeConfig | None = None) -> mock.Mock:+ manager = mock.Mock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++def _session(get_side_effect: Any, post_side_effect: Any = None) -> mock.Mock:+ session = mock.Mock()+ session.get.side_effect = get_side_effect+ session.post.side_effect = post_side_effect or (lambda *a, **k: _token_resp())+ return session+++class TestPlatformShClientAuth:+ def test_exchanges_api_token_before_first_request(self) -> None:+ session = _session([_resp(_envelope([{"id": "org-1"}]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ client = PlatformShClient("api-tok", "platform_sh", mock.Mock())+ client.get(f"{API}/organizations")++ post_call = session.post.call_args+ assert post_call.args[0] == "https://auth.api.platform.sh/oauth2/token"+ assert post_call.kwargs["auth"] == ("platform-api-user", "")+ assert post_call.kwargs["data"] == {"grant_type": "api_token", "api_token": "api-tok"}+ # The bearer token, not the raw API token, authenticates the data request.+ assert session.get.call_args.kwargs["headers"]["Authorization"] == "Bearer bearer-1"++ def test_upsun_platform_uses_upsun_hosts(self) -> None:+ session = _session([_resp(_envelope([]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ client = PlatformShClient("api-tok", "upsun", mock.Mock())+ client.get(f"{client.api_base}/organizations")++ assert client.api_base == "https://api.upsun.com"+ assert session.post.call_args.args[0] == "https://auth.upsun.com/oauth2/token"++ def test_mid_run_401_refreshes_token_and_retries_once(self) -> None:+ # Access tokens expire after ~15 minutes, so a long sync is guaranteed to hit a 401+ # mid-run; the client must re-exchange and retry instead of failing the job.+ tokens = iter([_token_resp("bearer-1"), _token_resp("bearer-2")])+ session = _session(+ [_resp({}, status=401), _resp(_envelope([{"id": "org-1"}]))],+ post_side_effect=lambda *a, **k: next(tokens),+ )+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ client = PlatformShClient("api-tok", "platform_sh", mock.Mock())+ response = client.get(f"{API}/organizations")++ assert response.status_code == 200+ assert session.post.call_count == 2+ assert session.get.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer bearer-2"++ @parameterized.expand([("unauthorized", 401), ("bad_request", 400)])+ def test_rejected_token_exchange_raises_auth_error(self, _name: str, status: int) -> None:+ session = _session([], post_side_effect=lambda *a, **k: _resp({"error": "request_unauthorized"}, status=status))+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ client = PlatformShClient("bad-tok", "platform_sh", mock.Mock())+ with pytest.raises(PlatformShAuthenticationError, match=AUTH_FAILED_MESSAGE):+ client.get(f"{API}/organizations")++ def test_refuses_off_host_urls(self) -> None:+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=mock.Mock()):+ client = PlatformShClient("api-tok", "platform_sh", mock.Mock())+ with pytest.raises(PlatformShUntrustedURLError):+ client.validate_url("https://evil.example.com/organizations")+ with pytest.raises(PlatformShUntrustedURLError):+ client.validate_url("http://api.platform.sh/organizations")++ def test_refuses_redirected_token_exchange(self) -> None:+ # requests preserves the POST body on 307/308, so following a redirect would re-send the+ # long-lived API token to whatever host the redirect names.+ session = _session([], post_side_effect=lambda *a, **k: _resp({}, status=307))+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ client = PlatformShClient("api-tok", "platform_sh", mock.Mock())+ with pytest.raises(PlatformShUntrustedURLError, match="redirect"):+ client.get(f"{API}/organizations")+ assert session.post.call_args.kwargs["allow_redirects"] is False++ def test_sessions_exclude_secret_bearing_bodies_from_capture(self) -> None:+ # Environment/activity responses carry secrets that `_clean_rows` strips only after HTTP+ # sample capture would have recorded the raw body, so capture must stay off — including on+ # the session rebuilt after each token exchange.+ session = _session([_resp(_envelope([{"id": "org-1"}]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session) as factory:+ client = PlatformShClient("api-tok", "platform_sh", mock.Mock())+ client.get(f"{API}/organizations")+ assert factory.call_count >= 2 # __init__ + post-exchange rebuild+ assert all(call.kwargs["capture"] is False for call in factory.call_args_list)+++class TestGetRowsOrganizations:+ def test_follows_relative_next_link_and_checkpoints_after_each_page(self) -> None:+ # `_links.next.href` is a relative HAL link; failing to resolve it against the request URL+ # would silently sync only the first page.+ manager = _manager()+ session = _session(+ [+ _resp(_envelope([{"id": "org-1"}], next_href="/organizations?page%5Bafter%5D=org-1")),+ _resp(_envelope([{"id": "org-2"}])),+ ]+ )+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "organizations", mock.Mock(), manager))++ assert batches == [[{"id": "org-1"}], [{"id": "org-2"}]]+ second_url = session.get.call_args_list[1].args[0]+ assert second_url == f"{API}/organizations?page%5Bafter%5D=org-1"+ # Saved once, after yielding the first page, pointing at the second.+ manager.save_state.assert_called_once_with(PlatformShResumeConfig(next_url=second_url))++ def test_resumes_from_saved_url(self) -> None:+ resume_url = f"{API}/organizations?page%5Bafter%5D=org-5"+ manager = _manager(PlatformShResumeConfig(next_url=resume_url))+ session = _session([_resp(_envelope([{"id": "org-6"}]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "organizations", mock.Mock(), manager))++ assert batches == [[{"id": "org-6"}]]+ assert session.get.call_args_list[0].args[0] == resume_url++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _manager()+ session = _session([_resp(_envelope([]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ assert list(get_rows("tok", "platform_sh", "organizations", mock.Mock(), manager)) == []+ manager.save_state.assert_not_called()+++class TestGetRowsOrgFanOut:+ def test_subscriptions_injects_organization_id_and_checkpoints_org_page(self) -> None:+ # Subscription rows carry no organization_id of their own; without the injected column the+ # table loses its org context.+ manager = _manager()++ def get(url: str, **_kwargs: Any) -> mock.Mock:+ if url == f"{API}/organizations?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "org-1"}]))+ if url == f"{API}/organizations/org-1/subscriptions?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "sub-1", "plan": "medium"}]))+ raise AssertionError(f"unexpected url: {url}")++ session = _session(get)+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "subscriptions", mock.Mock(), manager))++ assert batches == [[{"id": "sub-1", "plan": "medium", "organization_id": "org-1"}]]+ manager.save_state.assert_called_once_with(+ PlatformShResumeConfig(next_url=f"{API}/organizations?page%5Bsize%5D=100")+ )++ def test_environments_fan_out_walks_orgs_then_projects_and_strips_basic_auth(self) -> None:+ manager = _manager()++ def get(url: str, **_kwargs: Any) -> mock.Mock:+ if url == f"{API}/organizations?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "org-1"}]))+ if url == f"{API}/organizations/org-1/projects?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "proj-1"}]))+ if url == f"{API}/projects/proj-1/environments":+ return _resp(+ [+ {+ "id": "main",+ "status": "active",+ "http_access": {"is_enabled": True, "basic_auth": {"admin": "hunter2"}},+ }+ ]+ )+ raise AssertionError(f"unexpected url: {url}")++ session = _session(get)+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "environments", mock.Mock(), manager))++ # project_id is injected (feeds the composite primary key) and the plaintext+ # basic-auth credential block never reaches the warehouse row.+ assert batches == [+ [+ {+ "id": "main",+ "status": "active",+ "http_access": {"is_enabled": True},+ "project_id": "proj-1",+ }+ ]+ ]+++class TestGetRowsActivities:+ def _activity(self, activity_id: str, created_at: str) -> dict[str, Any]:+ return {"id": activity_id, "created_at": created_at, "type": "environment.push"}++ def _fan_out_session(self, activity_pages: list[mock.Mock]) -> mock.Mock:+ pages = iter(activity_pages)++ def get(url: str, **_kwargs: Any) -> mock.Mock:+ if url == f"{API}/organizations?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "org-1"}]))+ if url == f"{API}/organizations/org-1/projects?page%5Bsize%5D=100":+ return _resp(_envelope([{"id": "proj-1"}]))+ if url.startswith(f"{API}/projects/proj-1/activities"):+ return next(pages)+ raise AssertionError(f"unexpected url: {url}")++ return _session(get)++ def test_pages_backwards_with_starts_at_dedupes_and_terminates(self) -> None:+ # The feed is newest-first and `starts_at` bounds by "created before"; a boundary tie can+ # re-return rows. Without id dedupe + the nothing-new stop the walk would loop forever.+ first_page = [+ self._activity("a3", "2026-07-03T00:00:00+00:00"),+ self._activity("a2", "2026-07-02T00:00:00+00:00"),+ ]+ second_page = [+ self._activity("a2", "2026-07-02T00:00:00+00:00"),+ self._activity("a1", "2026-07-01T00:00:00+00:00"),+ ]+ session = self._fan_out_session([_resp(first_page), _resp(second_page), _resp(second_page)])++ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "activities", mock.Mock(), _manager()))++ rows = [row for batch in batches for row in batch]+ assert [row["id"] for row in rows] == ["a3", "a2", "a1"]+ assert all(row["project_id"] == "proj-1" for row in rows)++ activity_urls = [c.args[0] for c in session.get.call_args_list if "/activities" in c.args[0]]+ assert "starts_at" not in activity_urls[0]+ # Second page is bounded by the oldest created_at seen so far.+ assert "starts_at=2026-07-02T00%3A00%3A00%2B00%3A00" in activity_urls[1]++ def test_incremental_cutoff_stops_paging_at_watermark(self) -> None:+ # Without the client-side stop every incremental sync re-walks each project's full history:+ # an API-cost bug and, with pruned activities, a correctness trap.+ first_page = [+ self._activity("a3", "2026-07-03T00:00:00+00:00"),+ self._activity("a2", "2026-07-02T00:00:00+00:00"),+ ]+ session = self._fan_out_session([_resp(first_page)])++ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ "tok",+ "platform_sh",+ "activities",+ mock.Mock(),+ _manager(),+ should_use_incremental_field=True,+ incremental_field="created_at",+ db_incremental_field_last_value="2026-07-02T12:00:00+00:00",+ )+ )++ # Only the row at/after the watermark is yielded, and no second page is requested even+ # though the first page carried rows (the page crossed the watermark).+ rows = [row for batch in batches for row in batch]+ assert [row["id"] for row in rows] == ["a3"]+ activity_urls = [c.args[0] for c in session.get.call_args_list if "/activities" in c.args[0]]+ assert len(activity_urls) == 1++ def test_no_watermark_keeps_walking_until_exhausted(self) -> None:+ first_page = [self._activity("a2", "2026-07-02T00:00:00+00:00")]+ second_page = [self._activity("a1", "2026-07-01T00:00:00+00:00")]+ session = self._fan_out_session([_resp(first_page), _resp(second_page), _resp([])])++ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "activities", mock.Mock(), _manager()))++ rows = [row for batch in batches for row in batch]+ assert [row["id"] for row in rows] == ["a2", "a1"]++ def test_drops_log_field(self) -> None:+ # `log` is unbounded raw build output and prone to echoing secrets; it must not land in a+ # queryable warehouse row.+ page = [{**self._activity("a1", "2026-07-01T00:00:00+00:00"), "log": "building...\nsecret=x"}]+ session = self._fan_out_session([_resp(page), _resp([])])++ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ batches = list(get_rows("tok", "platform_sh", "activities", mock.Mock(), _manager()))++ assert "log" not in batches[0][0]+++class TestValidateCredentials:+ def test_valid_token(self) -> None:+ session = _session([_resp(_envelope([{"id": "org-1"}]))])+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ assert validate_credentials("tok", "platform_sh", mock.Mock()) == (True, None)++ def test_rejected_token(self) -> None:+ session = _session([], post_side_effect=lambda *a, **k: _resp({}, status=401))+ with mock.patch.object(platform_sh, "make_tracked_session", return_value=session):+ ok, error = validate_credentials("bad", "platform_sh", mock.Mock())+ assert ok is False+ assert error == "Invalid Platform.sh API token"+++class TestPlatformShSourceResponse:+ @parameterized.expand(list(PLATFORM_SH_ENDPOINTS.keys()))+ def test_source_response_matches_endpoint_config(self, endpoint: str) -> None:+ config = PLATFORM_SH_ENDPOINTS[endpoint]+ response = platform_sh_source("tok", "platform_sh", endpoint, mock.Mock(), _manager())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == config.sort_mode+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh_source.pynew file mode 100644index 000000000000..57c9d1e1e6da--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/platform_sh/tests/test_platform_sh_source.py@@ -0,0 +1,142 @@+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh import source as source_module+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.platform_sh import (+ AUTH_FAILED_MESSAGE,+ PlatformShResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.platform_sh.source import PlatformShSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestPlatformShSourceConfig:+ def test_source_type(self) -> None:+ assert PlatformShSource().source_type == ExternalDataSourceType.PLATFORMSH++ def test_source_config_shape(self) -> None:+ config = PlatformShSource().get_source_config+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/platform-sh"++ def test_token_and_platform_fields(self) -> None:+ fields = PlatformShSource().get_source_config.fields+ assert fields is not None and len(fields) == 2+ token_field, platform_field = fields+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.name == "api_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.required is True+ assert token_field.secret is True+ assert isinstance(platform_field, SourceFieldSelectConfig)+ assert platform_field.name == "platform"+ assert {option.value for option in platform_field.options} == {"platform_sh", "upsun"}+ assert platform_field.defaultValue == "platform_sh"++ def test_platform_is_a_connection_host_field(self) -> None:+ # `platform` retargets which vendor host the stored token is sent to, so changing it must+ # force the editor to re-enter the secret.+ assert PlatformShSource().connection_host_fields == ["platform"]+++class TestPlatformShGetSchemas:+ def test_only_activities_supports_incremental(self) -> None:+ schemas = {s.name: s for s in PlatformShSource().get_schemas(mock.Mock(), team_id=1)}+ assert set(schemas) == set(ENDPOINTS)++ activities = schemas["activities"]+ assert activities.supports_incremental is True+ assert activities.supports_append is True+ assert [f["field"] for f in activities.incremental_fields] == ["created_at"]+ # Activities mutate after creation; the lookback makes each sync re-read a trailing window+ # so completed states aren't frozen at first-imported values.+ assert activities.default_incremental_lookback_seconds == 86400++ for name, schema in schemas.items():+ if name == "activities":+ continue+ assert not schema.supports_incremental and not schema.supports_append+ assert schema.incremental_fields == []++ def test_names_filter(self) -> None:+ schemas = PlatformShSource().get_schemas(mock.Mock(), team_id=1, names=["projects", "activities"])+ assert {s.name for s in schemas} == {"projects", "activities"}+++class TestPlatformShValidateCredentials:+ def test_plumbs_to_transport(self) -> None:+ config = mock.Mock(api_token="tok", platform="upsun")+ with mock.patch.object(+ source_module, "validate_platform_sh_credentials", return_value=(True, None)+ ) as validate_mock:+ assert PlatformShSource().validate_credentials(config, team_id=1) == (True, None)+ assert validate_mock.call_args.args[:2] == ("tok", "upsun")++ def test_failure_propagates_message(self) -> None:+ config = mock.Mock(api_token="bad", platform="platform_sh")+ with mock.patch.object(+ source_module, "validate_platform_sh_credentials", return_value=(False, "Invalid Platform.sh API token")+ ):+ ok, error = PlatformShSource().validate_credentials(config, team_id=1)+ assert ok is False+ assert error == "Invalid Platform.sh API token"+++class TestPlatformShNonRetryableErrors:+ def test_covers_auth_failures_on_both_hosts(self) -> None:+ # Missing any of these means a permanently-bad credential retries forever.+ errors = PlatformShSource().get_non_retryable_errors()+ assert AUTH_FAILED_MESSAGE in errors+ for host in ("https://api.platform.sh", "https://api.upsun.com"):+ assert f"401 Client Error: Unauthorized for url: {host}" in errors+ assert f"403 Client Error: Forbidden for url: {host}" in errors+++class TestPlatformShCanonicalDescriptions:+ def test_covers_every_endpoint(self) -> None:+ descriptions = PlatformShSource().get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)+++class TestPlatformShResumableWiring:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ inputs = mock.Mock()+ inputs.logger = mock.Mock()+ manager = PlatformShSource().get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PlatformShResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ config = mock.Mock(api_token="tok", platform="upsun")+ inputs = mock.Mock(+ schema_name="activities",+ should_use_incremental_field=True,+ incremental_field="created_at",+ db_incremental_field_last_value="2026-07-01T00:00:00+00:00",+ )+ inputs.logger = mock.Mock()+ manager = mock.Mock()++ with mock.patch.object(source_module, "platform_sh_source") as source_mock:+ PlatformShSource().source_for_pipeline(config, manager, inputs)++ source_mock.assert_called_once_with(+ api_token="tok",+ platform="upsun",+ endpoint="activities",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ incremental_field="created_at",+ db_incremental_field_last_value="2026-07-01T00:00:00+00:00",+ )