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 electricity_maps import source (#107247)

Tom Owers23f1324d2cf2
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 7caeec4d515a..e64eb2850d29 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -264,6 +264,7 @@ the row lists both.
| easypost | HTTP | requests | ✅ |
| easypromos | HTTP | requests | ✅ |
| ecb_data_portal | HTTP | requests | ✅ |
+| electricity_maps | HTTP | requests + `rest_source.RESTClient` | ✅ |
| elevenlabs | HTTP | requests | ✅ |
| eppo | HTTP | requests + `rest_source.RESTClient` | ✅ |
| etsy | HTTP | requests | ✅ |
@@ -1013,7 +1014,6 @@ doesn't conflict with concurrent PRs.
- dwolla
- e2b
- ebay
-- electricity_maps
- eloqua
- emarsys
- embrace
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/canonical_descriptions.py
new file mode 100644
index 000000000000..3e38426a1d04
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/canonical_descriptions.py
@@ -0,0 +1,51 @@
+"""Canonical, documentation-sourced descriptions for Electricity Maps endpoints and columns.
+
+Sourced from the official Electricity Maps API reference (https://app.electricitymaps.com/docs/api).
+Keyed by the endpoint names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name`
+of a synced Electricity Maps 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 = {
+ "carbon_intensity": {
+ "description": "Hourly carbon intensity of electricity consumed in a zone, in grams of "
+ "CO2 equivalent per kilowatt-hour (gCO2eq/kWh).",
+ "docs_url": "https://app.electricitymaps.com/docs/api",
+ "columns": {
+ "zone": "Identifier of the electricity grid zone, e.g. `DE` or `DK-DK1`.",
+ "carbonIntensity": "Carbon intensity of consumed electricity for this hour, in gCO2eq/kWh.",
+ "datetime": "UTC start of the hour this measurement covers.",
+ "updatedAt": "When Electricity Maps last updated this data point.",
+ "createdAt": "When Electricity Maps first created this data point.",
+ "emissionFactorType": "Type of emission factors used to compute the intensity: `lifecycle` or `direct`.",
+ "isEstimated": "Whether this value is an estimate rather than measured data.",
+ "estimationMethod": "Model used to produce the estimate, or null for measured data.",
+ },
+ },
+ "power_breakdown": {
+ "description": "Hourly origin of electricity in a zone: production, consumption, import and "
+ "export flows broken down by source, in megawatts (MW).",
+ "docs_url": "https://app.electricitymaps.com/docs/api",
+ "columns": {
+ "zone": "Identifier of the electricity grid zone, e.g. `DE` or `DK-DK1`.",
+ "datetime": "UTC start of the hour this measurement covers.",
+ "updatedAt": "When Electricity Maps last updated this data point.",
+ "createdAt": "When Electricity Maps first created this data point.",
+ "powerConsumptionBreakdown": "Electricity consumed in the zone by production type (nuclear, wind, solar, ...), in MW, after imports and exports.",
+ "powerProductionBreakdown": "Electricity produced in the zone by production type, in MW.",
+ "powerImportBreakdown": "Physical electricity imports at the zone border, by neighbouring zone, in MW.",
+ "powerExportBreakdown": "Physical electricity exports at the zone border, by neighbouring zone, in MW.",
+ "fossilFreePercentage": "Share of consumed power from fossil-free sources (renewables and nuclear), in percent.",
+ "renewablePercentage": "Share of consumed power from renewable sources, in percent.",
+ "powerConsumptionTotal": "Total power consumed in the zone, in MW.",
+ "powerProductionTotal": "Total power produced in the zone, in MW.",
+ "powerImportTotal": "Total power imported into the zone, in MW.",
+ "powerExportTotal": "Total power exported from the zone, in MW.",
+ "isEstimated": "Whether this value is an estimate rather than measured data.",
+ "estimationMethod": "Model used to produce the estimate, or null for measured data.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/electricity_maps.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/electricity_maps.py
new file mode 100644
index 000000000000..0ab4bc590126
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/electricity_maps.py
@@ -0,0 +1,282 @@
+import re
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional
+
+from dateutil import parser as dateutil_parser
+from requests import Request, Response
+from requests.exceptions import RequestException
+
+from posthog.dataclasses import frozen
+
+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 (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.settings import (
+ BASE_URL,
+ DEFAULT_HISTORY_DAYS,
+ ENDPOINT_PATHS,
+ REQUEST_TIMEOUT_SECONDS,
+ WINDOW_DAYS,
+)
+
+# Zone identifiers are short uppercase codes like DE, DK-DK1, US-CAL-CISO. The value goes into a
+# query param, so this is a sanity check for typos (a pasted URL, a lowercase zone), not a
+# security boundary.
+_ZONE_RE = re.compile(r"^[A-Z0-9-]+$")
+
+
+@frozen
+class ElectricityMapsResumeConfig:
+ window_start: str
+ zone_index: int
+
+
+def parse_zones(zones: str) -> list[str]:
+ parsed: list[str] = []
+ for zone in zones.split(","):
+ normalized = zone.strip().upper()
+ if normalized and normalized not in parsed:
+ parsed.append(normalized)
+ return parsed
+
+
+def invalid_zones(zones: list[str]) -> list[str]:
+ return [zone for zone in zones if not _ZONE_RE.match(zone)]
+
+
+def _format_datetime(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _coerce_datetime(value: Any) -> Optional[datetime]:
+ if isinstance(value, datetime):
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ parsed = dateutil_parser.parse(value)
+ except (ValueError, OverflowError):
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+ return None
+
+
+def initial_window_start(db_incremental_field_last_value: Optional[Any], history_days: int, now: datetime) -> datetime:
+ watermark = _coerce_datetime(db_incremental_field_last_value)
+ if watermark is not None:
+ # Start at the watermark itself (start is inclusive) so the last synced hour is
+ # re-fetched and the merge picks up any revision the vendor made to it.
+ return watermark
+ return now - timedelta(days=history_days)
+
+
+class ElectricityMapsRangePaginator(BasePaginator):
+ """Walks fixed datetime windows across every configured zone.
+
+ Iteration is window-major (every zone for a window, then the next window) rather than
+ zone-major. The pipeline checkpoints the incremental watermark per batch assuming ascending
+ order, so a zone-major walk that finished zone A up to now before starting zone B would, on a
+ crash whose resume state has expired, leave zone B a whole backfill behind the watermark.
+ Window-major bounds that loss to a single window.
+ """
+
+ def __init__(self, zones: list[str], initial_start: datetime, until: datetime, window: timedelta) -> None:
+ super().__init__()
+ self._zones = zones
+ self._until = until
+ self._window = window
+ self._window_start = self._clamp_start(initial_start)
+ self._zone_index = 0
+
+ def _clamp_start(self, start: datetime) -> datetime:
+ # `end` is exclusive and must be after `start`, so a watermark at or past `until` still
+ # produces one valid window covering the latest hour.
+ return min(start, self._until - timedelta(hours=1))
+
+ def _window_end(self) -> datetime:
+ return min(self._window_start + self._window, self._until)
+
+ def _set_params(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["zone"] = self._zones[self._zone_index]
+ request.params["start"] = _format_datetime(self._window_start)
+ request.params["end"] = _format_datetime(self._window_end())
+
+ def init_request(self, request: Request) -> None:
+ self._set_params(request)
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ self._zone_index += 1
+ if self._zone_index < len(self._zones):
+ return
+
+ self._zone_index = 0
+ next_start = self._window_end()
+ if next_start >= self._until:
+ self._has_next_page = False
+ return
+ self._window_start = next_start
+
+ def update_request(self, request: Request) -> None:
+ self._set_params(request)
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"window_start": _format_datetime(self._window_start), "zone_index": self._zone_index}
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ window_start = _coerce_datetime(state.get("window_start"))
+ if window_start is not None:
+ self._window_start = self._clamp_start(window_start)
+ zone_index = state.get("zone_index")
+ if zone_index is not None:
+ # The zone list comes from the source config, which the user can edit between the
+ # save and the resume, so an out-of-range index falls back to the first zone.
+ index = int(zone_index)
+ self._zone_index = index if 0 <= index < len(self._zones) else 0
+
+
+def _get_resource(endpoint: str, should_use_incremental_field: bool) -> EndpointResource:
+ return {
+ "name": endpoint,
+ "table_name": endpoint,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}
+ if should_use_incremental_field
+ else "replace",
+ "endpoint": {
+ "path": ENDPOINT_PATHS[endpoint],
+ "data_selector": "data",
+ "data_selector_required": True,
+ "params": {},
+ },
+ "table_format": "delta",
+ "columns": {
+ "datetime": {"data_type": "timestamp"},
+ "updatedAt": {"data_type": "timestamp"},
+ "createdAt": {"data_type": "timestamp"},
+ },
+ }
+
+
+def electricity_maps_source(
+ api_token: str,
+ zones: list[str],
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ElectricityMapsResumeConfig],
+ db_incremental_field_last_value: Optional[Any],
+ should_use_incremental_field: bool = False,
+ history_days: Optional[int] = None,
+) -> SourceResponse:
+ if endpoint not in ENDPOINT_PATHS:
+ raise ValueError(f"Unknown Electricity Maps endpoint: {endpoint}")
+ if not zones:
+ raise ValueError("No Electricity Maps zones configured")
+
+ if history_days is None or history_days <= 0:
+ history_days = DEFAULT_HISTORY_DAYS
+
+ now = datetime.now(UTC)
+ start = initial_window_start(
+ db_incremental_field_last_value if should_use_incremental_field else None, history_days, now
+ )
+ paginator = ElectricityMapsRangePaginator(
+ zones=zones, initial_start=start, until=now, window=timedelta(days=WINDOW_DAYS)
+ )
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "name": "auth-token",
+ "api_key": api_token,
+ "location": "header",
+ },
+ # The auth-token header must never leave the API host: refuse redirects and pin every
+ # request (including resumed ones) to the base URL's host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ "paginator": paginator,
+ },
+ "resource_defaults": {},
+ "resources": [_get_resource(endpoint, should_use_incremental_field)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {
+ "window_start": resume_config.window_start,
+ "zone_index": resume_config.zone_index,
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("window_start"):
+ resumable_source_manager.save_state(
+ ElectricityMapsResumeConfig(
+ window_start=str(state["window_start"]), zone_index=int(state.get("zone_index") or 0)
+ )
+ )
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=["zone", "datetime"],
+ column_hints=resource.column_hints,
+ partition_keys=["datetime"],
+ partition_mode="datetime",
+ partition_format="month",
+ sort_mode="asc",
+ )
+
+
+def validate_credentials(api_token: str, zones: list[str]) -> tuple[bool, str | None]:
+ # Same redirect boundary as the extraction client: the auth-token header must never leave
+ # the API host, so this probe pins to BASE_URL rather than following the session default.
+ session = make_tracked_session(headers={"auth-token": api_token}, redact_values=(api_token,), allow_redirects=False)
+ # `/carbon-intensity/latest` is the cheapest authenticated call and is available on every
+ # plan, so it both proves the token and surfaces per-zone entitlement before the first sync.
+ for zone in zones:
+ try:
+ response = session.get(
+ f"{BASE_URL}/carbon-intensity/latest", params={"zone": zone}, timeout=REQUEST_TIMEOUT_SECONDS
+ )
+ except RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ continue
+ if response.status_code == 401:
+ return False, "Electricity Maps rejected your API token. Check the token in the Electricity Maps portal."
+ if response.status_code == 403:
+ return (
+ False,
+ f"Your Electricity Maps token does not have access to zone {zone}. "
+ "Check your plan in the Electricity Maps portal, or remove the zone.",
+ )
+ if response.status_code == 404:
+ return (
+ False,
+ f"Electricity Maps does not recognize zone {zone}. "
+ "Check the zone identifier against the Electricity Maps zone list.",
+ )
+ return False, f"Electricity Maps returned an unexpected status code ({response.status_code})."
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/settings.py
new file mode 100644
index 000000000000..7933bc9e8179
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/settings.py
@@ -0,0 +1,38 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+BASE_URL = "https://api.electricitymaps.com/v3"
+
+CARBON_INTENSITY = "carbon_intensity"
+POWER_BREAKDOWN = "power_breakdown"
+
+ENDPOINTS = (CARBON_INTENSITY, POWER_BREAKDOWN)
+
+ENDPOINT_PATHS: dict[str, str] = {
+ CARBON_INTENSITY: "/carbon-intensity/past-range",
+ POWER_BREAKDOWN: "/power-breakdown/past-range",
+}
+
+# The past-range endpoints have no pagination: one request returns every hourly point in the
+# requested window, and the API rejects windows longer than 10 days. Walk the range in windows
+# comfortably under that cap.
+WINDOW_DAYS = 5
+
+# (connect, read) timeout in seconds. Without it, a stalled response holds the import worker
+# indefinitely — see `request_timeout` on `ClientConfig`.
+REQUEST_TIMEOUT_SECONDS: tuple[float, float] = (10.0, 60.0)
+
+# How far back the first sync reaches when the user leaves the history field empty. History depth
+# is gated by the customer's Electricity Maps plan, so this stays modest.
+DEFAULT_HISTORY_DAYS = 30
+
+_DATETIME_FIELD: IncrementalField = {
+ "label": "datetime",
+ "type": IncrementalFieldType.DateTime,
+ "field": "datetime",
+ "field_type": IncrementalFieldType.DateTime,
+}
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ CARBON_INTENSITY: [_DATETIME_FIELD],
+ POWER_BREAKDOWN: [_DATETIME_FIELD],
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/source.py
index 3ae40abcaa27..b3727e5bec68 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/source.py
@@ -1,8 +1,34 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.electricity_maps import (
+ ElectricityMapsResumeConfig,
+ electricity_maps_source,
+ invalid_zones,
+ parse_zones,
+ validate_credentials as validate_electricity_maps_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.electricitymaps import (
ElectricityMapsSourceConfig,
)
@@ -10,19 +36,130 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ElectricityMapsSource(SimpleSource[ElectricityMapsSourceConfig]):
+class ElectricityMapsSource(ResumableSource[ElectricityMapsSourceConfig, ElectricityMapsResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v3",)
+ default_version = "v3"
+ api_docs_url = "https://app.electricitymaps.com/docs/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ELECTRICITYMAPS
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Electricity Maps rejected your API token. Check the token in the Electricity Maps portal and reconnect the source.",
+ "403 Client Error": "Your Electricity Maps token does not have access to a configured zone or the requested history range. Check your plan in the Electricity Maps portal.",
+ "404 Client Error": "Electricity Maps does not recognize one of the configured zones. Check the zone identifiers in the source settings.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: ElectricityMapsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: ElectricityMapsSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ zones = parse_zones(config.zones)
+ if not zones:
+ return False, "Enter at least one zone identifier, like DE or DK-DK1."
+
+ malformed = invalid_zones(zones)
+ if malformed:
+ return (
+ False,
+ f"These don't look like zone identifiers: {', '.join(malformed)}. "
+ "Enter comma-separated zone codes, like DE, DK-DK1, US-CAL-CISO.",
+ )
+
+ return validate_electricity_maps_credentials(config.api_token, zones)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ElectricityMapsResumeConfig]:
+ # carbon_intensity and power_breakdown each keep their own (window, zone) cursor, so a
+ # retry that switches endpoints can't load the other endpoint's resume state.
+ return ResumableSourceManager[ElectricityMapsResumeConfig](inputs, ElectricityMapsResumeConfig).with_namespace(
+ inputs.schema_name
+ )
+
+ def source_for_pipeline(
+ self,
+ config: ElectricityMapsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ElectricityMapsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return electricity_maps_source(
+ api_token=config.api_token,
+ zones=parse_zones(config.zones),
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ history_days=config.history_days,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.ELECTRICITYMAPS,
category=DataWarehouseSourceCategory.ANALYTICS,
label="Electricity Maps",
+ caption="Enter your Electricity Maps API token, created in the "
+ "[Electricity Maps portal](https://portal.electricitymaps.com/).\n\n"
+ "Zones is a comma-separated list of zone identifiers to sync, like `DE, DK-DK1, US-CAL-CISO`. "
+ "Zone access and history depth depend on your Electricity Maps plan.",
keywords=["carbon intensity", "grid", "electricity map"],
+ docsUrl="https://posthog.com/docs/cdp/sources/electricity-maps",
iconPath="/static/services/electricity_maps.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="zones",
+ label="Zones",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="DE, DK-DK1, US-CAL-CISO",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="history_days",
+ label="Days of history to sync initially",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder="30",
+ secret=False,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps.py
new file mode 100644
index 000000000000..d96401262f1a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps.py
@@ -0,0 +1,290 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+import time_machine
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.electricity_maps import (
+ ElectricityMapsResumeConfig,
+ electricity_maps_source,
+ initial_window_start,
+ invalid_zones,
+ parse_zones,
+ validate_credentials,
+)
+
+_NOW = datetime(2025, 6, 15, 12, 0, 0, tzinfo=UTC)
+
+
+def _make_http_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp._content = json.dumps(body).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _page(zone: str) -> Response:
+ return _make_http_response(
+ {"zone": zone, "data": [{"zone": zone, "carbonIntensity": 300, "datetime": "2025-06-10T00:00:00.000Z"}]}
+ )
+
+
+def _drive(
+ *,
+ manager: MagicMock,
+ responses: list[Response],
+ zones: list[str],
+ endpoint: str = "carbon_intensity",
+ incremental: bool = False,
+ last_value: Any = None,
+ history_days: int | None = None,
+) -> list[dict[str, Any]]:
+ # Capture shallow copies of request.params at send time: the paginator mutates the one
+ # Request object in place between pages, so call_args_list would only show the final state.
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ response = electricity_maps_source(
+ api_token="test-token",
+ zones=zones,
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ db_incremental_field_last_value=last_value,
+ should_use_incremental_field=incremental,
+ history_days=history_days,
+ )
+ list(cast(Iterable[Any], response.items()))
+ return sent_params
+
+
+def _fresh_manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+class TestZoneParsing:
+ @pytest.mark.parametrize(
+ ("raw", "expected"),
+ [
+ ("DE", ["DE"]),
+ ("de, dk-dk1 ,DE", ["DE", "DK-DK1"]),
+ (" , ,", []),
+ ("US-CAL-CISO", ["US-CAL-CISO"]),
+ ],
+ )
+ def test_parse_zones_normalizes_and_dedupes(self, raw: str, expected: list[str]) -> None:
+ assert parse_zones(raw) == expected
+
+ @pytest.mark.parametrize(
+ ("zones", "expected_invalid"),
+ [
+ (["DE", "DK-DK1"], []),
+ (["HTTPS://EXAMPLE.COM", "DE"], ["HTTPS://EXAMPLE.COM"]),
+ (["DE DE"], ["DE DE"]),
+ ],
+ )
+ def test_invalid_zones_flags_non_zone_values(self, zones: list[str], expected_invalid: list[str]) -> None:
+ assert invalid_zones(zones) == expected_invalid
+
+
+class TestInitialWindowStart:
+ @pytest.mark.parametrize(
+ ("last_value", "expected"),
+ [
+ (datetime(2025, 6, 10, 3, 0, 0, tzinfo=UTC), datetime(2025, 6, 10, 3, 0, 0, tzinfo=UTC)),
+ # A naive watermark from the DB is treated as UTC rather than rejected.
+ (datetime(2025, 6, 10, 3, 0, 0), datetime(2025, 6, 10, 3, 0, 0, tzinfo=UTC)),
+ ("2025-06-10T03:00:00+00:00", datetime(2025, 6, 10, 3, 0, 0, tzinfo=UTC)),
+ (None, datetime(2025, 6, 5, 12, 0, 0, tzinfo=UTC)),
+ # An unparseable watermark falls back to the history window instead of crashing the sync.
+ ("not-a-datetime", datetime(2025, 6, 5, 12, 0, 0, tzinfo=UTC)),
+ ],
+ )
+ def test_start_comes_from_watermark_or_history_window(self, last_value: Any, expected: datetime) -> None:
+ assert initial_window_start(last_value, history_days=10, now=_NOW) == expected
+
+
+class TestWindowWalk:
+ @time_machine.travel(_NOW, tick=False)
+ def test_walks_window_major_across_zones_and_clamps_final_window(self) -> None:
+ manager = _fresh_manager()
+ watermark = datetime(2025, 6, 7, 12, 0, 0, tzinfo=UTC)
+
+ sent_params = _drive(
+ manager=manager,
+ responses=[_page("DE"), _page("SE"), _page("DE"), _page("SE")],
+ zones=["DE", "SE"],
+ incremental=True,
+ last_value=watermark,
+ )
+
+ assert [(p["zone"], p["start"], p["end"]) for p in sent_params] == [
+ ("DE", "2025-06-07T12:00:00Z", "2025-06-12T12:00:00Z"),
+ ("SE", "2025-06-07T12:00:00Z", "2025-06-12T12:00:00Z"),
+ ("DE", "2025-06-12T12:00:00Z", "2025-06-15T12:00:00Z"),
+ ("SE", "2025-06-12T12:00:00Z", "2025-06-15T12:00:00Z"),
+ ]
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [
+ ElectricityMapsResumeConfig(window_start="2025-06-07T12:00:00Z", zone_index=1),
+ ElectricityMapsResumeConfig(window_start="2025-06-12T12:00:00Z", zone_index=0),
+ ElectricityMapsResumeConfig(window_start="2025-06-12T12:00:00Z", zone_index=1),
+ ]
+
+ @time_machine.travel(_NOW, tick=False)
+ def test_watermark_at_or_past_now_still_requests_one_valid_window(self) -> None:
+ manager = _fresh_manager()
+
+ sent_params = _drive(
+ manager=manager,
+ responses=[_page("DE")],
+ zones=["DE"],
+ incremental=True,
+ last_value=datetime(2025, 6, 15, 13, 0, 0, tzinfo=UTC),
+ )
+
+ assert sent_params == [{"zone": "DE", "start": "2025-06-15T11:00:00Z", "end": "2025-06-15T12:00:00Z"}]
+ manager.save_state.assert_not_called()
+
+ @time_machine.travel(_NOW, tick=False)
+ @pytest.mark.parametrize(
+ ("history_days", "expected_start"),
+ [
+ (None, "2025-05-16T12:00:00Z"),
+ (7, "2025-06-08T12:00:00Z"),
+ ],
+ )
+ def test_full_refresh_starts_at_history_window_and_ignores_watermark(
+ self, history_days: int | None, expected_start: str
+ ) -> None:
+ sent_params = _drive(
+ manager=_fresh_manager(),
+ responses=[_page("DE")] * 10,
+ zones=["DE"],
+ incremental=False,
+ last_value=datetime(2025, 6, 14, 0, 0, 0, tzinfo=UTC),
+ history_days=history_days,
+ )
+
+ assert sent_params[0]["start"] == expected_start
+
+ @time_machine.travel(_NOW, tick=False)
+ def test_resume_seeds_window_and_zone(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ElectricityMapsResumeConfig(window_start="2025-06-12T12:00:00Z", zone_index=1)
+
+ sent_params = _drive(
+ manager=manager,
+ responses=[_page("SE")],
+ zones=["DE", "SE"],
+ incremental=True,
+ last_value=datetime(2025, 6, 7, 12, 0, 0, tzinfo=UTC),
+ )
+
+ assert sent_params == [{"zone": "SE", "start": "2025-06-12T12:00:00Z", "end": "2025-06-15T12:00:00Z"}]
+
+ @time_machine.travel(_NOW, tick=False)
+ def test_resume_with_out_of_range_zone_index_falls_back_to_first_zone(self) -> None:
+ # The zone list is user-editable between a save and a resume, so a stale index must not crash.
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ElectricityMapsResumeConfig(window_start="2025-06-12T12:00:00Z", zone_index=5)
+
+ sent_params = _drive(
+ manager=manager,
+ responses=[_page("DE"), _page("SE")],
+ zones=["DE", "SE"],
+ incremental=True,
+ last_value=datetime(2025, 6, 7, 12, 0, 0, tzinfo=UTC),
+ )
+
+ assert [p["zone"] for p in sent_params] == ["DE", "SE"]
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown Electricity Maps endpoint"):
+ electricity_maps_source(
+ api_token="test-token",
+ zones=["DE"],
+ endpoint="forecast",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=_fresh_manager(),
+ db_incremental_field_last_value=None,
+ )
+
+ def test_no_zones_raises(self) -> None:
+ with pytest.raises(ValueError, match="zones"):
+ electricity_maps_source(
+ api_token="test-token",
+ zones=[],
+ endpoint="carbon_intensity",
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=_fresh_manager(),
+ db_incremental_field_last_value=None,
+ )
+
+
+class TestValidateCredentials:
+ _SESSION = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.electricity_maps"
+ ".make_tracked_session"
+ )
+
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid", "expected_fragment"),
+ [
+ (200, True, None),
+ (401, False, "rejected your API token"),
+ (403, False, "does not have access to zone DE"),
+ (404, False, "does not recognize zone DE"),
+ (500, False, "unexpected status code (500)"),
+ ],
+ )
+ def test_status_maps_to_user_message(
+ self, status_code: int, expected_valid: bool, expected_fragment: str | None
+ ) -> None:
+ with patch(self._SESSION) as MockSession:
+ MockSession.return_value.get.return_value = _make_http_response({}, status_code=status_code)
+ is_valid, message = validate_credentials("test-token", ["DE"])
+
+ assert is_valid is expected_valid
+ if expected_fragment is None:
+ assert message is None
+ else:
+ assert message is not None and expected_fragment in message
+
+ def test_stops_at_first_failing_zone(self) -> None:
+ with patch(self._SESSION) as MockSession:
+ MockSession.return_value.get.side_effect = [
+ _make_http_response({}, status_code=200),
+ _make_http_response({}, status_code=403),
+ ]
+ is_valid, message = validate_credentials("test-token", ["DE", "XX"])
+
+ assert is_valid is False
+ assert message is not None and "zone XX" in message
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps_source.py
new file mode 100644
index 000000000000..c543a303e561
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/electricity_maps/tests/test_electricity_maps_source.py
@@ -0,0 +1,50 @@
+import pytest
+from unittest.mock import patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.source import (
+ ElectricityMapsSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.electricitymaps import (
+ ElectricityMapsSourceConfig,
+)
+
+_VALIDATE = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.electricity_maps.source"
+ ".validate_electricity_maps_credentials"
+)
+
+
+class TestElectricityMapsCredentialValidation:
+ @pytest.mark.parametrize("zones", ["", " , ,"])
+ def test_rejects_empty_zone_list_without_calling_the_api(self, zones: str) -> None:
+ config = ElectricityMapsSourceConfig(api_token="token", zones=zones)
+ with patch(_VALIDATE) as mock_validate:
+ is_valid, message = ElectricityMapsSource().validate_credentials(config, team_id=1)
+
+ assert is_valid is False
+ assert message is not None and "zone" in message
+ mock_validate.assert_not_called()
+
+ @pytest.mark.parametrize(
+ ("zones", "malformed"),
+ [
+ ("DE, https://example.com", "HTTPS://EXAMPLE.COM"),
+ ("DE DE", "DE DE"),
+ ],
+ )
+ def test_rejects_malformed_zones_without_calling_the_api(self, zones: str, malformed: str) -> None:
+ config = ElectricityMapsSourceConfig(api_token="token", zones=zones)
+ with patch(_VALIDATE) as mock_validate:
+ is_valid, message = ElectricityMapsSource().validate_credentials(config, team_id=1)
+
+ assert is_valid is False
+ assert message is not None and malformed in message
+ mock_validate.assert_not_called()
+
+ def test_delegates_normalized_zones_to_the_api_probe(self) -> None:
+ config = ElectricityMapsSourceConfig(api_token="token", zones="de, dk-dk1")
+ with patch(_VALIDATE, return_value=(True, None)) as mock_validate:
+ is_valid, message = ElectricityMapsSource().validate_credentials(config, team_id=1)
+
+ assert (is_valid, message) == (True, None)
+ mock_validate.assert_called_once_with("token", ["DE", "DK-DK1"])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/electricitymaps.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/electricitymaps.py
index 54dcb4897bf5..2e4db4276034 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/electricitymaps.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/electricitymaps.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class ElectricityMapsSourceConfig(config.Config):
- pass
+ api_token: str
+ zones: str
+ history_days: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)