Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.4 KB
Raw Blame
from typing import Optional, cast

from products.warehouse_sources.sources.railway._config import RailwaySourceConfig
from products.warehouse_sources.sources.railway.railway import (
    RailwayResumeConfig,
    railway_source,
    validate_credentials as validate_railway_credentials,
)
from products.warehouse_sources.sources.railway.settings import ENDPOINTS, INCREMENTAL_FIELDS, RAILWAY_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
    CanonicalDescriptions,
    DataWarehouseSourceCategory,
    ExternalDataSourceType,
    FieldType,
    ReleaseStatus,
    ResumableSource,
    ResumableSourceManager,
    SourceConfig,
    SourceFieldInputConfig,
    SourceFieldInputConfigType,
    SourceInputs,
    SourceRegistry,
    SourceResponse,
    SourceSchema,
    detect,
)

_SCHEMA_DESCRIPTIONS: dict[str, str] = {
    "deployments": (
        "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."
    ),
    "deployment_events": (
        "Incremental syncs read events only for deployments created since the last-seen createdAt, "
        "with a 24h lookback for deployments that were still in progress."
    ),
    "usage": "Daily resource usage per project and service, over the last 90 days on the first sync.",
    "metrics": "Hourly resource metrics per service and environment. Railway keeps about 30 days of metrics.",
    "estimated_usage": "Estimated usage per project at the end of the current billing period.",
}


@SourceRegistry.register
class RailwaySource(ResumableSource[RailwaySourceConfig, RailwayResumeConfig]):
    codebase_detection = detect(env=("^RAILWAY_",), npm=("@railway/cli",))

    lists_tables_without_credentials = True  # static endpoint catalog — safe for public docs

    @property
    def source_type(self) -> ExternalDataSourceType:
        return ExternalDataSourceType.RAILWAY

    @property
    def get_source_config(self) -> SourceConfig:
        return SourceConfig(
            name=ExternalDataSourceType.RAILWAY,
            category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
            label="Railway",
            releaseStatus=ReleaseStatus.GA,
            caption="""Enter your Railway API token to pull your Railway workspaces, projects, services, service instances, environments, deployments, deployment events, deployment triggers, project events, members, volumes, volume instances, volume backups, usage, and metrics 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",
            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.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_retryable_errors(self) -> set[str]:
        # `_execute` already retries 429/5xx (as the "Railway API error (retryable)" sentinel),
        # connection failures, and read timeouts in-process. Once that budget exhausts, Temporal
        # retries the whole activity and the failure is transient and self-recovering, so don't
        # surface it as tracked exception noise. The host is a constant, not user input, so
        # matching on it doesn't risk swallowing an unrelated failure.
        return {
            "Railway API error (retryable)",
            "HTTPSConnectionPool(host='backboard.railway.com', port=443)",
        }

    def get_schemas(
        self,
        config: RailwaySourceConfig,
        team_id: int,
        with_counts: bool = False,
        names: list[str] | None = None,
        force_refresh: bool = False,
        api_version: str | None = None,
    ) -> 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=_SCHEMA_DESCRIPTIONS.get(endpoint),
                # Deployments still building/deploying keep changing after creation; re-read a trailing
                # window each incremental run so those rows settle without a full refresh.
                default_incremental_lookback_seconds=RAILWAY_ENDPOINTS[endpoint].default_incremental_lookback_seconds,
            )

        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,
        api_version: str | None = 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,
        )