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 marketstack import source (#67809)

Tom Owers59ebe5437089
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 b21865329092..4194ace4a8fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -199,6 +199,7 @@ the row lists both.
| mailersend | HTTP | requests | ✅ |
| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP | requests | ✅ |
+| marketstack | HTTP | requests | ✅ |
| matomo | HTTP | requests | ✅ |
| meta_ads | HTTP | requests | ✅ |
| metabase | HTTP | requests | ✅ |
@@ -508,7 +509,6 @@ doesn't conflict with concurrent PRs.
- mailtrap
- mantle
- marketo
-- marketstack
- mendeley
- mention
- mercado_ads
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 a731795f239e..25cb2eeb7854 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
@@ -1947,7 +1947,8 @@ class MarketoSourceConfig(config.Config):
@config.config
class MarketstackSourceConfig(config.Config):
- pass
+ access_key: str
+ symbols: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py
new file mode 100644
index 000000000000..6aa77d36da1e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/canonical_descriptions.py
@@ -0,0 +1,113 @@
+"""Canonical, documentation-sourced descriptions for Marketstack endpoints and columns.
+
+Sourced from the official Marketstack API documentation (https://marketstack.com/documentation).
+Keyed by the endpoint names in `settings.py` `MARKETSTACK_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,
+)
+
+_DOCS_URL = "https://marketstack.com/documentation"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "eod": {
+ "description": "End-of-day (daily OHLCV) stock prices per symbol, including adjusted prices, split factor, and dividend.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Exact UTC timestamp of the end-of-day data point (ISO 8601).",
+ "symbol": "Stock ticker symbol of the instrument.",
+ "exchange": "MIC identification of the exchange the data point is associated with.",
+ "open": "Opening price of the trading day.",
+ "high": "Highest price reached during the trading day.",
+ "low": "Lowest price reached during the trading day.",
+ "close": "Closing price of the trading day.",
+ "volume": "Trading volume of the day.",
+ "adj_open": "Split- and dividend-adjusted opening price.",
+ "adj_high": "Split- and dividend-adjusted high price.",
+ "adj_low": "Split- and dividend-adjusted low price.",
+ "adj_close": "Split- and dividend-adjusted closing price.",
+ "adj_volume": "Split- and dividend-adjusted trading volume.",
+ "split_factor": "Split factor applied on this date (1.0 when no split).",
+ "dividend": "Dividend paid on this date (0.0 when none).",
+ },
+ },
+ "intraday": {
+ "description": "Intraday (intra-day interval) stock prices per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Exact UTC timestamp of the intraday data point (ISO 8601).",
+ "symbol": "Stock ticker symbol of the instrument.",
+ "exchange": "MIC identification of the exchange the data point is associated with.",
+ "open": "Opening price of the interval.",
+ "high": "Highest price reached during the interval.",
+ "low": "Lowest price reached during the interval.",
+ "close": "Closing price of the interval.",
+ "last": "Last executed trade price in the interval.",
+ "volume": "Trading volume of the interval.",
+ },
+ },
+ "splits": {
+ "description": "Historical stock split factors per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Date the stock split took effect (YYYY-MM-DD).",
+ "symbol": "Stock ticker symbol of the instrument.",
+ "split_factor": "Split factor applied on this date (e.g. 4.0 for a 4-for-1 split).",
+ },
+ },
+ "dividends": {
+ "description": "Historical dividend payouts per symbol.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "date": "Date the dividend was paid (YYYY-MM-DD).",
+ "symbol": "Stock ticker symbol of the instrument.",
+ "dividend": "Dividend amount paid per share on this date.",
+ },
+ },
+ "tickers": {
+ "description": "Reference table of supported stock tickers with name, exchange, and EOD/intraday availability.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "name": "Full name of the company or instrument.",
+ "symbol": "Stock ticker symbol of the instrument.",
+ "has_intraday": "Whether intraday data is available for this ticker.",
+ "has_eod": "Whether end-of-day data is available for this ticker.",
+ "country": "Country the ticker is associated with (nullable).",
+ "stock_exchange": "Nested exchange the ticker is listed on, including name, acronym, MIC, and country.",
+ },
+ },
+ "exchanges": {
+ "description": "Reference table of supported stock exchanges with codes, country, and timezone.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "name": "Name of the stock exchange.",
+ "acronym": "Acronym of the stock exchange.",
+ "mic": "Market Identifier Code (MIC) of the stock exchange.",
+ "country": "Country the exchange is located in.",
+ "country_code": "ISO 3166-1 alpha-2 code of the exchange's country.",
+ "city": "City the exchange is located in.",
+ "website": "Website URL of the exchange.",
+ "timezone": "Nested timezone details of the exchange, including name and abbreviation.",
+ },
+ },
+ "currencies": {
+ "description": "Reference table of supported currencies.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "code": "ISO 4217 currency code.",
+ "symbol": "Display symbol of the currency.",
+ "name": "Name of the currency.",
+ },
+ },
+ "timezones": {
+ "description": "Reference table of supported timezones.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "timezone": "Name of the timezone (e.g. America/New_York).",
+ "abbr": "Standard-time abbreviation of the timezone (e.g. EST).",
+ "abbr_dst": "Daylight-saving-time abbreviation of the timezone (e.g. EDT).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx
new file mode 100644
index 000000000000..3a3dcda120f3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.mdx
@@ -0,0 +1,58 @@
+---
+title: Linking Marketstack as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Marketstack
+beta: true
+---
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+[Marketstack](https://marketstack.com) (an APILayer product) is a REST API for real-time, intraday, and historical stock market data covering 70+ exchanges and 125,000+ tickers. Linking Marketstack as a source pulls end-of-day, intraday, splits, and dividends data along with market reference tables (tickers, exchanges, currencies, timezones) into your PostHog Data warehouse, where you can join it with your product data.
+
+## Prerequisites
+
+Before connecting Marketstack, you need:
+
+- A [Marketstack account](https://marketstack.com/signup).
+- Your API **access key**, found in your [Marketstack dashboard](https://marketstack.com/dashboard). The free plan covers end-of-day and all reference tables; intraday data requires a paid plan.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+When configuring the source, provide:
+
+- **Access key**: your Marketstack API access key from the [dashboard](https://marketstack.com/dashboard).
+- **Symbols** (optional): a comma-separated list of ticker symbols, e.g. `AAPL,MSFT,TSLA`. Symbols are **required** for the EOD, intraday, splits, and dividends tables — those endpoints return data per symbol. The reference tables (tickers, exchanges, currencies, timezones) don't need symbols.
+
+Marketstack enforces a rate limit of 5 requests per second and a monthly request quota tied to your plan, so keep the number of symbols and the historical range in mind when backfilling.
+
+## Sync modes
+
+<SyncModes />
+
+The time-series tables (`eod`, `intraday`, `splits`, `dividends`) support incremental sync — after the first backfill, each run only requests data on or after the latest synced `date`, using Marketstack's `date_from` filter. The reference tables (`tickers`, `exchanges`, `currencies`, `timezones`) are full-refresh snapshots.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **`missing_symbols` / no rows for EOD, intraday, splits, or dividends**: these tables require at least one symbol. Add symbols to the source configuration and resync.
+- **`function_access_restricted`**: your Marketstack plan doesn't include this endpoint (intraday requires a paid plan). Upgrade your plan or deselect the restricted table.
+- **`usage_limit_reached`**: you've hit your monthly request quota. Upgrade your plan or wait for the quota to reset, then resync.
+- **`invalid_access_key`**: the access key is wrong or deactivated. Generate a new key in your Marketstack dashboard and reconnect.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
new file mode 100644
index 000000000000..1bfec8028782
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/marketstack.py
@@ -0,0 +1,226 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import date
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.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.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import MARKETSTACK_ENDPOINTS
+
+# Marketstack keeps two live API versions; v1 is stable, covers every endpoint we sync, and is
+# available on the free plan. v2 only adds indices and the /latest lookups we don't use here.
+MARKETSTACK_BASE_URL = "https://api.marketstack.com/v1"
+# limit maxes out at 1000; larger pages mean fewer round trips against the 5 req/sec rate limit.
+DEFAULT_PAGE_SIZE = 1000
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+
+# Marketstack (an APILayer product) can return HTTP 200 with an error envelope
+# (`{"error": {"code": ...}}`). Only genuinely transient codes are retried; every other code
+# (bad/blocked key, plan gating, exhausted monthly quota) fails fast and is surfaced as a permanent
+# failure matched by MarketstackSource.get_non_retryable_errors on the stable `[code]` token.
+_RETRYABLE_ERROR_CODES = {"rate_limit_reached", "too_many_requests"}
+
+
+class MarketstackRetryableError(Exception):
+ pass
+
+
+class MarketstackAPIError(Exception):
+ pass
+
+
+class MarketstackResumeConfig:
+ # Offset of the next page to fetch — Marketstack uses limit/offset pagination.
+ next_offset: int
+
+
+def _format_date(value: Any) -> str:
+ """Format an incremental cursor for the `date_from` filter (Marketstack expects YYYY-MM-DD)."""
+ # datetime is a subclass of date, so this covers both.
+ if isinstance(value, date):
+ return value.strftime("%Y-%m-%d")
+ # A stored string cursor is already an ISO timestamp/date — keep just the date portion.
+ return str(value)[:10]
+
+
+@retry(
+ retry=retry_if_exception_type((MarketstackRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ 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=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MarketstackRetryableError(f"Marketstack API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Marketstack 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") if isinstance(error, dict) else "unknown"
+ message = error.get("message", "") if isinstance(error, dict) else str(error)
+ if code in _RETRYABLE_ERROR_CODES:
+ raise MarketstackRetryableError(f"Marketstack 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 MarketstackAPIError(f"Marketstack API error [{code}]: {message}")
+
+ return body
+
+
+def get_rows(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+ symbols: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ page_size: int = DEFAULT_PAGE_SIZE,
+) -> Iterator[Any]:
+ config = MARKETSTACK_ENDPOINTS[endpoint]
+ url = f"{MARKETSTACK_BASE_URL}{config.path}"
+
+ if config.requires_symbols and not (symbols and symbols.strip()):
+ raise MarketstackAPIError(
+ f"Marketstack API error [missing_symbols]: the '{endpoint}' table requires one or more "
+ "symbols. Add symbols to the source configuration, then resync."
+ )
+
+ # `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)
+
+ base_params: dict[str, Any] = {"access_key": access_key, "limit": page_size}
+ if config.requires_symbols and symbols:
+ base_params["symbols"] = symbols
+ if config.incremental_fields:
+ # Ascending sort keeps rows in date order so the pipeline watermark advances correctly; it's
+ # also required for date_from windowing to line up with SourceResponse.sort_mode="asc".
+ base_params["sort"] = "ASC"
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ base_params["date_from"] = _format_date(db_incremental_field_last_value)
+
+ 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"Marketstack: resuming {endpoint} from offset={offset}")
+
+ while True:
+ body = _fetch_page(session, url, {**base_params, "offset": offset}, 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(MarketstackResumeConfig(next_offset=next_offset))
+
+ if not has_more:
+ break
+ offset = next_offset
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def marketstack_source(
+ access_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+ symbols: str | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = MARKETSTACK_ENDPOINTS[endpoint]
+
+ partition_kwargs: dict[str, Any] = {}
+ if config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_key=access_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ symbols=symbols,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ # We always request `sort=ASC` on the time-series feeds and reference tables are unordered
+ # full refreshes, so ascending is safe across the board.
+ sort_mode="asc",
+ **partition_kwargs,
+ )
+
+
+def validate_credentials(access_key: str) -> bool:
+ # `/exchanges` is a static reference endpoint available on every plan (including free) and needs
+ # no symbols, so it's a cheap probe that the access key is genuine.
+ url = f"{MARKETSTACK_BASE_URL}/exchanges"
+ 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/marketstack/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py
new file mode 100644
index 000000000000..103b2b784f1b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/settings.py
@@ -0,0 +1,110 @@
+import dataclasses
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# The time-series feeds carry a per-row `date`. Marketstack windows them server-side with the
+# `date_from` / `date_to` query params, so those endpoints sync incrementally on `date`. EOD and
+# intraday rows carry a full timestamp; splits and dividends carry a calendar date.
+_EOD_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+]
+
+
+class MarketstackEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str]
+ # Time-series endpoints require a `symbols` query param; reference tables ignore it.
+ requires_symbols: bool = False
+ # Empty list = full refresh only (no server-side date filter).
+ incremental_fields: list[IncrementalField] = dataclasses.field(default_factory=list)
+ default_incremental_field: str | None = None
+ # Stable datetime column for datetime partitioning (`date` never changes for a given row).
+ partition_key: str | None = None
+ description: str | None = None
+
+
+MARKETSTACK_ENDPOINTS: dict[str, MarketstackEndpointConfig] = {
+ "eod": MarketstackEndpointConfig(
+ name="eod",
+ path="/eod",
+ # A symbol trades on one exchange per row; the same symbol can appear on multiple exchanges,
+ # so the exchange MIC is part of the key to keep it unique table-wide.
+ primary_keys=["symbol", "exchange", "date"],
+ requires_symbols=True,
+ incremental_fields=_EOD_INCREMENTAL_FIELDS,
+ default_incremental_field="date",
+ partition_key="date",
+ description="End-of-day (daily OHLCV) stock prices per symbol, including adjusted prices, split factor, and dividend. Requires symbols. Incremental on date.",
+ ),
+ "intraday": MarketstackEndpointConfig(
+ name="intraday",
+ path="/intraday",
+ primary_keys=["symbol", "exchange", "date"],
+ requires_symbols=True,
+ incremental_fields=_EOD_INCREMENTAL_FIELDS,
+ default_incremental_field="date",
+ partition_key="date",
+ description="Intraday (intra-day interval) stock prices per symbol. Requires symbols and a paid plan. Incremental on date.",
+ ),
+ "splits": MarketstackEndpointConfig(
+ name="splits",
+ path="/splits",
+ primary_keys=["symbol", "date"],
+ requires_symbols=True,
+ incremental_fields=_DATE_INCREMENTAL_FIELDS,
+ default_incremental_field="date",
+ partition_key="date",
+ description="Historical stock split factors per symbol. Requires symbols. Incremental on date.",
+ ),
+ "dividends": MarketstackEndpointConfig(
+ name="dividends",
+ path="/dividends",
+ primary_keys=["symbol", "date"],
+ requires_symbols=True,
+ incremental_fields=_DATE_INCREMENTAL_FIELDS,
+ default_incremental_field="date",
+ partition_key="date",
+ description="Historical dividend payouts per symbol. Requires symbols. Incremental on date.",
+ ),
+ "tickers": MarketstackEndpointConfig(
+ name="tickers",
+ path="/tickers",
+ primary_keys=["symbol"],
+ description="Reference table of supported stock tickers with name, exchange, and EOD/intraday availability. Full refresh.",
+ ),
+ "exchanges": MarketstackEndpointConfig(
+ name="exchanges",
+ path="/exchanges",
+ primary_keys=["mic"],
+ description="Reference table of supported stock exchanges with MIC/acronym codes, country, and timezone. Full refresh.",
+ ),
+ "currencies": MarketstackEndpointConfig(
+ name="currencies",
+ path="/currencies",
+ primary_keys=["code"],
+ description="Reference table of supported currencies with ISO code, symbol, and name. Full refresh.",
+ ),
+ "timezones": MarketstackEndpointConfig(
+ name="timezones",
+ path="/timezones",
+ primary_keys=["timezone"],
+ description="Reference table of supported timezones with abbreviation and daylight-saving abbreviation. Full refresh.",
+ ),
+}
+
+ENDPOINTS = tuple(MARKETSTACK_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
index b950ede641e1..734499b30365 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/source.py
@@ -1,30 +1,162 @@
-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.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 MarketstackSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MarketstackResumeConfig,
+ marketstack_source,
+ validate_credentials as validate_marketstack_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import MARKETSTACK_ENDPOINTS
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class MarketstackSource(SimpleSource[MarketstackSourceConfig]):
+class MarketstackSource(ResumableSource[MarketstackSourceConfig, MarketstackResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MARKETSTACK
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # A bad/blocked key surfaces as an HTTP 401 — retrying can never satisfy a credential
+ # problem. Match the stable status text and base host.
+ "401 Client Error: Unauthorized for url: https://api.marketstack.com": "Your Marketstack access key is invalid or has been deactivated. Generate a new key in your Marketstack dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.marketstack.com": "Your Marketstack plan does not grant access to this data. Upgrade your Marketstack plan or deselect the restricted tables, then reconnect.",
+ # Marketstack also returns HTTP 200 with a body-level error envelope; these are raised as
+ # MarketstackAPIError with a stable `[code]` token (see marketstack._fetch_page).
+ "Marketstack API error [invalid_access_key]": "Your Marketstack access key is invalid or has been deactivated. Generate a new key in your Marketstack dashboard, then reconnect.",
+ "Marketstack API error [missing_access_key]": "No Marketstack access key was supplied. Reconnect the source with a valid access key.",
+ "Marketstack API error [inactive_user]": "Your Marketstack account is inactive. Reactivate it in your Marketstack dashboard, then reconnect.",
+ "Marketstack API error [usage_limit_reached]": "Your Marketstack monthly request quota has been reached. Upgrade your plan or wait for the quota to reset, then resync.",
+ "Marketstack API error [function_access_restricted]": "Your Marketstack plan does not grant access to this data (e.g. intraday requires a paid plan). Upgrade your Marketstack plan or deselect the restricted tables, then reconnect.",
+ "Marketstack API error [https_access_restricted]": "Your Marketstack plan does not allow HTTPS access. Upgrade your Marketstack plan, then reconnect.",
+ # The time-series tables need at least one symbol; without one the sync can never make
+ # progress, so fail permanently with a fix-it message rather than retrying.
+ "Marketstack API error [missing_symbols]": "One or more of the selected tables (EOD, intraday, splits, dividends) requires symbols. Add symbols to the source configuration, then resync.",
+ "Marketstack API error [no_valid_symbols_provided]": "None of the configured symbols are valid Marketstack tickers. Check the symbols in the source configuration, then resync.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: MarketstackSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint.name,
+ # Only the time-series feeds expose a server-side date_from filter; reference tables
+ # are full refresh only.
+ supports_incremental=bool(endpoint.incremental_fields),
+ supports_append=bool(endpoint.incremental_fields),
+ incremental_fields=list(endpoint.incremental_fields),
+ description=endpoint.description,
+ )
+ for endpoint in MARKETSTACK_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: MarketstackSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_marketstack_credentials(config.access_key):
+ return True, None
+
+ return False, "Invalid Marketstack access key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MarketstackResumeConfig]:
+ return ResumableSourceManager[MarketstackResumeConfig](inputs, MarketstackResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: MarketstackSourceConfig,
+ resumable_source_manager: ResumableSourceManager[MarketstackResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return marketstack_source(
+ access_key=config.access_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ symbols=config.symbols,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.MARKETSTACK,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Marketstack",
- iconPath="/static/services/marketstack.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Marketstack access key to pull end-of-day, intraday, splits, and dividends data plus market reference tables (tickers, exchanges, currencies, timezones) into the PostHog Data warehouse.
+
+You can find your access key in your [Marketstack dashboard](https://marketstack.com/dashboard).
+
+Add one or more comma-separated **symbols** (e.g. `AAPL,MSFT,TSLA`) to sync the EOD, intraday, splits, and dividends tables — those endpoints require at least one symbol. The reference tables don't need symbols.
+
+Note: Marketstack pricing is a monthly request quota tied to your plan. Some tables (e.g. intraday) require a paid plan.""",
+ iconPath="/static/services/marketstack.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/marketstack",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_key",
+ label="Access key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="symbols",
+ label="Symbols",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="AAPL,MSFT,TSLA",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
new file mode 100644
index 000000000000..3988e266930a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack.py
@@ -0,0 +1,279 @@
+from datetime import datetime
+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.marketstack import marketstack
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MarketstackAPIError,
+ MarketstackResumeConfig,
+ MarketstackRetryableError,
+ _fetch_page,
+ _format_date,
+ get_rows,
+ marketstack_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import MARKETSTACK_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack"
+
+
+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.marketstack.com/v1/eod?access_key=supersecret&symbols=AAPL"
+ 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": 1000, "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: MarketstackResumeConfig | 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 TestFormatDate:
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2021, 4, 9, 12, 30), "2021-04-09"),
+ ("iso_string", "2021-04-09T00:00:00+0000", "2021-04-09"),
+ ("date_string", "2020-08-31", "2020-08-31"),
+ ]
+ )
+ def test_formats_to_yyyy_mm_dd(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_date(value) == expected
+
+
+class TestFetchPage:
+ def test_returns_body_on_success(self) -> None:
+ session = _session_returning([_response(data=[{"symbol": "AAPL"}], total=1)])
+ body = _fetch_page(session, "https://api.marketstack.com/v1/eod", {"access_key": "k"}, MagicMock())
+ assert body["data"] == [{"symbol": "AAPL"}]
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_http_client_error_raises_without_leaking_key(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.marketstack.com/v1/eod", {"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(MarketstackRetryableError):
+ _fetch_page(session, "https://api.marketstack.com/v1/eod", {"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(MarketstackAPIError) as exc:
+ _fetch_page(session, "https://api.marketstack.com/v1/eod", {"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(MarketstackRetryableError):
+ _fetch_page(session, "https://api.marketstack.com/v1/eod", {"access_key": "k"}, MagicMock())
+ assert session.get.call_count == 5
+
+
+class TestGetRows:
+ def test_paginates_until_total_reached(self) -> None:
+ page1 = [{"symbol": "AAPL", "date": f"d{i}"} for i in range(2)]
+ page2 = [{"symbol": "AAPL", "date": f"d{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", "eod", MagicMock(), _resume_manager(), symbols="AAPL", page_size=2))
+ assert len(rows) == 4
+ assert session.get.call_count == 2
+
+ def test_stops_on_short_page(self) -> None:
+ session = _session_returning([_response(data=[{"code": "USD"}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ rows = _collect_rows(get_rows("k", "currencies", MagicMock(), _resume_manager(), page_size=1000))
+ assert [r["code"] for r in rows] == ["USD"]
+ 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", "currencies", MagicMock(), _resume_manager(), page_size=1000))
+ assert rows == []
+ assert session.get.call_count == 1
+
+ def test_resumes_from_saved_offset(self) -> None:
+ session = _session_returning([_response(data=[{"code": "USD"}], total=None)])
+ manager = _resume_manager(MarketstackResumeConfig(next_offset=2000))
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(get_rows("k", "currencies", MagicMock(), manager, page_size=1000))
+ # The first (and only) request must start from the persisted offset, not 0.
+ assert session.get.call_args_list[0].kwargs["params"]["offset"] == 2000
+
+ 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 = [{"code": f"c{i}"} for i in range(2000)]
+ page2 = [{"code": f"c{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", "currencies", MagicMock(), manager, page_size=2000))
+ assert len(rows) == 4000
+ manager.save_state.assert_called_once_with(MarketstackResumeConfig(next_offset=2000))
+
+ def test_time_series_endpoint_requests_ascending_sort(self) -> None:
+ session = _session_returning([_response(data=[{"symbol": "AAPL"}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(get_rows("k", "eod", MagicMock(), _resume_manager(), symbols="AAPL", page_size=1000))
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert params["sort"] == "ASC"
+ assert params["symbols"] == "AAPL"
+
+ def test_reference_endpoint_sends_no_symbols_or_sort(self) -> None:
+ session = _session_returning([_response(data=[{"code": "USD"}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(get_rows("k", "currencies", MagicMock(), _resume_manager(), page_size=1000))
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert "symbols" not in params
+ assert "sort" not in params
+ assert "date_from" not in params
+
+ def test_incremental_passes_date_from_watermark(self) -> None:
+ session = _session_returning([_response(data=[{"symbol": "AAPL"}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(
+ get_rows(
+ "k",
+ "eod",
+ MagicMock(),
+ _resume_manager(),
+ symbols="AAPL",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2021-04-09T00:00:00+0000",
+ page_size=1000,
+ )
+ )
+ params = session.get.call_args_list[0].kwargs["params"]
+ assert params["date_from"] == "2021-04-09"
+
+ def test_no_date_from_on_first_incremental_sync(self) -> None:
+ # A first incremental sync has no stored watermark, so no date_from should be sent.
+ session = _session_returning([_response(data=[{"symbol": "AAPL"}], total=None)])
+ with patch(f"{MODULE}.make_tracked_session", return_value=session):
+ _collect_rows(
+ get_rows(
+ "k",
+ "eod",
+ MagicMock(),
+ _resume_manager(),
+ symbols="AAPL",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ page_size=1000,
+ )
+ )
+ assert "date_from" not in session.get.call_args_list[0].kwargs["params"]
+
+ @parameterized.expand([("eod",), ("intraday",), ("splits",), ("dividends",)])
+ def test_time_series_endpoints_require_symbols(self, endpoint: str) -> None:
+ # Selecting a time-series table with no symbols is a permanent misconfiguration.
+ with pytest.raises(MarketstackAPIError) as exc:
+ _collect_rows(get_rows("k", endpoint, MagicMock(), _resume_manager(), symbols=None))
+ assert "[missing_symbols]" in str(exc.value)
+
+ def test_blank_symbols_treated_as_missing(self) -> None:
+ with pytest.raises(MarketstackAPIError):
+ _collect_rows(get_rows("k", "eod", MagicMock(), _resume_manager(), symbols=" "))
+
+
+class TestMarketstackSource:
+ @parameterized.expand(
+ [
+ ("eod", ["symbol", "exchange", "date"], "date"),
+ ("intraday", ["symbol", "exchange", "date"], "date"),
+ ("splits", ["symbol", "date"], "date"),
+ ("dividends", ["symbol", "date"], "date"),
+ ("tickers", ["symbol"], None),
+ ("exchanges", ["mic"], None),
+ ("currencies", ["code"], None),
+ ("timezones", ["timezone"], None),
+ ]
+ )
+ def test_source_response_keys_and_partitioning(
+ self, endpoint: str, expected_keys: list[str], expected_partition: str | None
+ ) -> None:
+ response = marketstack_source("k", endpoint, MagicMock(), _resume_manager(), symbols="AAPL")
+ assert response.name == endpoint
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == "asc"
+ if expected_partition is None:
+ assert response.partition_keys is None
+ else:
+ assert response.partition_keys == [expected_partition]
+ assert response.partition_mode == "datetime"
+
+ def test_every_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in MARKETSTACK_ENDPOINTS:
+ response = marketstack_source("k", endpoint, MagicMock(), _resume_manager(), symbols="AAPL")
+ 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 marketstack.MARKETSTACK_BASE_URL == "https://api.marketstack.com/v1"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
new file mode 100644
index 000000000000..9dcd70a4e54a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/marketstack/tests/test_marketstack_source.py
@@ -0,0 +1,143 @@
+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.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.marketstack import (
+ MarketstackResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source import MarketstackSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_TIME_SERIES = {"eod", "intraday", "splits", "dividends"}
+_REFERENCE = {"tickers", "exchanges", "currencies", "timezones"}
+
+
+def _make_config(access_key: str = "key", symbols: str | None = "AAPL") -> Any:
+ config = MagicMock()
+ config.access_key = access_key
+ config.symbols = symbols
+ return config
+
+
+class TestMarketstackSource:
+ def test_source_type(self) -> None:
+ assert MarketstackSource().source_type == ExternalDataSourceType.MARKETSTACK
+
+ def test_source_config_fields(self) -> None:
+ config = MarketstackSource().get_source_config
+ assert [f.name for f in config.fields] == ["access_key", "symbols"]
+
+ 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
+
+ symbols_field = config.fields[1]
+ assert isinstance(symbols_field, SourceFieldInputConfig)
+ # Symbols are only needed for the time-series tables, so the field is optional.
+ assert symbols_field.required is False
+ assert symbols_field.secret is False
+
+ def test_source_config_stays_unreleased_alpha(self) -> None:
+ config = MarketstackSource().get_source_config
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == "alpha"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/marketstack"
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = MarketstackSource().get_schemas(_make_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_marks_only_time_series_incremental(self) -> None:
+ schemas = {s.name: s for s in MarketstackSource().get_schemas(_make_config(), team_id=1)}
+ for name in _TIME_SERIES:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["date"]
+ for name in _REFERENCE:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = MarketstackSource().get_schemas(_make_config(), team_id=1, names=["eod", "exchanges"])
+ assert {s.name for s in schemas} == {"eod", "exchanges"}
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid Marketstack 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.marketstack.source.validate_marketstack_credentials",
+ return_value=probe_result,
+ ):
+ ok, message = MarketstackSource().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 = MarketstackSource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is MarketstackResumeConfig
+
+ def test_source_for_pipeline_plumbs_symbols_and_keys(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "eod"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2021-04-09"
+
+ response = MarketstackSource().source_for_pipeline(_make_config("abc", "AAPL,MSFT"), MagicMock(), inputs)
+
+ assert response.name == "eod"
+ assert response.primary_keys == ["symbol", "exchange", "date"]
+
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "tickers"
+ inputs.logger = MagicMock()
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.marketstack.source.marketstack_source"
+ ) as mocked:
+ MarketstackSource().source_for_pipeline(_make_config(), MagicMock(), inputs)
+ # A full-refresh run must never forward a stale watermark to the transport.
+ assert mocked.call_args.kwargs["db_incremental_field_last_value"] is None
+
+ @parameterized.expand(
+ [
+ ("http_unauthorized", "401 Client Error: Unauthorized for url: https://api.marketstack.com"),
+ ("body_invalid_key", "Marketstack API error [invalid_access_key]"),
+ ("body_usage_limit", "Marketstack API error [usage_limit_reached]"),
+ ("body_function_restricted", "Marketstack API error [function_access_restricted]"),
+ ("body_missing_symbols", "Marketstack API error [missing_symbols]"),
+ ]
+ )
+ def test_non_retryable_errors_cover_permanent_failures(self, _name: str, expected_key: str) -> None:
+ errors = MarketstackSource().get_non_retryable_errors()
+ assert expected_key in errors
+ assert errors[expected_key]
+
+ def test_canonical_descriptions_keyed_by_endpoint(self) -> None:
+ descriptions = MarketstackSource().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 "eod" in descriptions
+ assert "tickers" in descriptions