: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): add 1 missing tables to the NpmRegistry source (#118245)
Tom Owers6949b3ff3bd6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex d2c1513b3c0f..7821c3a5a764 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -8446,7 +8446,7 @@ Today (2): `Downloads`, `Versions`Diffed against: <https://raw.githubusercontent.com/npm/registry/master/docs/REGISTRY-API.md>-- [ ] `GET https://api.npmjs.org/versions/{package}/last-week` — per-version download counts - joins straight onto the Versions table already synced and is the only way to measure version adoption or upgrade lag (high)+- [x] `GET https://api.npmjs.org/versions/{package}/last-week` — per-version download counts - joins straight onto the Versions table already synced and is the only way to measure version adoption or upgrade lag (high)- [ ] `GET /-/v1/search` — search results carry npms.io quality, popularity and maintenance scores per package, unavailable from the packument (medium)- [ ] `GET https://api.npmjs.org/downloads/point/{period}/{pkg1},{pkg2}` — bulk point downloads for up to 128 packages in one call - same data as Downloads but far cheaper for large package lists (low)- [ ] `GET / (registry meta)` — registry-wide doc_count and update_seq, useful only as a sync watermark (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/canonical_descriptions.pyindex 19d46675d7bc..efd0a42b7d89 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/canonical_descriptions.py@@ -36,4 +36,15 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"Node.js versions.",},},+ "VersionDownloads": {+ "description": "Download counts per published version over the last 7 days, per configured package, "+ "from the npm downloads-counts API (api.npmjs.org/versions/{package}/last-week). Each sync replaces "+ "the table with the current rolling 7-day window.",+ "docs_url": _DOWNLOAD_COUNTS_DOCS,+ "columns": {+ "package": "Name of the npm package (injected by the connector).",+ "version": "Version string of the release; joins to the Versions table on package and version.",+ "downloads": "Number of downloads of this version over the last 7 available days.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/npm_registry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/npm_registry.pyindex 9c640b06d669..d655c02f690a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/npm_registry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/npm_registry.py@@ -80,6 +80,10 @@ def _downloads_url(package: str, start: date, end: date) -> str:return f"{NPM_DOWNLOADS_BASE_URL}/downloads/range/{start.isoformat()}:{end.isoformat()}/{_encode_package(package)}"+def _version_downloads_url(package: str) -> str:+ return f"{NPM_DOWNLOADS_BASE_URL}/versions/{_encode_package(package)}/last-week"++def _registry_url(package: str) -> str:return f"{NPM_REGISTRY_BASE_URL}/{_encode_package(package)}"@@ -197,6 +201,27 @@ def _iter_downloads(manager.save_state(NpmRegistryResumeConfig(package_index=package_index, window_start=window_start.isoformat()))+def _iter_version_downloads(+ session: requests.Session, package: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ # An unknown package returns 200 with an empty `downloads` map, not a 404.+ document = _fetch_json(session, _version_downloads_url(package), logger, DOWNLOADS_REQUEST_TIMEOUT_SECONDS)+ if document is None:+ return++ counts = document.get("downloads")+ if not isinstance(counts, dict):+ return++ rows = [+ {"package": package, "version": version, "downloads": downloads}+ for version, downloads in counts.items()+ if isinstance(downloads, int)+ ]+ if rows:+ yield rows++def _first_license(licenses: Any) -> str | None:"""Old package manifests (pre ~2015) used a `licenses: [{"type": ...}]` array instead of themodern single `license` string field."""@@ -272,6 +297,8 @@ def get_rows(resume_window_start, should_use_incremental_field, db_incremental_field_last_value)yield from _iter_downloads(session, package, index, logger, resumable_source_manager, window_start)+ elif endpoint == "VersionDownloads":+ yield from _iter_version_downloads(session, package, logger)else:yield from _iter_versions(session, package, logger)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/settings.pyindex 261ab7db95e6..d8adf62ab2ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/settings.py@@ -46,6 +46,14 @@ NPM_REGISTRY_ENDPOINTS: dict[str, NpmRegistryEndpointConfig] = {description="Published version metadata (publish time, dist-tags, tarball, license) per ""configured package, from the npm registry API.",),+ "VersionDownloads": NpmRegistryEndpointConfig(+ name="VersionDownloads",+ primary_keys=["package", "version"],+ # npm only serves per-version counts as a rolling last-7-days total with no date filter or+ # date in the response, so each sync replaces the table with the current week's snapshot.+ description="Downloads per published version over the last 7 days, per configured package, from the "+ "npm downloads-counts API.",+ ),}ENDPOINTS = tuple(NPM_REGISTRY_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.pyindex b29bd10c0a7c..ef657b193279 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py@@ -159,6 +159,47 @@ class TestGetRowsVersions:assert result.rows == []+class TestGetRowsVersionDownloads:+ @pytest.mark.parametrize(+ "response,expected_rows",+ [+ (+ ScriptedResponse(json={"package": "react", "downloads": {"1.0.0": 12, "1.0.1": 0, "1.0.2": None}}),+ [+ {"package": "react", "version": "1.0.0", "downloads": 12},+ {"package": "react", "version": "1.0.1", "downloads": 0},+ ],+ ),+ # An unknown package returns 200 with an empty map.+ (ScriptedResponse(json={"package": "react", "downloads": {}}), []),+ (ScriptedResponse(json={"error": "not found"}), []),+ (ScriptedResponse(status=404), []),+ ],+ )+ def test_row_shaping(self, response: ScriptedResponse, expected_rows: list[dict]) -> None:+ result = _driver().run("VersionDownloads", [response])++ assert result.raised is None+ assert result.rows == expected_rows+ assert result.paths == ["/versions/react/last-week"]++ def test_walks_every_package_and_encodes_scoped_names(self) -> None:+ result = _driver("@scope/name\nlodash").run(+ "VersionDownloads",+ [+ ScriptedResponse(json={"package": "@scope/name", "downloads": {"1.0.0": 3}}),+ ScriptedResponse(json={"package": "lodash", "downloads": {"4.0.0": 9}}),+ ],+ )++ assert result.raised is None+ assert result.paths == ["/versions/%40scope%2Fname/last-week", "/versions/lodash/last-week"]+ assert result.rows == [+ {"package": "@scope/name", "version": "1.0.0", "downloads": 3},+ {"package": "lodash", "version": "4.0.0", "downloads": 9},+ ]++class TestFetchJson:def _session(self, *, status: int, chunks: list[bytes]) -> mock.MagicMock:response = mock.MagicMock()