: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 pypi import source (#69998)
Tom Owers50f5b74bcd35
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex e9997e0516f5..115fa87f8252 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -331,6 +331,7 @@ the row lists both.| printify | HTTP | requests | ✅ || productboard | HTTP | requests | ✅ || pylon | HTTP | requests | ✅ |+| pypi | HTTP | requests | ✅ || qualaroo | HTTP | requests | ✅ || recurly | HTTP | requests + `rest_source.RESTClient` | ✅ || ramp | HTTP | requests | ✅ |@@ -727,7 +728,6 @@ doesn't conflict with concurrent PRs.- primetric- productive- prompting_company-- pypi- qdrant- qonto- qualtricsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 8994d7848d0f..7aad3dc86ebd 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@@ -2988,7 +2988,7 @@ class PromptingCompanySourceConfig(config.Config):@config.configclass PyPISourceConfig(config.Config):- pass+ packages: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/canonical_descriptions.pynew file mode 100644index 000000000000..771a47d3d811--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/canonical_descriptions.py@@ -0,0 +1,84 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_JSON_API_DOCS = "https://docs.pypi.org/api/json/"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "projects": {+ "description": "Project (package) metadata from the PyPI JSON API `info` block, one row per configured package.",+ "docs_url": _JSON_API_DOCS,+ "columns": {+ "name": "Normalized (canonical) project name.",+ "version": "The project's latest release version.",+ "summary": "Short one-line summary of the project.",+ "description": "Long description (README), rendered per `description_content_type`.",+ "description_content_type": "Content type of `description` (e.g. text/markdown).",+ "author": "Project author name.",+ "author_email": "Project author email.",+ "maintainer": "Project maintainer name.",+ "maintainer_email": "Project maintainer email.",+ "license": "License string as declared by the project.",+ "license_expression": "SPDX license expression, where declared.",+ "license_files": "List of declared license file paths.",+ "keywords": "Comma-separated keywords declared by the project.",+ "classifiers": "List of Trove classifiers (audience, license, supported Python versions, etc.).",+ "home_page": "Project home page URL.",+ "project_url": "Canonical PyPI project URL.",+ "package_url": "PyPI package URL (alias of project_url).",+ "release_url": "URL of the latest release on PyPI.",+ "project_urls": "Map of labelled project URLs (Homepage, Source, Documentation, etc.).",+ "docs_url": "Hosted documentation URL, if set.",+ "bugtrack_url": "Bug tracker URL, if set.",+ "download_url": "Legacy manual download URL, if set.",+ "downloads": "Deprecated download counts; always {last_day: -1, last_week: -1, last_month: -1}.",+ "requires_python": "Python version specifier required to install the project.",+ "requires_dist": "List of distribution dependencies (PEP 508 requirement strings).",+ "provides_extra": "List of optional dependency groups (extras) the project provides.",+ "platform": "Declared platform, if any.",+ "dynamic": "PEP 643 fields declared dynamic in the metadata.",+ "yanked": "Whether the latest release has been yanked.",+ "yanked_reason": "Reason the latest release was yanked, if any.",+ "last_serial": "Monotonic serial of the most recent event for the project (global change counter).",+ },+ },+ "releases": {+ "description": "Uploaded distribution files across every version of a project, one row per file.",+ "docs_url": _JSON_API_DOCS,+ "columns": {+ "package": "Canonical project name the file belongs to (injected by the connector).",+ "version": "Release version the file belongs to (injected by the connector).",+ "filename": "Distribution file name.",+ "url": "Direct download URL for the file.",+ "packagetype": "Distribution type (e.g. sdist, bdist_wheel).",+ "python_version": "Python tag for the distribution (e.g. py3, source).",+ "requires_python": "Python version specifier required by this file, if declared.",+ "size": "File size in bytes.",+ "upload_time": "Upload time (naive UTC).",+ "upload_time_iso_8601": "Upload time as an ISO 8601 UTC string; used as the partition key.",+ "digests": "Map of file hashes (e.g. blake2b_256, md5, sha256).",+ "md5_digest": "MD5 digest of the file.",+ "core-metadata": "Whether PEP 658 core metadata is available, and its hashes.",+ "has_sig": "Whether a PGP signature was uploaded alongside the file (deprecated).",+ "comment_text": "Optional comment supplied at upload time.",+ "downloads": "Deprecated download count; always -1.",+ "yanked": "Whether this file's release has been yanked.",+ "yanked_reason": "Reason the release was yanked, if any.",+ },+ },+ "vulnerabilities": {+ "description": "Known vulnerabilities affecting the latest version of a project, as reported by the PyPI JSON API.",+ "docs_url": _JSON_API_DOCS,+ "columns": {+ "package": "Canonical project name the advisory affects (injected by the connector).",+ "id": "Advisory identifier (e.g. a PYSEC id).",+ "aliases": "Other identifiers for the same advisory (e.g. CVE, GHSA).",+ "details": "Full description of the vulnerability.",+ "summary": "Short summary of the vulnerability, if provided.",+ "fixed_in": "List of versions in which the vulnerability is fixed.",+ "link": "URL to the advisory details.",+ "source": "Advisory database that reported the vulnerability (e.g. osv).",+ "withdrawn": "Timestamp the advisory was withdrawn, or null if still active.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/pypi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/pypi.pynew file mode 100644index 000000000000..da05cf94c7ef--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/pypi.py@@ -0,0 +1,256 @@+import re+from collections.abc import Callable, Iterator+from typing import Any+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.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.pypi.settings import (+ PYPI_ENDPOINTS,+ PyPIEndpointConfig,+)++PYPI_BASE_URL = "https://pypi.org"++REQUEST_TIMEOUT_SECONDS = 30+MAX_RETRY_ATTEMPTS = 5++# Each configured package costs one request per enabled stream on every sync, so cap the config to+# bound worker time and outbound fan-out — a malformed/abusive config can't tie up the pipeline.+MAX_PACKAGES = 500++# The PyPI JSON API sends `Accept: application/json`; the header keeps parity with the Stats API,+# which returns HTML without it.+_HEADERS = {"Accept": "application/json"}++# Rows for a single package are yielded in bounded chunks so a package with a huge release history+# never forces one oversized in-memory Arrow conversion downstream. The pipeline batches on top of+# this, so the exact value only caps the per-yield list size.+MAX_ROWS_PER_BATCH = 5000+++class PyPIRetryableError(Exception):+ pass+++def _normalize_name(name: str) -> str:+ """Normalize a project name per PEP 503 so aliases collapse to one key.++ PyPI treats ``Requests``, ``requests``, ``zope.interface`` and ``zope-interface`` as the same+ project, so we de-duplicate on this form. Otherwise two aliases both resolve to the same+ canonical name and emit rows with a colliding primary key.+ """+ return re.sub(r"[-_.]+", "-", name).lower()+++def parse_packages(raw: str | None) -> list[str]:+ """Parse the user's free-text ``packages`` field into a list of package names.++ Accepts one package per line and/or comma-separated names. Raises ``ValueError`` with an+ actionable message on empty input so the user fixes the config rather than getting a silently+ empty sync. Names are de-duplicated (on their PEP 503 normalized form) while preserving order.+ """+ if not raw:+ raise ValueError("At least one package name is required.")++ packages: list[str] = []+ seen: set[str] = set()+ for token in re.split(r"[\n,]", raw):+ name = token.strip()+ if not name:+ continue+ normalized = _normalize_name(name)+ if normalized not in seen:+ seen.add(normalized)+ packages.append(name)++ if len(packages) > MAX_PACKAGES:+ raise ValueError(f"Too many packages: at most {MAX_PACKAGES} are allowed per source.")++ if not packages:+ raise ValueError("At least one package name is required.")++ return packages+++def _project_url(package: str) -> str:+ # PyPI resolves and normalizes the project name itself; percent-encode the path segment so an+ # odd character can't break out of the path.+ return f"{PYPI_BASE_URL}/pypi/{quote(package, safe='')}/json"+++@retry(+ retry=retry_if_exception_type((PyPIRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_project(session: requests.Session, package: str, logger: FilteringBoundLogger) -> dict[str, Any] | None:+ """Fetch a single project's JSON document.++ Returns ``None`` for a 404 (package not found) so a typo'd or deleted package is skipped rather+ than failing the whole sync. Transient 429/5xx raise a retryable error; other client errors+ raise ``requests.HTTPError``.+ """+ url = _project_url(package)+ response = session.get(url, headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 404:+ logger.warning(f"PyPI: package {package!r} not found, skipping")+ return None++ if response.status_code == 429 or response.status_code >= 500:+ raise PyPIRetryableError(f"PyPI API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"PyPI API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _canonical_name(package: str, document: dict[str, Any]) -> str:+ """Prefer PyPI's canonical project name over the user's spelling.++ PyPI normalizes names (PEP 503), so ``Requests`` and ``requests`` resolve to the same project.+ Keying rows on the canonical name keeps the primary key stable regardless of how the user typed+ the package in the config.+ """+ info = document.get("info") or {}+ return info.get("name") or package+++def _project_rows(package: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per project: the `info` block plus the document's top-level serial."""+ info = dict(document.get("info") or {})+ info["last_serial"] = document.get("last_serial")+ # `name` is the primary key; fall back to the requested package if the API omits it.+ info.setdefault("name", package)+ yield info+++def _release_rows(package: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per distribution file across every version of the project.++ Each row is stamped with the canonical `package` and its `version` (the release key), neither of+ which lives on the raw file object, so the `[package, version, filename]` primary key is complete.+ Yields lazily so a huge release history is never materialized as one big list.+ """+ canonical = _canonical_name(package, document)+ releases = document.get("releases") or {}+ for version, files in releases.items():+ if not isinstance(files, list):+ continue+ for file_obj in files:+ if not isinstance(file_obj, dict):+ continue+ # `filename` completes the `[package, version, filename]` primary key; a file object+ # missing it would merge with a null key component, so skip it rather than emit a row+ # that can't upsert cleanly.+ if not file_obj.get("filename"):+ continue+ row = dict(file_obj)+ row["package"] = canonical+ row["version"] = version+ yield row+++def _vulnerability_rows(package: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per known vulnerability, stamped with the canonical `package`."""+ canonical = _canonical_name(package, document)+ for vuln in document.get("vulnerabilities") or []:+ if not isinstance(vuln, dict):+ continue+ row = dict(vuln)+ row["package"] = canonical+ yield row+++_ROW_BUILDERS: dict[str, Callable[[str, dict[str, Any]], Iterator[dict[str, Any]]]] = {+ "projects": _project_rows,+ "releases": _release_rows,+ "vulnerabilities": _vulnerability_rows,+}+++def validate_credentials(packages_raw: str | None) -> tuple[bool, str | None]:+ """Confirm the config is usable by probing the first configured package.++ PyPI's read APIs are unauthenticated, so there is no key to check; instead we confirm at least+ one package is configured and that it resolves (200). A 404 means the package name is wrong.+ """+ try:+ packages = parse_packages(packages_raw)+ except ValueError as exc:+ return False, str(exc)++ package = packages[0]+ try:+ response = make_tracked_session().get(_project_url(package), headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)+ except Exception:+ return False, "Could not reach the PyPI API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 404:+ return False, f"Package '{package}' was not found on PyPI. Check the spelling and try again."++ return False, f"PyPI API returned an unexpected status code: {response.status_code}"+++def get_rows(+ endpoint: str,+ packages: list[str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ build_rows = _ROW_BUILDERS[endpoint]+ # One session reused across every package so urllib3 keeps the connection alive.+ session = make_tracked_session()++ for package in packages:+ document = _fetch_project(session, package, logger)+ if document is None:+ continue+ # Stream the builder into bounded chunks: a package with a very large release history is+ # never materialized as one oversized list, and each yield caps the downstream Arrow+ # conversion. The pipeline batches on top of this.+ chunk: list[dict[str, Any]] = []+ for row in build_rows(package, document):+ chunk.append(row)+ if len(chunk) >= MAX_ROWS_PER_BATCH:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def pypi_source(+ endpoint: str,+ packages_raw: str | None,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config: PyPIEndpointConfig = PYPI_ENDPOINTS[endpoint]+ packages = parse_packages(packages_raw)++ partition_kwargs: dict[str, Any] = {}+ if config.partition_key is not None:+ partition_kwargs = {+ "partition_count": 1,+ "partition_size": 1,+ "partition_mode": "datetime",+ "partition_format": "month",+ "partition_keys": [config.partition_key],+ }++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(endpoint=endpoint, packages=packages, logger=logger),+ primary_keys=config.primary_keys,+ # No server-side ordering to rely on; rows are grouped per package as fetched.+ sort_mode="asc",+ **partition_kwargs,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/settings.pynew file mode 100644index 000000000000..73727f4f0477--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/settings.py@@ -0,0 +1,62 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# A file's upload time never changes once published, so it's a stable partition key for the+# releases stream. We expose the raw ISO 8601 string PyPI already returns (`upload_time_iso_8601`).+_UPLOAD_TIME_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "upload_time_iso_8601",+ "type": IncrementalFieldType.DateTime,+ "field": "upload_time_iso_8601",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++@dataclass+class PyPIEndpointConfig:+ name: str+ # Where the rows for this stream live inside the JSON project document+ # (GET /pypi/<project>/json). Handled explicitly per stream in `pypi.py`.+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime column used for partitioning, or `None` for streams without one.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ description: Optional[str] = None+++PYPI_ENDPOINTS: dict[str, PyPIEndpointConfig] = {+ "projects": PyPIEndpointConfig(+ name="projects",+ # PyPI project names are globally unique (normalized per PEP 503).+ primary_keys=["name"],+ description="Project (package) metadata: one row per configured package, from the `info` "+ "block of the JSON API.",+ ),+ "releases": PyPIEndpointConfig(+ name="releases",+ # A distribution filename is unique within a version, but versions and packages aggregate+ # into one table, so the package + version + filename together form the key.+ primary_keys=["package", "version", "filename"],+ incremental_fields=list(_UPLOAD_TIME_INCREMENTAL_FIELDS),+ partition_key="upload_time_iso_8601",+ description="Release files: one row per uploaded distribution file across every version of "+ "each configured package.",+ ),+ "vulnerabilities": PyPIEndpointConfig(+ name="vulnerabilities",+ # Vulnerability ids are unique per advisory source but rows aggregate across packages.+ primary_keys=["package", "id"],+ description="Known vulnerabilities affecting the latest version of each configured package, "+ "as reported by the PyPI JSON API.",+ ),+}++ENDPOINTS = tuple(PYPI_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PYPI_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/source.pyindex 8dc597e0ce29..7ff4f4e51043 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/source.py@@ -1,19 +1,41 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+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, SimpleSource+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.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PyPISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.pypi import (+ pypi_source,+ validate_credentials as validate_pypi_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PYPI_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass PyPISource(SimpleSource[PyPISourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PYPI@@ -24,7 +46,81 @@ class PyPISource(SimpleSource[PyPISourceConfig]):name=SchemaExternalDataSourceType.PY_PI,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="PyPI",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Pull metadata for Python packages from the [PyPI](https://pypi.org) JSON API into the PostHog Data warehouse.++PyPI's read APIs are public, so no credentials are required. There is no list endpoint, so enter the package names you want to track, one per line (or comma-separated). For example:++```+requests+django+posthog+```++Each sync fetches the current metadata for every configured package. PyPI has no server-side "changed since" filter, so all tables sync as a full refresh.""",iconPath="/static/services/pypi.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/pypi",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="packages",+ label="Packages",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="requests\ndjango\nposthog",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # PyPI's read APIs are unauthenticated, so there are no credential errors to permanently fail+ # on. A missing package surfaces as a 404 and is skipped per-package during the sync.+ return {}++ def get_schemas(+ self,+ config: PyPISourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # PyPI exposes no server-side timestamp filter, so no stream is truly incremental;+ # re-fetching would only duplicate immutable history, so append is off too.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=PYPI_ENDPOINTS[endpoint].should_sync_default,+ description=PYPI_ENDPOINTS[endpoint].description,+ )+ 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: PyPISourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_pypi_credentials(config.packages)++ def source_for_pipeline(self, config: PyPISourceConfig, inputs: SourceInputs) -> SourceResponse:+ return pypi_source(+ endpoint=inputs.schema_name,+ packages_raw=config.packages,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi.pynew file mode 100644index 000000000000..fa51e4f468f0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi.py@@ -0,0 +1,309 @@+import json+from typing import Any, Optional++import pytest+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.pypi import (+ MAX_PACKAGES,+ PYPI_BASE_URL,+ PyPIRetryableError,+ _canonical_name,+ _fetch_project,+ _project_rows,+ _project_url,+ _release_rows,+ _vulnerability_rows,+ get_rows,+ parse_packages,+ pypi_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.settings import PYPI_ENDPOINTS++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.pypi.pypi"+++def _response(status: int = 200, body: Optional[dict[str, Any]] = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.status_code = status+ resp.ok = 200 <= status < 300+ resp.json.return_value = body or {}+ resp.text = json.dumps(body or {})+ if not resp.ok:+ resp.raise_for_status.side_effect = requests.HTTPError(+ f"{status} Client Error for url: {PYPI_BASE_URL}", response=requests.Response()+ )+ return resp+++def _document(name: str = "requests") -> dict[str, Any]:+ return {+ "info": {"name": name, "summary": "Python HTTP for Humans."},+ "last_serial": 42,+ "releases": {+ "2.0.0": [{"filename": f"{name}-2.0.0.tar.gz", "upload_time_iso_8601": "2013-09-24T00:00:00Z"}],+ "2.31.0": [+ {"filename": f"{name}-2.31.0-py3-none-any.whl", "upload_time_iso_8601": "2023-05-22T15:12:42Z"},+ {"filename": f"{name}-2.31.0.tar.gz", "upload_time_iso_8601": "2023-05-22T15:12:44Z"},+ ],+ "2.99.0": "not-a-list",+ },+ "vulnerabilities": [{"id": "PYSEC-2023-1", "details": "boom"}],+ }+++class TestParsePackages:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("requests", ["requests"]),+ ("requests\ndjango", ["requests", "django"]),+ ("requests, django", ["requests", "django"]),+ (" requests , django \n posthog ", ["requests", "django", "posthog"]),+ # De-duplicated while preserving order so the primary key never sees the same package twice.+ ("requests\nrequests\ndjango", ["requests", "django"]),+ ("requests\n\n \ndjango", ["requests", "django"]),+ # PEP 503 aliases collapse to one entry; both would resolve to the same canonical name+ # and emit rows with a colliding primary key otherwise.+ ("Requests\nrequests", ["Requests"]),+ ("zope.interface\nzope-interface", ["zope.interface"]),+ ],+ )+ def test_valid(self, raw, expected):+ assert parse_packages(raw) == expected++ @pytest.mark.parametrize("raw", [None, "", " \n ", " , , "])+ def test_empty_raises(self, raw):+ with pytest.raises(ValueError):+ parse_packages(raw)++ def test_rejects_too_many_packages(self):+ raw = "\n".join(f"pkg{i}" for i in range(MAX_PACKAGES + 1))+ with pytest.raises(ValueError, match="Too many packages"):+ parse_packages(raw)++ def test_allows_max_packages(self):+ raw = "\n".join(f"pkg{i}" for i in range(MAX_PACKAGES))+ assert len(parse_packages(raw)) == MAX_PACKAGES+++class TestProjectUrl:+ def test_encodes_path_segment(self):+ assert _project_url("requests") == f"{PYPI_BASE_URL}/pypi/requests/json"+ # A stray slash must not escape the /pypi/<name>/json path.+ assert "/" not in _project_url("a/b").removeprefix(f"{PYPI_BASE_URL}/pypi/").removesuffix("/json")+++class TestCanonicalName:+ def test_prefers_info_name(self):+ assert _canonical_name("Requests", {"info": {"name": "requests"}}) == "requests"++ @pytest.mark.parametrize("document", [{}, {"info": {}}, {"info": {"name": None}}])+ def test_falls_back_to_requested_name(self, document):+ assert _canonical_name("Requests", document) == "Requests"+++class TestProjectRows:+ def test_single_row_with_serial_and_name(self):+ rows = list(_project_rows("requests", _document()))++ assert len(rows) == 1+ assert rows[0]["name"] == "requests"+ assert rows[0]["last_serial"] == 42++ def test_name_falls_back_to_requested_when_info_missing(self):+ rows = list(_project_rows("requests", {"last_serial": 1}))++ assert rows[0]["name"] == "requests"+++class TestReleaseRows:+ def test_one_row_per_file_stamped_with_package_and_version(self):+ rows = list(_release_rows("Requests", _document(name="requests")))++ # Both files of 2.31.0 plus the single 2.0.0 file; the malformed "2.99.0" entry is skipped.+ assert len(rows) == 3+ keys = {(r["package"], r["version"], r["filename"]) for r in rows}+ assert ("requests", "2.31.0", "requests-2.31.0.tar.gz") in keys+ assert ("requests", "2.0.0", "requests-2.0.0.tar.gz") in keys+ # Canonical package name is stamped even though the user typed "Requests".+ assert all(r["package"] == "requests" for r in rows)++ def test_handles_missing_releases(self):+ assert list(_release_rows("requests", {"info": {"name": "requests"}})) == []++ def test_skips_files_without_filename(self):+ # `filename` is part of the releases primary key, so a file object missing it can't upsert+ # cleanly and must be dropped rather than emitted with a null key component.+ document = {+ "info": {"name": "requests"},+ "releases": {+ "1.0.0": [+ {"filename": "requests-1.0.0.tar.gz"},+ {"upload_time_iso_8601": "2020-01-01T00:00:00Z"},+ {"filename": ""},+ ],+ },+ }++ rows = list(_release_rows("requests", document))++ assert [r["filename"] for r in rows] == ["requests-1.0.0.tar.gz"]+++class TestVulnerabilityRows:+ def test_stamps_package(self):+ rows = list(_vulnerability_rows("Requests", _document(name="requests")))++ assert len(rows) == 1+ assert rows[0]["package"] == "requests"+ assert rows[0]["id"] == "PYSEC-2023-1"++ def test_handles_no_vulnerabilities(self):+ assert list(_vulnerability_rows("requests", {"info": {"name": "requests"}, "vulnerabilities": []})) == []+++# tenacity exposes the undecorated function via `__wrapped__` so status classification can be+# asserted without waiting through retry backoff.+_fetch_once = _fetch_project.__wrapped__ # type: ignore[attr-defined]+++class TestFetchProject:+ def test_ok_returns_body(self):+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"info": {"name": "requests"}})++ assert _fetch_once(session, "requests", structlog.get_logger()) == {"info": {"name": "requests"}}++ def test_404_returns_none(self):+ # A typo'd or deleted package must be skipped, not fail the whole sync.+ session = mock.MagicMock()+ session.get.return_value = _response(404)++ assert _fetch_once(session, "nope", structlog.get_logger()) is None++ @pytest.mark.parametrize("status", [429, 500, 503])+ def test_retryable_statuses_raise_retryable(self, status):+ session = mock.MagicMock()+ session.get.return_value = _response(status)++ with pytest.raises(PyPIRetryableError):+ _fetch_once(session, "requests", structlog.get_logger())++ def test_other_client_error_raises(self):+ session = mock.MagicMock()+ session.get.return_value = _response(400)++ with pytest.raises(requests.HTTPError):+ _fetch_once(session, "requests", structlog.get_logger())+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid",+ [+ (200, True),+ (404, False),+ (500, False),+ ],+ )+ def test_status_mapping(self, status, expected_valid):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status)++ is_valid, _ = validate_credentials("requests")++ assert is_valid is expected_valid++ def test_empty_packages_is_invalid_without_request(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ is_valid, message = validate_credentials("")++ assert is_valid is False+ assert message is not None+ mock_session.return_value.get.assert_not_called()++ def test_network_error_is_invalid(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = Exception("boom")++ is_valid, message = validate_credentials("requests")++ assert is_valid is False+ assert message is not None++ def test_probes_first_package(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("requests\ndjango")++ called_url = mock_session.return_value.get.call_args[0][0]++ assert called_url == f"{PYPI_BASE_URL}/pypi/requests/json"+++class TestGetRows:+ def test_yields_a_batch_per_package_and_skips_404(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, _document(name="requests")),+ _response(404),+ _response(200, _document(name="django")),+ ]++ batches = list(get_rows("projects", ["requests", "nope", "django"], structlog.get_logger()))++ # The 404 package is skipped, so only two batches come back.+ assert len(batches) == 2+ assert batches[0][0]["name"] == "requests"+ assert batches[1][0]["name"] == "django"++ def test_releases_endpoint_flattens_files(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, _document(name="requests"))++ batches = list(get_rows("releases", ["requests"], structlog.get_logger()))++ assert len(batches) == 1+ assert len(batches[0]) == 3++ def test_chunks_large_release_history(self, monkeypatch):+ # A package with a large release history must not be yielded as one oversized list; it's+ # split into bounded chunks so downstream Arrow conversion stays capped.+ monkeypatch.setattr(f"{MODULE}.MAX_ROWS_PER_BATCH", 2)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, _document(name="requests"))++ batches = list(get_rows("releases", ["requests"], structlog.get_logger()))++ # The document has 3 release files; at 2 rows per chunk that's [2, 1].+ assert [len(b) for b in batches] == [2, 1]+++class TestPyPISource:+ @pytest.mark.parametrize("endpoint", list(PYPI_ENDPOINTS))+ def test_source_response_shape(self, endpoint):+ response = pypi_source(endpoint, "requests", structlog.get_logger())++ assert response.name == endpoint+ assert response.primary_keys == PYPI_ENDPOINTS[endpoint].primary_keys+ assert response.sort_mode == "asc"++ def test_only_releases_is_partitioned(self):+ # `releases` has a stable upload timestamp; the other streams have no stable datetime column.+ releases = pypi_source("releases", "requests", structlog.get_logger())+ projects = pypi_source("projects", "requests", structlog.get_logger())++ assert releases.partition_mode == "datetime"+ assert releases.partition_keys == ["upload_time_iso_8601"]+ assert projects.partition_mode is None+ assert projects.partition_keys is None++ def test_invalid_packages_raise(self):+ with pytest.raises(ValueError):+ pypi_source("projects", "", structlog.get_logger())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi_source.pynew file mode 100644index 000000000000..bce6d661eb6a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/pypi/tests/test_pypi_source.py@@ -0,0 +1,125 @@+import pytest+from unittest import mock++import structlog++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PyPISourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.pypi.source import PyPISource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "projects") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ 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-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestPyPISource:+ def setup_method(self):+ self.source = PyPISource()+ self.team_id = 123+ self.config = PyPISourceConfig(packages="requests\ndjango")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PYPI++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "PyPI"+ assert config.label == "PyPI"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/pypi"++ def test_get_source_config_fields(self):+ fields = self.source.get_source_config.fields++ by_name = {field.name: field for field in fields if isinstance(field, SourceFieldInputConfig)}+ assert set(by_name) == {"packages"}++ packages_field = by_name["packages"]+ assert packages_field.type == SourceFieldInputConfigType.TEXTAREA+ assert packages_field.required is True+ # No auth, so the field carries no secret.+ assert packages_field.secret is False++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_get_schemas_full_refresh_only(self, endpoint):+ # PyPI exposes no server-side timestamp filter, so no stream is incremental or append.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["releases"])++ assert [schema.name for schema in schemas] == ["releases"]++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ def test_no_non_retryable_errors(self):+ # Unauthenticated API: there are no credential errors to permanently fail on.+ assert self.source.get_non_retryable_errors() == {}++ def test_canonical_descriptions_cover_every_endpoint(self):+ descriptions = self.source.get_canonical_descriptions()++ assert set(descriptions) == set(ENDPOINTS)++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ ((True, None), True, None),+ ((False, "Package 'x' was not found on PyPI."), False, "Package 'x' was not found on PyPI."),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.pypi.source.validate_pypi_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "projects")++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.packages)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.pypi.source.pypi_source")+ def test_source_for_pipeline_plumbs_args(self, mock_pypi_source):+ inputs = _make_inputs(schema_name="releases")++ self.source.source_for_pipeline(self.config, inputs)++ mock_pypi_source.assert_called_once_with(+ endpoint="releases",+ packages_raw="requests\ndjango",+ logger=inputs.logger,+ )