: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 railway import source (#71204)
Tom Owers749df885c38b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4f4af8147c7b..7f6dfb136b86 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -389,6 +389,7 @@ the row lists both.| pypi | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ || qualys_vmdr | HTTP (XML responses) | requests | ✅ |+| railway | HTTP (GraphQL) | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ || ramp | HTTP | requests | ✅ || rapid7_insightvm | HTTP | requests | ✅ |@@ -842,7 +843,6 @@ doesn't conflict with concurrent PRs.- qonto- qualtrics- quickbooks-- railway- railz- rapid7_insightvm- raygundiff --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 aeb287b0fca8..04a3e87e6941 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@@ -3428,7 +3428,7 @@ class RKICovidSourceConfig(config.Config):@config.configclass RailwaySourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/canonical_descriptions.pynew file mode 100644index 000000000000..7419c29b7e35--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/canonical_descriptions.py@@ -0,0 +1,96 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Railway project — the top-level container that groups services, environments, deployments, and volumes.",+ "docs_url": "https://docs.railway.com/reference/projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "name": "Display name of the project.",+ "description": "User-provided description of the project.",+ "isPublic": "Whether the project is publicly visible.",+ "isTempProject": "Whether the project is a temporary project.",+ "prDeploys": "Whether pull-request environments deploy automatically for this project.",+ "botPrEnvironments": "Whether pull requests opened by bots create PR environments.",+ "workspaceId": "Identifier of the workspace the project belongs to.",+ "baseEnvironmentId": "Identifier of the environment new environments fork from.",+ "primaryEnvironmentId": "Identifier of the project's primary environment.",+ "createdAt": "When the project was created.",+ "updatedAt": "When the project was last updated.",+ "deletedAt": "When the project was deleted, if it has been.",+ },+ },+ "services": {+ "description": "A service within a Railway project — a deployable unit such as an app, database, or worker.",+ "docs_url": "https://docs.railway.com/reference/services",+ "columns": {+ "id": "Unique identifier for the service.",+ "name": "Display name of the service.",+ "icon": "Icon shown for the service in the Railway dashboard.",+ "projectId": "Identifier of the project the service belongs to.",+ "templateId": "Identifier of the template the service was created from, if any.",+ "templateServiceId": "Identifier of the source service within the template, if any.",+ "createdAt": "When the service was created.",+ "updatedAt": "When the service was last updated.",+ "deletedAt": "When the service was deleted, if it has been.",+ },+ },+ "environments": {+ "description": "An environment within a Railway project (e.g. production, staging, or an ephemeral PR environment).",+ "docs_url": "https://docs.railway.com/reference/environments",+ "columns": {+ "id": "Unique identifier for the environment.",+ "name": "Display name of the environment.",+ "projectId": "Identifier of the project the environment belongs to.",+ "isEphemeral": "Whether the environment is ephemeral (e.g. created for a pull request).",+ "unmergedChangesCount": "Number of staged changes not yet merged into the environment.",+ "createdAt": "When the environment was created.",+ "updatedAt": "When the environment was last updated.",+ "deletedAt": "When the environment was deleted, if it has been.",+ },+ },+ "deployments": {+ "description": "A deployment of a Railway service — one build/deploy attempt with its status and timestamps.",+ "docs_url": "https://docs.railway.com/reference/deployments",+ "columns": {+ "id": "Unique identifier for the deployment.",+ "status": "Current status of the deployment (e.g. BUILDING, DEPLOYING, SUCCESS, FAILED, CRASHED, REMOVED).",+ "statusUpdatedAt": "When the deployment's status last changed.",+ "projectId": "Identifier of the project the deployment belongs to.",+ "environmentId": "Identifier of the environment the deployment ran in.",+ "serviceId": "Identifier of the service that was deployed.",+ "snapshotId": "Identifier of the code/config snapshot the deployment was built from.",+ "staticUrl": "Stable URL assigned to the deployment, if any.",+ "url": "Public URL serving the deployment, if any.",+ "meta": "Deployment metadata such as the git branch, commit hash, and commit message.",+ "deploymentStopped": "Whether the deployment has been stopped.",+ "creator": "The user who triggered the deployment (id, name, email).",+ "createdAt": "When the deployment was created.",+ "updatedAt": "When the deployment was last updated.",+ },+ },+ "project_members": {+ "description": "A member of a Railway project and their role.",+ "docs_url": "https://docs.railway.com/reference/teams",+ "columns": {+ "project_id": "Identifier of the project the membership belongs to.",+ "id": "Unique identifier of the member (their Railway user id).",+ "name": "Display name of the member.",+ "email": "Email address of the member.",+ "avatar": "Avatar URL of the member.",+ "role": "The member's role in the project (ADMIN, MEMBER, or VIEWER).",+ },+ },+ "volumes": {+ "description": "A persistent storage volume attached to a Railway project.",+ "docs_url": "https://docs.railway.com/reference/volumes",+ "columns": {+ "id": "Unique identifier for the volume.",+ "name": "Display name of the volume.",+ "projectId": "Identifier of the project the volume belongs to.",+ "createdAt": "When the volume was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/railway.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/railway.pynew file mode 100644index 000000000000..fc02f2733ec0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/railway.py@@ -0,0 +1,365 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+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.railway.settings import (+ RAILWAY_API_URL,+ RAILWAY_ENDPOINTS,+ RAILWAY_PAGE_SIZE,+ VALIDATION_QUERY,+ RailwayEndpointConfig,+)++REQUEST_TIMEOUT_SECONDS = 60+++class RailwayRetryableError(Exception):+ pass+++class RailwayResumeConfig:+ # Relay cursor (`pageInfo.endCursor`) to resume the current connection from. None means+ # "start the connection at its first page".+ cursor: str | None = None+ # The project currently being processed for fan-out endpoints. A stable project-id bookmark+ # (not a positional index) so projects created/deleted between a crash and the retry can't+ # resume us into the wrong project. None for the top-level `projects` endpoint.+ project_id: str | None = None+++def _get_headers(api_token: str) -> dict[str, str]:+ # Railway sits behind a CDN that rejects some default python User-Agent strings with a+ # bare HTTP 403, so always send an explicit one.+ return {+ "Authorization": f"Bearer {api_token}",+ "Content-Type": "application/json",+ "User-Agent": "PostHog-Data-Warehouse/1.0",+ }+++def _raise_for_graphql_errors(payload: dict[str, Any]) -> None:+ errors = payload.get("errors")+ if not errors:+ return+ messages = "; ".join(e.get("message", "") for e in errors)+ if "Not Authorized" in messages:+ # Stable prefix matched by `get_non_retryable_errors` — Railway returns auth failures+ # as HTTP 200 + a GraphQL error, so there is no 401 status to key off.+ raise Exception(f"Railway API error: Not Authorized. GraphQL errors: {messages}")+ raise Exception(f"Railway GraphQL error: {messages}")+++@retry(+ retry=retry_if_exception_type(+ (+ RailwayRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _execute(+ session: requests.Session,+ headers: dict[str, str],+ query: str,+ variables: dict[str, Any],+ logger: FilteringBoundLogger,+) -> dict[str, Any]:+ response = session.post(+ RAILWAY_API_URL, json={"query": query, "variables": variables}, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS+ )++ # Railway rate limits per plan (as low as 100 req/hr on free accounts) and sends Retry-After.+ # An exhausted hourly quota can exceed our backoff window — in that case the attempt fails+ # after the retries and Temporal reschedules the whole activity later.+ if response.status_code == 429 or response.status_code >= 500:+ retry_after = response.headers.get("Retry-After")+ raise RailwayRetryableError(+ f"Railway API error (retryable): status={response.status_code}, retry_after={retry_after}"+ )++ if not response.ok:+ logger.error(f"Railway API error: status={response.status_code}, body={response.text[:500]}")+ response.raise_for_status()++ payload = response.json()+ _raise_for_graphql_errors(payload)++ data = payload.get("data")+ if data is None:+ raise Exception(f"Unexpected Railway response format. Keys: {list(payload.keys())}")++ return data+++def _dig(data: dict[str, Any], path: tuple[str, ...]) -> Any:+ value: Any = data+ for key in path:+ if value is None:+ return None+ value = value.get(key)+ return value+++def _parse_datetime(value: str) -> datetime:+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)+++def _as_utc_datetime(value: Any) -> datetime | None:+ if isinstance(value, datetime):+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)+ if isinstance(value, str):+ try:+ return _parse_datetime(value)+ except ValueError:+ return None+ return None+++def _page_predates_watermark(rows: list[dict[str, Any]], incremental_field: str, watermark: datetime) -> bool:+ """True when every row on the page is older than the incremental watermark.++ Railway's list connections have no server-side time filter, but deployments come back+ newest-first — so an incremental sync can stop paging once a whole page predates the+ last-seen value instead of walking the full history every run.+ """+ for row in rows:+ row_value = _as_utc_datetime(row.get(incremental_field))+ if row_value is None or row_value >= watermark:+ return False+ return True+++def _iter_connection_pages(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ endpoint_config: RailwayEndpointConfig,+ variables: dict[str, Any],+ start_cursor: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk a Relay connection, yielding (rows, next_cursor) per page. next_cursor is None on the last page."""+ cursor = start_cursor+ while True:+ data = _execute(+ session, headers, endpoint_config.query, {**variables, "first": RAILWAY_PAGE_SIZE, "after": cursor}, logger+ )+ connection = _dig(data, endpoint_config.data_path)+ if connection is None:+ # A project deleted between enumeration and this fetch resolves to null. Nothing to read.+ return++ rows = [edge["node"] for edge in connection.get("edges", []) if edge.get("node") is not None]+ page_info = connection.get("pageInfo", {})+ next_cursor = page_info.get("endCursor") if page_info.get("hasNextPage") else None++ yield rows, next_cursor++ if next_cursor is None:+ return+ cursor = next_cursor+++def _iter_project_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:+ projects_config = RAILWAY_ENDPOINTS["projects"]+ ids: list[str] = []+ for rows, _ in _iter_connection_pages(session, headers, logger, projects_config, {}, None):+ ids.extend(row["id"] for row in rows)+ return ids+++def _get_top_level_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ endpoint_config: RailwayEndpointConfig,+ resumable_source_manager: ResumableSourceManager[RailwayResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_cursor = resume.cursor if resume is not None else None+ if start_cursor:+ logger.debug(f"Railway: resuming {endpoint_config.name} from cursor {start_cursor}")++ for rows, next_cursor in _iter_connection_pages(session, headers, logger, endpoint_config, {}, start_cursor):+ if rows:+ yield rows+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last+ # page rather than skipping it — merge dedupes on the primary key.+ if next_cursor is not None:+ resumable_source_manager.save_state(RailwayResumeConfig(cursor=next_cursor))+++def _get_fan_out_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ endpoint_config: RailwayEndpointConfig,+ resumable_source_manager: ResumableSourceManager[RailwayResumeConfig],+ watermark: datetime | None,+ incremental_field: str | None,+) -> Iterator[list[dict[str, Any]]]:+ project_ids = _iter_project_ids(session, headers, logger)++ # Resolve the saved project-id bookmark to the slice of projects still to process. If the+ # bookmarked project no longer exists (deleted between runs), start over from the first+ # project — merge dedupes the re-pulled rows on the primary key.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = project_ids+ resume_cursor: str | None = None+ if resume is not None and resume.project_id is not None and resume.project_id in project_ids:+ remaining = project_ids[project_ids.index(resume.project_id) :]+ resume_cursor = resume.cursor+ logger.debug(f"Railway: resuming {endpoint_config.name} from project {resume.project_id}")++ for index, project_id in enumerate(remaining):+ variables = {"projectId": project_id}++ if not endpoint_config.paginated:+ data = _execute(session, headers, endpoint_config.query, variables, logger)+ items = _dig(data, endpoint_config.data_path) or []+ rows = [{"project_id": project_id, **item} for item in items]+ if rows:+ yield rows+ else:+ start_cursor = resume_cursor+ resume_cursor = None # only the resumed-into project uses the saved cursor+ for rows, next_cursor in _iter_connection_pages(+ session, headers, logger, endpoint_config, variables, start_cursor+ ):+ if rows:+ yield rows+ if next_cursor is not None:+ resumable_source_manager.save_state(RailwayResumeConfig(cursor=next_cursor, project_id=project_id))+ # Stop paging this project's history once an entire page predates the incremental+ # watermark — anything older was already synced (sort_mode="desc" persists the+ # watermark only after the whole job succeeds).+ if (+ watermark is not None+ and incremental_field is not None+ and rows+ and _page_predates_watermark(rows, incremental_field, watermark)+ ):+ logger.debug(+ f"Railway: {endpoint_config.name} page for project {project_id} predates watermark, stopping"+ )+ break++ # Advance the bookmark to the next project so a crash between projects resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(RailwayResumeConfig(cursor=None, project_id=remaining[index + 1]))+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RailwayResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = RAILWAY_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)+ session = make_tracked_session()++ watermark: datetime | None = None+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ watermark = _as_utc_datetime(db_incremental_field_last_value)++ try:+ if endpoint_config.fan_out_over_projects:+ yield from _get_fan_out_rows(+ session,+ headers,+ logger,+ endpoint_config,+ resumable_source_manager,+ watermark,+ incremental_field,+ )+ else:+ yield from _get_top_level_rows(session, headers, logger, endpoint_config, resumable_source_manager)+ finally:+ session.close()+++def railway_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RailwayResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ endpoint_config = RAILWAY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ incremental_field=incremental_field,+ ),+ primary_keys=endpoint_config.primary_keys,+ # Railway's connections return newest-first and have no server-side time filter, so the+ # incremental watermark must persist only at successful job end — a partial run's max+ # says nothing about older pages (or other projects) it never reached.+ sort_mode="desc",+ partition_count=1 if endpoint_config.partition_keys else None,+ partition_size=1 if endpoint_config.partition_keys else None,+ partition_mode="datetime" if endpoint_config.partition_keys else None,+ partition_format="month" if endpoint_config.partition_keys else None,+ partition_keys=endpoint_config.partition_keys,+ )+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ session = make_tracked_session()+ try:+ response = session.post(+ RAILWAY_API_URL,+ json={"query": VALIDATION_QUERY, "variables": {}},+ headers=_get_headers(api_token),+ timeout=10,+ )+ response.raise_for_status()+ payload = response.json()++ errors = payload.get("errors")+ if errors:+ messages = "; ".join(e.get("message", "") for e in errors)+ if "Not Authorized" in messages:+ return (+ False,+ "Invalid Railway API token. Create an account or workspace token in your Railway account settings (project tokens are not supported).",+ )+ return False, f"Railway API error: {messages}"++ if payload.get("data", {}).get("projects") is not None:+ return True, None+ return False, "Could not verify Railway credentials"+ except Exception as e:+ return False, str(e)+ finally:+ session.close()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/settings.pynew file mode 100644index 000000000000..9b15fd253c1f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/settings.py@@ -0,0 +1,223 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++RAILWAY_API_URL = "https://backboard.railway.com/graphql/v2"+# Railway doesn't document a hard max page size; dashboard queries use small values, so stay <= 100.+RAILWAY_PAGE_SIZE = 100++CREATED_AT = "createdAt"++INCREMENTAL_CREATED_AT: list[IncrementalField] = [+ {+ "label": CREATED_AT,+ "type": IncrementalFieldType.DateTime,+ "field": CREATED_AT,+ "field_type": IncrementalFieldType.DateTime,+ },+]++_PAGE_INFO = "pageInfo { hasNextPage endCursor }"++PROJECTS_QUERY = f"""+query Projects($first: Int!, $after: String) {{+ projects(first: $first, after: $after) {{+ edges {{+ node {{+ id+ name+ description+ isPublic+ isTempProject+ prDeploys+ botPrEnvironments+ workspaceId+ baseEnvironmentId+ primaryEnvironmentId+ createdAt+ updatedAt+ deletedAt+ }}+ }}+ {_PAGE_INFO}+ }}+}}+"""++SERVICES_QUERY = f"""+query ProjectServices($projectId: String!, $first: Int!, $after: String) {{+ project(id: $projectId) {{+ services(first: $first, after: $after) {{+ edges {{+ node {{+ id+ name+ icon+ projectId+ templateId+ templateServiceId+ createdAt+ updatedAt+ deletedAt+ }}+ }}+ {_PAGE_INFO}+ }}+ }}+}}+"""++ENVIRONMENTS_QUERY = f"""+query ProjectEnvironments($projectId: String!, $first: Int!, $after: String) {{+ environments(projectId: $projectId, first: $first, after: $after) {{+ edges {{+ node {{+ id+ name+ projectId+ isEphemeral+ unmergedChangesCount+ createdAt+ updatedAt+ deletedAt+ }}+ }}+ {_PAGE_INFO}+ }}+}}+"""++DEPLOYMENTS_QUERY = f"""+query ProjectDeployments($projectId: String!, $first: Int!, $after: String) {{+ deployments(input: {{ projectId: $projectId }}, first: $first, after: $after) {{+ edges {{+ node {{+ id+ status+ statusUpdatedAt+ projectId+ environmentId+ serviceId+ snapshotId+ staticUrl+ url+ meta+ deploymentStopped+ creator {{+ id+ name+ }}+ createdAt+ updatedAt+ }}+ }}+ {_PAGE_INFO}+ }}+}}+"""++PROJECT_MEMBERS_QUERY = """+query ProjectMembers($projectId: String!) {+ projectMembers(projectId: $projectId) {+ id+ name+ avatar+ role+ }+}+"""++VOLUMES_QUERY = f"""+query ProjectVolumes($projectId: String!, $first: Int!, $after: String) {{+ project(id: $projectId) {{+ volumes(first: $first, after: $after) {{+ edges {{+ node {{+ id+ name+ projectId+ createdAt+ }}+ }}+ {_PAGE_INFO}+ }}+ }}+}}+"""++# Cheapest authenticated probe that works for both account and workspace tokens+# (workspace/team tokens cannot call `me`, so probe `projects` instead).+VALIDATION_QUERY = """+query ValidateToken {+ projects(first: 1) {+ edges {+ node {+ id+ }+ }+ }+}+"""+++@dataclass+class RailwayEndpointConfig:+ name: str+ query: str+ # Path from the response `data` object down to the connection (or plain list) to read.+ data_path: tuple[str, ...]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ partition_keys: list[str] | None = None+ # Whether the query pages a Relay connection (edges/pageInfo) vs returning a plain list.+ paginated: bool = True+ # Whether the endpoint runs once per project (projects are enumerated first).+ fan_out_over_projects: bool = True+++RAILWAY_ENDPOINTS: dict[str, RailwayEndpointConfig] = {+ "projects": RailwayEndpointConfig(+ name="projects",+ query=PROJECTS_QUERY,+ data_path=("projects",),+ fan_out_over_projects=False,+ ),+ "services": RailwayEndpointConfig(+ name="services",+ query=SERVICES_QUERY,+ data_path=("project", "services"),+ ),+ "environments": RailwayEndpointConfig(+ name="environments",+ query=ENVIRONMENTS_QUERY,+ data_path=("environments",),+ ),+ "deployments": RailwayEndpointConfig(+ name="deployments",+ query=DEPLOYMENTS_QUERY,+ data_path=("deployments",),+ incremental_fields=INCREMENTAL_CREATED_AT,+ partition_keys=[CREATED_AT],+ ),+ "project_members": RailwayEndpointConfig(+ name="project_members",+ query=PROJECT_MEMBERS_QUERY,+ data_path=("projectMembers",),+ paginated=False,+ # Member ids are user ids, shared across projects — the project id must be in the key.+ primary_keys=["project_id", "id"],+ ),+ "volumes": RailwayEndpointConfig(+ name="volumes",+ query=VOLUMES_QUERY,+ data_path=("project", "volumes"),+ ),+}++ENDPOINTS = tuple(RAILWAY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in RAILWAY_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/source.pyindex b075bb367a46..f551c06f3048 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.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 RailwaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.railway import (+ RailwayResumeConfig,+ railway_source,+ validate_credentials as validate_railway_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class RailwaySource(SimpleSource[RailwaySourceConfig]):+class RailwaySource(ResumableSource[RailwaySourceConfig, RailwayResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.RAILWAY@@ -24,7 +47,100 @@ class RailwaySource(SimpleSource[RailwaySourceConfig]):name=SchemaExternalDataSourceType.RAILWAY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Railway",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Railway API token to pull your Railway projects, services, environments, deployments, members, and volumes into the PostHog Data warehouse.++Create an account or workspace token in your [Railway account settings](https://railway.com/account/tokens). Project tokens are not supported — they are scoped to a single environment and cannot list your projects.++Note that Railway rate limits API requests per plan (as low as 100 requests/hour on the Free plan), which can slow down large initial syncs.""",iconPath="/static/services/railway.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/railway",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.railway.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # Railway returns auth failures as HTTP 200 + a GraphQL "Not Authorized" error; the+ # transport re-raises them with this stable prefix. Retrying can never fix a bad token.+ "Railway API error: Not Authorized": "Your Railway API token is invalid, revoked, or lacks access to this resource. Create a new account or workspace token in your Railway account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: RailwaySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ # Deployment rows mutate after creation (status, updatedAt), so merge is the only+ # safe write mode — append would materialize stale duplicates.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ description=(+ "Incremental syncs page newest-first and stop at the last-seen createdAt. A 24h "+ "lookback re-pulls recent deployments so late status changes are picked up; older "+ "status changes only refresh on a full refresh."+ if endpoint == "deployments"+ else None+ ),+ # Deployments still building/deploying keep changing status after creation; re-read a+ # trailing day each incremental run so those rows settle without a full refresh.+ default_incremental_lookback_seconds=86400 if endpoint == "deployments" else None,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: RailwaySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_railway_credentials(config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RailwayResumeConfig]:+ return ResumableSourceManager[RailwayResumeConfig](inputs, RailwayResumeConfig)++ def source_for_pipeline(+ self,+ config: RailwaySourceConfig,+ resumable_source_manager: ResumableSourceManager[RailwayResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return railway_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ incremental_field=inputs.incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway.pynew file mode 100644index 000000000000..879d16ee05d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway.py@@ -0,0 +1,288 @@+from datetime import UTC, datetime+from typing import Any++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.railway import railway+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.railway import (+ RailwayResumeConfig,+ RailwayRetryableError,+ get_rows,+ railway_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.source import RailwaySource++RAILWAY_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.railway.railway"+++class FakeResumableSourceManager:+ def __init__(self, state: RailwayResumeConfig | None = None):+ self.state = state+ self.saved: list[RailwayResumeConfig] = []++ def can_resume(self) -> bool:+ return self.state is not None++ def load_state(self) -> RailwayResumeConfig | None:+ return self.state++ def save_state(self, state: RailwayResumeConfig) -> None:+ self.saved.append(state)+ self.state = state+++def _response(payload: dict[str, Any], status_code: int = 200, headers: dict[str, str] | None = None) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = payload+ response.headers = headers or {}+ response.text = ""+ return response+++def _connection(path: tuple[str, ...], nodes: list[dict[str, Any]], end_cursor: str | None = None) -> dict[str, Any]:+ data: Any = {+ "edges": [{"node": node} for node in nodes],+ "pageInfo": {"hasNextPage": end_cursor is not None, "endCursor": end_cursor},+ }+ for key in reversed(path):+ data = {key: data}+ return {"data": data}+++def _projects_page(ids: list[str], end_cursor: str | None = None) -> dict[str, Any]:+ return _connection(("projects",), [{"id": project_id} for project_id in ids], end_cursor)+++def _run(+ endpoint: str,+ responses: list[dict[str, Any] | mock.MagicMock],+ manager: FakeResumableSourceManager | None = None,+ **kwargs: Any,+) -> tuple[list[list[dict[str, Any]]], mock.MagicMock, FakeResumableSourceManager]:+ manager = manager or FakeResumableSourceManager()+ session = mock.MagicMock()+ session.post.side_effect = [r if isinstance(r, mock.MagicMock) else _response(r) for r in responses]++ with mock.patch(f"{RAILWAY_MODULE}.make_tracked_session", return_value=session):+ batches = list(+ get_rows(+ api_token="token",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ )+ )+ return batches, session, manager+++def _request_variables(session: mock.MagicMock, call_index: int) -> dict[str, Any]:+ return session.post.call_args_list[call_index].kwargs["json"]["variables"]+++class TestRailway:+ def test_projects_pagination_follows_cursor_and_saves_state_after_yield(self):+ batches, session, manager = _run(+ "projects",+ [+ _projects_page(["p1", "p2"], end_cursor="c1"),+ _projects_page(["p3"]),+ ],+ )++ assert [[row["id"] for row in batch] for batch in batches] == [["p1", "p2"], ["p3"]]+ assert _request_variables(session, 0)["after"] is None+ assert _request_variables(session, 1)["after"] == "c1"+ # State saved once (after the first page yielded) — never for the terminal page.+ assert [state.cursor for state in manager.saved] == ["c1"]++ def test_projects_resume_starts_from_saved_cursor(self):+ _, session, _ = _run(+ "projects",+ [_projects_page(["p3"])],+ manager=FakeResumableSourceManager(RailwayResumeConfig(cursor="c9")),+ )++ assert _request_variables(session, 0)["after"] == "c9"++ def test_fan_out_queries_each_project_and_bookmarks_the_next(self):+ batches, session, manager = _run(+ "services",+ [+ _projects_page(["p1", "p2"]),+ _connection(("project", "services"), [{"id": "s1", "projectId": "p1"}]),+ _connection(("project", "services"), [{"id": "s2", "projectId": "p2"}]),+ ],+ )++ assert [[row["id"] for row in batch] for batch in batches] == [["s1"], ["s2"]]+ assert _request_variables(session, 1)["projectId"] == "p1"+ assert _request_variables(session, 2)["projectId"] == "p2"+ # A crash between projects must resume at p2, not restart the whole fan-out.+ assert [(state.project_id, state.cursor) for state in manager.saved] == [("p2", None)]++ def test_fan_out_resume_skips_completed_projects_and_uses_saved_cursor(self):+ _, session, _ = _run(+ "services",+ [+ _projects_page(["p1", "p2", "p3"]),+ _connection(("project", "services"), [{"id": "s2b", "projectId": "p2"}]),+ _connection(("project", "services"), [{"id": "s3", "projectId": "p3"}]),+ ],+ manager=FakeResumableSourceManager(RailwayResumeConfig(cursor="c5", project_id="p2")),+ )++ first_child = _request_variables(session, 1)+ assert first_child["projectId"] == "p2"+ assert first_child["after"] == "c5"+ # p3 starts fresh — the saved cursor belongs to p2's connection only.+ assert _request_variables(session, 2)["after"] is None++ def test_fan_out_resume_with_deleted_bookmark_project_starts_over(self):+ batches, session, _ = _run(+ "services",+ [+ _projects_page(["p1"]),+ _connection(("project", "services"), [{"id": "s1", "projectId": "p1"}]),+ ],+ manager=FakeResumableSourceManager(RailwayResumeConfig(cursor="c5", project_id="gone")),+ )++ assert _request_variables(session, 1)["projectId"] == "p1"+ assert _request_variables(session, 1)["after"] is None++ def test_fan_out_skips_project_deleted_mid_sync(self):+ batches, _, _ = _run(+ "services",+ [+ _projects_page(["p1", "p2"]),+ {"data": {"project": None}},+ _connection(("project", "services"), [{"id": "s2", "projectId": "p2"}]),+ ],+ )++ assert [[row["id"] for row in batch] for batch in batches] == [["s2"]]++ def test_project_members_rows_carry_project_id(self):+ batches, _, _ = _run(+ "project_members",+ [+ _projects_page(["p1"]),+ {"data": {"projectMembers": [{"id": "u1", "email": "[email protected]", "role": "ADMIN"}]}},+ ],+ )++ assert batches == [[{"project_id": "p1", "id": "u1", "email": "[email protected]", "role": "ADMIN"}]]++ def test_deployments_incremental_stops_once_page_predates_watermark(self):+ deployments_path = ("deployments",)+ batches, session, _ = _run(+ "deployments",+ [+ _projects_page(["p1"]),+ _connection(+ deployments_path,+ [+ {"id": "d1", "createdAt": "2024-07-01T00:00:00Z"},+ {"id": "d2", "createdAt": "2024-06-15T00:00:00Z"},+ ],+ end_cursor="c1",+ ),+ _connection(+ deployments_path,+ [+ {"id": "d3", "createdAt": "2024-05-01T00:00:00Z"},+ {"id": "d4", "createdAt": "2024-04-01T00:00:00Z"},+ ],+ end_cursor="c2",+ ),+ # A third page exists server-side but must never be requested.+ ],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 6, 1, tzinfo=UTC),+ incremental_field="createdAt",+ )++ # Both pages yielded (the boundary page merges/dedupes), but pagination stops there.+ assert [[row["id"] for row in batch] for batch in batches] == [["d1", "d2"], ["d3", "d4"]]+ assert session.post.call_count == 3++ def test_deployments_full_history_walked_when_no_watermark(self):+ deployments_path = ("deployments",)+ batches, session, _ = _run(+ "deployments",+ [+ _projects_page(["p1"]),+ _connection(deployments_path, [{"id": "d1", "createdAt": "2024-07-01T00:00:00Z"}], end_cursor="c1"),+ _connection(deployments_path, [{"id": "d2", "createdAt": "2024-04-01T00:00:00Z"}]),+ ],+ )++ assert [[row["id"] for row in batch] for batch in batches] == [["d1"], ["d2"]]+ assert session.post.call_count == 3++ def test_not_authorized_error_matches_non_retryable_catalog(self):+ with pytest.raises(Exception) as exc_info:+ _run("projects", [{"errors": [{"message": "Not Authorized"}], "data": None}])++ non_retryable = RailwaySource().get_non_retryable_errors()+ assert any(key in str(exc_info.value) for key in non_retryable)++ @parameterized.expand([(429,), (500,), (503,)])+ def test_retryable_status_codes(self, status_code):+ session = mock.MagicMock()+ session.post.return_value = _response({}, status_code=status_code)++ with pytest.raises(RailwayRetryableError):+ railway._execute.__wrapped__(session, {}, "query {}", {}, mock.MagicMock()) # type: ignore[attr-defined]++ def test_source_response_shape_per_endpoint(self):+ manager = FakeResumableSourceManager()++ deployments = railway_source("token", "deployments", mock.MagicMock(), manager) # type: ignore[arg-type]+ assert deployments.primary_keys == ["id"]+ assert deployments.sort_mode == "desc"+ assert deployments.partition_mode == "datetime"+ assert deployments.partition_keys == ["createdAt"]++ members = railway_source("token", "project_members", mock.MagicMock(), manager) # type: ignore[arg-type]+ # Member ids repeat across projects — dropping the composite key would seed duplicate+ # rows that every later merge multi-matches.+ assert members.primary_keys == ["project_id", "id"]+ assert members.partition_mode is None++ @parameterized.expand(+ [+ ({"data": {"projects": {"edges": []}}}, True, None),+ ({"errors": [{"message": "Not Authorized"}], "data": None}, False, "token"),+ ({"errors": [{"message": "Something else"}], "data": None}, False, "Something else"),+ ]+ )+ def test_validate_credentials(self, payload, expected_valid, expected_message_contains):+ session = mock.MagicMock()+ session.post.return_value = _response(payload)++ with mock.patch(f"{RAILWAY_MODULE}.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("token")++ assert is_valid is expected_valid+ if expected_message_contains is None:+ assert message is None+ else:+ assert message is not None and expected_message_contains in message++ def test_validate_credentials_network_error_returns_invalid(self):+ session = mock.MagicMock()+ session.post.side_effect = ConnectionError("boom")++ with mock.patch(f"{RAILWAY_MODULE}.make_tracked_session", return_value=session):+ is_valid, message = validate_credentials("token")++ assert is_valid is False+ assert message is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway_source.pynew file mode 100644index 000000000000..1b6f6f9a6f5c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/railway/tests/test_railway_source.py@@ -0,0 +1,116 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import RailwaySourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.railway import RailwayResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.railway.source import RailwaySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestRailwaySource:+ def setup_method(self):+ self.source = RailwaySource()+ self.team_id = 123+ self.config = RailwaySourceConfig(api_token="railway-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.RAILWAY++ def test_source_is_released(self):+ config = self.source.get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA++ def test_token_field_is_secret_password(self):+ config = self.source.get_source_config++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_token"]++ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ # Railway has no server-side time filters; only deployments (newest-first, watermark-stop)+ # can sync incrementally.+ incremental = {schema.name for schema in schemas if schema.supports_incremental}+ assert incremental == {"deployments"}++ def test_deployments_schema_incremental_settings(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ deployments = schemas["deployments"]+ assert [f["field"] for f in deployments.incremental_fields] == ["createdAt"]+ # Deployment rows mutate (status) — merge-only, with a lookback so recent statuses settle.+ assert deployments.supports_append is False+ assert deployments.default_incremental_lookback_seconds == 86400++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["deployments", "nope"])++ assert [schema.name for schema in schemas] == ["deployments"]++ @parameterized.expand(+ [+ ((True, None), True, None),+ ((False, "Invalid Railway API token"), False, "Invalid Railway API token"),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.railway.source.validate_railway_credentials"+ )+ def test_validate_credentials(self, mock_return, expected_valid, expected_message, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("railway-token")++ def test_get_resumable_source_manager_binds_resume_config(self):+ inputs = mock.MagicMock()++ manager = self.source.get_resumable_source_manager(inputs)++ assert manager._data_class is RailwayResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.railway.source.railway_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_railway_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "deployments"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"+ inputs.incremental_field = "createdAt"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_railway_source.call_args.kwargs+ assert kwargs["api_token"] == "railway-token"+ assert kwargs["endpoint"] == "deployments"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05.000Z"+ assert kwargs["incremental_field"] == "createdAt"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.railway.source.railway_source")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_railway_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "deployments"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05.000Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_railway_source.call_args.kwargs["db_incremental_field_last_value"] is None