:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement oura import source (#65624)
Tom Owers6087d12aea74
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex ecfeae679dae..5bdc567c3331 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -153,6 +153,7 @@ the row lists both.| omnisend | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || ortto | HTTP | requests | ✅ |+| oura | HTTP | requests | ✅ || outbrain | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || optimizely | HTTP | requests | ✅ |@@ -533,7 +534,6 @@ doesn't conflict with concurrent PRs.- oracle_ebs- oracle_fusion- orbit-- oura- outlook- outreach- oveitdiff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 89db4ac5b1ce..30cbc8d80244 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -2192,7 +2192,7 @@ class OrttoSourceConfig(config.Config):@config.configclass OuraSourceConfig(config.Config):- pass+ access_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/oura/canonical_descriptions.py b/posthog/temporal/data_imports/sources/oura/canonical_descriptions.pynew file mode 100644index 000000000000..793c6d3e3ee7--- /dev/null+++ b/posthog/temporal/data_imports/sources/oura/canonical_descriptions.py@@ -0,0 +1,119 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++_DOCS = "https://cloud.ouraring.com/v2/docs"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "daily_sleep": {+ "description": "Daily sleep score and its contributing factors for the user.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the daily sleep summary.",+ "day": "Calendar day the summary covers (YYYY-MM-DD).",+ "score": "Overall sleep score from 1-100.",+ "contributors": "Breakdown of the factors contributing to the sleep score.",+ "timestamp": "ISO 8601 timestamp the summary refers to.",+ },+ },+ "daily_activity": {+ "description": "Daily activity score and movement metrics for the user.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the daily activity summary.",+ "day": "Calendar day the summary covers (YYYY-MM-DD).",+ "score": "Overall activity score from 1-100.",+ "active_calories": "Calories burned through activity during the day.",+ "total_calories": "Total calories burned during the day.",+ "steps": "Total number of steps taken during the day.",+ "equivalent_walking_distance": "Distance in metres equivalent to the day's activity.",+ "timestamp": "ISO 8601 timestamp the summary refers to.",+ },+ },+ "daily_readiness": {+ "description": "Daily readiness score reflecting the user's recovery and preparedness.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the daily readiness summary.",+ "day": "Calendar day the summary covers (YYYY-MM-DD).",+ "score": "Overall readiness score from 1-100.",+ "contributors": "Breakdown of the factors contributing to the readiness score.",+ "temperature_deviation": "Body temperature deviation from the user's baseline, in Celsius.",+ "timestamp": "ISO 8601 timestamp the summary refers to.",+ },+ },+ "daily_spo2": {+ "description": "Daily average blood oxygen saturation (SpO2) for the user.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the daily SpO2 summary.",+ "day": "Calendar day the summary covers (YYYY-MM-DD).",+ "spo2_percentage": "Average blood oxygen saturation percentage during sleep.",+ "breathing_disturbance_index": "Index summarising breathing disturbances during sleep.",+ },+ },+ "daily_stress": {+ "description": "Daily summary of time spent in stressful and restorative states.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the daily stress summary.",+ "day": "Calendar day the summary covers (YYYY-MM-DD).",+ "stress_high": "Seconds spent in a high-stress state during the day.",+ "recovery_high": "Seconds spent in a high-recovery state during the day.",+ "day_summary": "Categorical summary of the day's stress balance.",+ },+ },+ "sleep": {+ "description": "Detailed metrics for each individual sleep period (long and short naps).",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the sleep period.",+ "day": "Calendar day the sleep period is attributed to (YYYY-MM-DD).",+ },+ },+ "session": {+ "description": "Guided or unguided moment, breathing, or relaxation sessions.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the session.",+ "day": "Calendar day the session occurred (YYYY-MM-DD).",+ "type": "Type of session (e.g. breathing, meditation, nap, relaxation).",+ "start_datetime": "ISO 8601 start time of the session.",+ "end_datetime": "ISO 8601 end time of the session.",+ },+ },+ "workout": {+ "description": "Workouts recorded automatically or added manually by the user.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the workout.",+ "day": "Calendar day the workout occurred (YYYY-MM-DD).",+ "activity": "Type of activity for the workout (e.g. running, cycling).",+ "calories": "Calories burned during the workout.",+ "distance": "Distance covered during the workout, in metres.",+ "intensity": "Intensity of the workout (easy, moderate, hard).",+ "source": "How the workout was recorded (e.g. manual, auto, confirmed).",+ "start_datetime": "ISO 8601 start time of the workout.",+ "end_datetime": "ISO 8601 end time of the workout.",+ },+ },+ "heartrate": {+ "description": "Time-series heart-rate samples in beats per minute.",+ "docs_url": _DOCS,+ "columns": {+ "timestamp": "ISO 8601 timestamp of the heart-rate sample.",+ "bpm": "Heart rate in beats per minute.",+ "source": "Context the sample was measured in (awake, rest, sleep, session, live, workout).",+ },+ },+ "personal_info": {+ "description": "Static profile information for the authenticated user.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the user.",+ "age": "Age of the user in years.",+ "weight": "Weight of the user in kilograms.",+ "height": "Height of the user in metres.",+ "biological_sex": "Biological sex recorded for the user.",+ "email": "Email address associated with the Oura account.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/oura/oura.py b/posthog/temporal/data_imports/sources/oura/oura.pynew file mode 100644index 000000000000..5afc99812326--- /dev/null+++ b/posthog/temporal/data_imports/sources/oura/oura.py@@ -0,0 +1,214 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.oura.settings import OURA_ENDPOINTS, OuraEndpointConfig++OURA_BASE_URL = "https://api.ouraring.com/v2"++# Oura rings didn't exist before 2015; this lower bound guarantees a full backfill on first sync.+# The API defaults start_date to end_date - 1 day, so an explicit early start is required to pull+# history rather than just the most recent day.+DEFAULT_START_DATE = "2014-01-01"++PAGE_TIMEOUT_SECONDS = 60+VALIDATE_TIMEOUT_SECONDS = 10+++class OuraRetryableError(Exception):+ pass+++class OuraResumeConfig:+ # Opaque pagination cursor returned by the API as `next_token`. Resuming re-issues the same+ # date-windowed request with this token appended.+ next_token: str | None = None+++def _get_headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}", "Accept": "application/json"}+++def _format_date(value: Any) -> str:+ """Format a date cursor value as the YYYY-MM-DD string Oura's start_date expects."""+ if isinstance(value, datetime):+ return value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ # Stored cursor can come back as an ISO string; the date component is the first 10 chars.+ return str(value)[:10]+++def _format_datetime(value: Any) -> str:+ """Format a datetime cursor value as the ISO 8601 string Oura's start_datetime expects."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _clamp_date_to_today(value: str) -> str:+ """Cap a start_date at today. A future-dated record can push the cursor past today, and Oura+ 400s when start_date is after end_date (which defaults to today)."""+ today = datetime.now(UTC).date().isoformat()+ return today if value > today else value+++def _clamp_datetime_to_now(value: str) -> str:+ now = datetime.now(UTC).isoformat()+ return now if value > now else value+++def _build_initial_params(+ config: OuraEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, str]:+ """Build the date-window query params for the first page of a request."""+ params: dict[str, str] = {}++ have_cursor = should_use_incremental_field and db_incremental_field_last_value is not None++ if config.date_filter == "date":+ start = _format_date(db_incremental_field_last_value) if have_cursor else DEFAULT_START_DATE+ params["start_date"] = _clamp_date_to_today(start)+ elif config.date_filter == "datetime":+ if have_cursor:+ start = _clamp_datetime_to_now(_format_datetime(db_incremental_field_last_value))+ else:+ start = f"{DEFAULT_START_DATE}T00:00:00+00:00"+ params["start_datetime"] = start++ return params+++def _build_url(path: str, params: dict[str, str]) -> str:+ url = f"{OURA_BASE_URL}{path}"+ if params:+ return f"{url}?{urlencode(params)}"+ return url+++@retry(+ retry=retry_if_exception_type((OuraRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=PAGE_TIMEOUT_SECONDS)++ # Oura rate-limits at ~5000 requests / 5 min and returns 429 with backoff expected.+ if response.status_code == 429 or response.status_code >= 500:+ raise OuraRetryableError(f"Oura API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Oura API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def probe_endpoint(token: str, path: str) -> int:+ """Return the HTTP status code for a minimal GET against `path`. -1 on a transport failure."""+ try:+ response = make_tracked_session().get(+ f"{OURA_BASE_URL}{path}", headers=_get_headers(token), timeout=VALIDATE_TIMEOUT_SECONDS+ )+ return response.status_code+ except Exception:+ return -1+++def get_rows(+ token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OuraResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = OURA_ENDPOINTS[endpoint]+ headers = _get_headers(token)+ # One session reused across every page so urllib3 keeps the connection alive.+ session = make_tracked_session()++ # Single-document endpoints (e.g. personal_info) return a flat object, not a+ # {data: [...], next_token} envelope.+ if config.is_single_document:+ document = _fetch_page(session, _build_url(config.path, {}), headers, logger)+ yield [document]+ return++ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_token:+ params = {**params, "next_token": resume.next_token}+ logger.debug(f"Oura: resuming {endpoint} from next_token")++ while True:+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)++ # Use `data["data"]` (not `.get`) so an unexpected 200 without the documented envelope+ # raises a KeyError and fails the sync loudly, rather than silently ingesting zero rows.+ items = data["data"]+ next_token = data.get("next_token")++ if items:+ yield items++ if not next_token:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge+ # dedupes on the primary key. Advance the cursor before the next fetch to avoid re-looping+ # the same page.+ resumable_source_manager.save_state(OuraResumeConfig(next_token=next_token))+ params = {**params, "next_token": next_token}+++def oura_source(+ token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[OuraResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = OURA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ token=token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Oura returns records in ascending date order; we additionally re-window by start_date on+ # every sync, so the checkpointed watermark advances correctly.+ sort_mode="asc",+ )diff --git a/posthog/temporal/data_imports/sources/oura/settings.py b/posthog/temporal/data_imports/sources/oura/settings.pynew file mode 100644index 000000000000..6c01ad65acbb--- /dev/null+++ b/posthog/temporal/data_imports/sources/oura/settings.py@@ -0,0 +1,208 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class OuraEndpointConfig:+ name: str+ # Path under the v2 base URL, e.g. "/usercollection/daily_sleep".+ path: str+ incremental_fields: list[IncrementalField]+ # Column whose max value the pipeline checkpoints and that we feed back as the next sync's+ # start filter. Must be the date/datetime field the API actually filters on (e.g. "day",+ # "start_day", or "timestamp"), so max(cursor) -> next start_(date|datetime) is correct.+ cursor_field: Optional[str] = None+ # Stable field to partition by (never an updated_at style field). Daily summaries are keyed by+ # an immutable record date, so we partition by that date.+ partition_key: Optional[str] = None+ # Filter style this endpoint supports. "date" -> start_date/end_date (record-date filtering on+ # most usercollection endpoints), "datetime" -> start_datetime/end_datetime (time-series), and+ # None -> no date filtering at all (single/static documents -> full refresh only).+ date_filter: Optional[str] = None+ # Some endpoints (personal_info) return a single flat document rather than a+ # `{data: [...], next_token}` collection envelope; the transport dispatches on this.+ is_single_document: bool = False+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+++def _date_fields(*names: str) -> list[IncrementalField]:+ return [+ {+ "label": name,+ "type": IncrementalFieldType.Date,+ "field": name,+ "field_type": IncrementalFieldType.Date,+ }+ for name in names+ ]+++def _datetime_fields(*names: str) -> list[IncrementalField]:+ return [+ {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+ for name in names+ ]+++OURA_ENDPOINTS: dict[str, OuraEndpointConfig] = {+ "daily_activity": OuraEndpointConfig(+ name="daily_activity",+ path="/usercollection/daily_activity",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_readiness": OuraEndpointConfig(+ name="daily_readiness",+ path="/usercollection/daily_readiness",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_sleep": OuraEndpointConfig(+ name="daily_sleep",+ path="/usercollection/daily_sleep",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_spo2": OuraEndpointConfig(+ name="daily_spo2",+ path="/usercollection/daily_spo2",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_stress": OuraEndpointConfig(+ name="daily_stress",+ path="/usercollection/daily_stress",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_cardiovascular_age": OuraEndpointConfig(+ name="daily_cardiovascular_age",+ path="/usercollection/daily_cardiovascular_age",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "daily_resilience": OuraEndpointConfig(+ name="daily_resilience",+ path="/usercollection/daily_resilience",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "sleep": OuraEndpointConfig(+ name="sleep",+ path="/usercollection/sleep",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "sleep_time": OuraEndpointConfig(+ name="sleep_time",+ path="/usercollection/sleep_time",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "session": OuraEndpointConfig(+ name="session",+ path="/usercollection/session",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "workout": OuraEndpointConfig(+ name="workout",+ path="/usercollection/workout",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "tag": OuraEndpointConfig(+ name="tag",+ path="/usercollection/tag",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ "enhanced_tag": OuraEndpointConfig(+ name="enhanced_tag",+ path="/usercollection/enhanced_tag",+ cursor_field="start_day",+ partition_key="start_day",+ date_filter="date",+ incremental_fields=_date_fields("start_day"),+ ),+ "rest_mode_period": OuraEndpointConfig(+ name="rest_mode_period",+ path="/usercollection/rest_mode_period",+ cursor_field="start_day",+ partition_key="start_day",+ date_filter="date",+ incremental_fields=_date_fields("start_day"),+ ),+ "vO2_max": OuraEndpointConfig(+ name="vO2_max",+ path="/usercollection/vO2_max",+ cursor_field="day",+ partition_key="day",+ date_filter="date",+ incremental_fields=_date_fields("day"),+ ),+ # Time-series heart-rate samples. Filtered by start_datetime/end_datetime, not start_date/end_date,+ # and the response carries no `id` — a sample is identified by its timestamp and source.+ "heartrate": OuraEndpointConfig(+ name="heartrate",+ path="/usercollection/heartrate",+ cursor_field="timestamp",+ partition_key="timestamp",+ date_filter="datetime",+ incremental_fields=_datetime_fields("timestamp"),+ primary_keys=["timestamp", "source"],+ ),+ # Single, mostly-static document for the authenticated user. No date filtering -> full refresh.+ "personal_info": OuraEndpointConfig(+ name="personal_info",+ path="/usercollection/personal_info",+ date_filter=None,+ is_single_document=True,+ incremental_fields=[],+ ),+ # Ring hardware/configuration records. No date filtering -> full refresh.+ "ring_configuration": OuraEndpointConfig(+ name="ring_configuration",+ path="/usercollection/ring_configuration",+ date_filter=None,+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(OURA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in OURA_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/oura/source.py b/posthog/temporal/data_imports/sources/oura/source.pyindex 35e60fd6711e..6b3d697cd437 100644--- a/posthog/temporal/data_imports/sources/oura/source.py+++ b/posthog/temporal/data_imports/sources/oura/source.py@@ -1,20 +1,29 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import OuraSourceConfig+from posthog.temporal.data_imports.sources.oura.oura import OuraResumeConfig, oura_source, probe_endpoint+from posthog.temporal.data_imports.sources.oura.settings import ENDPOINTS, INCREMENTAL_FIELDS, OURA_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class OuraSource(SimpleSource[OuraSourceConfig]):+class OuraSource(ResumableSource[OuraSourceConfig, OuraResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OURA@@ -23,9 +32,108 @@ class OuraSource(SimpleSource[OuraSourceConfig]):def get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.OURA,- category=DataWarehouseSourceCategory.PRODUCTIVITY,+ category=DataWarehouseSourceCategory.ANALYTICS,label="Oura",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Oura personal access token to automatically pull your Oura Ring health data into the PostHog Data warehouse.++You can create a personal access token in the [Oura developer portal](https://cloud.ouraring.com/personal-access-tokens).+""",iconPath="/static/services/oura.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/oura",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="access_token",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # Retrying can never satisfy a credential/scope problem, so stop the sync. Match the+ # stable status text and base host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.ouraring.com": "Your Oura access token is invalid or has been revoked. Create a new personal access token in the Oura developer portal, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.ouraring.com": "Your Oura access token is missing the scopes needed to sync this data. Grant the required scopes, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.oura.canonical_descriptions import CANONICAL_DESCRIPTIONS++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: OuraSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = OURA_ENDPOINTS[endpoint]+ # Only endpoints with a server-side date filter can sync incrementally; the others+ # (personal_info, ring_configuration) are full refresh only.+ has_incremental = endpoint_config.date_filter is not None+ return SourceSchema(+ name=endpoint,+ supports_incremental=has_incremental,+ supports_append=has_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: OuraSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Probe the requested endpoint when validating a specific schema, otherwise the cheap+ # single-document personal_info endpoint at source-create.+ path = OURA_ENDPOINTS[schema_name].path if schema_name in OURA_ENDPOINTS else "/usercollection/personal_info"+ status = probe_endpoint(config.access_token, path)++ if status == 200:+ return True, None+ if status == 401:+ return False, "Invalid Oura access token"+ # A valid token can legitimately lack scope for an endpoint the user isn't trying to sync;+ # accept 403 at source-create and only reject it when validating a specific schema.+ if status == 403 and schema_name is None:+ return True, None+ if status == 403:+ return False, f"Your Oura access token is missing the scope required for {schema_name}"++ return False, "Could not validate Oura access token"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OuraResumeConfig]:+ return ResumableSourceManager[OuraResumeConfig](inputs, OuraResumeConfig)++ def source_for_pipeline(+ self,+ config: OuraSourceConfig,+ resumable_source_manager: ResumableSourceManager[OuraResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return oura_source(+ token=config.access_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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,)diff --git a/posthog/temporal/data_imports/sources/oura/tests/test_oura.py b/posthog/temporal/data_imports/sources/oura/tests/test_oura.pynew file mode 100644index 000000000000..4d7e1ad880d4--- /dev/null+++ b/posthog/temporal/data_imports/sources/oura/tests/test_oura.py@@ -0,0 +1,241 @@+from datetime import UTC, date, datetime+from typing import Any++from freezegun import freeze_time+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.temporal.data_imports.sources.oura import oura+from posthog.temporal.data_imports.sources.oura.oura import (+ DEFAULT_START_DATE,+ OuraResumeConfig,+ _build_initial_params,+ _build_url,+ _clamp_date_to_today,+ _clamp_datetime_to_now,+ _format_date,+ _format_datetime,+ get_rows,+ oura_source,+ probe_endpoint,+)+from posthog.temporal.data_imports.sources.oura.settings import OURA_ENDPOINTS+++class _FakeResumableManager:+ def __init__(self, state: OuraResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[OuraResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> OuraResumeConfig | None:+ return self._state++ def save_state(self, data: OuraResumeConfig) -> None:+ self.saved.append(data)+++class TestFormatHelpers:+ @parameterized.expand(+ [+ ("datetime", datetime(2021, 5, 1, 12, 30, tzinfo=UTC), "2021-05-01"),+ ("date", date(2021, 5, 1), "2021-05-01"),+ ("iso_string", "2021-05-01T00:00:00+00:00", "2021-05-01"),+ ]+ )+ def test_format_date(self, _name: str, value: Any, expected: str) -> None:+ assert _format_date(value) == expected++ @parameterized.expand(+ [+ ("aware_datetime", datetime(2021, 5, 1, 12, 0, tzinfo=UTC), "2021-05-01T12:00:00+00:00"),+ ("naive_datetime_assumed_utc", datetime(2021, 5, 1, 12, 0), "2021-05-01T12:00:00+00:00"),+ ("date_to_midnight", date(2021, 5, 1), "2021-05-01T00:00:00+00:00"),+ ]+ )+ def test_format_datetime(self, _name: str, value: Any, expected: str) -> None:+ assert _format_datetime(value) == expected+++class TestClamp:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_date_clamped_to_today(self) -> None:+ assert _clamp_date_to_today("2099-01-01") == "2026-06-15"++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_date_unchanged(self) -> None:+ assert _clamp_date_to_today("2021-05-01") == "2021-05-01"++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_clamped_to_now(self) -> None:+ assert _clamp_datetime_to_now("2099-01-01T00:00:00+00:00") == "2026-06-15T12:00:00+00:00"+++class TestBuildInitialParams:+ def test_date_endpoint_first_sync_uses_default_start(self) -> None:+ params = _build_initial_params(+ OURA_ENDPOINTS["daily_sleep"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert params == {"start_date": DEFAULT_START_DATE}++ def test_date_endpoint_incremental_uses_cursor(self) -> None:+ params = _build_initial_params(+ OURA_ENDPOINTS["daily_sleep"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2021, 5, 1),+ )+ assert params == {"start_date": "2021-05-01"}++ def test_datetime_endpoint_incremental_uses_start_datetime(self) -> None:+ params = _build_initial_params(+ OURA_ENDPOINTS["heartrate"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2021, 5, 1, 12, 0, tzinfo=UTC),+ )+ assert params == {"start_datetime": "2021-05-01T12:00:00+00:00"}++ def test_datetime_endpoint_first_sync_uses_default(self) -> None:+ params = _build_initial_params(+ OURA_ENDPOINTS["heartrate"], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert params == {"start_datetime": f"{DEFAULT_START_DATE}T00:00:00+00:00"}++ @parameterized.expand([("personal_info",), ("ring_configuration",)])+ def test_full_refresh_endpoints_send_no_date_params(self, endpoint: str) -> None:+ params = _build_initial_params(+ OURA_ENDPOINTS[endpoint], should_use_incremental_field=False, db_incremental_field_last_value=None+ )+ assert params == {}++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_cursor_is_clamped(self) -> None:+ # A future-dated record could push the cursor past today; Oura 400s when start_date > end_date.+ params = _build_initial_params(+ OURA_ENDPOINTS["daily_sleep"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2099, 1, 1),+ )+ assert params == {"start_date": "2026-06-15"}+++class TestBuildUrl:+ def test_no_params(self) -> None:+ assert _build_url("/usercollection/personal_info", {}) == (+ "https://api.ouraring.com/v2/usercollection/personal_info"+ )++ def test_with_params(self) -> None:+ url = _build_url("/usercollection/daily_sleep", {"start_date": "2021-05-01", "next_token": "abc"})+ assert url == "https://api.ouraring.com/v2/usercollection/daily_sleep?start_date=2021-05-01&next_token=abc"+++class TestGetRows:+ @staticmethod+ def _collect(manager: _FakeResumableManager, pages: dict[str, Any], **kwargs: Any) -> list[list[dict]]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return pages[url]++ with patch.object(oura, "_fetch_page", fake_fetch):+ return list(+ get_rows(+ token="tok",+ endpoint=kwargs.pop("endpoint", "daily_sleep"),+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ )+ )++ def test_follows_next_token_pagination(self) -> None:+ base = "https://api.ouraring.com/v2/usercollection/daily_sleep"+ pages = {+ f"{base}?start_date={DEFAULT_START_DATE}": {+ "data": [{"id": "a"}, {"id": "b"}],+ "next_token": "tok1",+ },+ f"{base}?start_date={DEFAULT_START_DATE}&next_token=tok1": {+ "data": [{"id": "c"}],+ "next_token": None,+ },+ }+ manager = _FakeResumableManager()+ batches = self._collect(manager, pages)+ assert batches == [[{"id": "a"}, {"id": "b"}], [{"id": "c"}]]++ def test_saves_state_after_each_yielded_page(self) -> None:+ base = "https://api.ouraring.com/v2/usercollection/daily_sleep"+ pages = {+ f"{base}?start_date={DEFAULT_START_DATE}": {"data": [{"id": "a"}], "next_token": "tok1"},+ f"{base}?start_date={DEFAULT_START_DATE}&next_token=tok1": {"data": [{"id": "b"}], "next_token": None},+ }+ manager = _FakeResumableManager()+ self._collect(manager, pages)+ # State saved only after the first page (which had a next_token); the terminal page saves nothing.+ assert manager.saved == [OuraResumeConfig(next_token="tok1")]++ def test_resumes_from_saved_next_token(self) -> None:+ base = "https://api.ouraring.com/v2/usercollection/daily_sleep"+ resume_url = f"{base}?start_date={DEFAULT_START_DATE}&next_token=saved"+ pages = {resume_url: {"data": [{"id": "z"}], "next_token": None}}+ manager = _FakeResumableManager(OuraResumeConfig(next_token="saved"))+ batches = self._collect(manager, pages)+ assert batches == [[{"id": "z"}]]++ def test_personal_info_yields_single_document(self) -> None:+ url = "https://api.ouraring.com/v2/usercollection/personal_info"+ pages = {url: {"id": "u1", "age": 30, "email": "[email protected]"}}+ manager = _FakeResumableManager()+ batches = self._collect(manager, pages, endpoint="personal_info")+ assert batches == [[{"id": "u1", "age": 30, "email": "[email protected]"}]]+ assert manager.saved == []++ def test_empty_page_is_not_yielded(self) -> None:+ base = "https://api.ouraring.com/v2/usercollection/daily_sleep"+ pages: dict[str, Any] = {f"{base}?start_date={DEFAULT_START_DATE}": {"data": [], "next_token": None}}+ batches = self._collect(_FakeResumableManager(), pages)+ assert batches == []+++class TestProbeEndpoint:+ @parameterized.expand([(200,), (401,), (403,), (404,)])+ def test_returns_status_code(self, status: int) -> None:+ response = MagicMock(status_code=status)+ session = MagicMock()+ session.get.return_value = response+ with patch.object(oura, "make_tracked_session", return_value=session):+ assert probe_endpoint("tok", "/usercollection/personal_info") == status++ def test_transport_failure_returns_minus_one(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with patch.object(oura, "make_tracked_session", return_value=session):+ assert probe_endpoint("tok", "/usercollection/personal_info") == -1+++class TestOuraSourceResponse:+ def test_daily_endpoint_partitions_on_day(self) -> None:+ response = oura_source("tok", "daily_sleep", MagicMock(), MagicMock())+ assert response.name == "daily_sleep"+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["day"]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ assert response.sort_mode == "asc"++ def test_heartrate_uses_composite_key_and_timestamp_partition(self) -> None:+ response = oura_source("tok", "heartrate", MagicMock(), MagicMock())+ assert response.primary_keys == ["timestamp", "source"]+ assert response.partition_keys == ["timestamp"]++ def test_enhanced_tag_partitions_on_start_day(self) -> None:+ response = oura_source("tok", "enhanced_tag", MagicMock(), MagicMock())+ assert response.partition_keys == ["start_day"]++ @parameterized.expand([("personal_info",), ("ring_configuration",)])+ def test_full_refresh_endpoints_are_unpartitioned(self, endpoint: str) -> None:+ response = oura_source("tok", endpoint, MagicMock(), MagicMock())+ assert response.partition_keys is None+ assert response.partition_mode is Nonediff --git a/posthog/temporal/data_imports/sources/oura/tests/test_oura_source.py b/posthog/temporal/data_imports/sources/oura/tests/test_oura_source.pynew file mode 100644index 000000000000..cc0ac0bfb034--- /dev/null+++ b/posthog/temporal/data_imports/sources/oura/tests/test_oura_source.py@@ -0,0 +1,180 @@+from typing import Any++from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.oura import source as oura_source_module+from posthog.temporal.data_imports.sources.oura.oura import OuraResumeConfig+from posthog.temporal.data_imports.sources.oura.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.oura.source import OuraSource++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _config(token: str = "tok") -> Any:+ return OuraSource().parse_config({"access_token": token})+++def _inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "daily_sleep",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 1,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestSourceConfig:+ def test_source_type(self) -> None:+ assert OuraSource().source_type == ExternalDataSourceType.OURA++ def test_config_basics(self) -> None:+ cfg = OuraSource().get_source_config+ assert cfg.name == "Oura"+ assert cfg.category == "Analytics"+ assert cfg.releaseStatus == "alpha"+ # A finished source must be visible — no unreleasedSource flag.+ assert getattr(cfg, "unreleasedSource", None) is None++ def test_single_password_token_field(self) -> None:+ fields = OuraSource().get_source_config.fields+ assert [f.name for f in fields] == ["access_token"]+ token_field = fields[0]+ assert isinstance(token_field, SourceFieldInputConfig)+ assert token_field.required is True+ assert token_field.type == "password"+ assert token_field.secret is True+++class TestGetSchemas:+ def test_lists_every_endpoint(self) -> None:+ schemas = OuraSource().get_schemas(_config(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("daily_sleep", True),+ ("heartrate", True),+ ("enhanced_tag", True),+ ("personal_info", False),+ ("ring_configuration", False),+ ]+ )+ def test_incremental_support_follows_date_filter(self, endpoint: str, expected: bool) -> None:+ schemas = {s.name: s for s in OuraSource().get_schemas(_config(), team_id=1)}+ assert schemas[endpoint].supports_incremental is expected+ assert schemas[endpoint].supports_append is expected++ def test_names_filter(self) -> None:+ schemas = OuraSource().get_schemas(_config(), team_id=1, names=["daily_sleep", "heartrate"])+ assert {s.name for s in schemas} == {"daily_sleep", "heartrate"}+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, None, True),+ ("unauthorized", 401, None, False),+ ("forbidden_at_create_is_accepted", 403, None, True),+ ("forbidden_for_specific_schema_is_rejected", 403, "daily_sleep", False),+ ("transport_failure", -1, None, False),+ ]+ )+ def test_validation(self, _name: str, status: int, schema_name: str | None, expected_ok: bool) -> None:+ with patch.object(oura_source_module, "probe_endpoint", return_value=status):+ ok, error = OuraSource().validate_credentials(_config(), team_id=1, schema_name=schema_name)+ assert ok is expected_ok+ if expected_ok:+ assert error is None+ else:+ assert error is not None++ def test_probes_personal_info_at_source_create(self) -> None:+ with patch.object(oura_source_module, "probe_endpoint", return_value=200) as probe:+ OuraSource().validate_credentials(_config(), team_id=1, schema_name=None)+ probe.assert_called_once_with("tok", "/usercollection/personal_info")++ def test_probes_requested_endpoint_for_schema(self) -> None:+ with patch.object(oura_source_module, "probe_endpoint", return_value=200) as probe:+ OuraSource().validate_credentials(_config(), team_id=1, schema_name="heartrate")+ probe.assert_called_once_with("tok", "/usercollection/heartrate")+++class TestResumableManager:+ def test_returns_manager_bound_to_resume_config(self) -> None:+ manager = OuraSource().get_resumable_source_manager(_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is OuraResumeConfig+++class TestSourceForPipeline:+ def test_passes_incremental_value_only_when_incremental(self) -> None:+ with patch.object(oura_source_module, "oura_source") as mock_source:+ OuraSource().source_for_pipeline(+ _config("secret"),+ MagicMock(),+ _inputs(+ schema_name="daily_sleep",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2021-05-01",+ ),+ )+ kwargs = mock_source.call_args.kwargs+ assert kwargs["token"] == "secret"+ assert kwargs["endpoint"] == "daily_sleep"+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2021-05-01"++ def test_drops_incremental_value_on_full_refresh(self) -> None:+ with patch.object(oura_source_module, "oura_source") as mock_source:+ OuraSource().source_for_pipeline(+ _config(),+ MagicMock(),+ _inputs(+ schema_name="daily_sleep",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2021-05-01",+ ),+ )+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None+++class TestNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.ouraring.com/v2/usercollection/sleep",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.ouraring.com/v2/usercollection/heartrate"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:+ non_retryable = OuraSource().get_non_retryable_errors()+ assert any(key in observed for key in non_retryable)++ @parameterized.expand(+ [+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.ouraring.com"),+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.ouraring.com"),+ ("read_timeout", "HTTPSConnectionPool(host='api.ouraring.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:+ non_retryable = OuraSource().get_non_retryable_errors()+ assert not any(key in observed for key in non_retryable)