Skip to content

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

feat(data-warehouse): implement aviationstack import source (#66721)

Tom Owers9a6743ca2b4f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 159a0bb11c23..0fc2de2bce70 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -57,6 +57,7 @@ the row lists both.
| ashby | HTTP | requests | ✅ |
| attentive | HTTP (webhook-first) | requests (webhook management) | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| aviationstack | HTTP | requests | ✅ |
| azure_devops | HTTP | requests | ✅ |
| bamboohr | HTTP | requests | ✅ |
| beamer | HTTP | requests | ✅ |
@@ -313,7 +314,6 @@ doesn't conflict with concurrent PRs.
- apptivo
- assemblyai
- auth0
-- aviationstack
- awin
- aws_cloudtrail
- azure_blob
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/aviationstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/aviationstack.py
new file mode 100644
index 000000000000..a706b64a4fa5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/aviationstack.py
@@ -0,0 +1,177 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+
+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.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
+ AVIATIONSTACK_ENDPOINTS,
+)
+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
+
+AVIATIONSTACK_BASE_URL = "https://api.aviationstack.com/v1"
+DEFAULT_PAGE_SIZE = 100
+
+# aviationstack returns HTTP 200 with an error envelope (`{"error": {"code": ...}}`). Transient
+# body-level codes are retried with backoff; every other code (bad/blocked key, plan gating,
+# exhausted monthly quota — e.g. invalid_access_key, missing_access_key, inactive_user,
+# function_access_restricted, https_access_restricted, usage_limit_reached) fails fast and is
+# surfaced as a permanent failure matched by AviationstackSource.get_non_retryable_errors.
+_RETRYABLE_ERROR_CODES = {"rate_limit_reached"}
+
+
+class AviationstackRetryableError(Exception):
+ pass
+
+
+class AviationstackAPIError(Exception):
+ pass
+
+
+class AviationstackResumeConfig:
+ # Offset of the next page to fetch — aviationstack uses limit/offset pagination.
+ next_offset: int
+
+
+@retry(
+ retry=retry_if_exception_type((AviationstackRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ # `url` carries no secrets — the access_key lives in `params`, which requests keeps out of the
+ # log line emitted here — so it's safe to log on error.
+ response = session.get(url, params=params, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AviationstackRetryableError(
+ f"aviationstack API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"aviationstack API error: status={response.status_code}, url={url}")
+ # Don't use `response.raise_for_status()` — it embeds `response.url` (which carries the
+ # access_key query param) in the error message, and that exception is later logged via
+ # `str(error)` outside the tracked session's redaction. Strip the query string instead.
+ kind = "Client Error" if response.status_code < 500 else "Server Error"
+ safe_url = response.url.split("?", 1)[0]
+ raise requests.HTTPError(
+ f"{response.status_code} {kind}: {response.reason} for url: {safe_url}", response=response
+ )
+
+ body = response.json()
+ error = body.get("error") if isinstance(body, dict) else None
+ if error:
+ code = error.get("code", "unknown")
+ message = error.get("message", "")
+ if code in _RETRYABLE_ERROR_CODES:
+ raise AviationstackRetryableError(f"aviationstack API error (retryable) [{code}]: {message}")
+ # Permanent codes (and anything unrecognized) fail fast — the keys in
+ # get_non_retryable_errors match on the `[code]` token.
+ raise AviationstackAPIError(f"aviationstack API error [{code}]: {message}")
+
+ return body
+
+
+def get_rows(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AviationstackResumeConfig],
+ page_size: int = DEFAULT_PAGE_SIZE,
+) -> Iterator[Any]:
+ config = AVIATIONSTACK_ENDPOINTS[endpoint]
+ url = f"{AVIATIONSTACK_BASE_URL}{config.path}"
+ # `access_key` is passed as a query param on every request, so mask its value from the
+ # tracked session's logged URLs and captured samples.
+ session = make_tracked_session(redact_values=(access_key,))
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.next_offset if resume is not None else 0
+ if resume is not None:
+ logger.debug(f"aviationstack: resuming {endpoint} from offset={offset}")
+
+ while True:
+ params = {"access_key": access_key, "offset": offset, "limit": page_size}
+ body = _fetch_page(session, url, params, logger)
+
+ items = body.get("data") if isinstance(body, dict) else None
+ if not isinstance(items, list):
+ items = []
+
+ pagination = body.get("pagination") if isinstance(body, dict) else None
+ total = pagination.get("total") if isinstance(pagination, dict) else None
+
+ next_offset = offset + page_size
+ has_more = len(items) >= page_size and (not isinstance(total, int) or next_offset < total)
+
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the last
+ # page rather than skipping it — merge/replace dedupes the re-pulled rows.
+ if has_more:
+ resumable_source_manager.save_state(AviationstackResumeConfig(next_offset=next_offset))
+
+ if not has_more or len(items) == 0:
+ break
+ offset = next_offset
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def aviationstack_source(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AviationstackResumeConfig],
+) -> SourceResponse:
+ config = AVIATIONSTACK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_key=access_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ )
+
+
+def validate_credentials(access_key: str) -> bool:
+ # `/countries` is a static reference endpoint available on every plan (including free), so it's a
+ # cheap probe that the access key is genuine without depending on a paid-tier endpoint.
+ url = f"{AVIATIONSTACK_BASE_URL}/countries"
+ params: dict[str, Any] = {"access_key": access_key, "limit": 1}
+ try:
+ session = make_tracked_session(redact_values=(access_key,))
+ response = session.get(url, params=params, timeout=10)
+ except Exception:
+ return False
+
+ if response.status_code != 200:
+ return False
+
+ try:
+ body = response.json()
+ except ValueError:
+ return False
+
+ return not (isinstance(body, dict) and bool(body.get("error")))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/canonical_descriptions.py
new file mode 100644
index 000000000000..342df65cf59e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/canonical_descriptions.py
@@ -0,0 +1,164 @@
+"""Canonical, documentation-sourced descriptions for aviationstack endpoints and columns.
+
+Sourced from the official aviationstack API documentation (https://aviationstack.com/documentation).
+Keyed by the endpoint names in `settings.py` `AVIATIONSTACK_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "flights": {
+ "description": "Real-time and recent flight records, including status, departure/arrival, airline, flight number, aircraft, and live position.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "flight_date": "Date of the flight in YYYY-MM-DD format.",
+ "flight_status": "Status of the flight (e.g. scheduled, active, landed, cancelled, incident, diverted).",
+ "departure": "Departure details, including airport name, IATA/ICAO codes, terminal, gate, and scheduled/actual times.",
+ "arrival": "Arrival details, including airport name, IATA/ICAO codes, terminal, gate, baggage, and scheduled/actual times.",
+ "airline": "Operating airline, including name and IATA/ICAO codes.",
+ "flight": "Flight identifiers, including the flight number and IATA/ICAO codes plus any codeshare info.",
+ "aircraft": "Aircraft details, including registration and IATA/ICAO type codes (null when unavailable).",
+ "live": "Live tracking data, including latitude, longitude, altitude, direction, and speed (null when unavailable).",
+ },
+ },
+ "routes": {
+ "description": "Scheduled airline routes with departure, arrival, airline, and flight details.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "departure": "Departure airport details, including IATA/ICAO codes, terminal, and scheduled time.",
+ "arrival": "Arrival airport details, including IATA/ICAO codes, terminal, and scheduled time.",
+ "airline": "Operating airline, including name, callsign, and IATA/ICAO codes.",
+ "flight": "Flight identifiers, including the flight number and IATA/ICAO codes.",
+ },
+ },
+ "airports": {
+ "description": "Reference table of airports with location, codes, and timezone.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the airport record.",
+ "gmt": "GMT offset for the airport.",
+ "airport_id": "aviationstack internal airport ID.",
+ "iata_code": "IATA code of the airport.",
+ "icao_code": "ICAO code of the airport.",
+ "city_iata_code": "IATA code of the city the airport serves.",
+ "country_iso2": "ISO 3166-1 alpha-2 code of the airport's country.",
+ "geoname_id": "GeoNames identifier for the airport location.",
+ "latitude": "Latitude of the airport.",
+ "longitude": "Longitude of the airport.",
+ "airport_name": "Name of the airport.",
+ "country_name": "Name of the airport's country.",
+ "phone_number": "Phone number of the airport.",
+ "timezone": "Timezone of the airport (e.g. America/New_York).",
+ },
+ },
+ "airlines": {
+ "description": "Reference table of airlines with codes, fleet, and status.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the airline record.",
+ "airline_id": "aviationstack internal airline ID.",
+ "airline_name": "Name of the airline.",
+ "iata_code": "IATA code of the airline.",
+ "icao_code": "ICAO code of the airline.",
+ "callsign": "Radio callsign of the airline.",
+ "hub_code": "IATA code of the airline's primary hub airport.",
+ "fleet_size": "Number of aircraft in the airline's fleet.",
+ "fleet_average_age": "Average age of the airline's fleet in years.",
+ "date_founded": "Year the airline was founded.",
+ "iata_prefix_accounting": "IATA accounting/ticketing prefix code.",
+ "country_iso2": "ISO 3166-1 alpha-2 code of the airline's country.",
+ "country_name": "Name of the airline's country.",
+ "status": "Operational status of the airline (e.g. active).",
+ "type": "Type of airline (e.g. scheduled).",
+ },
+ },
+ "airplanes": {
+ "description": "Reference table of individual aircraft with registration, model, and operator details.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the airplane record.",
+ "airplane_id": "aviationstack internal airplane ID.",
+ "registration_number": "Aircraft registration number.",
+ "production_line": "Production line of the aircraft.",
+ "iata_type": "IATA type designator of the aircraft.",
+ "model_name": "Model name of the aircraft.",
+ "model_code": "Model code of the aircraft.",
+ "icao_code_hex": "ICAO 24-bit hexadecimal aircraft address.",
+ "iata_code_long": "Long IATA aircraft code.",
+ "iata_code_short": "Short IATA aircraft code.",
+ "construction_number": "Manufacturer construction (serial) number.",
+ "test_registration_number": "Test registration number used before delivery.",
+ "delivery_date": "Date the aircraft was delivered.",
+ "first_flight_date": "Date of the aircraft's first flight.",
+ "registration_date": "Date the aircraft was registered.",
+ "rollout_date": "Date the aircraft rolled out of production.",
+ "line_number": "Production line number.",
+ "plane_age": "Age of the aircraft in years.",
+ "plane_class": "Class of the aircraft.",
+ "plane_owner": "Owner of the aircraft.",
+ "plane_series": "Series of the aircraft.",
+ "plane_status": "Status of the aircraft (e.g. active).",
+ "engines_count": "Number of engines on the aircraft.",
+ "engines_type": "Type of engines on the aircraft (e.g. JET).",
+ "airline_iata_code": "IATA code of the operating airline.",
+ "airline_icao_code": "ICAO code of the operating airline.",
+ },
+ },
+ "aircraft_types": {
+ "description": "Reference table of aircraft types with IATA codes.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the aircraft type record.",
+ "iata_code": "IATA code of the aircraft type.",
+ "aircraft_name": "Name of the aircraft type.",
+ "plane_type_id": "aviationstack internal plane type ID.",
+ },
+ },
+ "cities": {
+ "description": "Reference table of cities with codes, location, and timezone.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the city record.",
+ "gmt": "GMT offset for the city.",
+ "city_id": "aviationstack internal city ID.",
+ "iata_code": "IATA code of the city.",
+ "country_iso2": "ISO 3166-1 alpha-2 code of the city's country.",
+ "geoname_id": "GeoNames identifier for the city.",
+ "latitude": "Latitude of the city.",
+ "longitude": "Longitude of the city.",
+ "city_name": "Name of the city.",
+ "timezone": "Timezone of the city (e.g. Europe/London).",
+ },
+ },
+ "countries": {
+ "description": "Reference table of countries with ISO codes, currency, and population.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the country record.",
+ "country_name": "Name of the country.",
+ "country_iso2": "ISO 3166-1 alpha-2 code of the country.",
+ "country_iso3": "ISO 3166-1 alpha-3 code of the country.",
+ "country_iso_numeric": "ISO 3166-1 numeric code of the country.",
+ "population": "Population of the country.",
+ "capital": "Capital city of the country.",
+ "continent": "Continent the country belongs to.",
+ "currency_name": "Name of the country's currency.",
+ "currency_code": "ISO 4217 currency code of the country.",
+ "fips_code": "FIPS code of the country.",
+ "phone_prefix": "International dialing prefix of the country.",
+ },
+ },
+ "taxes": {
+ "description": "Reference table of aviation taxes with names and IATA codes.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "id": "Unique identifier for the tax record.",
+ "tax_id": "aviationstack internal tax ID.",
+ "tax_name": "Name of the tax.",
+ "iata_code": "IATA code of the tax.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/settings.py
new file mode 100644
index 000000000000..375b3f3ea7d4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/settings.py
@@ -0,0 +1,74 @@
+import dataclasses
+
+
+class AviationstackEndpointConfig:
+ name: str
+ path: str
+ # aviationstack reference tables expose a stable row `id`; the flight/route feeds do not (each
+ # record is a nested flight document with no top-level identifier), so those sync as keyless full
+ # refresh snapshots.
+ primary_keys: list[str] | None
+ description: str | None = None
+
+
+# aviationstack has no record-level updated-at cursor (the `flight_date` filter is a per-day window
+# limited to ~3 months, not a true incremental cursor), so every endpoint is full refresh.
+AVIATIONSTACK_ENDPOINTS: dict[str, AviationstackEndpointConfig] = {
+ "flights": AviationstackEndpointConfig(
+ name="flights",
+ path="/flights",
+ primary_keys=None,
+ description="Real-time and recent flight status, including departure, arrival, airline, and live position. Full refresh snapshot.",
+ ),
+ "routes": AviationstackEndpointConfig(
+ name="routes",
+ path="/routes",
+ primary_keys=None,
+ description="Scheduled airline routes with departure, arrival, airline, and flight details. Full refresh snapshot.",
+ ),
+ "airports": AviationstackEndpointConfig(
+ name="airports",
+ path="/airports",
+ primary_keys=["id"],
+ description="Reference table of airports with IATA/ICAO codes, location, and timezone.",
+ ),
+ "airlines": AviationstackEndpointConfig(
+ name="airlines",
+ path="/airlines",
+ primary_keys=["id"],
+ description="Reference table of airlines with IATA/ICAO codes, fleet, and status.",
+ ),
+ "airplanes": AviationstackEndpointConfig(
+ name="airplanes",
+ path="/airplanes",
+ primary_keys=["id"],
+ description="Reference table of individual aircraft with registration, model, and operator details.",
+ ),
+ "aircraft_types": AviationstackEndpointConfig(
+ name="aircraft_types",
+ path="/aircraft_types",
+ primary_keys=["id"],
+ description="Reference table of aircraft types with IATA codes.",
+ ),
+ "cities": AviationstackEndpointConfig(
+ name="cities",
+ path="/cities",
+ primary_keys=["id"],
+ description="Reference table of cities with IATA codes, location, and timezone.",
+ ),
+ "countries": AviationstackEndpointConfig(
+ name="countries",
+ path="/countries",
+ primary_keys=["id"],
+ description="Reference table of countries with ISO codes, currency, and population.",
+ ),
+ "taxes": AviationstackEndpointConfig(
+ name="taxes",
+ path="/taxes",
+ primary_keys=["id"],
+ description="Reference table of aviation taxes with names and IATA codes.",
+ ),
+}
+
+ENDPOINTS = tuple(AVIATIONSTACK_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/source.py
index 7f0b1560d53d..d5f5678de984 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/source.py
@@ -1,30 +1,144 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack import (
+ AviationstackResumeConfig,
+ aviationstack_source,
+ validate_credentials as validate_aviationstack_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
+ AVIATIONSTACK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AviationstackSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AviationstackSource(SimpleSource[AviationstackSourceConfig]):
+class AviationstackSource(ResumableSource[AviationstackSourceConfig, AviationstackResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AVIATIONSTACK
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Bad/blocked key surfaces as an HTTP 401 (missing or invalid access_key) — retrying can
+ # never satisfy a credential problem. Match the stable status text and base host.
+ "401 Client Error: Unauthorized for url: https://api.aviationstack.com": "Your aviationstack access key is invalid or has been deactivated. Generate a new key in your aviationstack dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.aviationstack.com": "Your aviationstack plan does not grant access to this data. Upgrade your aviationstack plan or deselect the restricted tables, then reconnect.",
+ # aviationstack also returns HTTP 200 with a body-level error envelope; these are raised as
+ # AviationstackAPIError with a stable `[code]` token (see aviationstack._fetch_page).
+ "aviationstack API error [invalid_access_key]": "Your aviationstack access key is invalid or has been deactivated. Generate a new key in your aviationstack dashboard, then reconnect.",
+ "aviationstack API error [missing_access_key]": "No aviationstack access key was supplied. Reconnect the source with a valid access key.",
+ "aviationstack API error [inactive_user]": "Your aviationstack account is inactive. Reactivate it in your aviationstack dashboard, then reconnect.",
+ "aviationstack API error [function_access_restricted]": "Your aviationstack plan does not grant access to this data. Upgrade your aviationstack plan or deselect the restricted tables, then reconnect.",
+ "aviationstack API error [https_access_restricted]": "Your aviationstack plan does not allow HTTPS access. Upgrade your aviationstack plan, then reconnect.",
+ "aviationstack API error [usage_limit_reached]": "Your aviationstack monthly request quota has been reached. Upgrade your plan or wait for the quota to reset, then resync.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AviationstackSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # aviationstack has no server-side updated-at cursor, so every table is full refresh only.
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ description=endpoint.description,
+ )
+ for endpoint in AVIATIONSTACK_ENDPOINTS.values()
+ ]
+
+ 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: AviationstackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_aviationstack_credentials(config.access_key):
+ return True, None
+
+ return False, "Invalid aviationstack access key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AviationstackResumeConfig]:
+ return ResumableSourceManager[AviationstackResumeConfig](inputs, AviationstackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AviationstackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AviationstackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return aviationstack_source(
+ access_key=config.access_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.AVIATIONSTACK,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Aviationstack",
- iconPath="/static/services/aviationstack.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your aviationstack access key to pull real-time, scheduled, and historical flight data plus aviation reference tables into the PostHog Data warehouse.
+
+You can find your access key in your [aviationstack dashboard](https://aviationstack.com/dashboard).
+
+Note: aviationstack pricing is a monthly request quota tied to your plan. Some tables (e.g. historical flights and certain filters) require a paid plan.""",
+ iconPath="/static/services/aviationstack.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/aviationstack",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_key",
+ label="Access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack.py
new file mode 100644
index 000000000000..67789b3b5dca
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack.py
@@ -0,0 +1,194 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack import aviationstack
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack import (
+ AviationstackAPIError,
+ AviationstackResumeConfig,
+ AviationstackRetryableError,
+ _fetch_page,
+ aviationstack_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
+ AVIATIONSTACK_ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack"
+
+
+def _response(
+ *, data: Any = None, total: int | None = None, status: int = 200, ok: bool = True, error: dict | None = None
+) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ response.reason = "Client Error" if status < 500 else "Server Error"
+ # Real requests responses expose the full URL (access_key included) on `response.url`.
+ response.url = "https://api.aviationstack.com/v1/airlines?access_key=supersecret&limit=1"
+ body: dict[str, Any] = {}
+ if error is not None:
+ body["error"] = error
+ else:
+ body["data"] = data if data is not None else []
+ body["pagination"] = {"limit": 100, "offset": 0, "count": len(data or []), "total": total}
+ response.json.return_value = body
+ return response
+
+
+def _session_returning(responses: list[MagicMock]) -> MagicMock:
+ session = MagicMock()
+ session.get.side_effect = responses
+ return session
+
+
+def _resume_manager(saved: AviationstackResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = saved is not None
+ manager.load_state.return_value = saved
+ return manager
+
+
+def _collect_rows(tables: Any) -> list[dict]:
+ rows: list[dict] = []
+ for table in tables:
+ rows.extend(table.to_pylist())
+ return rows
+
+
+class TestFetchPage:
+ def test_returns_body_on_success(self) -> None:
+ session = _session_returning([_response(data=[{"id": 1}], total=1)])
+ body = _fetch_page(session, "https://api.aviationstack.com/v1/airlines", {"access_key": "k"}, MagicMock())
+ assert body["data"] == [{"id": 1}]
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_http_client_error_raises(self, _name: str, status: int) -> None:
+ session = _session_returning([_response(status=status, ok=False)])
+ with pytest.raises(requests.HTTPError) as exc:
+ _fetch_page(session, "https://api.aviationstack.com/v1/airlines", {"access_key": "k"}, MagicMock())
+ # The access_key must never appear in the error message — it's logged downstream via str(error).
+ assert "supersecret" not in str(exc.value)
+ assert "access_key" not in str(exc.value)
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_retries_then_raises(self, _name: str, status: int) -> None:
+ session = _session_returning([_response(status=status, ok=False)] * 5)
+ with patch("time.sleep"), pytest.raises(AviationstackRetryableError):
+ _fetch_page(session, "https://api.aviationstack.com/v1/airlines", {"access_key": "k"}, MagicMock())
+ assert session.get.call_count == 5
+
+ def test_body_error_envelope_raises_permanent(self) -> None:
+ session = _session_returning([_response(error={"code": "invalid_access_key", "message": "bad"})])
+ with pytest.raises(AviationstackAPIError) as exc:
+ _fetch_page(session, "https://api.aviationstack.com/v1/airlines", {"access_key": "k"}, MagicMock())
+ # The stable [code] token is what get_non_retryable_errors matches on.
+ assert "[invalid_access_key]" in str(exc.value)
+
+ def test_body_error_envelope_rate_limit_is_retryable(self) -> None:
+ session = _session_returning([_response(error={"code": "rate_limit_reached", "message": "slow down"})] * 5)
+ with patch("time.sleep"), pytest.raises(AviationstackRetryableError):
+ _fetch_page(session, "https://api.aviationstack.com/v1/airlines", {"access_key": "k"}, MagicMock())
+ assert session.get.call_count == 5
+
+
+class TestGetRows:
+ def test_paginates_until_total_reached(self) -> None:
+ page1 = [{"id": i} for i in range(2)]
+ page2 = [{"id": i} for i in range(2, 4)]
+ session = _session_returning([_response(data=page1, total=4), _response(data=page2, total=4)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("k", "airlines", MagicMock(), _resume_manager(), page_size=2))
+ assert [r["id"] for r in rows] == [0, 1, 2, 3]
+ assert session.get.call_count == 2
+
+ def test_stops_on_short_page(self) -> None:
+ # A page shorter than the limit means there's no further page, even without a total.
+ session = _session_returning([_response(data=[{"id": 1}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("k", "airlines", MagicMock(), _resume_manager(), page_size=100))
+ assert [r["id"] for r in rows] == [1]
+ assert session.get.call_count == 1
+
+ def test_stops_on_empty_first_page(self) -> None:
+ session = _session_returning([_response(data=[], total=0)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("k", "airlines", MagicMock(), _resume_manager(), page_size=100))
+ assert rows == []
+ assert session.get.call_count == 1
+
+ def test_resumes_from_saved_offset(self) -> None:
+ session = _session_returning([_response(data=[{"id": 9}], total=None)])
+ manager = _resume_manager(AviationstackResumeConfig(next_offset=200))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(get_rows("k", "airlines", MagicMock(), manager, page_size=100))
+ # The first (and only) request must start from the persisted offset, not 0.
+ assert session.get.call_args_list[0].kwargs["params"]["offset"] == 200
+
+ def test_saves_state_after_yielding_a_batch(self) -> None:
+ # Batcher flushes at 2000 rows, so two full 2000-row pages force a mid-stream yield + save.
+ page1 = [{"id": i} for i in range(2000)]
+ page2 = [{"id": i} for i in range(2000, 4000)]
+ session = _session_returning([_response(data=page1, total=4000), _response(data=page2, total=4000)])
+ manager = _resume_manager()
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("k", "airlines", MagicMock(), manager, page_size=2000))
+ assert len(rows) == 4000
+ # State is saved with the next offset to resume from, only while more pages remain.
+ manager.save_state.assert_called_once_with(AviationstackResumeConfig(next_offset=2000))
+
+
+class TestAviationstackSource:
+ @parameterized.expand(
+ [
+ ("airlines", ["id"]),
+ ("airports", ["id"]),
+ ("countries", ["id"]),
+ ("flights", None),
+ ("routes", None),
+ ]
+ )
+ def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str] | None) -> None:
+ response = aviationstack_source("k", endpoint, MagicMock(), _resume_manager())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+
+ def test_every_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in AVIATIONSTACK_ENDPOINTS:
+ response = aviationstack_source("k", endpoint, MagicMock(), _resume_manager())
+ assert response.name == endpoint
+ assert callable(response.items)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, {"data": []}, True),
+ ("unauthorized", 401, {"error": {"code": "invalid_access_key"}}, False),
+ ("ok_status_but_error_body", 200, {"error": {"code": "usage_limit_reached"}}, False),
+ ]
+ )
+ def test_validate_credentials_status_mapping(self, _name: str, status: int, body: dict, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.json.return_value = body
+ session = MagicMock()
+ session.get.return_value = response
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("k") is expected
+
+ def test_validate_credentials_handles_network_error(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ assert validate_credentials("k") is False
+
+
+def test_module_exposes_base_url() -> None:
+ assert aviationstack.AVIATIONSTACK_BASE_URL == "https://api.aviationstack.com/v1"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack_source.py
new file mode 100644
index 000000000000..8665e73aeda2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/tests/test_aviationstack_source.py
@@ -0,0 +1,117 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack import (
+ AviationstackResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.source import AviationstackSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_config(access_key: str = "key") -> Any:
+ config = MagicMock()
+ config.access_key = access_key
+ return config
+
+
+class TestAviationstackSource:
+ def test_source_type(self) -> None:
+ assert AviationstackSource().source_type == ExternalDataSourceType.AVIATIONSTACK
+
+ def test_source_config_has_single_access_key_field(self) -> None:
+ config = AviationstackSource().get_source_config
+ assert [f.name for f in config.fields] == ["access_key"]
+ access_key_field = config.fields[0]
+ assert isinstance(access_key_field, SourceFieldInputConfig)
+ # The access key is a secret credential, so it must render as a password input.
+ assert access_key_field.type == "password"
+ assert access_key_field.secret is True
+ assert access_key_field.required is True
+
+ def test_source_config_stays_unreleased_alpha(self) -> None:
+ config = AviationstackSource().get_source_config
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/aviationstack"
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:
+ schemas = AviationstackSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # aviationstack has no server-side updated-at cursor, so nothing supports incremental.
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = AviationstackSource().get_schemas(_make_config(), team_id=1, names=["airlines", "airports"])
+ assert {s.name for s in schemas} == {"airlines", "airports"}
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid aviationstack access key"),
+ ]
+ )
+ def test_validate_credentials(
+ self, _name: str, probe_result: bool, expected_ok: bool, expected_message: str | None
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.source.validate_aviationstack_credentials",
+ return_value=probe_result,
+ ):
+ ok, message = AviationstackSource().validate_credentials(_make_config(), team_id=1)
+ assert ok is expected_ok
+ assert message == expected_message
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = AviationstackSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AviationstackResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "airlines"
+ inputs.logger = MagicMock()
+ manager = MagicMock()
+
+ response = AviationstackSource().source_for_pipeline(_make_config("abc"), manager, inputs)
+
+ assert response.name == "airlines"
+ # Reference tables carry a stable row id.
+ assert response.primary_keys == ["id"]
+
+ def test_source_for_pipeline_keyless_for_flight_feeds(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "flights"
+ inputs.logger = MagicMock()
+ response = AviationstackSource().source_for_pipeline(_make_config(), MagicMock(), inputs)
+ assert response.primary_keys is None
+
+ @parameterized.expand(
+ [
+ ("http_unauthorized", "401 Client Error: Unauthorized for url: https://api.aviationstack.com"),
+ ("body_invalid_key", "aviationstack API error [invalid_access_key]"),
+ ("body_usage_limit", "aviationstack API error [usage_limit_reached]"),
+ ("body_function_restricted", "aviationstack API error [function_access_restricted]"),
+ ]
+ )
+ def test_non_retryable_errors_cover_permanent_failures(self, _name: str, expected_key: str) -> None:
+ errors = AviationstackSource().get_non_retryable_errors()
+ assert expected_key in errors
+ assert errors[expected_key]
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = AviationstackSource().get_canonical_descriptions()
+ # Every documented entry must map to a real endpoint or the docs render orphaned tables.
+ assert set(descriptions.keys()) <= set(ENDPOINTS)
+ assert "flights" in descriptions
+ assert "airlines" in descriptions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 0074afd13eee..1c6b05ed1c8c 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
@@ -348,7 +348,7 @@ class Auth0SourceConfig(config.Config):
@config.config
class AviationstackSourceConfig(config.Config):
- pass
+ access_key: str
@config.config