: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 packagist import source (#71151)
Tom Owers07a53a9440c3
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 253014bf96e2..8f249d51cc41 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -327,6 +327,7 @@ the row lists both.| ortto | HTTP | requests | ✅ || oura | HTTP | requests | ✅ || outbrain | HTTP | requests | ✅ |+| packagist | HTTP | requests | ✅ || paddle | HTTP | requests | ✅ || optimizely | HTTP | requests | ✅ || pagerduty | HTTP | requests | ✅ |@@ -791,7 +792,6 @@ doesn't conflict with concurrent PRs.- outreach- oveit- pabbly_subscriptions_billing-- packagist- pagerduty- pardot- paylocitydiff --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 b57fc8a3797c..3561967f745f 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@@ -3022,7 +3022,7 @@ class PabblySubscriptionsBillingSourceConfig(config.Config):@config.configclass PackagistSourceConfig(config.Config):- pass+ packages: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/canonical_descriptions.pynew file mode 100644index 000000000000..69beeed79ec6--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/canonical_descriptions.py@@ -0,0 +1,78 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "packages": {+ "description": "One row per configured package with its registry metadata: description, "+ "type, repository, download totals, favers, and GitHub stats.",+ "docs_url": "https://packagist.org/apidoc#get-package-data",+ "columns": {+ "name": "Full package name in vendor/package form. Globally unique on Packagist.",+ "description": "Short description of the package from its composer.json.",+ "time": "When the package was first published on Packagist (ISO 8601).",+ "maintainers": "Packagist users who maintain the package (name and avatar URL).",+ "type": "Composer package type, e.g. library, project, composer-plugin.",+ "repository": "URL of the package's source repository.",+ "downloads": "Download counters: total, monthly, and daily.",+ "favers": "Number of Packagist users who favorited the package.",+ "github_stars": "Star count of the package's GitHub repository, if hosted on GitHub.",+ "github_forks": "Fork count of the package's GitHub repository.",+ "github_watchers": "Watcher count of the package's GitHub repository.",+ "github_open_issues": "Open issue count of the package's GitHub repository.",+ "language": "Primary language of the repository as reported by GitHub.",+ "dependents": "Number of packages that depend on this package.",+ "suggesters": "Number of packages that suggest this package.",+ },+ },+ "versions": {+ "description": "One row per released version (and dev branch) of each configured package, "+ "with its dependencies, dist/source links, authors, and license.",+ "docs_url": "https://packagist.org/apidoc#get-package-data",+ "columns": {+ "package": "Full name (vendor/package) of the package this version belongs to.",+ "version": "Version string as published, e.g. 3.10.0 or dev-main.",+ "version_normalized": "Normalized version used by Composer for comparisons.",+ "name": "Full package name, repeated on every version object.",+ "description": "Description of the package at this version.",+ "time": "When this version was released (for dev branches: the last commit time).",+ "license": "SPDX license identifiers for this version.",+ "authors": "Authors listed in the version's composer.json.",+ "require": "Runtime dependencies as Composer package name to version constraint.",+ "require-dev": "Development dependencies of this version.",+ "dist": "Downloadable archive for this version (type, URL, reference).",+ "source": "Source repository pointer for this version (type, URL, reference).",+ "keywords": "Keywords declared in the version's composer.json.",+ "homepage": "Homepage URL declared in the version's composer.json.",+ },+ },+ "downloads": {+ "description": "Daily download statistics: one row per configured package per day, from "+ "the package download stats API.",+ "docs_url": "https://packagist.org/apidoc#get-package-stats",+ "columns": {+ "package": "Full name (vendor/package) of the package.",+ "date": "Day the downloads were counted (YYYY-MM-DD).",+ "downloads": "Number of Composer installs of the package on that day.",+ },+ },+ "security_advisories": {+ "description": "Security advisories affecting the configured packages, from the Packagist "+ "security advisories API.",+ "docs_url": "https://packagist.org/apidoc#list-security-advisories",+ "columns": {+ "advisoryId": "Packagist's unique identifier for the advisory (PKSA-...).",+ "packageName": "Full name (vendor/package) of the affected package.",+ "title": "Human-readable title of the advisory.",+ "link": "URL with details about the vulnerability.",+ "cve": "CVE identifier, when one has been assigned.",+ "affectedVersions": "Composer version constraint describing the vulnerable versions.",+ "severity": "Reported severity of the advisory, when available.",+ "reportedAt": "When the advisory was reported.",+ "source": "Primary advisory source, e.g. GitHub or FriendsOfPHP/security-advisories.",+ "sources": "All advisory sources and their remote identifiers.",+ "remoteId": "Identifier of the advisory in its source database.",+ "composerRepository": "Composer repository the advisory applies to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/packagist.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/packagist.pynew file mode 100644index 000000000000..ddb0b2f82b0d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/packagist.py@@ -0,0 +1,368 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import date, datetime+from typing import Any, Optional+from urllib.parse import quote, urlencode++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.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.settings import (+ PACKAGIST_ENDPOINTS,+ PackagistEndpointConfig,+)++PACKAGIST_BASE_URL = "https://packagist.org"++REQUEST_TIMEOUT_SECONDS = 30+MAX_RETRY_ATTEMPTS = 5++# Each configured package costs one request per enabled stream on every sync, so cap the expanded+# package list to bound worker time and outbound fan-out.+MAX_PACKAGES = 500++# The security advisories endpoint accepts many `packages[]` per request, so advisories are+# fetched in batches instead of one request per package.+ADVISORIES_BATCH_SIZE = 100++# Packagist asks API consumers to send a descriptive User-Agent with a contact address.+_HEADERS = {+ "User-Agent": "PostHog Data Warehouse (https://posthog.com; mailto:[email protected])",+ "Accept": "application/json",+}++# Rows for a single package are yielded in bounded chunks so a package with a long download+# history never forces one oversized in-memory Arrow conversion downstream.+MAX_ROWS_PER_BATCH = 5000++# Composer package names are lowercase `vendor/package`; keep validation lenient but reject+# tokens that could break out of the URL path. Alnum runs and separators alternate without+# ambiguity (each group starts with a separator) so malformed input can't trigger the+# exponential backtracking Composer's own upstream pattern is prone to.+_PACKAGE_NAME_RE = re.compile(r"^[a-z0-9]+([_.-][a-z0-9]+)*/[a-z0-9]+((_|\.|-{1,2})[a-z0-9]+)*$")+_VENDOR_NAME_RE = re.compile(r"^[a-z0-9]+([_.-][a-z0-9]+)*$")+++class PackagistRetryableError(Exception):+ pass+++class PackagistResumeConfig:+ # Index into the expanded package list (advisories: into its batch walk) of the next+ # package still to fetch.+ next_package_index: int = 0+++def parse_packages(raw: str | None) -> list[str]:+ """Parse the user's free-text ``packages`` field into a list of tokens.++ Accepts one entry per line and/or comma-separated. Each entry is either a full+ ``vendor/package`` name or a bare ``vendor`` (expanded to all of the vendor's packages at+ sync time). Composer names are lowercase, so tokens are lowercased before validation.+ Raises ``ValueError`` with an actionable message on empty or malformed input.+ """+ if not raw:+ raise ValueError("At least one package or vendor name is required.")++ tokens: list[str] = []+ seen: set[str] = set()+ for token in re.split(r"[\n,]", raw):+ name = token.strip().lower()+ if not name:+ continue+ if "/" in name:+ if not _PACKAGE_NAME_RE.match(name):+ raise ValueError(f"'{name}' is not a valid Composer package name (expected vendor/package).")+ elif not _VENDOR_NAME_RE.match(name):+ raise ValueError(f"'{name}' is not a valid Packagist vendor or package name.")+ if name not in seen:+ seen.add(name)+ tokens.append(name)++ if len(tokens) > MAX_PACKAGES:+ raise ValueError(f"Too many entries: at most {MAX_PACKAGES} are allowed per source.")++ if not tokens:+ raise ValueError("At least one package or vendor name is required.")++ return tokens+++def _package_url(package: str) -> str:+ vendor, name = package.split("/", 1)+ return f"{PACKAGIST_BASE_URL}/packages/{quote(vendor, safe='')}/{quote(name, safe='')}.json"+++def _stats_url(package: str) -> str:+ vendor, name = package.split("/", 1)+ return f"{PACKAGIST_BASE_URL}/packages/{quote(vendor, safe='')}/{quote(name, safe='')}/stats/all.json"+++def _vendor_list_url(vendor: str) -> str:+ return f"{PACKAGIST_BASE_URL}/packages/list.json?{urlencode({'vendor': vendor})}"+++def _advisories_url(packages: list[str]) -> str:+ return f"{PACKAGIST_BASE_URL}/api/security-advisories/?{urlencode([('packages[]', p) for p in packages])}"+++@retry(+ retry=retry_if_exception_type((PackagistRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict[str, Any] | None:+ """Fetch a JSON document, returning ``None`` on 404 so a typo'd or removed package is+ skipped rather than failing the whole sync. Transient 429/5xx raise a retryable error."""+ response = session.get(url, headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 404:+ logger.warning(f"Packagist: {url} returned 404, skipping")+ return None++ if response.status_code == 429 or response.status_code >= 500:+ raise PackagistRetryableError(f"Packagist API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Packagist API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def expand_vendors(session: requests.Session, tokens: list[str], logger: FilteringBoundLogger) -> list[str]:+ """Resolve bare vendor tokens into that vendor's full package list.++ ``vendor/package`` tokens pass through unchanged. Order is preserved and duplicates are+ dropped, so the resume index stays stable across attempts (Packagist returns vendor package+ lists in sorted order). The expanded list is capped at ``MAX_PACKAGES`` with a log line+ naming what was dropped — never silently.+ """+ packages: list[str] = []+ seen: set[str] = set()++ def _add(name: str) -> bool:+ if name in seen:+ return True+ if len(packages) >= MAX_PACKAGES:+ return False+ seen.add(name)+ packages.append(name)+ return True++ for token in tokens:+ if "/" in token:+ if not _add(token):+ logger.warning(f"Packagist: package list capped at {MAX_PACKAGES}; dropping {token!r} and the rest")+ break+ continue++ listing = _fetch_json(session, _vendor_list_url(token), logger)+ vendor_packages = (listing or {}).get("packageNames") or []+ if not vendor_packages:+ logger.warning(f"Packagist: vendor {token!r} has no packages, skipping")+ continue+ for name in vendor_packages:+ if not _add(name):+ logger.warning(+ f"Packagist: package list capped at {MAX_PACKAGES} while expanding vendor {token!r}; "+ "dropping the rest"+ )+ break++ return packages+++def _package_rows(document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per package: the `package` object minus its (potentially huge) versions dict."""+ package = dict(document.get("package") or {})+ if not package.get("name"):+ return+ package.pop("versions", None)+ yield package+++def _version_rows(package: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per version, stamped with `package` so the `[package, version]` key is complete."""+ package_obj = document.get("package") or {}+ canonical = package_obj.get("name") or package+ versions = package_obj.get("versions") or {}+ for version, version_obj in versions.items():+ if not isinstance(version_obj, dict):+ continue+ row = dict(version_obj)+ row["package"] = canonical+ row.setdefault("version", version)+ yield row+++def _download_rows(package: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ """One row per day from the stats endpoint's parallel `labels`/`values` arrays."""+ labels = document.get("labels") or []+ values_by_package = document.get("values") or {}+ values = values_by_package.get(package)+ if values is None and len(values_by_package) == 1:+ values = next(iter(values_by_package.values()))+ if not isinstance(values, list):+ return+ for day, downloads in zip(labels, values):+ yield {"package": package, "date": day, "downloads": downloads}+++def _advisory_rows(document: dict[str, Any]) -> Iterator[dict[str, Any]]:+ for advisories in (document.get("advisories") or {}).values():+ if not isinstance(advisories, list):+ continue+ for advisory in advisories:+ if isinstance(advisory, dict) and advisory.get("advisoryId"):+ yield advisory+++def _format_from_date(value: Any) -> str | None:+ """Coerce the incremental watermark into the `YYYY-MM-DD` string the stats endpoint takes."""+ if isinstance(value, datetime | date):+ return value.strftime("%Y-%m-%d")+ if isinstance(value, str) and re.match(r"^\d{4}-\d{2}-\d{2}", value):+ return value[:10]+ return None+++def validate_credentials(packages_raw: str | None) -> tuple[bool, str | None]:+ """Confirm the config is usable by probing the first configured entry.++ Packagist's read APIs are unauthenticated, so there is no key to check; instead we confirm+ the first package resolves (or the first vendor lists at least one package).+ """+ try:+ tokens = parse_packages(packages_raw)+ except ValueError as exc:+ return False, str(exc)++ token = tokens[0]+ session = make_tracked_session()+ is_package = "/" in token+ url = _package_url(token) if is_package else _vendor_list_url(token)+ try:+ response = session.get(url, headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)+ except Exception:+ return False, "Could not reach the Packagist API. Please try again."++ if response.status_code == 404:+ return False, f"Package '{token}' was not found on Packagist. Check the spelling and try again."+ if response.status_code != 200:+ return False, f"Packagist API returned an unexpected status code: {response.status_code}"++ if not is_package and not (response.json().get("packageNames") or []):+ return False, f"No packages were found for vendor '{token}' on Packagist."+ return True, None+++def _chunked(rows: Iterator[dict[str, Any]]) -> Iterator[list[dict[str, Any]]]:+ chunk: list[dict[str, Any]] = []+ for row in rows:+ chunk.append(row)+ if len(chunk) >= MAX_ROWS_PER_BATCH:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def get_rows(+ endpoint: str,+ tokens: list[str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PackagistResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ # One session reused across every request so urllib3 keeps the connection alive.+ session = make_tracked_session()+ packages = expand_vendors(session, tokens, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ start_index = resume.next_package_index if resume is not None else 0+ if start_index:+ logger.debug(f"Packagist: resuming {endpoint} from package index {start_index}")++ if endpoint == "security_advisories":+ for index in range(start_index, len(packages), ADVISORIES_BATCH_SIZE):+ batch = packages[index : index + ADVISORIES_BATCH_SIZE]+ document = _fetch_json(session, _advisories_url(batch), logger)+ if document is not None:+ yield from _chunked(_advisory_rows(document))+ # Save AFTER yielding so a crash re-yields the last batch rather than skipping it —+ # merge dedupes on the primary key.+ resumable_source_manager.save_state(PackagistResumeConfig(next_package_index=index + len(batch)))+ return++ from_date: str | None = None+ if endpoint == "downloads" and should_use_incremental_field:+ from_date = _format_from_date(db_incremental_field_last_value)++ for index in range(start_index, len(packages)):+ package = packages[index]++ if endpoint == "downloads":+ params = {"average": "daily"}+ if from_date is not None:+ params["from"] = from_date+ document = _fetch_json(session, f"{_stats_url(package)}?{urlencode(params)}", logger)+ rows = _download_rows(package, document) if document is not None else iter(())+ else:+ document = _fetch_json(session, _package_url(package), logger)+ if document is None:+ rows = iter(())+ elif endpoint == "packages":+ rows = _package_rows(document)+ else:+ rows = _version_rows(package, document)++ yield from _chunked(rows)+ resumable_source_manager.save_state(PackagistResumeConfig(next_package_index=index + 1))+++def packagist_source(+ endpoint: str,+ packages_raw: str | None,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PackagistResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config: PackagistEndpointConfig = PACKAGIST_ENDPOINTS[endpoint]+ tokens = 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,+ tokens=tokens,+ 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,+ # Download stats arrive in ascending date order (curl-verified); the metadata streams+ # have no server-side ordering to rely on and are grouped per package as fetched.+ sort_mode="asc",+ **partition_kwargs,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/settings.pynew file mode 100644index 000000000000..99093ea45bfd--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/settings.py@@ -0,0 +1,77 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Packagist download stats lag ~1-2 days behind real time and the trailing day is partial, so+# incremental syncs re-read a trailing window instead of freezing days at their first value.+_DOWNLOADS_LOOKBACK_SECONDS = 3 * 24 * 60 * 60++_DOWNLOADS_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class PackagistEndpointConfig:+ name: str+ primary_keys: list[str]+ # `True` only when the API endpoint takes a server-side filter (the stats endpoints'+ # `from`/`to` date window). Metadata endpoints return the full document every time.+ supports_incremental: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime/date column used for partitioning, or `None` for streams without one.+ partition_key: Optional[str] = None+ default_incremental_lookback_seconds: Optional[int] = None+ should_sync_default: bool = True+ description: Optional[str] = None+++PACKAGIST_ENDPOINTS: dict[str, PackagistEndpointConfig] = {+ "packages": PackagistEndpointConfig(+ name="packages",+ # Packagist package names (`vendor/package`) are globally unique.+ primary_keys=["name"],+ description="Package metadata: one row per configured package with description, type, "+ "repository, download totals, GitHub stats, and maintainers.",+ ),+ "versions": PackagistEndpointConfig(+ name="versions",+ # Versions aggregate across packages into one table, so the package name is part of the key.+ primary_keys=["package", "version"],+ # No partition key: tagged versions have a stable `time`, but branch versions+ # (`dev-main`, `2.x-dev`) restamp `time` on every commit, which would rewrite partitions.+ description="Package versions: one row per released version (and dev branch) of each "+ "configured package, with dependencies, dist/source links, and license.",+ ),+ "downloads": PackagistEndpointConfig(+ name="downloads",+ primary_keys=["package", "date"],+ # The stats endpoint takes a server-side `from`/`to` date window (curl-verified), so this+ # stream is genuinely incremental on `date`.+ supports_incremental=True,+ incremental_fields=list(_DOWNLOADS_INCREMENTAL_FIELDS),+ # A day's download count never moves to another day, so `date` is a stable partition key.+ partition_key="date",+ default_incremental_lookback_seconds=_DOWNLOADS_LOOKBACK_SECONDS,+ description="Daily download statistics: one row per configured package per day.",+ ),+ "security_advisories": PackagistEndpointConfig(+ name="security_advisories",+ # Advisory ids repeat across packages only via distinct packageName rows.+ primary_keys=["packageName", "advisoryId"],+ description="Security advisories affecting the configured packages, as reported by the "+ "Packagist security advisories API.",+ ),+}++ENDPOINTS = tuple(PACKAGIST_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in PACKAGIST_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/source.pyindex 483cc08be121..aad155596b16 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/source.py@@ -1,19 +1,43 @@-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 import PackagistSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.packagist import (+ PackagistResumeConfig,+ packagist_source,+ validate_credentials as validate_packagist_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ PACKAGIST_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class PackagistSource(SimpleSource[PackagistSourceConfig]):+class PackagistSource(ResumableSource[PackagistSourceConfig, PackagistResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PACKAGIST@@ -23,8 +47,95 @@ class PackagistSource(SimpleSource[PackagistSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.PACKAGIST,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Packagist (packagist.org, operated by Packagist Conductors GmbH)",+ label="Packagist",+ keywords=["composer", "php"],+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Pull metadata, download statistics, and security advisories for PHP packages from [Packagist](https://packagist.org) (the Composer package registry) into the PostHog Data warehouse.++Packagist's read APIs are public, so no credentials are required. Enter the packages you want to track, one per line (or comma-separated), as `vendor/package` names. A bare vendor name syncs every package published by that vendor. For example:++```+monolog/monolog+symfony/console+yourvendor+```++Download statistics sync incrementally per day; the other tables sync as a full refresh.""",iconPath="/static/services/packagist.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/packagist",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="packages",+ label="Packages",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="monolog/monolog\nsymfony/console\nyourvendor",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # Packagist'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.+ return {}++ def get_schemas(+ self,+ config: PackagistSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=PACKAGIST_ENDPOINTS[endpoint].supports_incremental,+ supports_append=PACKAGIST_ENDPOINTS[endpoint].supports_incremental,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=PACKAGIST_ENDPOINTS[endpoint].should_sync_default,+ description=PACKAGIST_ENDPOINTS[endpoint].description,+ default_incremental_lookback_seconds=PACKAGIST_ENDPOINTS[endpoint].default_incremental_lookback_seconds,+ )+ 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: PackagistSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_packagist_credentials(config.packages)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PackagistResumeConfig]:+ return ResumableSourceManager[PackagistResumeConfig](inputs, PackagistResumeConfig)++ def source_for_pipeline(+ self,+ config: PackagistSourceConfig,+ resumable_source_manager: ResumableSourceManager[PackagistResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return packagist_source(+ endpoint=inputs.schema_name,+ packages_raw=config.packages,+ 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/packagist/tests/test_packagist.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/tests/test_packagist.pynew file mode 100644index 000000000000..6d0c9e0f6bd3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/tests/test_packagist.py@@ -0,0 +1,449 @@+import json+from typing import Any, Optional+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.packagist import (+ MAX_PACKAGES,+ PACKAGIST_BASE_URL,+ PackagistResumeConfig,+ PackagistRetryableError,+ _advisory_rows,+ _download_rows,+ _fetch_json,+ _format_from_date,+ _package_rows,+ _package_url,+ _version_rows,+ expand_vendors,+ get_rows,+ packagist_source,+ parse_packages,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.settings import PACKAGIST_ENDPOINTS++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.packagist.packagist"+++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: {PACKAGIST_BASE_URL}", response=requests.Response()+ )+ return resp+++def _metadata_document(name: str = "monolog/monolog") -> dict[str, Any]:+ return {+ "package": {+ "name": name,+ "description": "Logging for PHP",+ "time": "2011-09-27T00:35:19+00:00",+ "downloads": {"total": 100, "monthly": 10, "daily": 1},+ "versions": {+ "3.10.0": {"name": name, "version": "3.10.0", "time": "2025-01-01T00:00:00+00:00"},+ "dev-main": {"name": name, "version": "dev-main", "time": "2026-07-01T00:00:00+00:00"},+ "bad": "not-a-dict",+ },+ }+ }+++def _stats_document(name: str = "monolog/monolog") -> dict[str, Any]:+ return {+ "labels": ["2026-07-01", "2026-07-02"],+ "values": {name: [678190, 695724]},+ "average": "daily",+ }+++def _advisories_document() -> dict[str, Any]:+ return {+ "advisories": {+ "monolog/monolog": [+ {"advisoryId": "PKSA-1", "packageName": "monolog/monolog", "title": "Header injection"},+ {"packageName": "monolog/monolog", "title": "missing id, skipped"},+ ],+ "empty/package": "not-a-list",+ }+ }+++class _FakeResumableManager:+ def __init__(self, state: PackagistResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[PackagistResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> PackagistResumeConfig | None:+ return self._state++ def save_state(self, data: PackagistResumeConfig) -> None:+ self.saved.append(data)+++class TestParsePackages:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("monolog/monolog", ["monolog/monolog"]),+ ("monolog/monolog\nsymfony/console", ["monolog/monolog", "symfony/console"]),+ ("monolog/monolog, symfony/console", ["monolog/monolog", "symfony/console"]),+ # A bare vendor token is kept as-is for sync-time expansion.+ ("symfony", ["symfony"]),+ # Composer names are lowercase; user input is normalized before validation.+ ("Monolog/Monolog", ["monolog/monolog"]),+ ("monolog/monolog\nMONOLOG/MONOLOG", ["monolog/monolog"]),+ ("monolog/monolog\n\n \nsymfony", ["monolog/monolog", "symfony"]),+ # Separator shapes Composer allows: `.`/`_`/`-` in both halves, `--` in the package half.+ ("my-vendor/my_package.name", ["my-vendor/my_package.name"]),+ ("vendor.name/pkg--name", ["vendor.name/pkg--name"]),+ ],+ )+ 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)++ @pytest.mark.parametrize(+ "raw",+ [+ # Path-traversal or URL-breaking tokens must be rejected, not fetched.+ "../etc/passwd",+ "monolog/mono/log",+ "monolog/",+ "/monolog",+ "monolog monolog",+ "a--b",+ # Long almost-valid tokens must be rejected in linear time — with ambiguous nested+ # quantifiers in the name regexes these hang the API worker (ReDoS) instead.+ "a" * 5000 + "!",+ "vendor/" + "a" * 5000 + "!",+ ],+ )+ def test_malformed_raises(self, raw):+ with pytest.raises(ValueError):+ parse_packages(raw)++ def test_rejects_too_many_entries(self):+ raw = "\n".join(f"vendor{i}/pkg" for i in range(MAX_PACKAGES + 1))+ with pytest.raises(ValueError, match="Too many entries"):+ parse_packages(raw)+++class TestExpandVendors:+ def test_expands_vendor_tokens_and_passes_packages_through(self):+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"packageNames": ["symfony/console", "symfony/yaml"]})++ packages = expand_vendors(session, ["monolog/monolog", "symfony", "symfony/console"], structlog.get_logger())++ # Vendor expands in place; the duplicate of an already-expanded package is dropped.+ assert packages == ["monolog/monolog", "symfony/console", "symfony/yaml"]+ session.get.assert_called_once()+ assert "vendor=symfony" in session.get.call_args[0][0]++ def test_unknown_vendor_is_skipped(self):+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"packageNames": []})++ packages = expand_vendors(session, ["ghost-vendor", "monolog/monolog"], structlog.get_logger())++ assert packages == ["monolog/monolog"]++ def test_expansion_is_capped(self, monkeypatch):+ monkeypatch.setattr(f"{MODULE}.MAX_PACKAGES", 3)+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"packageNames": [f"big/pkg{i}" for i in range(10)]})++ packages = expand_vendors(session, ["big"], structlog.get_logger())++ assert packages == ["big/pkg0", "big/pkg1", "big/pkg2"]+++# tenacity exposes the undecorated function via `__wrapped__` so status classification can be+# asserted without waiting through retry backoff.+_fetch_once = _fetch_json.__wrapped__ # type: ignore[attr-defined]+++class TestFetchJson:+ def test_404_returns_none(self):+ session = mock.MagicMock()+ session.get.return_value = _response(404)++ assert _fetch_once(session, "https://packagist.org/x", 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(PackagistRetryableError):+ _fetch_once(session, "https://packagist.org/x", 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, "https://packagist.org/x", structlog.get_logger())+++class TestRowBuilders:+ def test_package_rows_drop_versions(self):+ rows = list(_package_rows(_metadata_document()))++ assert len(rows) == 1+ assert rows[0]["name"] == "monolog/monolog"+ assert "versions" not in rows[0]++ def test_package_rows_skip_document_without_name(self):+ assert list(_package_rows({"package": {}})) == []++ def test_version_rows_stamp_package_and_skip_malformed(self):+ rows = list(_version_rows("monolog/monolog", _metadata_document()))++ # The "bad" (non-dict) version entry is skipped.+ assert {(r["package"], r["version"]) for r in rows} == {+ ("monolog/monolog", "3.10.0"),+ ("monolog/monolog", "dev-main"),+ }++ def test_download_rows_zip_labels_and_values(self):+ rows = list(_download_rows("monolog/monolog", _stats_document()))++ assert rows == [+ {"package": "monolog/monolog", "date": "2026-07-01", "downloads": 678190},+ {"package": "monolog/monolog", "date": "2026-07-02", "downloads": 695724},+ ]++ def test_download_rows_fall_back_to_single_values_entry(self):+ # Packagist keys `values` by its canonical spelling, which can differ from the requested+ # token; with exactly one entry the mismatch must not drop the whole stream.+ document = {"labels": ["2026-07-01"], "values": {"Monolog/Monolog": [5]}}++ rows = list(_download_rows("monolog/monolog", document))++ assert rows == [{"package": "monolog/monolog", "date": "2026-07-01", "downloads": 5}]++ def test_advisory_rows_flatten_and_require_advisory_id(self):+ rows = list(_advisory_rows(_advisories_document()))++ assert len(rows) == 1+ assert rows[0]["advisoryId"] == "PKSA-1"+++class TestFormatFromDate:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("2026-07-01", "2026-07-01"),+ ("2026-07-01T12:34:56+00:00", "2026-07-01"),+ (None, None),+ ("not-a-date", None),+ ],+ )+ def test_strings(self, value, expected):+ assert _format_from_date(value) == expected++ def test_date_and_datetime(self):+ from datetime import date, datetime++ assert _format_from_date(date(2026, 7, 1)) == "2026-07-01"+ assert _format_from_date(datetime(2026, 7, 1, 12, 30)) == "2026-07-01"+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid",+ [+ (200, True),+ (404, False),+ (500, False),+ ],+ )+ def test_package_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, {"package": {"name": "monolog/monolog"}})++ is_valid, _ = validate_credentials("monolog/monolog")++ assert is_valid is expected_valid++ def test_vendor_with_no_packages_is_invalid(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200, {"packageNames": []})++ is_valid, message = validate_credentials("ghost-vendor")++ assert is_valid is False+ assert message is not None and "ghost-vendor" in message++ def test_empty_config_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("monolog/monolog")++ assert is_valid is False+ assert message is not None+++class TestGetRows:+ def _run(+ self,+ endpoint: str,+ responses: list[mock.MagicMock],+ manager: _FakeResumableManager | None = None,+ tokens: list[str] | None = None,+ **kwargs: Any,+ ) -> tuple[list[list[dict[str, Any]]], mock.MagicMock, _FakeResumableManager]:+ manager = manager or _FakeResumableManager()+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = responses+ batches = list(+ get_rows(+ endpoint,+ tokens or ["monolog/monolog", "symfony/console"],+ structlog.get_logger(),+ manager, # type: ignore[arg-type]+ **kwargs,+ )+ )+ return batches, mock_session.return_value, manager++ def test_yields_per_package_and_skips_404(self):+ batches, _, _ = self._run(+ "packages",+ [+ _response(200, _metadata_document("monolog/monolog")),+ _response(404),+ ],+ )++ assert len(batches) == 1+ assert batches[0][0]["name"] == "monolog/monolog"++ def test_saves_state_after_each_package(self):+ _, _, manager = self._run(+ "packages",+ [+ _response(200, _metadata_document("monolog/monolog")),+ _response(200, _metadata_document("symfony/console")),+ ],+ )++ assert manager.saved == [+ PackagistResumeConfig(next_package_index=1),+ PackagistResumeConfig(next_package_index=2),+ ]++ def test_resumes_from_saved_state(self):+ batches, session, _ = self._run(+ "packages",+ [_response(200, _metadata_document("symfony/console"))],+ manager=_FakeResumableManager(PackagistResumeConfig(next_package_index=1)),+ )++ # Only the second package is fetched; the first was completed before the crash.+ session.get.assert_called_once()+ assert session.get.call_args[0][0] == _package_url("symfony/console")+ assert batches[0][0]["name"] == "symfony/console"++ def test_downloads_passes_from_param_only_when_incremental(self):+ _, session, _ = self._run(+ "downloads",+ [_response(200, _stats_document())],+ tokens=["monolog/monolog"],+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )+ query = parse_qs(urlparse(session.get.call_args[0][0]).query)+ assert query == {"average": ["daily"], "from": ["2026-07-01"]}++ _, session, _ = self._run(+ "downloads",+ [_response(200, _stats_document())],+ tokens=["monolog/monolog"],+ should_use_incremental_field=False,+ )+ query = parse_qs(urlparse(session.get.call_args[0][0]).query)+ assert query == {"average": ["daily"]}++ def test_advisories_are_batched_and_state_advances_by_batch(self, monkeypatch):+ monkeypatch.setattr(f"{MODULE}.ADVISORIES_BATCH_SIZE", 2)+ tokens = ["a/one", "b/two", "c/three"]++ batches, session, manager = self._run(+ "security_advisories",+ [_response(200, _advisories_document()), _response(200, {"advisories": {}})],+ tokens=tokens,+ )++ assert session.get.call_count == 2+ first_query = parse_qs(urlparse(session.get.call_args_list[0][0][0]).query)+ assert first_query == {"packages[]": ["a/one", "b/two"]}+ assert manager.saved == [+ PackagistResumeConfig(next_package_index=2),+ PackagistResumeConfig(next_package_index=3),+ ]+ assert len(batches) == 1++ def test_chunks_large_row_sets(self, monkeypatch):+ monkeypatch.setattr(f"{MODULE}.MAX_ROWS_PER_BATCH", 1)++ batches, _, _ = self._run(+ "downloads",+ [_response(200, _stats_document())],+ tokens=["monolog/monolog"],+ )++ # The stats document has 2 days; at 1 row per chunk that's two batches.+ assert [len(b) for b in batches] == [1, 1]+++class TestPackagistSource:+ @pytest.mark.parametrize("endpoint", list(PACKAGIST_ENDPOINTS))+ def test_source_response_shape(self, endpoint):+ response = packagist_source(endpoint, "monolog/monolog", structlog.get_logger(), _FakeResumableManager()) # type: ignore[arg-type]++ assert response.name == endpoint+ assert response.primary_keys == PACKAGIST_ENDPOINTS[endpoint].primary_keys+ assert response.sort_mode == "asc"++ def test_only_downloads_is_partitioned(self):+ downloads = packagist_source("downloads", "monolog/monolog", structlog.get_logger(), _FakeResumableManager()) # type: ignore[arg-type]+ packages = packagist_source("packages", "monolog/monolog", structlog.get_logger(), _FakeResumableManager()) # type: ignore[arg-type]++ assert downloads.partition_mode == "datetime"+ assert downloads.partition_keys == ["date"]+ assert packages.partition_mode is None+ assert packages.partition_keys is None++ def test_invalid_packages_raise(self):+ with pytest.raises(ValueError):+ packagist_source("packages", "", structlog.get_logger(), _FakeResumableManager()) # type: ignore[arg-type]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/tests/test_packagist_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/tests/test_packagist_source.pynew file mode 100644index 000000000000..f2285d76afee--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/packagist/tests/test_packagist_source.py@@ -0,0 +1,160 @@+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 PackagistSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.packagist import PackagistResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.packagist.source import PackagistSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(+ schema_name: str = "packages",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: str | None = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=123,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="date" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-id",+ logger=structlog.get_logger(),+ reset_pipeline=False,+ )+++class TestPackagistSource:+ def setup_method(self):+ self.source = PackagistSource()+ self.team_id = 123+ self.config = PackagistSourceConfig(packages="monolog/monolog\nsymfony/console")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.PACKAGIST++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Packagist"+ assert config.label == "Packagist"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/packagist"+ # A finished source must be visible in the wizard, not hidden behind unreleasedSource.+ 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) == {"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_incremental_flags(self, endpoint):+ # Only the download stats endpoint has a server-side date-window filter; the metadata+ # endpoints return the full document every time, so they are full refresh only.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ expected = endpoint == "downloads"+ assert schemas[endpoint].supports_incremental is expected+ assert schemas[endpoint].supports_append is expected++ def test_downloads_has_incremental_lookback(self):+ # Packagist stats lag behind real time, so incremental syncs re-read a trailing window.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas["downloads"].default_incremental_lookback_seconds == 3 * 24 * 60 * 60+ assert schemas["packages"].default_incremental_lookback_seconds is None++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["downloads"])++ assert [schema.name for schema in schemas] == ["downloads"]++ 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",+ [+ (True, None),+ (False, "Package 'x' was not found on Packagist."),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.packagist.source.validate_packagist_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, "packages")++ assert result == mock_return+ mock_validate.assert_called_once_with(self.config.packages)++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(_make_inputs())++ assert manager._data_class is PackagistResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.packagist.source.packagist_source")+ def test_source_for_pipeline_plumbs_args(self, mock_packagist_source):+ inputs = _make_inputs(+ schema_name="downloads", should_use_incremental_field=True, db_incremental_field_last_value="2026-07-01"+ )+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_packagist_source.assert_called_once_with(+ endpoint="downloads",+ packages_raw="monolog/monolog\nsymfony/console",+ logger=inputs.logger,+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-07-01",+ )++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.packagist.source.packagist_source")+ def test_source_for_pipeline_drops_watermark_when_not_incremental(self, mock_packagist_source):+ # A stale watermark from a previous incremental run must not leak into a full refresh.+ inputs = _make_inputs(schema_name="downloads", db_incremental_field_last_value="2026-07-01")++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_packagist_source.call_args.kwargs["db_incremental_field_last_value"] is None