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 openfda import source (#67822)

Tom Owers459fb3b498b3
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 9242b05b404d..a020d6d94835 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -229,6 +229,7 @@ the row lists both.
| open_exchange_rates | HTTP | requests | ✅ |
| orb | HTTP | requests + `rest_source.RESTClient` | ✅ |
| openaq | HTTP | requests | ✅ |
+| openfda | HTTP | requests | ✅ |
| openweather | HTTP | requests | ✅ |
| ortto | HTTP | requests | ✅ |
| oura | HTTP | requests | ✅ |
@@ -551,7 +552,6 @@ doesn't conflict with concurrent PRs.
- onepagecrm
- onesignal
- open_data_dc
-- openfda
- opinion_stage
- opsgenie
- opuswatch
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 d2158c8dd7a9..0459c04508f4 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
@@ -2265,7 +2265,7 @@ class OpenExchangeRatesSourceConfig(config.Config):
@config.config
class OpenFDASourceConfig(config.Config):
- pass
+ api_key: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/canonical_descriptions.py
new file mode 100644
index 000000000000..c2c8b80abd7a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/canonical_descriptions.py
@@ -0,0 +1,121 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the official openFDA field-reference docs (https://open.fda.gov/apis/).
+# Keyed by endpoint name (matches ENDPOINTS / get_schemas). Partial coverage is fine — any endpoint,
+# column, or table without an entry falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "drug_events": {
+ "description": "Adverse event and medication error reports submitted to the FDA (FAERS). One row per safety report.",
+ "docs_url": "https://open.fda.gov/apis/drug/event/",
+ "columns": {
+ "safetyreportid": "Unique identifier for the adverse event report.",
+ "receivedate": "Date the FDA received the most recent version of this report (YYYYMMDD).",
+ "receiptdate": "Date the FDA received this specific version of the report (YYYYMMDD).",
+ "serious": "Whether the adverse event resulted in a serious outcome (1 = yes, 2 = no).",
+ "patient": "Nested object describing the patient, their reactions, and the drugs involved.",
+ "primarysource": "Nested object describing the qualification and country of the report's source.",
+ "occurcountry": "Two-letter country code where the adverse event occurred.",
+ },
+ },
+ "drug_labels": {
+ "description": "Structured Product Labeling (SPL) — the FDA-approved prescription and OTC drug labeling content. One row per label document.",
+ "docs_url": "https://open.fda.gov/apis/drug/label/",
+ "columns": {
+ "id": "Unique identifier for this label document version.",
+ "set_id": "Identifier grouping all versions of a given product's label.",
+ "effective_time": "Date the labeling became effective (format is inconsistent across records).",
+ "openfda": "Nested object of harmonized identifiers (NDC, brand name, generic name, RxCUI, etc.).",
+ "indications_and_usage": "The approved indications and usage section of the label.",
+ "warnings": "The warnings section of the label.",
+ },
+ },
+ "drug_ndc": {
+ "description": "National Drug Code (NDC) Directory — every drug product currently or recently marketed in the U.S. One row per product.",
+ "docs_url": "https://open.fda.gov/apis/drug/ndc/",
+ "columns": {
+ "product_id": "Unique identifier for the product (product NDC + SPL document id).",
+ "product_ndc": "The labeler and product segments of the NDC.",
+ "generic_name": "Generic name(s) of the drug.",
+ "brand_name": "Brand or trade name of the drug.",
+ "labeler_name": "Name of the company that labels or distributes the product.",
+ "dosage_form": "The drug's dosage form (e.g. TABLET, INJECTION).",
+ "product_type": "Product type (e.g. HUMAN PRESCRIPTION DRUG, HUMAN OTC DRUG).",
+ },
+ },
+ "drug_enforcement": {
+ "description": "Drug recall enforcement reports — recalls of drug products classified by the FDA. One row per recall.",
+ "docs_url": "https://open.fda.gov/apis/drug/enforcement/",
+ "columns": {
+ "recall_number": "Unique FDA-assigned identifier for the recall.",
+ "report_date": "Date the FDA published the enforcement report (YYYYMMDD).",
+ "recall_initiation_date": "Date the recalling firm first notified the public or began the recall (YYYYMMDD).",
+ "classification": "Recall class indicating relative health hazard (Class I, II, or III).",
+ "status": "Current status of the recall (e.g. Ongoing, Completed, Terminated).",
+ "recalling_firm": "Name of the firm that initiated the recall.",
+ "reason_for_recall": "Explanation of why the product was recalled.",
+ "product_description": "Description of the recalled product.",
+ },
+ },
+ "device_events": {
+ "description": "Medical device adverse event reports (MAUDE). One row per report of a device suspected of a death, injury, or malfunction.",
+ "docs_url": "https://open.fda.gov/apis/device/event/",
+ "columns": {
+ "mdr_report_key": "Unique identifier for the Medical Device Report.",
+ "date_received": "Date the FDA received the report (YYYYMMDD).",
+ "event_type": "Type of adverse event (e.g. Death, Injury, Malfunction).",
+ "device": "Nested object describing the device(s) involved.",
+ "patient": "Nested object describing the patient outcome(s).",
+ "report_number": "Report number assigned by the reporting entity.",
+ },
+ },
+ "device_510k": {
+ "description": "510(k) premarket notification clearances — devices cleared by the FDA as substantially equivalent to a legally marketed device. One row per clearance.",
+ "docs_url": "https://open.fda.gov/apis/device/510k/",
+ "columns": {
+ "k_number": "Unique FDA-assigned 510(k) submission number.",
+ "decision_date": "Date the FDA made its clearance decision (YYYY-MM-DD).",
+ "decision_code": "Code for the FDA's decision (e.g. SESE = substantially equivalent).",
+ "device_name": "Name of the cleared device.",
+ "applicant": "Company that submitted the 510(k).",
+ "product_code": "FDA product classification code for the device.",
+ },
+ },
+ "device_enforcement": {
+ "description": "Medical device recall enforcement reports. One row per recall.",
+ "docs_url": "https://open.fda.gov/apis/device/enforcement/",
+ "columns": {
+ "recall_number": "Unique FDA-assigned identifier for the recall.",
+ "report_date": "Date the FDA published the enforcement report (YYYYMMDD).",
+ "classification": "Recall class indicating relative health hazard (Class I, II, or III).",
+ "status": "Current status of the recall (e.g. Ongoing, Completed, Terminated).",
+ "recalling_firm": "Name of the firm that initiated the recall.",
+ "reason_for_recall": "Explanation of why the product was recalled.",
+ },
+ },
+ "food_enforcement": {
+ "description": "Food recall enforcement reports. One row per recall.",
+ "docs_url": "https://open.fda.gov/apis/food/enforcement/",
+ "columns": {
+ "recall_number": "Unique FDA-assigned identifier for the recall.",
+ "report_date": "Date the FDA published the enforcement report (YYYYMMDD).",
+ "classification": "Recall class indicating relative health hazard (Class I, II, or III).",
+ "status": "Current status of the recall (e.g. Ongoing, Completed, Terminated).",
+ "recalling_firm": "Name of the firm that initiated the recall.",
+ "reason_for_recall": "Explanation of why the product was recalled.",
+ },
+ },
+ "food_events": {
+ "description": "Food and cosmetic adverse event reports (CAERS). One row per report submitted to the FDA.",
+ "docs_url": "https://open.fda.gov/apis/food/event/",
+ "columns": {
+ "report_number": "Unique identifier for the CAERS report.",
+ "date_created": "Date the report was created in the CAERS database (YYYYMMDD).",
+ "date_started": "Date the adverse event began (YYYYMMDD).",
+ "products": "Nested list of products implicated in the report.",
+ "reactions": "List of reactions reported by the consumer.",
+ "outcomes": "List of outcomes (e.g. hospitalization, death) associated with the event.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/openfda.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/openfda.py
new file mode 100644
index 000000000000..7f75ca7f4140
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/openfda.py
@@ -0,0 +1,275 @@
+"""openFDA (U.S. Food and Drug Administration) REST API transport.
+
+openFDA (https://api.fda.gov) is the FDA's free public API over drug, device, and food regulatory
+datasets (adverse events, recalls/enforcement reports, drug labeling, 510(k) clearances, the NDC
+directory). Every dataset is its own endpoint with its own schema and date field; responses wrap the
+records in `{"meta": ..., "results": [...]}`.
+
+Pagination is a `search_after` cursor exposed via the HTTP `Link: rel="next"` header (the `skip`
+offset param is capped at 25,000, so the cursor is the only way to walk a large dataset). Each next
+URL is absolute and pre-encoded, so we follow it verbatim and it preserves the original `search`
+(date filter) and `sort` params — which lets an incremental sync stay server-side-bounded on every
+page. A single page has no next link once the results are exhausted, which is the loop terminator.
+
+Incremental sync uses the endpoint's date field: `search=<field>:[<watermark> TO 99991231]` with
+`sort=<field>:asc`. openFDA date fields are `YYYYMMDD` (a few, like `decision_date`, arrive dashed,
+but the API accepts `YYYYMMDD` in the search filter uniformly), and the range is inclusive on both
+ends, so we re-request the watermark day each run and let the delta merge dedupe on the primary key.
+
+Auth is an optional free API key. Without one, openFDA throttles to 240 req/min and 1,000 req/day
+per IP; with one, 240 req/min and 120,000 req/day per key. The key is sent as the HTTP Basic auth
+username (openFDA's documented header method) so it never lands in a logged URL or in the saved
+cursor state.
+
+An empty result set surfaces as HTTP 404 with `{"error": {"code": "NOT_FOUND"}}`, not an empty
+`results` array — so a 404 is treated as "no matching records" and ends the sync cleanly (common on
+an up-to-date incremental run whose watermark is already at the latest record).
+"""
+
+import dataclasses
+from collections.abc import Iterator
+from datetime import date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from requests.auth import HTTPBasicAuth
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from urllib3.util.retry import Retry
+
+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.openfda.settings import (
+ OPENFDA_ENDPOINTS,
+ OpenFDAEndpointConfig,
+)
+
+OPENFDA_BASE_URL = "https://api.fda.gov"
+_OPENFDA_HOST = "api.fda.gov"
+
+# openFDA caps a single search request at 1,000 results; larger values 400.
+PAGE_SIZE = 1000
+
+# Inclusive upper bound for the incremental date-range filter — effectively "no ceiling".
+_MAX_DATE = "99991231"
+
+
+class OpenFDARetryableError(Exception):
+ pass
+
+
+class OpenFDAResumeConfig:
+ # Absolute, pre-encoded `Link: rel="next"` URL to fetch next. None means "start from the first
+ # page" (the initial URL is rebuilt from the endpoint config + watermark).
+ next_url: str | None = None
+
+
+def _is_valid_openfda_url(url: str) -> bool:
+ """Only absolute `https://api.fda.gov/...` URLs may be followed. A pagination cursor comes from a
+ `Link` header or from resumed state — both are attacker-influenceable, and following one off-host
+ would leak the API key (sent as Basic auth) or hit an internal address."""
+ parsed = urlparse(url)
+ return parsed.scheme == "https" and parsed.hostname == _OPENFDA_HOST
+
+
+def _get_headers() -> dict[str, str]:
+ return {"Accept": "application/json", "User-Agent": "PostHog-DataWarehouse"}
+
+
+def _format_date_value(value: Any) -> str:
+ """Format an incremental watermark as the `YYYYMMDD` openFDA expects in a search date range."""
+ if isinstance(value, datetime):
+ return value.strftime("%Y%m%d")
+ if isinstance(value, date):
+ return value.strftime("%Y%m%d")
+ # A raw string watermark (e.g. "20200101" or "2020-01-01"): strip separators to YYYYMMDD.
+ return str(value).replace("-", "")[:8]
+
+
+def _build_initial_url(
+ config: OpenFDAEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> str:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+
+ field = incremental_field or config.incremental_field
+ if field is not None:
+ # Sort ascending on the date field so the pipeline's watermark advances monotonically as we
+ # page (sort_mode="asc"). Full-refresh endpoints have no date field and page on the cursor's
+ # internal ordering without a sort.
+ params["sort"] = f"{field}:asc"
+
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ low = _format_date_value(db_incremental_field_last_value)
+ params["search"] = f"{field}:[{low} TO {_MAX_DATE}]"
+
+ return f"{OPENFDA_BASE_URL}{config.path}?{urlencode(params)}"
+
+
+@retry(
+ # ChunkedEncodingError is a mid-stream connection break; transient like ConnectionError/ReadTimeout.
+ retry=retry_if_exception_type(
+ (
+ OpenFDARetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ auth: HTTPBasicAuth | None,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], str | None] | None:
+ """Fetch one page. Returns (results, next_url), or None when openFDA reports no matching records."""
+ response = session.get(url, headers=_get_headers(), auth=auth, timeout=60)
+
+ # openFDA signals "no matching records" with a 404, not an empty results array. That's an expected
+ # terminal state (e.g. an incremental run already caught up), so end the sync rather than error.
+ if response.status_code == 404:
+ logger.debug(f"openFDA: no matching records (404), url={url}")
+ return None
+
+ # 429 (rate limited) and 5xx are transient — back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OpenFDARetryableError(f"openFDA API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"openFDA API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ body = response.json()
+ # openFDA guarantees `results` on every 200 (empty sets come back as a 404, handled above), so
+ # access it directly — a missing key means an unexpected response shape we want to surface, not
+ # silently treat as an empty page.
+ results = body["results"]
+ # `Link: rel="next"` carries the search_after cursor; absent once the dataset is exhausted.
+ next_url = response.links.get("next", {}).get("url")
+ if next_url is not None and not _is_valid_openfda_url(next_url):
+ # A poisoned `Link` header pointing off-host would leak the API key (sent as Basic auth) to
+ # another server or fetch an internal URL — refuse to follow it.
+ raise ValueError(f"openFDA returned an off-host pagination URL, refusing to follow: {next_url}")
+ return results, next_url
+
+
+def validate_credentials(api_key: str | None) -> bool:
+ # A single cheap probe of the drug enforcement endpoint confirms reachability and (if provided)
+ # that the key is accepted. openFDA allows unauthenticated access, so a blank key is still valid —
+ # it just gets the lower rate-limit tier.
+ url = f"{OPENFDA_BASE_URL}/drug/enforcement.json?{urlencode({'limit': 1})}"
+ try:
+ session = make_tracked_session(
+ redact_values=(api_key,) if api_key else (),
+ allow_redirects=False,
+ # Disable urllib3 adapter retries — a slow/unreachable endpoint shouldn't hang the
+ # connect-time UI probe for minutes.
+ retry=Retry(total=0),
+ )
+ response = session.get(url, headers=_get_headers(), auth=_make_auth(api_key), timeout=30)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _make_auth(api_key: str | None) -> HTTPBasicAuth | None:
+ # openFDA accepts the API key as the HTTP Basic auth username (empty password). Sending it in the
+ # header keeps it out of logged URLs and out of the saved cursor state.
+ return HTTPBasicAuth(api_key, "") if api_key else None
+
+
+def get_rows(
+ api_key: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenFDAResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = OPENFDA_ENDPOINTS[endpoint]
+ auth = _make_auth(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive instead of
+ # re-handshaking per request. `redact_values` scrubs the key from logged URLs/samples;
+ # `allow_redirects=False` stops a 30x from forwarding the credential off-host.
+ session = make_tracked_session(
+ redact_values=(api_key,) if api_key else (),
+ allow_redirects=False,
+ # `_fetch_page` already retries 429/5xx and connection errors via tenacity, so disable the
+ # urllib3 adapter retries — otherwise the two layers stack and multiply the backoff.
+ retry=Retry(total=0),
+ )
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ if not _is_valid_openfda_url(resume.next_url):
+ # Poisoned resume state must not be followed — see `_is_valid_openfda_url`.
+ raise ValueError(f"openFDA resume cursor is not a valid api.fda.gov URL: {resume.next_url}")
+ url: str | None = resume.next_url
+ logger.debug(f"openFDA: resuming {endpoint} from cursor")
+ else:
+ url = _build_initial_url(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ while url is not None:
+ page = _fetch_page(session, url, auth, logger)
+ if page is None:
+ break
+
+ results, next_url = page
+ if results:
+ yield results
+
+ if not next_url:
+ break
+
+ # Save AFTER yielding (the pipeline has persisted the page by the time it asks for the next
+ # item) so a crash re-fetches the just-yielded page rather than skipping it; merge dedupes the
+ # re-pulled rows on the primary key.
+ resumable_source_manager.save_state(OpenFDAResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def openfda_source(
+ api_key: str | None,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpenFDAResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = OPENFDA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # Incremental endpoints request sort=<field>:asc so rows arrive oldest-first and the watermark
+ # advances safely after each batch. Full-refresh endpoints add no sort (they page on the bare
+ # cursor), so their arrival order is undefined — don't claim "asc" for them.
+ sort_mode="asc" if config.incremental_field else None,
+ 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,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/settings.py
new file mode 100644
index 000000000000..9017da32bc41
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/settings.py
@@ -0,0 +1,113 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class OpenFDAEndpointConfig:
+ name: str
+ # Path under https://api.fda.gov, e.g. "/drug/enforcement.json".
+ path: str
+ primary_keys: list[str]
+ # Server-side date field used both for incremental filtering (search=<field>:[low TO high]) and for
+ # ascending sort. None means the endpoint has no reliable date cursor, so it ships full refresh only.
+ incremental_field: Optional[str] = None
+ # Stable date field to partition by. openFDA date fields record when the FDA received/created/posted
+ # the record, so they don't move once written — safe partition keys. None disables partitioning.
+ partition_key: Optional[str] = None
+ should_sync_default: bool = True
+
+ def build_incremental_fields(self) -> list[IncrementalField]:
+ if self.incremental_field is None:
+ return []
+ return [
+ {
+ "label": self.incremental_field,
+ "type": IncrementalFieldType.Date,
+ "field": self.incremental_field,
+ "field_type": IncrementalFieldType.Date,
+ }
+ ]
+
+
+# openFDA exposes one endpoint per dataset, each with its own schema and date field. We surface the
+# datasets a user is most likely to want across the drug, device, and food domains. Adverse-event and
+# enforcement (recall) endpoints carry a genuine server-side date filter, so they sync incrementally;
+# the NDC directory and drug labeling endpoints have no reliable row-level date cursor, so they ship
+# full refresh only.
+OPENFDA_ENDPOINTS: dict[str, OpenFDAEndpointConfig] = {
+ "drug_events": OpenFDAEndpointConfig(
+ name="drug_events",
+ path="/drug/event.json",
+ primary_keys=["safetyreportid"],
+ incremental_field="receivedate",
+ partition_key="receivedate",
+ ),
+ "drug_labels": OpenFDAEndpointConfig(
+ name="drug_labels",
+ path="/drug/label.json",
+ primary_keys=["id"],
+ # `effective_time` is frequently malformed (e.g. 9-digit values), so it can't anchor an
+ # incremental watermark — full refresh only.
+ incremental_field=None,
+ partition_key=None,
+ should_sync_default=False,
+ ),
+ "drug_ndc": OpenFDAEndpointConfig(
+ name="drug_ndc",
+ path="/drug/ndc.json",
+ primary_keys=["product_id"],
+ # The NDC directory is a current-state snapshot with no per-record date — full refresh only.
+ incremental_field=None,
+ partition_key=None,
+ ),
+ "drug_enforcement": OpenFDAEndpointConfig(
+ name="drug_enforcement",
+ path="/drug/enforcement.json",
+ primary_keys=["recall_number"],
+ incremental_field="report_date",
+ partition_key="report_date",
+ ),
+ "device_events": OpenFDAEndpointConfig(
+ name="device_events",
+ path="/device/event.json",
+ primary_keys=["mdr_report_key"],
+ incremental_field="date_received",
+ partition_key="date_received",
+ ),
+ "device_510k": OpenFDAEndpointConfig(
+ name="device_510k",
+ path="/device/510k.json",
+ primary_keys=["k_number"],
+ incremental_field="decision_date",
+ partition_key="decision_date",
+ ),
+ "device_enforcement": OpenFDAEndpointConfig(
+ name="device_enforcement",
+ path="/device/enforcement.json",
+ primary_keys=["recall_number"],
+ incremental_field="report_date",
+ partition_key="report_date",
+ ),
+ "food_enforcement": OpenFDAEndpointConfig(
+ name="food_enforcement",
+ path="/food/enforcement.json",
+ primary_keys=["recall_number"],
+ incremental_field="report_date",
+ partition_key="report_date",
+ ),
+ "food_events": OpenFDAEndpointConfig(
+ name="food_events",
+ path="/food/event.json",
+ primary_keys=["report_number"],
+ incremental_field="date_created",
+ partition_key="date_created",
+ ),
+}
+
+ENDPOINTS = tuple(OPENFDA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.build_incremental_fields() for name, config in OPENFDA_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/source.py
index d46fe94cc736..b3082f28d062 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/source.py
@@ -1,19 +1,43 @@
-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 OpenFDASourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.openfda import (
+ OpenFDAResumeConfig,
+ openfda_source,
+ validate_credentials as validate_openfda_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ OPENFDA_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OpenFDASource(SimpleSource[OpenFDASourceConfig]):
+class OpenFDASource(ResumableSource[OpenFDASourceConfig, OpenFDAResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPENFDA
@@ -23,8 +47,96 @@ class OpenFDASource(SimpleSource[OpenFDASourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.OPEN_FDA,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="OpenFDA",
+ label="openFDA",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Pull U.S. FDA drug, device, and food data — adverse event reports, recalls, drug labeling, 510(k) clearances, and the NDC directory — into the PostHog Data warehouse.
+
+An API key is optional but recommended. Without one, openFDA limits you to 1,000 requests/day per IP; with one, 120,000 requests/day. Get a free key from the [openFDA API basics page](https://open.fda.gov/apis/authentication/).""",
iconPath="/static/services/openfda.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/openfda",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key (optional)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="Your openFDA API key",
+ secret=True,
+ ),
+ ],
+ ),
+ keywords=["fda", "openfda", "drug", "device", "food"],
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # openFDA returns 401/403 only for an invalid or over-quota API key. Retrying can't satisfy
+ # a credential/quota problem, so stop the sync. Match the stable status text and base host.
+ "401 Client Error: Unauthorized for url: https://api.fda.gov": "Your openFDA API key is invalid. Generate a new key from the openFDA developer portal and reconnect, or remove it to use the unauthenticated tier.",
+ "403 Client Error: Forbidden for url: https://api.fda.gov": "Your openFDA API key is invalid or has exceeded its daily request quota. Check the key, wait for the quota to reset, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: OpenFDASourceConfig,
+ 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 = OPENFDA_ENDPOINTS[endpoint]
+ has_incremental = endpoint_config.incremental_field 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,
+ detected_primary_keys=endpoint_config.primary_keys,
+ )
+
+ 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: OpenFDASourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_openfda_credentials(config.api_key):
+ return True, None
+
+ return False, "Could not reach the openFDA API. Check your API key (if provided) and try again."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpenFDAResumeConfig]:
+ return ResumableSourceManager[OpenFDAResumeConfig](inputs, OpenFDAResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OpenFDASourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpenFDAResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return openfda_source(
+ api_key=config.api_key,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda.py
new file mode 100644
index 000000000000..799c9e622cb7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda.py
@@ -0,0 +1,290 @@
+from collections.abc import Mapping
+from datetime import date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda import openfda
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.openfda import (
+ OPENFDA_BASE_URL,
+ PAGE_SIZE,
+ OpenFDAResumeConfig,
+ _build_initial_url,
+ _fetch_page,
+ _format_date_value,
+ _make_auth,
+ get_rows,
+ openfda_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.settings import OPENFDA_ENDPOINTS
+
+
+class _FakeResumableManager:
+ def __init__(self, state: OpenFDAResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[OpenFDAResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> OpenFDAResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: OpenFDAResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestFormatDateValue:
+ @parameterized.expand(
+ [
+ ("datetime", datetime(2020, 1, 2, 3, 4, 5), "20200102"),
+ ("date", date(2020, 1, 2), "20200102"),
+ ("yyyymmdd_string", "20200102", "20200102"),
+ ("dashed_string", "2020-01-02", "20200102"),
+ ]
+ )
+ def test_formats_to_yyyymmdd(self, _name: str, value: Any, expected: str) -> None:
+ # The openFDA search date range only accepts YYYYMMDD; a mis-formatted watermark silently
+ # matches nothing (404) and wedges the incremental sync.
+ assert _format_date_value(value) == expected
+
+
+class TestBuildInitialUrl:
+ def test_incremental_endpoint_bounds_by_date_and_sorts_ascending(self) -> None:
+ config = OPENFDA_ENDPOINTS["drug_enforcement"]
+ url = _build_initial_url(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2020, 1, 1),
+ incremental_field=None,
+ )
+ # The server-side date filter must survive: without it every "incremental" sync re-scans the
+ # whole dataset. Ascending sort keeps the pipeline watermark advancing monotonically.
+ assert f"{OPENFDA_BASE_URL}/drug/enforcement.json?" in url
+ assert "search=report_date%3A%5B20200101+TO+99991231%5D" in url
+ assert "sort=report_date%3Aasc" in url
+ assert f"limit={PAGE_SIZE}" in url
+
+ def test_first_incremental_sync_has_no_date_filter(self) -> None:
+ config = OPENFDA_ENDPOINTS["drug_enforcement"]
+ url = _build_initial_url(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ # No watermark yet -> backfill the whole history, still ordered so the watermark is valid.
+ assert "search=" not in url
+ assert "sort=report_date%3Aasc" in url
+
+ def test_user_selected_incremental_field_overrides_default(self) -> None:
+ config = OPENFDA_ENDPOINTS["drug_enforcement"]
+ url = _build_initial_url(
+ config,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=date(2020, 1, 1),
+ incremental_field="recall_initiation_date",
+ )
+ # Honor the user's chosen cursor field instead of hardcoding the endpoint default.
+ assert "search=recall_initiation_date%3A" in url
+ assert "sort=recall_initiation_date%3Aasc" in url
+
+ def test_full_refresh_endpoint_omits_search_and_sort(self) -> None:
+ config = OPENFDA_ENDPOINTS["drug_ndc"]
+ url = _build_initial_url(
+ config,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ # drug/ndc has no date cursor; it must page on the bare search_after cursor with no sort.
+ assert "search=" not in url
+ assert "sort=" not in url
+ assert f"limit={PAGE_SIZE}" in url
+
+
+class TestMakeAuth:
+ def test_key_becomes_basic_auth_username(self) -> None:
+ auth = _make_auth("secret")
+ assert auth is not None
+ assert auth.username == "secret"
+ assert auth.password == ""
+
+ def test_blank_key_sends_no_auth(self) -> None:
+ # openFDA allows the unauthenticated tier; a missing key must not become `HTTPBasicAuth("", "")`.
+ assert _make_auth(None) is None
+ assert _make_auth("") is None
+
+
+def _response(status: int, *, body: Any = None, next_url: str | None = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = 200 <= status < 300
+ response.json.return_value = body or {}
+ response.links = {"next": {"url": next_url}} if next_url else {}
+ if not response.ok:
+ response.raise_for_status.side_effect = requests.HTTPError(f"{status} error", response=response)
+ return response
+
+
+class TestFetchPage:
+ def test_404_is_terminal_not_an_error(self) -> None:
+ # openFDA returns 404 (not an empty results array) when nothing matches — expected at the tail
+ # of an incremental run. Treating it as an error would fail every caught-up sync.
+ session = MagicMock()
+ session.get.return_value = _response(404)
+ assert _fetch_page(session, "http://x", None, MagicMock()) is None
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_status_raises_retryable_error(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status)
+ _fetch_page.retry.sleep = lambda _s: None # type: ignore[attr-defined]
+ with pytest.raises(openfda.OpenFDARetryableError):
+ _fetch_page(session, "http://x", None, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ def test_auth_error_raises_for_status(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page(session, "http://x", None, MagicMock())
+
+ def test_success_returns_results_and_next_cursor(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(
+ 200, body={"results": [{"recall_number": "D-1"}]}, next_url="https://api.fda.gov/next"
+ )
+ page = _fetch_page(session, "http://x", None, MagicMock())
+ assert page is not None
+ results, next_url = page
+ assert results == [{"recall_number": "D-1"}]
+ assert next_url == "https://api.fda.gov/next"
+
+ def test_last_page_has_no_next_cursor(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(200, body={"results": [{"recall_number": "D-9"}]})
+ page = _fetch_page(session, "http://x", None, MagicMock())
+ assert page is not None
+ assert page[1] is None
+
+ @parameterized.expand(
+ [
+ ("off_host", "https://evil.example.com/next"),
+ ("insecure_scheme", "http://api.fda.gov/next"),
+ ("subdomain_spoof", "https://api.fda.gov.evil.example.com/next"),
+ ]
+ )
+ def test_off_host_next_cursor_is_rejected(self, _name: str, next_url: str) -> None:
+ # A poisoned `Link` header would send the API key (Basic auth) off-host or hit an internal
+ # address. Following it must fail loudly, not be saved and requested.
+ session = MagicMock()
+ session.get.return_value = _response(200, body={"results": []}, next_url=next_url)
+ with pytest.raises(ValueError):
+ _fetch_page(session, "https://api.fda.gov/x", None, MagicMock())
+
+ def test_missing_results_key_raises(self) -> None:
+ # openFDA guarantees `results` on a 200; an unexpected shape should surface, not silently look
+ # like an empty page.
+ session = MagicMock()
+ session.get.return_value = _response(200, body={"meta": {}})
+ with pytest.raises(KeyError):
+ _fetch_page(session, "https://api.fda.gov/x", None, MagicMock())
+
+
+def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: Mapping[str, tuple[list[dict], str | None] | None],
+ endpoint: str = "drug_enforcement",
+) -> list[dict]:
+ def fake_fetch(session: Any, url: str, auth: Any, logger: Any) -> Any:
+ return pages[url]
+
+ monkeypatch.setattr(openfda, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(openfda, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key=None,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(page)
+ return rows
+
+
+class TestGetRows:
+ def test_follows_link_cursor_across_pages(self, monkeypatch: Any) -> None:
+ initial = _build_initial_url(OPENFDA_ENDPOINTS["drug_enforcement"], False, None, None)
+ pages = {
+ initial: ([{"recall_number": "D-1"}], "https://api.fda.gov/p2"),
+ "https://api.fda.gov/p2": ([{"recall_number": "D-2"}], None),
+ }
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages)
+ assert rows == [{"recall_number": "D-1"}, {"recall_number": "D-2"}]
+
+ def test_saves_cursor_after_yielding_each_page(self, monkeypatch: Any) -> None:
+ initial = _build_initial_url(OPENFDA_ENDPOINTS["drug_enforcement"], False, None, None)
+ pages = {
+ initial: ([{"recall_number": "D-1"}], "https://api.fda.gov/p2"),
+ "https://api.fda.gov/p2": ([{"recall_number": "D-2"}], None),
+ }
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, pages)
+ # State is saved only while more pages remain, and only the next cursor — so a crash re-fetches
+ # the just-yielded page (merge dedupes) rather than skipping it. The final page saves nothing.
+ assert [s.next_url for s in manager.saved] == ["https://api.fda.gov/p2"]
+
+ def test_resumes_from_saved_cursor(self, monkeypatch: Any) -> None:
+ pages = {
+ "https://api.fda.gov/p2": ([{"recall_number": "D-2"}], None),
+ }
+ manager = _FakeResumableManager(OpenFDAResumeConfig(next_url="https://api.fda.gov/p2"))
+ rows = _collect(manager, monkeypatch, pages)
+ # Resume must start at the saved cursor, not rebuild the initial URL (which would re-pull page 1).
+ assert rows == [{"recall_number": "D-2"}]
+
+ def test_404_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ initial = _build_initial_url(OPENFDA_ENDPOINTS["drug_enforcement"], False, None, None)
+ rows = _collect(_FakeResumableManager(), monkeypatch, {initial: None})
+ assert rows == []
+
+ def test_off_host_resume_cursor_is_rejected(self, monkeypatch: Any) -> None:
+ # Poisoned resume state must not be followed — it would leak the API key off-host.
+ manager = _FakeResumableManager(OpenFDAResumeConfig(next_url="https://evil.example.com/p2"))
+ with pytest.raises(ValueError):
+ _collect(manager, monkeypatch, {})
+
+
+class TestOpenfdaSource:
+ @parameterized.expand(
+ [
+ ("drug_enforcement", ["recall_number"], "report_date"),
+ ("drug_ndc", ["product_id"], None),
+ ("device_510k", ["k_number"], "decision_date"),
+ ]
+ )
+ def test_source_response_carries_endpoint_config(
+ self, endpoint: str, primary_keys: list[str], partition_key: str | None
+ ) -> None:
+ response = openfda_source(
+ api_key=None, endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ if partition_key is None:
+ # Full-refresh endpoint: no sort requested, so arrival order is undefined.
+ assert response.partition_mode is None
+ assert response.sort_mode is None
+ else:
+ # Incremental endpoint: ascending sort must be declared so the pipeline checkpoints the
+ # watermark correctly, and the stable date field partitions the table.
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [partition_key]
+ assert response.sort_mode == "asc"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda_source.py
new file mode 100644
index 000000000000..25cb24e4fdc2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/openfda/tests/test_openfda_source.py
@@ -0,0 +1,160 @@
+from typing import Any
+
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.openfda import OpenFDAResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.openfda.source import OpenFDASource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(api_key: str | None = "key") -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ return config
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert OpenFDASource().source_type == ExternalDataSourceType.OPENFDA
+
+ def test_config_metadata(self) -> None:
+ config = OpenFDASource().get_source_config
+ assert config.label == "openFDA"
+ assert config.category == DataWarehouseSourceCategory.ANALYTICS
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # docsUrl slug must match the published doc filename so the website doesn't 404.
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/openfda"
+ # Still gated off until it's been exercised end-to-end.
+ assert config.unreleasedSource is True
+
+ def test_api_key_field_is_optional_secret(self) -> None:
+ fields: dict[str, Any] = {f.name: f for f in OpenFDASource().get_source_config.fields}
+ assert set(fields) == {"api_key"}
+ # openFDA works unauthenticated (lower quota), so the key must not be required.
+ assert fields["api_key"].required is False
+ assert fields["api_key"].secret is True
+
+ @parameterized.expand([("api_key", "abc"), ("no_key", None)])
+ def test_parse_config_accepts_optional_key(self, _name: str, api_key: str | None) -> None:
+ # Guards the generated config: api_key is optional, so a source created without one must parse.
+ parsed = OpenFDASource().parse_config({"api_key": api_key} if api_key else {})
+ assert parsed.api_key == api_key
+
+
+class TestGetSchemas:
+ def test_lists_all_endpoints(self) -> None:
+ names = {s.name for s in OpenFDASource().get_schemas(_config(), team_id=1)}
+ assert names == {
+ "drug_events",
+ "drug_labels",
+ "drug_ndc",
+ "drug_enforcement",
+ "device_events",
+ "device_510k",
+ "device_enforcement",
+ "food_enforcement",
+ "food_events",
+ }
+
+ @parameterized.expand(
+ [
+ ("drug_events", True, ["safetyreportid"]),
+ ("drug_enforcement", True, ["recall_number"]),
+ ("food_events", True, ["report_number"]),
+ # No reliable server-side date filter -> must be full refresh only, or every "incremental"
+ # sync silently re-scans the whole dataset.
+ ("drug_labels", False, ["id"]),
+ ("drug_ndc", False, ["product_id"]),
+ ]
+ )
+ def test_incremental_support_matches_endpoint(
+ self, endpoint: str, expect_incremental: bool, primary_keys: list[str]
+ ) -> None:
+ schema = {s.name: s for s in OpenFDASource().get_schemas(_config(), team_id=1)}[endpoint]
+ assert schema.supports_incremental is expect_incremental
+ assert schema.supports_append is expect_incremental
+ assert schema.detected_primary_keys == primary_keys
+ assert bool(schema.incremental_fields) is expect_incremental
+
+ def test_names_filter(self) -> None:
+ names = {s.name for s in OpenFDASource().get_schemas(_config(), team_id=1, names=["drug_ndc"])}
+ assert names == {"drug_ndc"}
+
+
+class TestValidateCredentials:
+ def test_success(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openfda.source.validate_openfda_credentials",
+ lambda _key: True,
+ )
+ assert OpenFDASource().validate_credentials(_config(), team_id=1) == (True, None)
+
+ def test_failure_returns_message(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openfda.source.validate_openfda_credentials",
+ lambda _key: False,
+ )
+ ok, message = OpenFDASource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert message
+
+
+class TestNonRetryableErrors:
+ def test_auth_errors_are_non_retryable(self) -> None:
+ errors = OpenFDASource().get_non_retryable_errors()
+ # 401/403 (bad or over-quota key) can never be fixed by retrying — they must stop the sync.
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
+
+
+class TestResumableWiring:
+ def test_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = OpenFDASource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OpenFDAResumeConfig
+
+ def test_source_for_pipeline_plumbs_incremental_inputs(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openfda.source.openfda_source",
+ fake_source,
+ )
+ inputs = MagicMock()
+ inputs.schema_name = "drug_enforcement"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "20200101"
+ inputs.incremental_field = "report_date"
+
+ result: Any = OpenFDASource().source_for_pipeline(_config(api_key="k"), MagicMock(), inputs)
+ assert result == "response"
+ assert captured["endpoint"] == "drug_enforcement"
+ assert captured["api_key"] == "k"
+ assert captured["db_incremental_field_last_value"] == "20200101"
+ assert captured["incremental_field"] == "report_date"
+
+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, monkeypatch: Any) -> None:
+ captured: dict[str, Any] = {}
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.openfda.source.openfda_source",
+ lambda **kwargs: captured.update(kwargs),
+ )
+ inputs = MagicMock()
+ inputs.schema_name = "drug_ndc"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "20200101"
+ inputs.incremental_field = None
+
+ OpenFDASource().source_for_pipeline(_config(), MagicMock(), inputs)
+ # A full-refresh run must not pass a stale watermark through as a filter.
+ assert captured["db_incremental_field_last_value"] is None