: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 northflank import source (#70007)
Tom Owers252a1280d6d9
diff --git a/frontend/public/services/northflank.svg b/frontend/public/services/northflank.svgnew file mode 100644index 000000000000..67538abc3bca--- /dev/null+++ b/frontend/public/services/northflank.svg@@ -0,0 +1,54 @@+<svg viewBox="0 0 52 36" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path+ d="M35.209 17.099l-3.688.909-2.105-3.666-1.301-2.259-1.466-2.522-3.41-5.906h-5.514L3.934 27.547l2.76 4.766H8.8v3.666H5.64a1.833 1.833 0 01-1.58-.913L.245 28.467a1.833 1.833 0 010-1.833L15.096.913A1.833 1.833 0 0116.677 0h7.626a1.833 1.833 0 011.58.913l4.994 8.64.648 1.134 1.467 2.518.653 1.13 1.565 2.764z"+ fill="url(#paint0_linear)" />+ <path+ d="M19.839 26.436l-4.99 8.641a1.834 1.834 0 01-1.58.917H8.8l-4.864-8.432 2.76 4.766h5.5l5.52-9.561 2.123 3.67z"+ fill="url(#paint1_linear)" />+ <path+ d="M35.208 18.924l-3.813 6.6a1.833 1.833 0 01-1.58.916h-4.458l-1.466-2.523-.653-1.129h5.5l2.756-4.765-.524-.91h4.212a1.832 1.832 0 01.026 1.811z"+ fill="url(#paint2_linear)" />+ <path+ d="M45.32 3.674h-5.521l-5.5 9.558-2.104-3.667 4.993-8.64a1.833 1.833 0 011.58-.913h4.447l2.105 3.662z"+ fill="url(#paint3_linear)" />+ <path+ d="M51.767 9.366L36.919 35.084a1.833 1.833 0 01-1.58.916h-7.625a1.833 1.833 0 01-1.58-.916l-4.34-7.516-1.306-2.255-1.466-2.522-.653-1.129-1.58-2.738 3.688-.917 2.108 3.666.653 1.13.652 1.128 1.467 2.523.649 1.125 2.107 3.666.653 1.13h5.5L48.06 8.478l-2.757-4.766h-2.042L43.196.047h3.16a1.833 1.833 0 011.58.913l3.813 6.599a1.834 1.834 0 01.018 1.807z"+ fill="url(#paint4_linear)" />+ <path+ d="M23.245 13.228l-2.757 4.766.528.916H16.8a1.833 1.833 0 010-1.833l3.813-6.599a1.833 1.833 0 011.584-.916h4.461l1.467 2.522.652 1.129-5.532.015z"+ fill="url(#paint5_linear)" />+ <defs>+ <linearGradient id="paint0_linear" x1="-1.228" y1="25.93" x2="29.93"+ y2="7.941" gradientUnits="userSpaceOnUse">+ <stop offset=".2" stop-color="#668CFF" />+ <stop offset=".49" stop-color="#0AF" />+ <stop offset=".8" stop-color="#00BFB5" />+ </linearGradient>+ <linearGradient id="paint1_linear" x1="6.986" y1="32.852" x2="19.403"+ y2="25.681" gradientUnits="userSpaceOnUse">+ <stop offset=".5" stop-color="#668CFF" />+ <stop offset="1" stop-color="#0AF" stop-opacity="0" />+ </linearGradient>+ <linearGradient id="paint2_linear" x1="24.657" y1="25.234" x2="36.092"+ y2="18.631" gradientUnits="userSpaceOnUse">+ <stop stop-color="#0AF" stop-opacity="0" />+ <stop offset=".4" stop-color="#00BFB5" />+ </linearGradient>+ <linearGradient id="paint3_linear" x1="31.92" y1="9.14" x2="44.337"+ y2="1.973" gradientUnits="userSpaceOnUse">+ <stop stop-color="#00BFB5" stop-opacity="0" />+ <stop offset=".5" stop-color="#00CC7C" />+ </linearGradient>+ <linearGradient id="paint4_linear" x1="22.087" y1="28.078" x2="53.241"+ y2="10.092" gradientUnits="userSpaceOnUse">+ <stop offset=".2" stop-color="#0AF" />+ <stop offset=".51" stop-color="#00BFB5" />+ <stop offset=".8" stop-color="#00CC7C" />+ </linearGradient>+ <linearGradient id="paint5_linear" x1="15.917" y1="17.392" x2="27.355"+ y2="10.786" gradientUnits="userSpaceOnUse">+ <stop offset=".6" stop-color="#0AF" />+ <stop offset="1" stop-color="#00BFB5" stop-opacity="0" />+ </linearGradient>+ </defs>+</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 7de38567bfe2..6d60fa909222 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -294,6 +294,7 @@ the row lists both.| newsdata | HTTP | requests | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ |+| northflank | HTTP | requests | ✅ || northpass_lms | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ |@@ -752,7 +753,6 @@ doesn't conflict with concurrent PRs.- nexiopay- ninjaone_rmm- nocrm-- northflank- northpass_lms- nuget- nutshelldiff --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 fb13d12d17df..69df9e5dc62e 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@@ -2772,7 +2772,7 @@ class NoCRMSourceConfig(config.Config):@config.configclass NorthflankSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/canonical_descriptions.pynew file mode 100644index 000000000000..c52f2467a0e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/canonical_descriptions.py@@ -0,0 +1,79 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions sourced from the public Northflank API reference (https://northflank.com/docs/v1/api).+# Fan-out child tables carry a `projectId` column injected by the transport so the row can be tied+# back to its parent project.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "A Northflank project — the top-level container that groups services, jobs, addons, and volumes.",+ "docs_url": "https://northflank.com/docs/v1/api/team/projects/list-projects",+ "columns": {+ "id": "Identifier for the project.",+ "name": "The name of the project.",+ "description": "A short description of the project.",+ },+ },+ "services": {+ "description": "A deployable unit within a project (a combined, build, or deployment service).",+ "docs_url": "https://northflank.com/docs/v1/api/project/services/list-services",+ "columns": {+ "id": "Identifier for the service.",+ "projectId": "Identifier of the project the service belongs to.",+ "appId": "Full identifier used for service deployment.",+ "name": "The name of the service.",+ "tags": "User-defined tags applied to the service.",+ "description": "A short description of the service.",+ "serviceType": "The service type: combined, build, or deployment.",+ "disabledCI": "Whether continuous integration is disabled for the service.",+ "disabledCD": "Whether continuous deployment is disabled for the service.",+ "status": "Build and deployment status of the service.",+ },+ },+ "jobs": {+ "description": "A manual or cron job defined within a project.",+ "docs_url": "https://northflank.com/docs/v1/api/project/jobs/list-jobs",+ "columns": {+ "id": "Identifier for the job.",+ "projectId": "Identifier of the project the job belongs to.",+ "appId": "Full identifier used for job deployment.",+ "name": "The name of the job.",+ "tags": "User-defined tags applied to the job.",+ "description": "A short description of the job.",+ "jobType": "The job type: manual or cron.",+ "disabledCI": "Whether continuous integration is disabled for the job.",+ "disabledCD": "Whether continuous deployment is disabled for the job.",+ "suspended": "Whether the job is suspended.",+ },+ },+ "addons": {+ "description": "A managed addon (e.g. a database) provisioned within a project.",+ "docs_url": "https://northflank.com/docs/v1/api/project/addons/list-addons",+ "columns": {+ "id": "Identifier for the addon.",+ "projectId": "Identifier of the project the addon belongs to.",+ "appId": "Full identifier used for the addon.",+ "name": "The name of the addon.",+ "tags": "User-defined tags applied to the addon.",+ "description": "A short description of the addon.",+ "spec": "The addon specification, including its type.",+ "status": "The current status of the addon.",+ },+ },+ "volumes": {+ "description": "A persistent volume provisioned within a project.",+ "docs_url": "https://northflank.com/docs/v1/api/project/volumes/list-volumes",+ "columns": {+ "id": "Identifier for the volume.",+ "projectId": "Identifier of the project the volume belongs to.",+ "name": "The name of the volume.",+ "tags": "User-defined tags applied to the volume.",+ "spec": "The volume specification (access mode, storage class, and size).",+ "attachedObjects": "Objects the volume is attached to.",+ "status": "The current status of the volume.",+ "createdAt": "When the volume was created.",+ "updatedAt": "When the volume was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/northflank.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/northflank.pynew file mode 100644index 000000000000..64a299facdc3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/northflank.py@@ -0,0 +1,260 @@+from collections.abc import Callable, Iterator+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.northflank.settings import NORTHFLANK_ENDPOINTS++NORTHFLANK_BASE_URL = "https://api.northflank.com"+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+# Northflank paginates at up to 100 results per page (defaults to 50 if unset).+PAGE_SIZE = 100+# Guardrails against an unbounded scan. The 1000 req/hour account rate limit makes deep fan-out+# expensive, so bound both the project scan and each project's child scan by pages.+MAX_PROJECT_PAGES = 500+MAX_CHILD_PAGES_PER_PROJECT = 500+# The API asks us to wait via rate-limit headers on a 429; clamp anything absurd.+MAX_RATE_LIMIT_SLEEP_SECONDS = 120+++class NorthflankRetryableError(Exception):+ def __init__(self, message: str, retry_after: int = 0) -> None:+ super().__init__(message)+ # Seconds the API asked us to wait (from Retry-After/x-ratelimit-reset); 0 when unknown.+ self.retry_after = retry_after+++FetchPageFn = Callable[[str], dict[str, Any]]++_EXPONENTIAL_WAIT = wait_exponential_jitter(initial=1, max=60)+++def _retry_wait(retry_state: RetryCallState) -> float:+ # Honor the API's reset hint once; otherwise back off exponentially. Doing the wait here (rather+ # than sleeping inside fetch_page) avoids stacking both delays.+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, NorthflankRetryableError) and exc.retry_after:+ return exc.retry_after+ return _EXPONENTIAL_WAIT(retry_state)+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_token}",+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _build_url(path: str, params: dict[str, Any] | None = None) -> str:+ clean_params = {key: value for key, value in (params or {}).items() if value is not None}+ if not clean_params:+ return f"{NORTHFLANK_BASE_URL}{path}"+ return f"{NORTHFLANK_BASE_URL}{path}?{urlencode(clean_params)}"+++def _rate_limit_sleep_seconds(response: requests.Response) -> int:+ # `x-ratelimit-reset` is documented as time-to-reset in seconds; prefer a Retry-After if present.+ for header in ("retry-after", "x-ratelimit-reset"):+ raw = response.headers.get(header)+ if raw is None:+ continue+ try:+ seconds = int(float(raw))+ except (TypeError, ValueError):+ continue+ return max(0, min(seconds, MAX_RATE_LIMIT_SLEEP_SECONDS))+ return 0+++def _extract_rows(body: dict[str, Any], data_key: str) -> list[dict[str, Any]]:+ """Pull the row array out of Northflank's `{"data": {...}}` envelope.++ List endpoints nest the array under `data.<resource>` (e.g. `data.projects`). We also tolerate+ `data` being the array itself, since the API reference is inconsistent on this for some+ endpoints and we can't curl-verify every one.+ """+ data = body.get("data")+ if isinstance(data, list):+ return data+ if isinstance(data, dict):+ rows = data.get(data_key)+ if isinstance(rows, list):+ return rows+ return []+++def _next_cursor(body: dict[str, Any]) -> str | None:+ pagination = body.get("pagination") or {}+ if not pagination.get("hasNextPage"):+ return None+ return pagination.get("cursor")+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ """Confirm the token by listing projects (the resource every stream depends on)."""+ # Disable the adapter's urllib3 retry layer: an already rate-limited token would otherwise make+ # validation block the worker for the provider's full (uncapped) Retry-After. Fail fast instead.+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_token,))+ try:+ response = session.get(+ _build_url("/v1/projects", {"per_page": 1}),+ headers=_get_headers(api_token),+ timeout=10,+ )+ except Exception:+ return False, "Could not reach the Northflank API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid Northflank API token. Please check that your token is valid and not revoked."+ return False, f"Northflank API returned an unexpected status: {response.status_code}."+++def _make_fetch_page(api_token: str, logger: FilteringBoundLogger) -> FetchPageFn:+ headers = _get_headers(api_token)+ # One session reused across pages/retries so connection pooling and per-session tracking hold;+ # redact_values masks the token in logs and captured samples. retry=Retry(total=0) disables the+ # adapter's urllib3 retry layer so the tenacity policy below is the only one — otherwise urllib3+ # would retry 429/5xx underneath it, honoring an uncapped Retry-After and stacking retry layers,+ # bypassing this connector's capped rate-limit backoff.+ session = make_tracked_session(retry=Retry(total=0), redact_values=(api_token,))++ @retry(+ retry=retry_if_exception_type((NorthflankRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(url: str) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429:+ sleep_seconds = _rate_limit_sleep_seconds(response)+ logger.debug(f"Northflank: rate limited, retrying after {sleep_seconds}s. url={url}")+ raise NorthflankRetryableError(+ f"Northflank API rate limited: status=429, url={url}", retry_after=sleep_seconds+ )++ if response.status_code >= 500:+ raise NorthflankRetryableError(+ f"Northflank API error (retryable): status={response.status_code}, url={url}"+ )++ if not response.ok:+ logger.error(f"Northflank API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ return fetch_page+++def _iter_pages(+ fetch_page: FetchPageFn,+ path: str,+ logger: FilteringBoundLogger,+ max_pages: int,+ resource: str,+ data_key: str,+) -> Iterator[list[dict[str, Any]]]:+ """Yield each page's rows for a cursor-paginated list endpoint."""+ cursor: str | None = None+ pages_fetched = 0++ while True:+ params = {"per_page": PAGE_SIZE, "cursor": cursor}+ body = fetch_page(_build_url(path, params))+ pages_fetched += 1++ rows = _extract_rows(body, data_key)+ if rows:+ yield rows++ cursor = _next_cursor(body)+ if not cursor:+ return++ if pages_fetched >= max_pages:+ logger.warning(+ f"Northflank: page cap reached for {resource}, stopping pagination. max_pages={max_pages}, path={path}"+ )+ return+++def _iter_project_ids(fetch_page: FetchPageFn, logger: FilteringBoundLogger) -> Iterator[str]:+ for projects in _iter_pages(+ fetch_page, "/v1/projects", logger, max_pages=MAX_PROJECT_PAGES, resource="projects", data_key="projects"+ ):+ for project in projects:+ project_id = project.get("id")+ if not project_id:+ # A project without an id would silently drop all of its nested resources+ # (services, jobs, addons, volumes), leaving a partial import. Fail loudly instead.+ raise ValueError(f"Northflank: project is missing a required 'id' field: {project!r}")+ yield project_id+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ if endpoint not in NORTHFLANK_ENDPOINTS:+ raise ValueError(f"Unknown Northflank endpoint: {endpoint}")++ config = NORTHFLANK_ENDPOINTS[endpoint]+ fetch_page = _make_fetch_page(api_token, logger)++ if not config.fan_out_over_projects:+ yield from _iter_pages(+ fetch_page,+ config.path,+ logger,+ max_pages=MAX_PROJECT_PAGES,+ resource=endpoint,+ data_key=config.data_key,+ )+ return++ for project_id in _iter_project_ids(fetch_page, logger):+ path = config.path.format(project_id=project_id)+ for rows in _iter_pages(+ fetch_page,+ path,+ logger,+ max_pages=MAX_CHILD_PAGES_PER_PROJECT,+ resource=f"{endpoint} of project {project_id}",+ data_key=config.data_key,+ ):+ # Inject the parent project id so the composite primary key is present even on child+ # objects that don't carry it natively (addons, volumes).+ yield [{**row, "projectId": project_id} for row in rows]+++def northflank_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config = NORTHFLANK_ENDPOINTS[endpoint]+ partition_key: Optional[str] = config.partition_key++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(api_token=api_token, endpoint=endpoint, logger=logger),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if partition_key else None,+ partition_format="month" if partition_key else None,+ partition_keys=[partition_key] if partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/settings.pynew file mode 100644index 000000000000..2bc00f8f7f30--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/settings.py@@ -0,0 +1,66 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField+++@dataclass+class NorthflankEndpointConfig:+ name: str+ # Path relative to the API base. Fan-out children use a `{project_id}` placeholder.+ path: str+ # Key inside the response `data` object that holds the row array (e.g. `data.projects`).+ data_key: str+ # Whether the endpoint is queried once per project (fan-out) rather than once globally.+ fan_out_over_projects: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field for datetime partitioning. Only volumes document one; the other+ # list objects expose no timestamps, so they ship unpartitioned.+ partition_key: Optional[str] = None+++# Northflank list endpoints document no server-side timestamp filter (no updated-since/created-after+# param), so every stream is full refresh. Most resources are project-scoped, so the fan-out streams+# first list projects then query the child endpoint once per project.+NORTHFLANK_ENDPOINTS: dict[str, NorthflankEndpointConfig] = {+ "projects": NorthflankEndpointConfig(+ name="projects",+ path="/v1/projects",+ data_key="projects",+ ),+ "services": NorthflankEndpointConfig(+ name="services",+ path="/v1/projects/{project_id}/services",+ data_key="services",+ fan_out_over_projects=True,+ # Service `id` is unique within a project, not across projects, so key on the pair.+ primary_keys=["projectId", "id"],+ ),+ "jobs": NorthflankEndpointConfig(+ name="jobs",+ path="/v1/projects/{project_id}/jobs",+ data_key="jobs",+ fan_out_over_projects=True,+ primary_keys=["projectId", "id"],+ ),+ "addons": NorthflankEndpointConfig(+ name="addons",+ path="/v1/projects/{project_id}/addons",+ data_key="addons",+ fan_out_over_projects=True,+ primary_keys=["projectId", "id"],+ ),+ "volumes": NorthflankEndpointConfig(+ name="volumes",+ path="/v1/projects/{project_id}/volumes",+ data_key="volumes",+ fan_out_over_projects=True,+ primary_keys=["projectId", "id"],+ partition_key="createdAt",+ ),+}++ENDPOINTS = tuple(NORTHFLANK_ENDPOINTS.keys())++# No endpoint exposes a server-side timestamp filter, so there are no advertised incremental fields.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/source.pyindex 91f73a7e611f..bbcbcf0e3a3f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/source.py@@ -1,31 +1,119 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NorthflankSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.northflank import (+ northflank_source,+ validate_credentials as validate_northflank_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass NorthflankSource(SimpleSource[NorthflankSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NORTHFLANK+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.northflank.com": "Your Northflank API token is invalid or has been revoked. Create a new token in your Northflank account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.northflank.com": "Your Northflank API token is missing the permissions needed to sync this data. Grant the required read access, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: NorthflankSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # No Northflank list endpoint exposes a server-side timestamp filter, so every table is+ # full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(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: NorthflankSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_northflank_credentials(config.api_token)++ def source_for_pipeline(self, config: NorthflankSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return northflank_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.NORTHFLANK,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Northflank",- iconPath="/static/services/northflank.png",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Northflank API token to pull your Northflank projects, services, jobs, addons, and volumes into the PostHog Data warehouse.++You can create a personal or team API token in your [Northflank account settings](https://app.northflank.com/). Grant it read access to the resources you want to sync.""",+ iconPath="/static/services/northflank.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/northflank",keywords=["deployment", "containers", "paas", "devops"],- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank.pynew file mode 100644index 000000000000..bea7dff144dd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank.py@@ -0,0 +1,326 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.northflank import (+ MAX_PROJECT_PAGES,+ NorthflankRetryableError,+ _build_url,+ _extract_rows,+ _next_cursor,+ _rate_limit_sleep_seconds,+ get_rows,+ northflank_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.settings import (+ ENDPOINTS,+ NORTHFLANK_ENDPOINTS,+)++PATCH_SESSION = (+ "products.warehouse_sources.backend.temporal.data_imports.sources.northflank.northflank.make_tracked_session"+)+++def _response(body: 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.headers = headers or {}+ response.json.return_value = body+ return response+++def _page(data_key: str, items: list[dict[str, Any]], cursor: str | None) -> dict[str, Any]:+ return {"data": {data_key: items}, "pagination": {"hasNextPage": cursor is not None, "cursor": cursor}}+++def _route_session(mock_session: mock.MagicMock, routes: dict[str, list[dict[str, Any]] | dict[str, Any]]) -> None:+ """Route GET calls by path; values are either a body dict or a list of bodies consumed in order."""+ state: dict[str, int] = {}++ def get(url: str, **kwargs: Any) -> mock.MagicMock:+ path = urlparse(url).path+ body = routes[path]+ if isinstance(body, list):+ index = min(state.get(path, 0), len(body) - 1)+ state[path] = index + 1+ return _response(body[index])+ return _response(body)++ mock_session.return_value.get.side_effect = get+++def _requested_urls(mock_session: mock.MagicMock) -> list[str]:+ return [call.args[0] for call in mock_session.return_value.get.call_args_list]+++class TestBuildUrl:+ def test_no_params(self):+ assert _build_url("/v1/projects") == "https://api.northflank.com/v1/projects"++ def test_drops_none_values_and_encodes(self):+ url = _build_url("/v1/projects", {"per_page": 100, "cursor": None})+ assert url == "https://api.northflank.com/v1/projects?per_page=100"+++class TestExtractRows:+ @parameterized.expand(+ [+ ("nested_under_data_key", {"data": {"projects": [{"id": "p1"}]}}, "projects", [{"id": "p1"}]),+ ("data_is_the_array", {"data": [{"id": "v1"}]}, "volumes", [{"id": "v1"}]),+ ("missing_key", {"data": {"other": []}}, "projects", []),+ ("empty_body", {}, "projects", []),+ ]+ )+ def test_extract_rows(self, _name, body, data_key, expected):+ assert _extract_rows(body, data_key) == expected+++class TestNextCursor:+ @parameterized.expand(+ [+ ({"pagination": {"hasNextPage": True, "cursor": "abc"}}, "abc"),+ ({"pagination": {"hasNextPage": False, "cursor": "abc"}}, None),+ ({"pagination": {"hasNextPage": True}}, None),+ ({}, None),+ ]+ )+ def test_next_cursor(self, body, expected):+ assert _next_cursor(body) == expected+++class TestRateLimitSleep:+ @parameterized.expand(+ [+ ({"retry-after": "5"}, 5),+ ({"x-ratelimit-reset": "30"}, 30),+ ({"retry-after": "9999"}, 120),+ ({"retry-after": "-3"}, 0),+ ({"retry-after": "nope"}, 0),+ ({}, 0),+ ]+ )+ def test_sleep_seconds_from_headers(self, headers, expected):+ response = mock.MagicMock()+ response.headers = headers+ assert _rate_limit_sleep_seconds(response) == expected+++class TestValidateCredentials:+ @parameterized.expand([(200, True), (401, False), (403, False), (500, False)])+ @mock.patch(PATCH_SESSION)+ def test_status_mapping(self, status, expected, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=status)++ is_valid, error = validate_credentials("token")++ assert is_valid is expected+ assert (error is None) is expected++ @mock.patch(PATCH_SESSION)+ def test_connection_error_is_not_valid(self, mock_session):+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, error = validate_credentials("token")++ assert is_valid is False+ assert error is not None++ @mock.patch(PATCH_SESSION)+ def test_sends_bearer_header(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=200)++ validate_credentials("token")++ headers = mock_session.return_value.get.call_args.kwargs["headers"]+ assert headers["Authorization"] == "Bearer token"+++class TestProjectsPagination:+ @mock.patch(PATCH_SESSION)+ def test_paginates_via_cursor(self, mock_session):+ _route_session(+ mock_session,+ {+ "/v1/projects": [+ _page("projects", [{"id": "p1"}, {"id": "p2"}], "cursor-2"),+ _page("projects", [{"id": "p3"}], None),+ ]+ },+ )++ batches = list(get_rows("token", "projects", mock.MagicMock()))++ assert [row["id"] for batch in batches for row in batch] == ["p1", "p2", "p3"]+ urls = _requested_urls(mock_session)+ assert "cursor" not in parse_qs(urlparse(urls[0]).query)+ assert parse_qs(urlparse(urls[1]).query)["cursor"] == ["cursor-2"]++ @mock.patch(PATCH_SESSION)+ def test_empty_page_yields_nothing(self, mock_session):+ _route_session(mock_session, {"/v1/projects": _page("projects", [], None)})++ assert list(get_rows("token", "projects", mock.MagicMock())) == []++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.northflank.northflank.MAX_PROJECT_PAGES", 2+ )+ @mock.patch(PATCH_SESSION)+ def test_page_cap_stops_and_logs(self, mock_session):+ _route_session(mock_session, {"/v1/projects": _page("projects", [{"id": "p"}], "always-more")})+ logger = mock.MagicMock()++ batches = list(get_rows("token", "projects", logger))++ assert len(batches) == 2+ assert mock_session.return_value.get.call_count == 2+ logger.warning.assert_called_once()+ assert "page cap" in logger.warning.call_args.args[0]++ def test_unknown_endpoint_raises(self):+ with pytest.raises(ValueError, match="Unknown Northflank endpoint"):+ list(get_rows("token", "nope", mock.MagicMock()))+++class TestFanOut:+ @mock.patch(PATCH_SESSION)+ def test_child_rows_carry_project_id_across_projects(self, mock_session):+ _route_session(+ mock_session,+ {+ "/v1/projects": _page("projects", [{"id": "proj-a"}, {"id": "proj-b"}], None),+ "/v1/projects/proj-a/services": _page("services", [{"id": "svc-1"}], None),+ "/v1/projects/proj-b/services": _page("services", [{"id": "svc-2"}], None),+ },+ )++ batches = list(get_rows("token", "services", mock.MagicMock()))+ rows = [row for batch in batches for row in batch]++ assert [(row["id"], row["projectId"]) for row in rows] == [("svc-1", "proj-a"), ("svc-2", "proj-b")]++ @mock.patch(PATCH_SESSION)+ def test_injected_project_id_does_not_clobber_native_field(self, mock_session):+ # Volumes don't carry projectId natively; the transport must add it for the composite key.+ _route_session(+ mock_session,+ {+ "/v1/projects": _page("projects", [{"id": "proj-a"}], None),+ "/v1/projects/proj-a/volumes": _page(+ "volumes", [{"id": "vol-1", "createdAt": "2026-01-01T00:00:00Z"}], None+ ),+ },+ )++ rows = [row for batch in get_rows("token", "volumes", mock.MagicMock()) for row in batch]++ assert rows == [{"id": "vol-1", "createdAt": "2026-01-01T00:00:00Z", "projectId": "proj-a"}]++ @mock.patch(PATCH_SESSION)+ def test_child_pagination_per_project(self, mock_session):+ _route_session(+ mock_session,+ {+ "/v1/projects": _page("projects", [{"id": "proj-a"}], None),+ "/v1/projects/proj-a/jobs": [+ _page("jobs", [{"id": "j1"}], "jobs-cursor-2"),+ _page("jobs", [{"id": "j2"}], None),+ ],+ },+ )++ rows = [row for batch in get_rows("token", "jobs", mock.MagicMock()) for row in batch]++ assert [row["id"] for row in rows] == ["j1", "j2"]+ job_urls = [u for u in _requested_urls(mock_session) if "/jobs" in u]+ assert parse_qs(urlparse(job_urls[1]).query)["cursor"] == ["jobs-cursor-2"]++ @mock.patch(PATCH_SESSION)+ def test_project_without_id_raises(self, mock_session):+ # A project missing its id would silently drop all of its nested resources; fail loudly instead.+ _route_session(+ mock_session,+ {"/v1/projects": _page("projects", [{"name": "no id"}], None)},+ )++ with pytest.raises(ValueError, match="missing a required 'id' field"):+ list(get_rows("token", "services", mock.MagicMock()))+++class TestRetryBehavior:+ @mock.patch("tenacity.nap.time.sleep")+ @mock.patch(PATCH_SESSION)+ def test_429_honors_rate_limit_header(self, mock_session, mock_sleep):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=429, headers={"retry-after": "7"}),+ _response(_page("projects", [{"id": "p1"}], None)),+ ]++ rows = [row for batch in get_rows("token", "projects", mock.MagicMock()) for row in batch]++ assert [row["id"] for row in rows] == ["p1"]+ mock_sleep.assert_called_once_with(7)++ @mock.patch(PATCH_SESSION)+ def test_5xx_retries_then_succeeds(self, mock_session):+ mock_session.return_value.get.side_effect = [+ _response({}, status_code=503),+ _response(_page("projects", [{"id": "p1"}], None)),+ ]++ rows = [row for batch in get_rows("token", "projects", mock.MagicMock()) for row in batch]++ assert [row["id"] for row in rows] == ["p1"]+ assert mock_session.return_value.get.call_count == 2++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.northflank.northflank.MAX_RETRIES", 2)+ @mock.patch(PATCH_SESSION)+ def test_persistent_5xx_raises(self, mock_session):+ mock_session.return_value.get.return_value = _response({}, status_code=500)++ with pytest.raises(NorthflankRetryableError):+ list(get_rows("token", "projects", mock.MagicMock()))++ @mock.patch(PATCH_SESSION)+ def test_4xx_raises_immediately(self, mock_session):+ response = _response({}, status_code=401)+ response.raise_for_status.side_effect = Exception("401 Client Error")+ mock_session.return_value.get.return_value = response++ with pytest.raises(Exception, match="401 Client Error"):+ list(get_rows("token", "projects", mock.MagicMock()))++ assert mock_session.return_value.get.call_count == 1+++class TestNorthflankSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_response_metadata_per_endpoint(self, endpoint):+ config = NORTHFLANK_ENDPOINTS[endpoint]+ response = northflank_source("token", endpoint, mock.MagicMock())++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is None+ assert response.partition_keys is None++ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_fan_out_children_key_includes_project(self, endpoint):+ config = NORTHFLANK_ENDPOINTS[endpoint]+ # A fan-out child's id is only unique within its project, so the key must include projectId+ # or duplicate rows accumulate and every merge multi-matches them.+ if config.fan_out_over_projects:+ assert "projectId" in config.primary_keys++ def test_project_page_cap_is_bounded(self):+ assert MAX_PROJECT_PAGES <= 1000diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank_source.pynew file mode 100644index 000000000000..e13b2e76a297--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northflank/tests/test_northflank_source.py@@ -0,0 +1,114 @@+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 NorthflankSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.northflank.source import NorthflankSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestNorthflankSource:+ def setup_method(self):+ self.source = NorthflankSource()+ self.team_id = 123+ self.config = NorthflankSourceConfig(api_token="nf-token")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.NORTHFLANK++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Northflank"+ assert config.label == "Northflank"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source is visible: it must not carry the scaffolding hide flag.+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/northflank.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/northflank"++ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig))+ assert token_field.name == "api_token"+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.northflank.com/v1/projects?per_page=1",),+ ("403 Client Error: Forbidden for url: https://api.northflank.com/v1/projects/abc/services",),+ ]+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ("429 Client Error: Too Many Requests for url: https://api.northflank.com/v1/projects",),+ ("500 Server Error for url: https://api.northflank.com/v1/projects",),+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",),+ ]+ )+ def test_non_retryable_errors_ignore_transient_and_unrelated(self, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])+ def test_no_endpoint_advertises_incremental(self, endpoint):+ # Northflank exposes no server-side timestamp filter, so every table is full refresh.+ schema = next(s for s in self.source.get_schemas(self.config, self.team_id) if s.name == endpoint)+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["services"])+ assert [s.name for s in schemas] == ["services"]++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_without_credentials(self):+ # The static endpoint catalog powers the public docs' Supported tables section.+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ for table in tables:+ assert "Full refresh" in table["sync_methods"]++ @parameterized.expand(+ [+ ((True, None), True),+ ((False, "Invalid Northflank API token. Please check that your token is valid and not revoked."), False),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.northflank.source.validate_northflank_credentials"+ )+ def test_validate_credentials_plumbs_result(self, mock_return, expected_valid, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert (error is None) is expected_valid+ mock_validate.assert_called_once_with("nf-token")++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.northflank.source.northflank_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_northflank_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "services"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_northflank_source.call_args.kwargs+ assert kwargs["api_token"] == "nf-token"+ assert kwargs["endpoint"] == "services"+ assert kwargs["logger"] is inputs.logger