: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 npm registry source (#73199)
Tom Owers97e64ed85801
diff --git a/frontend/public/services/npm_registry.png b/frontend/public/services/npm_registry.pngindex c5736e43b50d..13625feb985a 100644Binary files a/frontend/public/services/npm_registry.png and b/frontend/public/services/npm_registry.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 43676e300d16..bc64ce4fb826 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -383,6 +383,7 @@ the row lists both.| new_york_times | HTTP | requests | ✅ || news_api | HTTP | requests | ✅ || newsdata | HTTP | requests | ✅ |+| npm_registry | HTTP | requests | ✅ || okta | HTTP | requests | ✅ || nocrm | HTTP | requests | ✅ || northflank | HTTP | requests | ✅ |@@ -1119,7 +1120,6 @@ doesn't conflict with concurrent PRs.- nolt- nops- northpass_lms-- npm_registry- nuntly- nutshell- nylasdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/npmregistry.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/npmregistry.pyindex 3226666cb156..dbf75cdfc3dc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/npmregistry.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/npmregistry.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass NpmRegistrySourceConfig(config.Config):- pass+ package_names: strdiff --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.pynew file mode 100644index 000000000000..19d46675d7bc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/canonical_descriptions.py@@ -0,0 +1,39 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOWNLOAD_COUNTS_DOCS = "https://github.com/npm/registry/blob/master/docs/download-counts.md"+_REGISTRY_API_DOCS = "https://github.com/npm/registry/blob/master/docs/REGISTRY-API.md"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Downloads": {+ "description": "Daily download counts per configured package, from the npm downloads-counts API "+ "(api.npmjs.org).",+ "docs_url": _DOWNLOAD_COUNTS_DOCS,+ "columns": {+ "package": "Name of the npm package (injected by the connector; not returned by the endpoint).",+ "day": "Day the downloads were counted (UTC); used as the partition key.",+ "downloads": "Number of package downloads (tarball fetches) on that day.",+ },+ },+ "Versions": {+ "description": "Published version metadata across every configured package, one row per version, "+ "from the npm registry's package document (registry.npmjs.org/{package}).",+ "docs_url": _REGISTRY_API_DOCS,+ "columns": {+ "package": "Name of the npm package (injected by the connector; not returned per-version).",+ "version": "Version string of this release (semver).",+ "published_at": "When this version was published, from the document's `time` map; used as the "+ "partition key.",+ "is_latest": "Whether this version is the package's current `latest` dist-tag.",+ "deprecated": "Deprecation message set on this version, if the maintainer deprecated it.",+ "license": "License declared for this version (SPDX identifier or free text).",+ "description": "Package description at the time this version was published.",+ "tarball": "URL to download this version's packaged tarball.",+ "shasum": "SHA-1 checksum of the packaged tarball.",+ "integrity": "Subresource Integrity (SRI) hash of the packaged tarball.",+ "node_engine": "Value of the `engines.node` manifest field, if declared, constraining compatible "+ "Node.js versions.",+ },+ },+}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.pynew file mode 100644index 000000000000..e60dca830d07--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/npm_registry.py@@ -0,0 +1,345 @@+import re+import json+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from typing import Any, Optional+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger++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.npm_registry.settings import (+ EARLIEST_DOWNLOAD_DATE,+ MAX_DOWNLOADS_WINDOW_DAYS,+ MAX_PACKAGES,+ MAX_RESPONSE_BYTES,+ MAX_ROWS_PER_BATCH,+ NPM_REGISTRY_ENDPOINTS,+ NpmRegistryEndpointConfig,+)++NPM_DOWNLOADS_BASE_URL = "https://api.npmjs.org"+NPM_REGISTRY_BASE_URL = "https://registry.npmjs.org"++DOWNLOADS_REQUEST_TIMEOUT_SECONDS = 30+# The full registry document for a popular package (every published version's manifest, inlined)+# can run several MB, so allow more time than a small downloads-range response needs.+REGISTRY_REQUEST_TIMEOUT_SECONDS = 60+++class NpmRegistryResumeConfig:+ # Index into the parsed package list of the package currently in progress. Packages before+ # this index are considered fully synced for this run.+ package_index: int = 0+ # Downloads stream only: next date window's start (yyyy-mm-dd) within the in-progress package.+ window_start: Optional[str] = None+++def parse_packages(raw: str | None) -> list[str]:+ """Parse the user's free-text `package_names` field into a list of npm package names.++ Accepts one package per line and/or comma-separated names (scoped names like `@scope/name`+ contain no comma or newline, so they pass through untouched). Raises `ValueError` with an+ actionable message on empty/oversized input rather than silently syncing nothing or everything.+ Names are de-duplicated (exact match — npm package names are always lowercase) 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+ if name not in seen:+ seen.add(name)+ packages.append(name)++ if not packages:+ raise ValueError("At least one package name is required.")+ if len(packages) > MAX_PACKAGES:+ raise ValueError(f"Too many packages: at most {MAX_PACKAGES} are allowed per source.")++ return packages+++def _encode_package(package: str) -> str:+ # Percent-encode the whole path segment (including `@` and `/` for scoped packages like+ # `@scope/name`) so it can't break out of the URL path.+ return quote(package, safe="")+++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 _registry_url(package: str) -> str:+ return f"{NPM_REGISTRY_BASE_URL}/{_encode_package(package)}"+++def _read_capped(response: requests.Response, url: str) -> bytes:+ """Read a streamed response body into memory, aborting once it exceeds `MAX_RESPONSE_BYTES`.++ The document is user-selected, so we never buffer an unbounded body: we read in chunks and raise+ as soon as the running total crosses the cap, before the full body (and its parsed form) can+ exhaust the worker's memory.+ """+ total = 0+ chunks: list[bytes] = []+ for chunk in response.iter_content(chunk_size=1 << 20):+ total += len(chunk)+ if total > MAX_RESPONSE_BYTES:+ raise ValueError(+ f"npm registry response exceeded the {MAX_RESPONSE_BYTES}-byte limit (url={url}); "+ "refusing to buffer it to protect worker memory."+ )+ chunks.append(chunk)+ return b"".join(chunks)+++def _fetch_json(+ session: requests.Session, url: str, logger: FilteringBoundLogger, timeout: int+) -> dict[str, Any] | None:+ """Fetch a single JSON document. Returns `None` for a 404 (package not found) so a typo'd or+ unpublished package is skipped rather than failing the whole sync — other configured packages+ are unaffected. `make_tracked_session()` already retries transient 429/5xx transport errors.++ Streams the body and caps how much we buffer (see `_read_capped`) so a user-selected package+ can't return an unbounded document that exhausts worker memory."""+ with session.get(url, timeout=timeout, stream=True) as response:+ if response.status_code == 404:+ logger.warning(f"npm registry: package not found, skipping: url={url}")+ return None++ if not response.ok:+ logger.error(f"npm registry API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ body = _read_capped(response, url)++ return json.loads(body)+++def _to_date(value: Any) -> date | None:+ """Coerce a datetime/date/ISO-string incremental value to a `date`."""+ if value is None:+ return None+ if isinstance(value, datetime):+ return value.astimezone(UTC).date() if value.tzinfo else value.date()+ if isinstance(value, date):+ return value+ text = str(value)[:10]+ try:+ return date.fromisoformat(text)+ except ValueError as e:+ raise ValueError(f"Could not derive a yyyy-mm-dd date from incremental value {value!r}") from e+++def _first_download_window_start(+ resume_window_start: str | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> date:+ if resume_window_start:+ return date.fromisoformat(resume_window_start)+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ last = _to_date(db_incremental_field_last_value)+ if last is not None:+ return last + timedelta(days=1)+ return date.fromisoformat(EARLIEST_DOWNLOAD_DATE)+++def _iter_downloads(+ session: requests.Session,+ package: str,+ package_index: int,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[NpmRegistryResumeConfig],+ window_start: date,+) -> Iterator[list[dict[str, Any]]]:+ """Walk one package's daily download history in fixed-size date windows.++ The API silently truncates a too-long range to its tail instead of erroring (see+ `MAX_DOWNLOADS_WINDOW_DAYS`), so every request stays within the safe cap.+ """+ today = datetime.now(UTC).date()++ while window_start <= today:+ window_end = min(window_start + timedelta(days=MAX_DOWNLOADS_WINDOW_DAYS - 1), today)+ document = _fetch_json(+ session, _downloads_url(package, window_start, window_end), logger, DOWNLOADS_REQUEST_TIMEOUT_SECONDS+ )+ if document is None:+ # Package doesn't exist (or was unpublished) — stop trying further windows for it.+ return++ rows = [+ {"package": package, "day": entry["day"], "downloads": entry.get("downloads", 0)}+ for entry in document.get("downloads") or []+ if isinstance(entry, dict) and entry.get("day")+ ]+ if rows:+ yield rows++ if window_end >= today:+ break++ window_start = window_end + timedelta(days=1)+ # Save AFTER yielding the window so a crash re-fetches it rather than skipping it; merge+ # dedupes the re-pulled days on the [package, day] primary key.+ manager.save_state(NpmRegistryResumeConfig(package_index=package_index, window_start=window_start.isoformat()))+++def _first_license(licenses: Any) -> str | None:+ """Old package manifests (pre ~2015) used a `licenses: [{"type": ...}]` array instead of the+ modern single `license` string field."""+ if not isinstance(licenses, list) or not licenses:+ return None+ first = licenses[0]+ return first.get("type") if isinstance(first, dict) else None+++def _iter_versions(+ session: requests.Session, package: str, logger: FilteringBoundLogger+) -> Iterator[list[dict[str, Any]]]:+ """One row per published version of a package, from its full registry document.++ Uses the full (non-abbreviated) document because only it carries the per-version `time[]`+ publish timestamps — the abbreviated `install-v1+json` form omits them.+ """+ document = _fetch_json(session, _registry_url(package), logger, REGISTRY_REQUEST_TIMEOUT_SECONDS)+ if document is None:+ return++ dist_tags = document.get("dist-tags") or {}+ latest_version = dist_tags.get("latest")+ publish_times = document.get("time") or {}+ versions = document.get("versions") or {}++ chunk: list[dict[str, Any]] = []+ for version, manifest in versions.items():+ if not isinstance(manifest, dict):+ continue+ dist = manifest.get("dist") or {}+ chunk.append(+ {+ "package": package,+ "version": version,+ "published_at": publish_times.get(version),+ "is_latest": version == latest_version,+ "deprecated": manifest.get("deprecated"),+ "license": manifest.get("license") or _first_license(manifest.get("licenses")),+ "description": manifest.get("description"),+ "tarball": dist.get("tarball"),+ "shasum": dist.get("shasum"),+ "integrity": dist.get("integrity"),+ "node_engine": (manifest.get("engines") or {}).get("node"),+ }+ )+ if len(chunk) >= MAX_ROWS_PER_BATCH:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def get_rows(+ endpoint: str,+ packages: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NpmRegistryResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session()+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.package_index if resume else 0++ for index, package in enumerate(packages):+ if index < start_index:+ continue++ if endpoint == "Downloads":+ resume_window_start = resume.window_start if resume and index == start_index else None+ window_start = _first_download_window_start(+ 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)+ else:+ yield from _iter_versions(session, package, logger)++ # Advance past this package before moving on, so a crash between packages resumes at the+ # next one rather than re-walking one we already finished.+ resumable_source_manager.save_state(NpmRegistryResumeConfig(package_index=index + 1, window_start=None))+++def validate_packages(packages_raw: str | None) -> tuple[bool, str | None]:+ """Confirm the config is usable by probing the first configured package.++ npm's read APIs are unauthenticated, so there's no key to check — instead we confirm at least+ one package is configured and that it resolves (200) against the small downloads-point endpoint.+ """+ try:+ packages = parse_packages(packages_raw)+ except ValueError as exc:+ return False, str(exc)++ package = packages[0]+ url = f"{NPM_DOWNLOADS_BASE_URL}/downloads/point/last-day/{_encode_package(package)}"+ try:+ response = make_tracked_session().get(url, timeout=DOWNLOADS_REQUEST_TIMEOUT_SECONDS)+ except Exception:+ return False, "Could not reach the npm registry 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 the npm registry. Check the spelling and try again."++ return False, f"npm registry API returned an unexpected status code: {response.status_code}"+++def npm_registry_source(+ endpoint: str,+ package_names: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NpmRegistryResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config: NpmRegistryEndpointConfig = NPM_REGISTRY_ENDPOINTS[endpoint]+ packages = parse_packages(package_names)++ 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,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ # Downloads are walked oldest-window-first per package; Versions are emitted in whatever+ # order the registry document lists them (not time-ordered, but Versions isn't incremental).+ sort_mode="asc",+ **partition_kwargs,+ )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.pynew file mode 100644index 000000000000..261ab7db95e6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/settings.py@@ -0,0 +1,81 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# A download row's day never changes once the day is over, so it's a stable incremental/partition+# field. npm's downloads-range API is a genuine server-side date-window filter (we only request the+# days we don't have yet), unlike the registry document below.+_DOWNLOADS_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "day",+ "type": IncrementalFieldType.Date,+ "field": "day",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class NpmRegistryEndpointConfig:+ name: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable field to partition/checkpoint by, or `None` for streams without one.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ description: Optional[str] = None+++NPM_REGISTRY_ENDPOINTS: dict[str, NpmRegistryEndpointConfig] = {+ "Downloads": NpmRegistryEndpointConfig(+ name="Downloads",+ # A day's download count is only ever reported once per configured package.+ primary_keys=["package", "day"],+ incremental_fields=list(_DOWNLOADS_INCREMENTAL_FIELDS),+ partition_key="day",+ description="Daily download counts per configured package, from the npm downloads-counts API.",+ ),+ "Versions": NpmRegistryEndpointConfig(+ name="Versions",+ # A version string is only unique within its own package.+ primary_keys=["package", "version"],+ # The registry document has no server-side "changed since" filter — every sync re-fetches+ # the whole document per package, so this stays full refresh (see npm_registry.py).+ partition_key="published_at",+ description="Published version metadata (publish time, dist-tags, tarball, license) per "+ "configured package, from the npm registry API.",+ ),+}++ENDPOINTS = tuple(NPM_REGISTRY_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in NPM_REGISTRY_ENDPOINTS.items()+}++# npm's download-counts API has no data before this date.+EARLIEST_DOWNLOAD_DATE = "2015-01-10"++# The range endpoint doesn't error past ~18 months — it silently returns only the *tail* of the+# requested window instead (verified: requesting 2015-01-10:2020-01-10 returns only the last ~550+# days, ending 2020-01-10, not the first). Always request windows no larger than this or older+# history is dropped without any error to catch it.+MAX_DOWNLOADS_WINDOW_DAYS = 540++# Each configured package costs at least one request per enabled stream every sync (more for a long+# Downloads backfill), and the registry document for a popular package can run several MB. Cap the+# config so a large list can't tie up the worker indefinitely.+MAX_PACKAGES = 100++# Rows for a single package's Versions stream are yielded in bounded chunks so a package with a huge+# version history (some popular packages have thousands of versions) never forces one oversized+# in-memory batch. The pipeline batches on top of this; this value only caps the per-yield list size.+MAX_ROWS_PER_BATCH = 5000++# Hard cap on the raw bytes we'll buffer for a single npm response before parsing JSON. The registry+# document is user-selected (anyone can publish a package and point a source at it), so without a cap+# a package crafted with enough versions/metadata could make one response exhaust the worker's memory.+# Set well above the largest real full-registry documents (tens of MB) so legitimate packages sync,+# while still bounding the pathological case.+MAX_RESPONSE_BYTES = 250 * 1024 * 1024diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/source.pyindex 28ba7dc4cc7c..5f5a06f98c45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/source.py@@ -1,21 +1,46 @@-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.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.npmregistry import (NpmRegistrySourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.npm_registry import (+ NpmRegistryResumeConfig,+ npm_registry_source,+ validate_packages,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NPM_REGISTRY_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NpmRegistrySource(SimpleSource[NpmRegistrySourceConfig]):+class NpmRegistrySource(ResumableSource[NpmRegistrySourceConfig, NpmRegistryResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ api_docs_url = "https://github.com/npm/registry/blob/master/docs/download-counts.md"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NPMREGISTRY@@ -25,8 +50,99 @@ class NpmRegistrySource(SimpleSource[NpmRegistrySourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.NPM_REGISTRY,category=DataWarehouseSourceCategory.ANALYTICS,- label="npm, Inc. (GitHub / Microsoft)",+ label="npm registry",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["npm", "node", "javascript", "downloads"],+ caption="""Pull daily download counts and published-version metadata for npm packages from the public npm registry into the PostHog Data warehouse.++npm's read APIs are public, so no credentials are required. There is no practical way to sync the whole registry, so enter the package names you want to track, one per line (or comma-separated). For example:++```+react+@slack/client+lodash+```++Daily download counts only go back to 2015-01-10 and are fetched in windows, so the first sync of a long-lived package can take a while. The registry has no server-side "changed since" filter for version metadata, so the Versions table always syncs as a full refresh.""",iconPath="/static/services/npm_registry.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="package_names",+ label="Package names",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="react\n@slack/client\nlodash",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # npm'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: NpmRegistrySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=NPM_REGISTRY_ENDPOINTS[endpoint].should_sync_default,+ description=NPM_REGISTRY_ENDPOINTS[endpoint].description,+ detected_primary_keys=NPM_REGISTRY_ENDPOINTS[endpoint].primary_keys,+ )+ 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: NpmRegistrySourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_packages(config.package_names)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NpmRegistryResumeConfig]:+ return ResumableSourceManager[NpmRegistryResumeConfig](inputs, NpmRegistryResumeConfig)++ def source_for_pipeline(+ self,+ config: NpmRegistrySourceConfig,+ resumable_source_manager: ResumableSourceManager[NpmRegistryResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return npm_registry_source(+ endpoint=inputs.schema_name,+ package_names=config.package_names,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/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.pynew file mode 100644index 000000000000..0aa053a9b9b7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry.py@@ -0,0 +1,372 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.npm_registry import (+ NpmRegistryResumeConfig,+ _encode_package,+ _fetch_json,+ _first_download_window_start,+ _first_license,+ _to_date,+ get_rows,+ npm_registry_source,+ parse_packages,+ validate_packages,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.settings import MAX_PACKAGES++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.npm_registry"+++def _manager(resume: NpmRegistryResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume is not None+ manager.load_state.return_value = resume+ return manager+++class TestParsePackages:+ @pytest.mark.parametrize(+ "raw,expected",+ [+ ("react", ["react"]),+ ("react,lodash", ["react", "lodash"]),+ ("react\nlodash", ["react", "lodash"]),+ ("react, lodash , vue\n", ["react", "lodash", "vue"]),+ ("@slack/client,react", ["@slack/client", "react"]),+ ("react,react,lodash", ["react", "lodash"]), # de-duplicated, order preserved+ ("react,, ,lodash", ["react", "lodash"]), # blank tokens skipped+ ],+ )+ def test_parses_delimited_names(self, raw: str, expected: list[str]):+ assert parse_packages(raw) == expected++ @pytest.mark.parametrize("raw", [None, "", " ", ",,\n,"])+ def test_raises_on_empty_input(self, raw: str | None):+ with pytest.raises(ValueError, match="At least one package name is required"):+ parse_packages(raw)++ def test_raises_when_over_the_cap(self):+ raw = ",".join(f"pkg{i}" for i in range(MAX_PACKAGES + 1))+ with pytest.raises(ValueError, match="Too many packages"):+ parse_packages(raw)++ def test_at_the_cap_is_allowed(self):+ raw = ",".join(f"pkg{i}" for i in range(MAX_PACKAGES))+ assert len(parse_packages(raw)) == MAX_PACKAGES+++class TestEncodePackage:+ @pytest.mark.parametrize(+ "package,expected",+ [+ ("react", "react"),+ ("@slack/client", "%40slack%2Fclient"),+ ],+ )+ def test_percent_encodes_scoped_names(self, package: str, expected: str):+ assert _encode_package(package) == expected+++class TestToDate:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (None, None),+ (datetime(2024, 3, 4, 2, 58, 14, tzinfo=UTC), date(2024, 3, 4)),+ (datetime(2024, 3, 4, 23, 0, 0), date(2024, 3, 4)),+ (date(2024, 3, 4), date(2024, 3, 4)),+ ("2024-03-04T05:06:07", date(2024, 3, 4)),+ ("2024-03-04", date(2024, 3, 4)),+ ],+ )+ def test_to_date(self, value, expected):+ assert _to_date(value) == expected++ @pytest.mark.parametrize("value", ["2024-01", "not-a-date"])+ def test_raises_on_unparseable_fragment(self, value: str):+ with pytest.raises(ValueError, match="Could not derive a yyyy-mm-dd date"):+ _to_date(value)+++class TestFirstDownloadWindowStart:+ def test_resume_state_wins(self):+ result = _first_download_window_start("2024-06-01", True, date(2024, 1, 1))+ assert result == date(2024, 6, 1)++ def test_incremental_starts_the_day_after_the_watermark(self):+ result = _first_download_window_start(None, True, date(2024, 1, 1))+ assert result == date(2024, 1, 2)++ def test_first_sync_starts_at_the_earliest_available_date(self):+ result = _first_download_window_start(None, False, None)+ assert result == date(2015, 1, 10)+++class TestFirstLicense:+ def test_modern_manifest_has_no_licenses_array(self):+ assert _first_license(None) is None++ def test_legacy_licenses_array(self):+ assert _first_license([{"type": "MIT", "url": "http://example.com"}]) == "MIT"++ def test_empty_array(self):+ assert _first_license([]) is None+++class TestGetRowsDownloads:+ @freeze_time("2016-08-01")+ def test_windows_date_range_into_chunks(self):+ # First 540-day window from EARLIEST_DOWNLOAD_DATE runs 2015-01-10..2016-07-02; the second+ # window then starts 2016-07-03 and is clamped to "today" (frozen at 2016-08-01).+ body_by_start = {+ "2015-01-10": {"downloads": [{"day": "2015-01-10", "downloads": 5}]},+ "2016-07-03": {"downloads": [{"day": "2016-07-03", "downloads": 9}]},+ }++ def fake_fetch(_session, url, _logger, _timeout):+ for start, body in body_by_start.items():+ if f"/{start}:" in url:+ return body+ raise AssertionError(f"unexpected url: {url}")++ manager = _manager()+ with mock.patch(f"{_MODULE}._fetch_json", side_effect=fake_fetch) as fetch:+ batches = list(+ get_rows(+ endpoint="Downloads",+ packages=["react"],+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )++ rows = [row for batch in batches for row in batch]+ assert rows == [+ {"package": "react", "day": "2015-01-10", "downloads": 5},+ {"package": "react", "day": "2016-07-03", "downloads": 9},+ ]+ assert fetch.call_count == 2++ @freeze_time("2024-02-15")+ def test_incremental_starts_the_day_after_the_watermark(self):+ with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": []}) as fetch:+ list(+ get_rows(+ endpoint="Downloads",+ packages=["react"],+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2024, 2, 1),+ )+ )+ assert "2024-02-02:2024-02-15" in fetch.call_args_list[0].args[1]++ @freeze_time("2024-02-15")+ def test_resume_starts_from_saved_package_and_window(self):+ with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": []}) as fetch:+ list(+ get_rows(+ endpoint="Downloads",+ packages=["react", "lodash"],+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(+ NpmRegistryResumeConfig(package_index=1, window_start="2024-02-10")+ ),+ )+ )+ # `react` (index 0) is skipped entirely; `lodash` resumes from the saved window.+ assert len(fetch.call_args_list) == 1+ url = fetch.call_args_list[0].args[1]+ assert "lodash" in url+ assert "2024-02-10:2024-02-15" in url++ @freeze_time("2024-02-15")+ def test_missing_package_is_skipped_without_raising(self):+ with mock.patch(f"{_MODULE}._fetch_json", return_value=None) as fetch:+ batches = list(+ get_rows(+ endpoint="Downloads",+ packages=["this-package-does-not-exist"],+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+ assert batches == []+ assert fetch.call_count == 1++ @freeze_time("2024-02-15")+ def test_saves_state_after_each_window_and_advances_package_on_completion(self):+ manager = _manager()+ with mock.patch(f"{_MODULE}._fetch_json", return_value={"downloads": [{"day": "2015-01-10", "downloads": 1}]}):+ list(+ get_rows(+ endpoint="Downloads",+ packages=["react"],+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )+ # Final call always advances to the next package index with no in-progress window.+ assert manager.save_state.call_args_list[-1] == mock.call(NpmRegistryResumeConfig(package_index=1))+++class TestGetRowsVersions:+ def test_extracts_one_row_per_version(self):+ document = {+ "dist-tags": {"latest": "1.1.0"},+ "time": {"1.0.0": "2020-01-01T00:00:00.000Z", "1.1.0": "2021-01-01T00:00:00.000Z"},+ "versions": {+ "1.0.0": {+ "version": "1.0.0",+ "license": "MIT",+ "description": "first",+ "dist": {"tarball": "https://example.com/1.0.0.tgz", "shasum": "abc", "integrity": "sha512-abc"},+ "engines": {"node": ">=10"},+ },+ "1.1.0": {+ "version": "1.1.0",+ "deprecated": "use 2.x instead",+ "licenses": [{"type": "ISC"}],+ "dist": {"tarball": "https://example.com/1.1.0.tgz"},+ },+ },+ }+ with mock.patch(f"{_MODULE}._fetch_json", return_value=document):+ batches = list(+ get_rows(+ endpoint="Versions",+ packages=["react"],+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+ rows = {row["version"]: row for batch in batches for row in batch}++ assert rows["1.0.0"]["package"] == "react"+ assert rows["1.0.0"]["published_at"] == "2020-01-01T00:00:00.000Z"+ assert rows["1.0.0"]["is_latest"] is False+ assert rows["1.0.0"]["license"] == "MIT"+ assert rows["1.0.0"]["node_engine"] == ">=10"++ assert rows["1.1.0"]["is_latest"] is True+ assert rows["1.1.0"]["deprecated"] == "use 2.x instead"+ # Legacy `licenses` array falls back to its first entry's type.+ assert rows["1.1.0"]["license"] == "ISC"++ def test_missing_package_is_skipped_without_raising(self):+ with mock.patch(f"{_MODULE}._fetch_json", return_value=None):+ assert (+ list(+ get_rows(+ endpoint="Versions",+ packages=["this-package-does-not-exist"],+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )+ )+ == []+ )++ def test_versions_advances_package_index_with_no_window(self):+ manager = _manager()+ document: dict[str, Any] = {"dist-tags": {}, "time": {}, "versions": {}}+ with mock.patch(f"{_MODULE}._fetch_json", return_value=document):+ list(+ get_rows(+ endpoint="Versions",+ packages=["react", "lodash"],+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ )+ )+ assert manager.save_state.call_args_list == [+ mock.call(NpmRegistryResumeConfig(package_index=1)),+ mock.call(NpmRegistryResumeConfig(package_index=2)),+ ]+++class TestFetchJson:+ def _session(self, *, status: int, chunks: list[bytes]) -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status+ response.ok = 200 <= status < 400+ response.iter_content.return_value = iter(chunks)+ response.__enter__.return_value = response+ response.__exit__.return_value = False+ session = mock.MagicMock()+ session.get.return_value = response+ return session++ def test_streams_and_parses_body(self):+ session = self._session(status=200, chunks=[b'{"versions":', b'{"1.0.0":1}}'])+ result = _fetch_json(session, "https://example.com/pkg", mock.MagicMock(), 60)+ assert result == {"versions": {"1.0.0": 1}}+ # stream=True keeps us from buffering the whole body up front.+ assert session.get.call_args.kwargs["stream"] is True++ def test_404_returns_none(self):+ session = self._session(status=404, chunks=[])+ assert _fetch_json(session, "https://example.com/missing", mock.MagicMock(), 60) is None++ def test_raises_when_body_exceeds_cap(self):+ # Two chunks over a tiny patched cap: the read must abort instead of buffering the whole body.+ session = self._session(status=200, chunks=[b"x" * 8, b"x" * 8])+ with mock.patch(f"{_MODULE}.MAX_RESPONSE_BYTES", 10):+ with pytest.raises(ValueError, match="exceeded the .*-byte limit"):+ _fetch_json(session, "https://example.com/huge", mock.MagicMock(), 60)+++class TestValidatePackages:+ def test_empty_config_is_invalid(self):+ ok, message = validate_packages(None)+ assert ok is False+ assert message is not None and "At least one package name is required" in message++ @pytest.mark.parametrize(+ "status,expected_ok",+ [(200, True), (404, False), (500, False)],+ )+ def test_probes_first_configured_package(self, status: int, expected_ok: bool):+ session = mock.MagicMock()+ session.get.return_value = mock.MagicMock(status_code=status)+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ ok, _ = validate_packages("react\nlodash")+ assert ok is expected_ok+ # Only the first configured package is probed.+ assert "react" in session.get.call_args.args[0]++ def test_network_failure_returns_error(self):+ session = mock.MagicMock()+ session.get.side_effect = Exception("boom")+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):+ ok, message = validate_packages("react")+ assert ok is False+ assert message is not None and "Could not reach" in message+++class TestNpmRegistrySourceResponse:+ @pytest.mark.parametrize(+ "endpoint,primary_keys,partition_key",+ [+ ("Downloads", ["package", "day"], "day"),+ ("Versions", ["package", "version"], "published_at"),+ ],+ )+ def test_response_shape(self, endpoint, primary_keys, partition_key):+ response = npm_registry_source(+ endpoint=endpoint,+ package_names="react",+ logger=mock.MagicMock(),+ resumable_source_manager=_manager(),+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ 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/npm_registry/tests/test_npm_registry_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry_source.pynew file mode 100644index 000000000000..c13f377ac038--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/npm_registry/tests/test_npm_registry_source.py@@ -0,0 +1,166 @@+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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.npmregistry import (+ NpmRegistrySourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.npm_registry import (+ NpmRegistryResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.source import NpmRegistrySource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "Downloads") -> 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 TestNpmRegistrySource:+ def setup_method(self):+ self.source = NpmRegistrySource()+ self.team_id = 123+ self.config = NpmRegistrySourceConfig(package_names="react\nlodash")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.NPMREGISTRY++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "NpmRegistry"+ assert config.label == "npm registry"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source ships visible — re-adding the flag would hide it from every user.+ assert not config.unreleasedSource++ 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) == {"package_names"}++ package_names_field = by_name["package_names"]+ assert package_names_field.type == SourceFieldInputConfigType.TEXTAREA+ assert package_names_field.required is True+ # No auth, so the field carries no secret.+ assert package_names_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)++ def test_downloads_supports_incremental_versions_full_refresh_only(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["Downloads"].supports_incremental is True+ assert [f["field"] for f in schemas["Downloads"].incremental_fields] == ["day"]++ # The registry document has no server-side "changed since" filter, so Versions is always a+ # full refresh — re-fetching wouldn't reduce the amount of data pulled per sync.+ assert schemas["Versions"].supports_incremental is False+ assert schemas["Versions"].incremental_fields == []++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Versions"])++ assert [schema.name for schema in schemas] == ["Versions"]++ 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 the npm registry. Check the spelling and try again."),+ False,+ "Package 'x' was not found on the npm registry. Check the spelling and try again.",+ ),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.source.validate_packages"+ )+ 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, "Downloads")++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.package_names)++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is NpmRegistryResumeConfig++ def test_source_for_pipeline_plumbs_args(self):+ manager = mock.MagicMock()+ inputs = _make_inputs(schema_name="Downloads")+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-01"++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.source.npm_registry_source"+ ) as mock_npm_registry_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_npm_registry_source.assert_called_once_with(+ endpoint="Downloads",+ package_names="react\nlodash",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2024-01-01",+ )++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):+ manager = mock.MagicMock()+ inputs = _make_inputs(schema_name="Downloads")+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-01"++ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.npm_registry.source.npm_registry_source"+ ) as mock_npm_registry_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ assert mock_npm_registry_source.call_args.kwargs["db_incremental_field_last_value"] is None