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(warehouse-sources): sync aviationstack timetable and future flights (#99677)

Tom Owers919d4800f96c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 322098ce2af0..9b6d6fa823e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -612,14 +612,14 @@ Note: Every list endpoint in the API reference is already synced: listCustomers,
## Aviationstack — gaps
-Today (9): `aircraft_types`, `airlines`, `airplanes`, `airports`, `cities`, `countries`, `flights`, `routes`, `taxes`
+Today (11): `aircraft_types`, `airlines`, `airplanes`, `airports`, `cities`, `countries`, `flights`, `flights_future`, `routes`, `taxes`, `timetable`
Diffed against: <http://web.archive.org/web/20260411010945/https://aviationstack.com/documentation>
-- [ ] `GET /v1/timetable` — live airport departure/arrival schedules with terminal, gate and delay status - the operational view flights alone does not give per-airport (high)
-- [ ] `GET /v1/flightsFuture` — future scheduled flights by airport and date, needed for any forward-looking capacity or schedule analysis (medium)
+- [x] `GET /v1/timetable` — live airport departure/arrival schedules with terminal, gate and delay status - the operational view flights alone does not give per-airport (high)
+- [x] `GET /v1/flightsFuture` — future scheduled flights by airport and date, needed for any forward-looking capacity or schedule analysis (medium)
-Note: The live docs URL now 301s to docs.apilayer.com and lands in an auth-gated SwaggerHub login loop, so the endpoint list was read from a recent Wayback snapshot of the vendor's own documentation page and cross-checked against the api.aviationstack.com/v1/\* URLs embedded in it. The 9 synced tables cover every other documented endpoint (historical flights are the same /flights endpoint with flight_date). /v1/autocomplete is a typeahead helper, not a queryable collection. Both gap endpoints require an iata_code/airport parameter, so they would need a per-airport configuration rather than a plain full-table pull.
+Note: The live docs URL now 301s to docs.apilayer.com and lands in an auth-gated SwaggerHub login loop, so the endpoint list was read from a recent Wayback snapshot of the vendor's own documentation page and cross-checked against the api.aviationstack.com/v1/\* URLs embedded in it. The 11 synced tables cover every documented endpoint (historical flights are the same /flights endpoint with flight_date). /v1/autocomplete is a typeahead helper, not a queryable collection. Both per-airport endpoints fan out over the airport IATA codes configured on the source rather than doing a plain full-table pull.
## Aviator — gaps
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
index 4f21c34694b8..dc883e12ed35 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/aviationstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/aviationstack.py
@@ -1,8 +1,16 @@
+import datetime
import dataclasses
+from collections.abc import Iterator
from typing import Any, Optional
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
AVIATIONSTACK_ENDPOINTS,
+ FLIGHTS_FUTURE_DEFAULT_DAYS,
+ FLIGHTS_FUTURE_FIRST_DAY_AHEAD,
+ FLIGHTS_FUTURE_MAX_DAYS,
+ MAX_AIRPORTS,
+ SCHEDULE_TYPES,
+ AviationstackEndpointConfig,
)
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.rest_source import (
@@ -12,13 +20,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ ResponseAction,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
AVIATIONSTACK_BASE_URL = "https://api.aviationstack.com/v1"
DEFAULT_PAGE_SIZE = 100
+# The per-airport feeds allow one request every 10s (paid) or 60s (free), so a throttled page has to
+# be able to wait out a whole window. The client's default budget (5 attempts, doubling from 1s)
+# tops out at 15s of waiting, which clears neither window.
+THROTTLED_RETRY_ATTEMPTS = 8
+THROTTLED_RETRY_BACKOFF_MAX_SECONDS = 70.0
+
+# Every IATA airport code is exactly three letters; anything else is junk we should not request.
+IATA_CODE_LENGTH = 3
+
# aviationstack returns HTTP 200 with an error envelope (`{"error": {"code": ...}}`). The single
# transient body code is retried in-process; every listed permanent code (bad/blocked key, plan
# gating, exhausted monthly quota) fails fast and is surfaced with a stable `[code]` token matched by
@@ -35,10 +56,76 @@ _PERMANENT_BODY_CODES = (
)
[email protected](frozen=True)
class AviationstackResumeConfig:
# Offset of the next page to fetch — aviationstack uses limit/offset pagination.
next_offset: int
+ # Position in the per-airport request plan to pick back up from. Always 0 for the endpoints that
+ # take a single request.
+ next_request_index: int = 0
+ # First lookahead date of the plan the index refers to, so a resume rebuilds the same plan.
+ plan_start_date: str | None = None
+
+
[email protected](frozen=True)
+class AviationstackRequest:
+ """One (airport, schedule type, date) request in a per-airport endpoint's fan-out plan."""
+
+ params: dict[str, str]
+ # Which airport/type/date produced a row. /flightsFuture rows carry a weekday and a wall-clock
+ # time but no date, so without this the future schedule cannot be placed on a calendar at all.
+ row_context: dict[str, str]
+
+
+def parse_iata_codes(raw: str | None) -> list[str]:
+ """Split the user's airport list into upper-case IATA codes, dropping junk and duplicates."""
+ if not raw:
+ return []
+
+ codes: list[str] = []
+ seen: set[str] = set()
+ for token in raw.replace("\n", ",").replace(" ", ",").split(","):
+ code = token.strip().upper()
+ if len(code) != IATA_CODE_LENGTH or not code.isascii() or not code.isalpha() or code in seen:
+ continue
+ seen.add(code)
+ codes.append(code)
+ # Stop at the cap rather than walking a list of any length just to truncate it after.
+ if len(codes) == MAX_AIRPORTS:
+ break
+ return codes
+
+
+def _future_dates(days: int | None, today: datetime.date | None = None) -> list[str]:
+ window = FLIGHTS_FUTURE_DEFAULT_DAYS if days is None else days
+ window = max(1, min(window, FLIGHTS_FUTURE_MAX_DAYS))
+ start = (today or datetime.datetime.now(datetime.UTC).date()) + datetime.timedelta(
+ days=FLIGHTS_FUTURE_FIRST_DAY_AHEAD
+ )
+ return [(start + datetime.timedelta(days=offset)).isoformat() for offset in range(window)]
+
+
+def build_request_plan(
+ config: AviationstackEndpointConfig,
+ iata_codes: list[str],
+ flights_future_days: int | None = None,
+ today: datetime.date | None = None,
+) -> list[AviationstackRequest]:
+ if not config.per_airport:
+ return [AviationstackRequest(params={}, row_context={})]
+
+ dates = _future_dates(flights_future_days, today) if config.needs_date else [None]
+ plan: list[AviationstackRequest] = []
+ for code in iata_codes:
+ for schedule_type in SCHEDULE_TYPES:
+ for date in dates:
+ params = {"iataCode": code, "type": schedule_type}
+ context = {"queried_iata_code": code, "queried_type": schedule_type}
+ if date is not None:
+ params["date"] = date
+ context["queried_date"] = date
+ plan.append(AviationstackRequest(params=params, row_context=context))
+ return plan
def _response_actions() -> list[ResponseAction]:
@@ -80,6 +167,47 @@ def _response_actions() -> list[ResponseAction]:
return actions
+def _rest_config(access_key: str, config: AviationstackEndpointConfig, params: dict[str, str]) -> RESTAPIConfig:
+ client: ClientConfig = {
+ "base_url": AVIATIONSTACK_BASE_URL,
+ # access_key rides in the query string; the framework auth redacts its value from every
+ # logged URL, captured sample, and raised error message.
+ "auth": {"type": "api_key", "api_key": access_key, "name": "access_key", "location": "query"},
+ "paginator": OffsetPaginator(limit=DEFAULT_PAGE_SIZE, total_path="pagination.total"),
+ }
+ if config.throttled:
+ client["max_retries"] = THROTTLED_RETRY_ATTEMPTS
+ client["retry_backoff_max_seconds"] = THROTTLED_RETRY_BACKOFF_MAX_SECONDS
+
+ endpoint: Endpoint = {
+ "path": config.path,
+ "data_selector": "data",
+ # A 200 body without `data` means an error envelope (recognized codes are caught
+ # by response_actions first) or a changed shape — fail loud, don't sync 0 rows.
+ "data_selector_required": True,
+ "response_actions": _response_actions(),
+ }
+ if params:
+ endpoint["params"] = dict(params)
+
+ return {"client": client, "resources": [{"name": config.name, "endpoint": endpoint}]}
+
+
+def _plan_anchor(resume: Optional[AviationstackResumeConfig]) -> Optional[datetime.date]:
+ """Recover the date the saved plan was built from, so a resumed run rebuilds the same plan.
+
+ The lookahead dates are derived from "today", so a job resumed after a UTC midnight would
+ otherwise shift its window by a day and skip whichever date the crash interrupted.
+ """
+ if resume is None or not resume.plan_start_date:
+ return None
+ try:
+ first_date = datetime.date.fromisoformat(resume.plan_start_date)
+ except ValueError:
+ return None
+ return first_date - datetime.timedelta(days=FLIGHTS_FUTURE_FIRST_DAY_AHEAD)
+
+
def aviationstack_source(
access_key: str,
endpoint: str,
@@ -87,56 +215,65 @@ def aviationstack_source(
job_id: str,
resumable_source_manager: ResumableSourceManager[AviationstackResumeConfig],
db_incremental_field_last_value: Optional[Any] = None,
+ airport_iata_codes: Optional[str] = None,
+ flights_future_days: Optional[int] = None,
) -> SourceResponse:
config = AVIATIONSTACK_ENDPOINTS[endpoint]
+ iata_codes = parse_iata_codes(airport_iata_codes)
- rest_config: RESTAPIConfig = {
- "client": {
- "base_url": AVIATIONSTACK_BASE_URL,
- # access_key rides in the query string; the framework auth redacts its value from every
- # logged URL, captured sample, and raised error message.
- "auth": {"type": "api_key", "api_key": access_key, "name": "access_key", "location": "query"},
- "paginator": OffsetPaginator(limit=DEFAULT_PAGE_SIZE, total_path="pagination.total"),
- },
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "data_selector": "data",
- # A 200 body without `data` means an error envelope (recognized codes are caught
- # by response_actions first) or a changed shape — fail loud, don't sync 0 rows.
- "data_selector_required": True,
- "response_actions": _response_actions(),
- },
- }
- ],
- }
+ if config.per_airport and not iata_codes:
+ raise ValueError(
+ f"The {endpoint} table needs at least one airport. Add an airport IATA code to the "
+ "source settings, then sync again."
+ )
- initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
- resume = resumable_source_manager.load_state()
- if resume is not None:
- initial_paginator_state = {"offset": resume.next_offset}
-
- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
- # Persist only while a next page remains; save AFTER a page is yielded so a crash re-yields
- # the last page (merge/replace dedupes) rather than skipping it.
- if state and state.get("offset") is not None:
- resumable_source_manager.save_state(AviationstackResumeConfig(next_offset=int(state["offset"])))
-
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- db_incremental_field_last_value,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ plan = build_request_plan(config, iata_codes, flights_future_days, today=_plan_anchor(resume))
+ plan_start_date = plan[0].row_context.get("queried_date") if config.needs_date else None
+
+ def items() -> Iterator[list[dict[str, Any]]]:
+ start_index = min(resume.next_request_index, len(plan) - 1) if resume is not None else 0
+
+ for index in range(start_index, len(plan)):
+ request = plan[index]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resume is not None and index == start_index and resume.next_offset:
+ initial_paginator_state = {"offset": resume.next_offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]], _index: int = index) -> None:
+ # Persist only while work remains; save AFTER a page is yielded so a crash re-yields
+ # the last page (merge/replace dedupes) rather than skipping it.
+ if state and state.get("offset") is not None:
+ next_state = AviationstackResumeConfig(
+ next_offset=int(state["offset"]),
+ next_request_index=_index,
+ plan_start_date=plan_start_date,
+ )
+ elif _index + 1 < len(plan):
+ # This request is exhausted, so a resumed attempt starts at the next one.
+ next_state = AviationstackResumeConfig(
+ next_offset=0, next_request_index=_index + 1, plan_start_date=plan_start_date
+ )
+ else:
+ return
+ resumable_source_manager.save_state(next_state)
+
+ resource = rest_api_resource(
+ _rest_config(access_key, config, request.params),
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ for page in resource:
+ yield [row | request.row_context for row in page] if request.row_context else page
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=config.primary_keys,
)
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
index 342df65cf59e..a7e06598c160 100644
--- 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
@@ -24,6 +24,37 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"live": "Live tracking data, including latitude, longitude, altitude, direction, and speed (null when unavailable).",
},
},
+ "timetable": {
+ "description": "Live departure and arrival schedules for each configured airport, covering flights on the current day. One row per flight per requested airport and schedule type.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "queried_iata_code": "IATA code of the airport this row was requested for.",
+ "queried_type": "Schedule direction this row was requested for: departure or arrival.",
+ "airline": "Operating airline, including name and IATA/ICAO codes.",
+ "departure": "Departure details, including IATA/ICAO codes, terminal, gate, baggage, delay in minutes, and scheduled/estimated/actual times.",
+ "arrival": "Arrival details, including IATA/ICAO codes, terminal, gate, baggage, delay in minutes, and scheduled/estimated/actual times.",
+ "codeshared": "Airline and flight identifiers of the codeshare partner, when the flight is a codeshare.",
+ "flight": "Flight identifiers, including the flight number and its IATA/ICAO numbers.",
+ "status": "Current status of the flight: scheduled, active, landed, cancelled, incident, or diverted.",
+ "type": "Schedule direction of the record as reported by aviationstack: departure or arrival.",
+ },
+ },
+ "flights_future": {
+ "description": "Future scheduled departures and arrivals for each configured airport. aviationstack only serves dates more than 7 days out, so the window starts 8 days ahead.",
+ "docs_url": "https://aviationstack.com/documentation",
+ "columns": {
+ "queried_iata_code": "IATA code of the airport this row was requested for.",
+ "queried_type": "Schedule direction this row was requested for: departure or arrival.",
+ "queried_date": "Future date this row was requested for, in YYYY-MM-DD format. The flight record itself carries only a weekday and a time.",
+ "weekday": "Day of the week the flight operates, 1 (Monday) through 7 (Sunday).",
+ "departure": "Departure details, including IATA/ICAO codes, terminal, gate, and scheduled time as a wall-clock HH:MM value.",
+ "arrival": "Arrival details, including IATA/ICAO codes, terminal, gate, and scheduled time as a wall-clock HH:MM value.",
+ "aircraft": "Aircraft details, including the model code and model text.",
+ "airline": "Operating airline, including name and IATA/ICAO codes.",
+ "flight": "Flight identifiers, including the flight number and its IATA/ICAO numbers.",
+ "codeshared": "Airline and flight identifiers of the codeshare partner, when the flight is a codeshare.",
+ },
+ },
"routes": {
"description": "Scheduled airline routes with departure, arrival, airline, and flight details.",
"docs_url": "https://aviationstack.com/documentation",
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
index 375b3f3ea7d4..f77298854d5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/aviationstack/settings.py
@@ -1,7 +1,7 @@
import dataclasses
[email protected](frozen=True)
class AviationstackEndpointConfig:
name: str
path: str
@@ -10,6 +10,14 @@ class AviationstackEndpointConfig:
# refresh snapshots.
primary_keys: list[str] | None
description: str | None = None
+ # `/timetable` and `/flightsFuture` are per-airport feeds: each request must name one airport
+ # and one schedule type, so they fan out over the airport IATA codes configured on the source.
+ per_airport: bool = False
+ # `/flightsFuture` additionally requires a date, so it fans out over a lookahead window too.
+ needs_date: bool = False
+ # aviationstack throttles the per-airport feeds far harder than the rest of the API
+ # (1 request/10s on paid plans, 1 request/60s on free ones).
+ throttled: bool = False
# aviationstack has no record-level updated-at cursor (the `flight_date` filter is a per-day window
@@ -21,6 +29,23 @@ AVIATIONSTACK_ENDPOINTS: dict[str, AviationstackEndpointConfig] = {
primary_keys=None,
description="Real-time and recent flight status, including departure, arrival, airline, and live position. Full refresh snapshot.",
),
+ "timetable": AviationstackEndpointConfig(
+ name="timetable",
+ path="/timetable",
+ primary_keys=None,
+ per_airport=True,
+ throttled=True,
+ description="Live departure and arrival schedules for the configured airports, with terminal, gate, delay, and status. Full refresh snapshot.",
+ ),
+ "flights_future": AviationstackEndpointConfig(
+ name="flights_future",
+ path="/flightsFuture",
+ primary_keys=None,
+ per_airport=True,
+ needs_date=True,
+ throttled=True,
+ description="Future scheduled departures and arrivals for the configured airports, one request per lookahead date. Full refresh snapshot.",
+ ),
"routes": AviationstackEndpointConfig(
name="routes",
path="/routes",
@@ -72,3 +97,16 @@ AVIATIONSTACK_ENDPOINTS: dict[str, AviationstackEndpointConfig] = {
}
ENDPOINTS = tuple(AVIATIONSTACK_ENDPOINTS.keys())
+
+# Both per-airport feeds serve one schedule direction per request.
+SCHEDULE_TYPES = ("departure", "arrival")
+
+# aviationstack only serves /flightsFuture for dates more than 7 days out, so day 8 is the first
+# date we can ask for. The window is bounded because every extra day is another request per airport
+# and schedule type against an endpoint that allows one request every 10 seconds.
+FLIGHTS_FUTURE_FIRST_DAY_AHEAD = 8
+FLIGHTS_FUTURE_DEFAULT_DAYS = 7
+FLIGHTS_FUTURE_MAX_DAYS = 30
+
+# Bounds the per-airport fan-out so one oversized airport list cannot stall a sync indefinitely.
+MAX_AIRPORTS = 25
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 c2a4013349e9..bc3dbf9eaa9c 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
@@ -12,6 +12,7 @@ from posthog.schema import (
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack import (
AviationstackResumeConfig,
aviationstack_source,
+ parse_iata_codes,
validate_credentials as validate_aviationstack_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
@@ -97,6 +98,10 @@ class AviationstackSource(ResumableSource[AviationstackSourceConfig, Aviationsta
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
+ endpoint = AVIATIONSTACK_ENDPOINTS.get(schema_name) if schema_name else None
+ if endpoint is not None and endpoint.per_airport and not parse_iata_codes(config.airport_iata_codes):
+ return False, f"The {endpoint.name} table needs at least one airport IATA code, for example JFK."
+
if validate_aviationstack_credentials(config.access_key):
return True, None
@@ -118,6 +123,8 @@ class AviationstackSource(ResumableSource[AviationstackSourceConfig, Aviationsta
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
db_incremental_field_last_value=None, # aviationstack has no server-side cursor; full refresh only
+ airport_iata_codes=config.airport_iata_codes,
+ flights_future_days=config.flights_future_days,
)
@property
@@ -131,7 +138,9 @@ class AviationstackSource(ResumableSource[AviationstackSourceConfig, Aviationsta
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.""",
+The `timetable` and `flights_future` tables are per-airport: list the airport IATA codes you want, and those tables sync for those airports only. aviationstack serves future flights from 8 days out, so `flights_future` starts there and covers the number of days you set.
+
+Note: aviationstack pricing is a monthly request quota tied to your plan. Some tables (e.g. historical flights, timetable, and future flights) require a paid plan.""",
iconPath="/static/services/aviationstack.png",
docsUrl="https://posthog.com/docs/cdp/sources/aviationstack",
fields=cast(
@@ -145,6 +154,22 @@ Note: aviationstack pricing is a monthly request quota tied to your plan. Some t
placeholder="",
secret=True,
),
+ SourceFieldInputConfig(
+ name="airport_iata_codes",
+ label="Airport IATA codes",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="JFK, DXB",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="flights_future_days",
+ label="Days of future flights to sync",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder="7",
+ secret=False,
+ ),
],
),
)
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
index 4aefe15cb734..5292deea6aae 100644
--- 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
@@ -1,4 +1,6 @@
import json
+import string
+import datetime
from typing import Any
import pytest
@@ -12,10 +14,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aviationst
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.aviationstack import (
AviationstackResumeConfig,
aviationstack_source,
+ build_request_plan,
+ parse_iata_codes,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.settings import (
AVIATIONSTACK_ENDPOINTS,
+ FLIGHTS_FUTURE_FIRST_DAY_AHEAD,
+ FLIGHTS_FUTURE_MAX_DAYS,
+ MAX_AIRPORTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
@@ -80,9 +87,20 @@ def _rows(source_response: Any) -> list[dict[str, Any]]:
return [row for page in source_response.items() for row in page]
-def _source(endpoint: str = "airlines", manager: mock.MagicMock | None = None) -> Any:
+def _source(
+ endpoint: str = "airlines",
+ manager: mock.MagicMock | None = None,
+ airport_iata_codes: str | None = None,
+ flights_future_days: int | None = None,
+) -> Any:
return aviationstack_source(
- "supersecret", endpoint, team_id=1, job_id="j", resumable_source_manager=manager or _make_manager()
+ "supersecret",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager or _make_manager(),
+ airport_iata_codes=airport_iata_codes,
+ flights_future_days=flights_future_days,
)
@@ -231,6 +249,151 @@ class TestHttpErrors:
assert session.send.call_count == 5
+class TestAirportFanOut:
+ @parameterized.expand(
+ [
+ ("blank", None, []),
+ ("empty", " ", []),
+ ("comma_separated", "jfk,DXB", ["JFK", "DXB"]),
+ ("mixed_separators", "JFK DXB\nLHR", ["JFK", "DXB", "LHR"]),
+ ("dedupes", "JFK, jfk", ["JFK"]),
+ # Real IATA airport codes are exactly three letters; junk must not become a request.
+ ("drops_wrong_length", "JFK, HEATHROW, LH", ["JFK"]),
+ ("drops_non_alpha", "JFK, 123", ["JFK"]),
+ ]
+ )
+ def test_parse_iata_codes(self, _name: str, raw: str | None, expected: list[str]) -> None:
+ assert parse_iata_codes(raw) == expected
+
+ def test_parse_iata_codes_caps_fan_out(self) -> None:
+ codes = ",".join(f"A{first}{second}" for first in string.ascii_uppercase for second in "ABCD")
+ assert len(parse_iata_codes(codes)) == MAX_AIRPORTS
+
+ def test_per_airport_endpoint_without_airports_raises(self) -> None:
+ with pytest.raises(ValueError, match="needs at least one airport"):
+ _source("timetable")
+
+ def test_timetable_plans_one_request_per_airport_and_direction(self) -> None:
+ plan = build_request_plan(AVIATIONSTACK_ENDPOINTS["timetable"], ["JFK", "DXB"])
+
+ assert [(r.params["iataCode"], r.params["type"]) for r in plan] == [
+ ("JFK", "departure"),
+ ("JFK", "arrival"),
+ ("DXB", "departure"),
+ ("DXB", "arrival"),
+ ]
+ assert all("date" not in r.params for r in plan)
+
+ def test_flights_future_starts_beyond_the_vendor_cutoff(self) -> None:
+ # aviationstack only serves /flightsFuture for dates more than 7 days out.
+ today = datetime.date(2026, 3, 1)
+ plan = build_request_plan(AVIATIONSTACK_ENDPOINTS["flights_future"], ["JFK"], 3, today=today)
+
+ assert [r.params["date"] for r in plan if r.params["type"] == "departure"] == [
+ "2026-03-09",
+ "2026-03-10",
+ "2026-03-11",
+ ]
+ assert (today + datetime.timedelta(days=FLIGHTS_FUTURE_FIRST_DAY_AHEAD)).isoformat() == "2026-03-09"
+
+ @parameterized.expand([("zero", 0, 1), ("negative", -5, 1), ("oversized", 500, FLIGHTS_FUTURE_MAX_DAYS)])
+ def test_flights_future_window_is_bounded(self, _name: str, days: int, expected: int) -> None:
+ plan = build_request_plan(AVIATIONSTACK_ENDPOINTS["flights_future"], ["JFK"], days)
+ # Two schedule directions per date.
+ assert len(plan) == expected * 2
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_timetable_walks_every_planned_request_and_tags_rows(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_page([{"flight": {"number": str(i)}}], total=None) for i in range(4)])
+
+ rows = _rows(_source("timetable", airport_iata_codes="JFK,DXB"))
+
+ assert [(p["iataCode"], p["type"]) for p in params] == [
+ ("JFK", "departure"),
+ ("JFK", "arrival"),
+ ("DXB", "departure"),
+ ("DXB", "arrival"),
+ ]
+ assert [(r["queried_iata_code"], r["queried_type"]) for r in rows] == [
+ ("JFK", "departure"),
+ ("JFK", "arrival"),
+ ("DXB", "departure"),
+ ("DXB", "arrival"),
+ ]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_flights_future_rows_carry_the_requested_date(self, MockSession) -> None:
+ session = MockSession.return_value
+ # The payload has a weekday and a wall-clock time but no date, so without the injected
+ # queried_date a future schedule cannot be placed on a calendar at all.
+ _wire(session, [_page([{"weekday": "7", "departure": {"scheduledTime": "06:15"}}]) for _ in range(2)])
+
+ rows = _rows(_source("flights_future", airport_iata_codes="JFK", flights_future_days=1))
+
+ assert len({r["queried_date"] for r in rows}) == 1
+ assert all("date" not in r for r in rows)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_skips_completed_requests(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_page([{"flight": {"number": "1"}}], total=None)])
+
+ manager = _make_manager(AviationstackResumeConfig(next_offset=0, next_request_index=3))
+ _rows(_source("timetable", manager=manager, airport_iata_codes="JFK,DXB"))
+
+ # Index 3 is the last planned request (DXB arrivals) — the first three must not be re-sent.
+ assert session.send.call_count == 1
+ assert (params[0]["iataCode"], params[0]["type"]) == ("DXB", "arrival")
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_exhausted_request_checkpoints_the_next_one(self, MockSession) -> None:
+ session = MockSession.return_value
+ _wire(session, [_page([{"flight": {"number": str(i)}}], total=None) for i in range(2)])
+
+ manager = _make_manager()
+ _rows(_source("timetable", manager=manager, airport_iata_codes="JFK"))
+
+ # After JFK departures completes, a resumed attempt must start at JFK arrivals, not re-run it.
+ assert manager.save_state.call_args_list[0].args[0] == AviationstackResumeConfig(
+ next_offset=0, next_request_index=1, plan_start_date=None
+ )
+ # The final request leaves no checkpoint behind.
+ assert manager.save_state.call_count == 1
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_rebuilds_the_same_future_date_window(self, MockSession) -> None:
+ session = MockSession.return_value
+ params = _wire(session, [_page([{"weekday": "1"}], total=None)])
+
+ # A job resumed after a UTC midnight would otherwise shift its window by a day and skip the
+ # date the crash interrupted.
+ manager = _make_manager(
+ AviationstackResumeConfig(next_offset=0, next_request_index=1, plan_start_date="2020-01-09")
+ )
+ _rows(_source("flights_future", manager=manager, airport_iata_codes="JFK", flights_future_days=1))
+
+ assert params[0]["date"] == "2020-01-09"
+
+
+class TestThrottledEndpoints:
+ @parameterized.expand([("timetable",), ("flights_future",)])
+ @mock.patch("tenacity.nap.time.sleep")
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_throttled_feeds_outlast_the_rate_limit_window(self, endpoint: str, MockSession, sleep) -> None:
+ session = MockSession.return_value
+ session.headers = {}
+ session.prepare_request.return_value = mock.MagicMock()
+ session.send.return_value = _response({}, status=429, reason="Too Many Requests")
+
+ with pytest.raises(RESTClientRetryableError):
+ _rows(_source(endpoint, airport_iata_codes="JFK", flights_future_days=1))
+
+ # The per-airport feeds allow one request every 60s on free plans, so the retry budget has to
+ # outlast a whole window rather than the 15s the client's default budget covers.
+ assert sum(call.args[0] for call in sleep.call_args_list) > 60
+
+
class TestSourceResponse:
@parameterized.expand(
[
@@ -248,7 +411,7 @@ class TestSourceResponse:
def test_every_endpoint_builds_a_source_response(self) -> None:
for endpoint in AVIATIONSTACK_ENDPOINTS:
- response = _source(endpoint)
+ response = _source(endpoint, airport_iata_codes="JFK")
assert response.name == endpoint
assert callable(response.items)
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
index 95a2f2e5e085..91a6ac08d166 100644
--- 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
@@ -10,18 +10,27 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.aviationst
from products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.source import AviationstackSource
-def _make_config(access_key: str = "key") -> Any:
+def _make_manager() -> Any:
+ manager = MagicMock()
+ manager.can_resume.return_value = False
+ return manager
+
+
+def _make_config(access_key: str = "key", airport_iata_codes: str | None = "JFK") -> Any:
config = MagicMock()
config.access_key = access_key
+ config.airport_iata_codes = airport_iata_codes
+ config.flights_future_days = None
return config
class TestAviationstackSource:
- 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)
+ def test_only_the_access_key_field_is_secret(self) -> None:
+ fields = AviationstackSource().get_source_config.fields
+ inputs = [field for field in fields if isinstance(field, SourceFieldInputConfig)]
+ assert len(inputs) == len(fields)
+ assert [field.name for field in inputs if field.secret] == ["access_key"]
+ access_key_field = inputs[0]
# 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
@@ -56,23 +65,56 @@ class TestAviationstackSource:
assert ok is expected_ok
assert message == expected_message
+ @parameterized.expand([("timetable",), ("flights_future",)])
+ def test_validate_credentials_rejects_per_airport_table_without_airports(self, schema_name: str) -> None:
+ # The probe must not even run: a valid key still cannot sync these tables with no airport.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.source.validate_aviationstack_credentials",
+ return_value=True,
+ ) as probe:
+ ok, message = AviationstackSource().validate_credentials(
+ _make_config(airport_iata_codes=None), team_id=1, schema_name=schema_name
+ )
+ assert ok is False
+ assert message is not None and "airport IATA code" in message
+ probe.assert_not_called()
+
+ def test_validate_credentials_ignores_airports_for_other_tables(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.aviationstack.source.validate_aviationstack_credentials",
+ return_value=True,
+ ):
+ ok, _ = AviationstackSource().validate_credentials(
+ _make_config(airport_iata_codes=None), team_id=1, schema_name="airlines"
+ )
+ assert ok is True
+
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)
+ response = AviationstackSource().source_for_pipeline(_make_config("abc"), _make_manager(), inputs)
assert response.name == "airlines"
# Reference tables carry a stable row id.
assert response.primary_keys == ["id"]
+ def test_source_for_pipeline_plumbs_the_airport_list(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "timetable"
+ inputs.logger = MagicMock()
+
+ # Without the airport list reaching the transport, the per-airport feeds cannot be planned.
+ response = AviationstackSource().source_for_pipeline(_make_config(), _make_manager(), inputs)
+
+ assert response.name == "timetable"
+ assert response.primary_keys is None
+
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)
+ response = AviationstackSource().source_for_pipeline(_make_config(), _make_manager(), inputs)
assert response.primary_keys is None
@parameterized.expand(
@@ -94,3 +136,5 @@ class TestAviationstackSource:
assert set(descriptions.keys()) <= set(ENDPOINTS)
assert "flights" in descriptions
assert "airlines" in descriptions
+ assert "timetable" in descriptions
+ assert "flights_future" in descriptions
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aviationstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aviationstack.py
index 8bf1a3c910e6..567f55baeddc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aviationstack.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/aviationstack.py
@@ -7,3 +7,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AviationstackSourceConfig(config.Config):
access_key: str
+ flights_future_days: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)
+ airport_iata_codes: str | None = None