: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 crates_io import source (#71161)
Tom Owersef3c1485ff09
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 85a8fe3554cc..c2af4d689fe4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -137,6 +137,7 @@ the row lists both.| convex | HTTP | requests | ✅ || copper | HTTP | requests | ✅ || coupa | HTTP | requests | ✅ |+| crates_io | HTTP | requests | ✅ || crunchbase | HTTP | requests | ✅ || culture_amp | HTTP | requests | ✅ || cursor | HTTP | requests | ✅ |@@ -600,7 +601,6 @@ doesn't conflict with concurrent PRs.- cosmosdb- couchbase- coveralls-- crates_io- criteo- cronitor- curvediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.pynew file mode 100644index 000000000000..4008dbc5eddc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/canonical_descriptions.py@@ -0,0 +1,95 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DATA_ACCESS_DOCS = "https://crates.io/data-access"++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "crates": {+ "description": "Crate metadata from the crates.io API crate detail endpoint, one row per configured crate.",+ "docs_url": _DATA_ACCESS_DOCS,+ "columns": {+ "id": "Globally unique crate name (the crate's identifier on crates.io).",+ "name": "Crate name as registered on crates.io.",+ "description": "Short description of the crate.",+ "created_at": "When the crate was first published.",+ "updated_at": "When the crate was last updated (new version, metadata change).",+ "downloads": "All-time download count across every version.",+ "recent_downloads": "Downloads over the last 90 days across every version.",+ "versions": "List of registry-wide numeric version ids belonging to the crate.",+ "num_versions": "Number of published versions.",+ "default_version": "Version crates.io presents by default (usually the newest non-yanked stable).",+ "max_version": "Highest version number ever published.",+ "newest_version": "Most recently published version number.",+ "max_stable_version": "Highest non-prerelease version number.",+ "yanked": "Whether every version of the crate has been yanked.",+ "keywords": "Keywords declared by the crate.",+ "categories": "crates.io category slugs the crate belongs to.",+ "badges": "Deprecated badge metadata; always empty.",+ "homepage": "Homepage URL declared by the crate.",+ "documentation": "Documentation URL declared by the crate.",+ "repository": "Source repository URL declared by the crate.",+ "links": "API paths to the crate's sub-resources (versions, owners, downloads).",+ "exact_match": "Whether the crate matched a search query exactly; always false outside search.",+ "trustpub_only": "Whether new versions may only be published via trusted publishing.",+ },+ },+ "versions": {+ "description": "Published versions across every configured crate, one row per version.",+ "docs_url": _DATA_ACCESS_DOCS,+ "columns": {+ "id": "Registry-wide unique numeric version id.",+ "crate": "Name of the crate the version belongs to.",+ "num": "Version number (semver string).",+ "created_at": "When the version was published; used as the partition key.",+ "updated_at": "When the version record was last updated (e.g. yanked).",+ "downloads": "All-time download count for this version.",+ "crate_size": "Size of the packaged .crate file in bytes.",+ "checksum": "SHA-256 checksum of the packaged .crate file.",+ "dl_path": "API path to download this version's package file.",+ "readme_path": "API path to this version's rendered README.",+ "license": "License expression declared for this version.",+ "edition": "Rust edition declared by the version (e.g. 2021).",+ "rust_version": "Minimum supported Rust version (MSRV), if declared.",+ "yanked": "Whether the version has been yanked.",+ "yank_message": "Reason given when the version was yanked, if any.",+ "published_by": "User who published the version (id, login, name, avatar).",+ "audit_actions": "Publish/yank/unyank audit trail with acting user and timestamp.",+ "features": "Cargo feature flags declared by the version.",+ "has_lib": "Whether the package contains a library target.",+ "bin_names": "Names of binary targets in the package.",+ "lib_links": "Value of the `links` manifest key, if any.",+ "linecounts": "Source line counts by language for the package.",+ "trustpub_data": "Trusted-publishing provenance metadata, if published that way.",+ "description": "Crate description at the time this version was published.",+ "homepage": "Homepage URL declared by this version.",+ "documentation": "Documentation URL declared by this version.",+ "repository": "Repository URL declared by this version.",+ },+ },+ "downloads": {+ "description": "Daily download counts per version of each configured crate, over the trailing ~90-day "+ "window the crates.io API exposes.",+ "docs_url": _DATA_ACCESS_DOCS,+ "columns": {+ "crate": "Canonical crate name (injected by the connector; not returned by the endpoint).",+ "version": "Registry-wide numeric version id, or 0 for downloads crates.io reports only in "+ "aggregate (versions outside the per-version breakdown).",+ "date": "Day the downloads were counted (UTC); used as the partition key.",+ "downloads": "Number of downloads on that day.",+ },+ },+ "owners": {+ "description": "Owners (users and teams) of each configured crate, one row per owner.",+ "docs_url": _DATA_ACCESS_DOCS,+ "columns": {+ "crate": "Canonical crate name (injected by the connector; not returned by the endpoint).",+ "id": "Registry-wide unique numeric id of the owning user or team.",+ "login": "Login of the owning user or team (teams look like `github:org:team`).",+ "kind": "Owner kind: `user` or `team`.",+ "name": "Display name of the owner.",+ "url": "Profile URL of the owner (e.g. their GitHub page).",+ "avatar": "Avatar image URL of the owner.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.pynew file mode 100644index 000000000000..3eb42de74e95--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/crates_io.py@@ -0,0 +1,357 @@+import re+import time+from collections.abc import Callable, Iterator+from typing import Any+from urllib.parse import quote++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.settings import (+ CRATES_IO_ENDPOINTS,+ CratesIOEndpointConfig,+)++CRATES_IO_BASE_URL = "https://crates.io/api/v1"++REQUEST_TIMEOUT_SECONDS = 30+MAX_RETRY_ATTEMPTS = 5++# crates.io's crawler policy requires a descriptive User-Agent identifying the app and a contact;+# requests without one are blocked.+USER_AGENT = "posthog-data-warehouse (https://posthog.com; [email protected])"++# The crawler policy also asks clients to self-throttle to roughly one request per second rather+# than parallel-hammer the API.+THROTTLE_SECONDS = 1.0++# Each configured crate costs one or two requests per enabled stream on every sync, so cap the+# config to bound worker time and outbound fan-out — a malformed/abusive config can't tie up the+# pipeline.+MAX_CRATES = 500++VERSIONS_PER_PAGE = 100++# Rows for a single crate are yielded in bounded chunks so a crate with a huge version history+# never forces one oversized in-memory Arrow conversion downstream. The pipeline batches on top of+# this, so the exact value only caps the per-yield list size.+MAX_ROWS_PER_BATCH = 5000++# crates.io only breaks daily downloads down per version for a crate's most recent versions; the+# remainder arrives in aggregate (`meta.extra_downloads`) with no version attribution. Those rows+# carry this sentinel so the `[crate, date, version]` primary key stays non-null and mergeable.+# Real crates.io version ids start at 1, so 0 can never collide.+EXTRA_DOWNLOADS_VERSION_ID = 0+++class CratesIORetryableError(Exception):+ pass+++class _RequestThrottle:+ """Spaces requests out per the crates.io crawler policy (~1 request/second)."""++ def __init__(self, interval_seconds: float) -> None:+ self._interval_seconds = interval_seconds+ self._last_request_at: float | None = None++ def wait(self) -> None:+ if self._last_request_at is not None:+ elapsed = time.monotonic() - self._last_request_at+ if elapsed < self._interval_seconds:+ time.sleep(self._interval_seconds - elapsed)+ self._last_request_at = time.monotonic()+++def _normalize_name(name: str) -> str:+ """Normalize a crate name so aliases collapse to one key.++ crates.io treats ``-`` and ``_`` as interchangeable and names as case-insensitive+ (``serde-json`` and ``serde_json`` resolve to the same crate), so we de-duplicate on this+ form. Otherwise two aliases both resolve to the same canonical crate and emit rows with a+ colliding primary key.+ """+ return re.sub(r"-", "_", name).lower()+++def parse_crates(raw: str | None) -> list[str]:+ """Parse the user's free-text ``crates`` field into a list of crate names.++ Accepts one crate per line and/or comma-separated names. Raises ``ValueError`` with an+ actionable message on empty input so the user fixes the config rather than getting a silently+ empty sync. Names are de-duplicated (on their normalized form) while preserving order.+ """+ if not raw:+ raise ValueError("At least one crate name is required.")++ crates: list[str] = []+ seen: set[str] = set()+ for token in re.split(r"[\n,]", raw):+ name = token.strip()+ if not name:+ continue+ normalized = _normalize_name(name)+ if normalized not in seen:+ seen.add(normalized)+ crates.append(name)++ if len(crates) > MAX_CRATES:+ raise ValueError(f"Too many crates: at most {MAX_CRATES} are allowed per source.")++ if not crates:+ raise ValueError("At least one crate name is required.")++ return crates+++def _crate_url(crate: str) -> str:+ # crates.io resolves name aliases itself; percent-encode the path segment so an odd character+ # can't break out of the path.+ return f"{CRATES_IO_BASE_URL}/crates/{quote(crate, safe='')}"+++@retry(+ retry=retry_if_exception_type((CratesIORetryableError, 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,+ throttle: _RequestThrottle,+ url: str,+ logger: FilteringBoundLogger,+) -> dict[str, Any] | None:+ """Fetch a single JSON document from the crates.io API.++ Returns ``None`` for a 404 (crate not found) so a typo'd or deleted crate is skipped rather+ than failing the whole sync. Transient 429/5xx raise a retryable error; other client errors+ raise ``requests.HTTPError``.+ """+ throttle.wait()+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 404:+ logger.warning(f"crates.io: resource not found, skipping: url={url}")+ return None++ if response.status_code == 429 or response.status_code >= 500:+ raise CratesIORetryableError(f"crates.io API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"crates.io API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _canonical_name(crate: str, detail: dict[str, Any]) -> str:+ """Prefer crates.io's canonical crate id over the user's spelling.++ crates.io resolves ``serde-json`` and ``Serde_JSON`` to the same crate, but sub-resource+ responses (downloads, owners) don't echo the crate name back. Stamping rows with the canonical+ id keeps primary keys stable regardless of how the user typed the crate, and keeps join keys+ aligned with the `crates` and `versions` streams.+ """+ crate_obj = detail.get("crate") or {}+ return crate_obj.get("id") or crate+++def _resolve_canonical_name(+ session: requests.Session,+ throttle: _RequestThrottle,+ crate: str,+ logger: FilteringBoundLogger,+) -> str | None:+ detail = _fetch_json(session, throttle, _crate_url(crate), logger)+ if detail is None:+ return None+ return _canonical_name(crate, detail)+++def _crate_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ crate: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per crate: the `crate` block of the detail endpoint."""+ detail = _fetch_json(session, throttle, _crate_url(crate), logger)+ if detail is None:+ return+ crate_obj = detail.get("crate")+ if isinstance(crate_obj, dict):+ yield crate_obj+++def _version_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ crate: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per published version, paginated via the API's seek cursor.++ ``meta.next_page`` is a ready-made query string (e.g. ``?per_page=100&seek=...``) or ``null``+ on the last page.+ """+ base_url = f"{_crate_url(crate)}/versions"+ next_query: str | None = f"?per_page={VERSIONS_PER_PAGE}"+ while next_query:+ document = _fetch_json(session, throttle, f"{base_url}{next_query}", logger)+ if document is None:+ return+ for version in document.get("versions") or []:+ if isinstance(version, dict):+ yield version+ next_query = (document.get("meta") or {}).get("next_page")+++def _download_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ crate: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per (crate, date, version id) from the ~90-day daily download window.++ Rows are stamped with the canonical crate name — the downloads response doesn't carry it, and+ `meta.extra_downloads` rows (aggregate downloads of versions outside the per-version breakdown)+ have no version either, so they get the sentinel version id so daily totals stay complete.+ """+ canonical = _resolve_canonical_name(session, throttle, crate, logger)+ if canonical is None:+ return+ document = _fetch_json(session, throttle, f"{_crate_url(crate)}/downloads", logger)+ if document is None:+ return++ for entry in document.get("version_downloads") or []:+ # `date` completes the primary key; a row missing it can't upsert cleanly, so skip it.+ if not isinstance(entry, dict) or not entry.get("date"):+ continue+ row = dict(entry)+ row["crate"] = canonical+ yield row++ for entry in (document.get("meta") or {}).get("extra_downloads") or []:+ if not isinstance(entry, dict) or not entry.get("date"):+ continue+ row = dict(entry)+ row["crate"] = canonical+ row["version"] = EXTRA_DOWNLOADS_VERSION_ID+ yield row+++def _owner_rows(+ session: requests.Session,+ throttle: _RequestThrottle,+ crate: str,+ logger: FilteringBoundLogger,+) -> Iterator[dict[str, Any]]:+ """One row per owner (user or team), stamped with the canonical crate name."""+ canonical = _resolve_canonical_name(session, throttle, crate, logger)+ if canonical is None:+ return+ document = _fetch_json(session, throttle, f"{_crate_url(crate)}/owners", logger)+ if document is None:+ return+ for owner in document.get("users") or []:+ if not isinstance(owner, dict):+ continue+ row = dict(owner)+ row["crate"] = canonical+ yield row+++_ROW_BUILDERS: dict[+ str, Callable[[requests.Session, _RequestThrottle, str, FilteringBoundLogger], Iterator[dict[str, Any]]]+] = {+ "crates": _crate_rows,+ "versions": _version_rows,+ "downloads": _download_rows,+ "owners": _owner_rows,+}+++def validate_credentials(crates_raw: str | None) -> tuple[bool, str | None]:+ """Confirm the config is usable by probing the first configured crate.++ crates.io's read APIs are unauthenticated, so there is no key to check; instead we confirm at+ least one crate is configured and that it resolves (200). A 404 means the crate name is wrong.+ """+ try:+ crates = parse_crates(crates_raw)+ except ValueError as exc:+ return False, str(exc)++ crate = crates[0]+ try:+ response = make_tracked_session(headers={"User-Agent": USER_AGENT}).get(+ _crate_url(crate), timeout=REQUEST_TIMEOUT_SECONDS+ )+ except Exception:+ return False, "Could not reach the crates.io API. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 404:+ return False, f"Crate '{crate}' was not found on crates.io. Check the spelling and try again."++ return False, f"crates.io API returned an unexpected status code: {response.status_code}"+++def get_rows(+ endpoint: str,+ crates: list[str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ build_rows = _ROW_BUILDERS[endpoint]+ # One session reused across every crate so urllib3 keeps the connection alive; the User-Agent+ # is mandatory under the crates.io crawler policy.+ session = make_tracked_session(headers={"User-Agent": USER_AGENT})+ throttle = _RequestThrottle(THROTTLE_SECONDS)++ for crate in crates:+ # Stream the builder into bounded chunks: a crate with a very large version history is+ # never materialized as one oversized list, and each yield caps the downstream Arrow+ # conversion. The pipeline batches on top of this.+ chunk: list[dict[str, Any]] = []+ for row in build_rows(session, throttle, crate, logger):+ chunk.append(row)+ if len(chunk) >= MAX_ROWS_PER_BATCH:+ yield chunk+ chunk = []+ if chunk:+ yield chunk+++def crates_io_source(+ endpoint: str,+ crates_raw: str | None,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ config: CratesIOEndpointConfig = CRATES_IO_ENDPOINTS[endpoint]+ crates = parse_crates(crates_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, crates=crates, logger=logger),+ primary_keys=config.primary_keys,+ # No server-side ordering to rely on; rows are grouped per crate as fetched.+ sort_mode="asc",+ **partition_kwargs,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.pynew file mode 100644index 000000000000..de8aaa55dc1a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/settings.py@@ -0,0 +1,78 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# A version's publish time never changes once released, so it's a stable partition key for the+# versions stream. Exposed as the raw ISO 8601 string crates.io already returns (`created_at`).+_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]++# A download row's date never changes; counts for a given day are final once the day is over.+_DATE_INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+ },+]+++@dataclass+class CratesIOEndpointConfig:+ name: str+ primary_keys: list[str]+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Stable datetime column used for partitioning, or `None` for streams without one.+ partition_key: Optional[str] = None+ should_sync_default: bool = True+ description: Optional[str] = None+++CRATES_IO_ENDPOINTS: dict[str, CratesIOEndpointConfig] = {+ "crates": CratesIOEndpointConfig(+ name="crates",+ # A crate's id is its globally unique name.+ primary_keys=["id"],+ description="Crate metadata: one row per configured crate, from the `crate` block of the "+ "crates.io API crate detail endpoint.",+ ),+ "versions": CratesIOEndpointConfig(+ name="versions",+ # crates.io version ids are numeric and unique across the whole registry (the downloads+ # endpoint references versions by this id alone).+ primary_keys=["id"],+ incremental_fields=list(_CREATED_AT_INCREMENTAL_FIELDS),+ partition_key="created_at",+ description="Published versions: one row per version across every configured crate.",+ ),+ "downloads": CratesIOEndpointConfig(+ name="downloads",+ # One row per crate + day + version id. Downloads crates.io only reports in aggregate+ # (versions outside the per-version breakdown) carry the sentinel version id 0.+ primary_keys=["crate", "date", "version"],+ incremental_fields=list(_DATE_INCREMENTAL_FIELDS),+ partition_key="date",+ description="Daily download counts per version of each configured crate, over the trailing "+ "~90-day window the crates.io API exposes.",+ ),+ "owners": CratesIOEndpointConfig(+ name="owners",+ # Owner (user/team) ids are global on crates.io; rows aggregate across crates.+ primary_keys=["crate", "id"],+ description="Owners (users and teams) of each configured crate.",+ ),+}++ENDPOINTS = tuple(CRATES_IO_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CRATES_IO_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.pyindex dceb004c0e9a..0782563a0926 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/source.py@@ -1,19 +1,41 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.crates_io import (+ crates_io_source,+ validate_credentials as validate_crates_io_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.settings import (+ CRATES_IO_ENDPOINTS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CratesIOSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass CratesIOSource(SimpleSource[CratesIOSourceConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CRATESIO@@ -23,8 +45,85 @@ class CratesIOSource(SimpleSource[CratesIOSourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.CRATES_IO,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="crates.io (Rust Foundation / rust-lang)",+ label="crates.io",+ releaseStatus=ReleaseStatus.ALPHA,+ keywords=["rust", "cargo", "crates"],+ caption="""Pull metadata, versions, owners, and daily download counts for Rust crates from the [crates.io](https://crates.io) API into the PostHog Data warehouse.++crates.io's read APIs are public, so no credentials are required. There is no practical way to sync the whole registry, so enter the crate names you want to track, one per line (or comma-separated). For example:++```+serde+tokio+posthog-rs+```++Each sync fetches the current data for every configured crate. crates.io has no server-side "changed since" filter, and daily download counts only cover the trailing ~90 days, so all tables sync as a full refresh.""",iconPath="/static/services/crates_io.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/crates-io",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="crates",+ label="Crates",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=True,+ placeholder="serde\ntokio\nposthog-rs",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # crates.io's read APIs are unauthenticated, so there are no credential errors to+ # permanently fail on. A missing crate surfaces as a 404 and is skipped per-crate during+ # the sync.+ return {}++ def get_schemas(+ self,+ config: CratesIOSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ # crates.io exposes no server-side timestamp filter, so no stream is truly+ # incremental; re-fetching would only duplicate immutable history, so append is+ # off too.+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=CRATES_IO_ENDPOINTS[endpoint].should_sync_default,+ description=CRATES_IO_ENDPOINTS[endpoint].description,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: CratesIOSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_crates_io_credentials(config.crates)++ def source_for_pipeline(self, config: CratesIOSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return crates_io_source(+ endpoint=inputs.schema_name,+ crates_raw=config.crates,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.pynew file mode 100644index 000000000000..db99128fed2e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io.py@@ -0,0 +1,331 @@+import json+from typing import Any, Optional++import pytest+from unittest import mock++import requests+import structlog++from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.crates_io import (+ CRATES_IO_BASE_URL,+ EXTRA_DOWNLOADS_VERSION_ID,+ MAX_CRATES,+ USER_AGENT,+ CratesIORetryableError,+ _canonical_name,+ _crate_url,+ _fetch_json,+ crates_io_source,+ get_rows,+ parse_crates,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.settings import CRATES_IO_ENDPOINTS++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.crates_io"++[email protected](autouse=True)+def _no_throttle(monkeypatch):+ # The crawler-policy throttle would add a real 1s sleep between mocked requests.+ monkeypatch.setattr(f"{MODULE}.THROTTLE_SECONDS", 0.0)+++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: {CRATES_IO_BASE_URL}", response=requests.Response()+ )+ return resp+++def _crate_detail(name: str = "serde") -> dict[str, Any]:+ return {+ "crate": {+ "id": name,+ "name": name,+ "created_at": "2014-12-05T20:20:32Z",+ "updated_at": "2025-09-27T16:51:35Z",+ "downloads": 1000,+ },+ "versions": [],+ "keywords": [],+ "categories": [],+ }+++def _versions_page(nums: list[str], next_page: str | None) -> dict[str, Any]:+ return {+ "versions": [+ {"id": index + 1, "crate": "serde", "num": num, "created_at": "2020-01-01T00:00:00Z"}+ for index, num in enumerate(nums)+ ],+ "meta": {"total": len(nums), "next_page": next_page},+ }+++def _downloads_document() -> dict[str, Any]:+ return {+ "version_downloads": [+ {"version": 1748414, "downloads": 1731354, "date": "2026-07-01"},+ {"version": 1748414, "downloads": 1650000, "date": "2026-07-02"},+ {"downloads": 5, "date": ""},+ ],+ "meta": {+ "extra_downloads": [+ {"date": "2026-07-01", "downloads": 526826},+ ]+ },+ }+++class TestParseCrates:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ ("serde", ["serde"]),+ ("serde\ntokio", ["serde", "tokio"]),+ ("serde, tokio", ["serde", "tokio"]),+ (" serde , tokio \n posthog-rs ", ["serde", "tokio", "posthog-rs"]),+ # De-duplicated while preserving order so the primary key never sees the same crate twice.+ ("serde\nserde\ntokio", ["serde", "tokio"]),+ ("serde\n\n \ntokio", ["serde", "tokio"]),+ # crates.io treats `-`/`_` as interchangeable and names as case-insensitive; both aliases+ # would resolve to the same canonical crate and emit rows with a colliding primary key.+ ("serde-json\nserde_json", ["serde-json"]),+ ("Serde\nserde", ["Serde"]),+ ],+ )+ def test_valid(self, raw, expected):+ assert parse_crates(raw) == expected++ @pytest.mark.parametrize("raw", [None, "", " \n ", " , , "])+ def test_empty_raises(self, raw):+ with pytest.raises(ValueError):+ parse_crates(raw)++ def test_rejects_too_many_crates(self):+ raw = "\n".join(f"crate{i}" for i in range(MAX_CRATES + 1))+ with pytest.raises(ValueError, match="Too many crates"):+ parse_crates(raw)++ def test_allows_max_crates(self):+ raw = "\n".join(f"crate{i}" for i in range(MAX_CRATES))+ assert len(parse_crates(raw)) == MAX_CRATES+++class TestCrateUrl:+ def test_encodes_path_segment(self):+ assert _crate_url("serde") == f"{CRATES_IO_BASE_URL}/crates/serde"+ # A stray slash must not escape the /crates/<name> path.+ assert "/" not in _crate_url("a/b").removeprefix(f"{CRATES_IO_BASE_URL}/crates/")+++class TestCanonicalName:+ def test_prefers_crate_id(self):+ assert _canonical_name("serde-json", {"crate": {"id": "serde_json"}}) == "serde_json"++ @pytest.mark.parametrize("detail", [{}, {"crate": {}}, {"crate": {"id": None}}])+ def test_falls_back_to_requested_name(self, detail):+ assert _canonical_name("serde-json", detail) == "serde-json"+++# 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]+++def _throttle() -> mock.MagicMock:+ return mock.MagicMock()+++class TestFetchJson:+ def test_ok_returns_body(self):+ session = mock.MagicMock()+ session.get.return_value = _response(200, {"crate": {"id": "serde"}})++ assert _fetch_once(session, _throttle(), "url", structlog.get_logger()) == {"crate": {"id": "serde"}}++ def test_404_returns_none(self):+ # A typo'd or deleted crate must be skipped, not fail the whole sync.+ session = mock.MagicMock()+ session.get.return_value = _response(404)++ assert _fetch_once(session, _throttle(), "url", 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(CratesIORetryableError):+ _fetch_once(session, _throttle(), "url", 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, _throttle(), "url", structlog.get_logger())+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid",+ [+ (200, True),+ (404, False),+ (500, False),+ ],+ )+ def test_status_mapping(self, status, expected_valid):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(status)++ is_valid, _ = validate_credentials("serde")++ assert is_valid is expected_valid++ def test_empty_crates_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_probes_first_crate_with_crawler_policy_user_agent(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(200)++ validate_credentials("serde\ntokio")++ called_url = mock_session.return_value.get.call_args[0][0]+ session_headers = mock_session.call_args.kwargs["headers"]++ assert called_url == f"{CRATES_IO_BASE_URL}/crates/serde"+ # crates.io blocks requests without a descriptive User-Agent.+ assert session_headers["User-Agent"] == USER_AGENT++ 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("serde")++ assert is_valid is False+ assert message is not None+++class TestGetRows:+ def test_crates_yields_a_batch_per_crate_and_skips_404(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, _crate_detail("serde")),+ _response(404),+ _response(200, _crate_detail("tokio")),+ ]++ batches = list(get_rows("crates", ["serde", "nope", "tokio"], structlog.get_logger()))++ # The 404 crate is skipped, so only two batches come back.+ assert len(batches) == 2+ assert batches[0][0]["id"] == "serde"+ assert batches[1][0]["id"] == "tokio"++ def test_versions_follows_seek_pagination(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, _versions_page(["1.0.1", "1.0.0"], next_page="?per_page=100&seek=abc")),+ _response(200, _versions_page(["0.9.0"], next_page=None)),+ ]++ batches = list(get_rows("versions", ["serde"], structlog.get_logger()))++ second_url = mock_session.return_value.get.call_args_list[1][0][0]++ assert [row["num"] for batch in batches for row in batch] == ["1.0.1", "1.0.0", "0.9.0"]+ # The follow-up request must use the API's ready-made `next_page` query string.+ assert second_url == f"{CRATES_IO_BASE_URL}/crates/serde/versions?per_page=100&seek=abc"++ def test_downloads_stamps_canonical_crate_and_sentinel_version(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ # The canonical id (`serde_json`) differs from the user's spelling (`serde-json`);+ # rows must be keyed on the canonical form so joins with `crates`/`versions` align.+ _response(200, _crate_detail("serde_json")),+ _response(200, _downloads_document()),+ ]++ batches = list(get_rows("downloads", ["serde-json"], structlog.get_logger()))++ rows = [row for batch in batches for row in batch]+ # The malformed entry without a `date` (a primary key component) is dropped.+ assert len(rows) == 3+ assert all(row["crate"] == "serde_json" for row in rows)+ # Aggregate `extra_downloads` rows carry the sentinel version id so the primary key stays+ # non-null and daily totals stay complete.+ extra_rows = [row for row in rows if row["version"] == EXTRA_DOWNLOADS_VERSION_ID]+ assert [(row["date"], row["downloads"]) for row in extra_rows] == [("2026-07-01", 526826)]++ def test_owners_stamps_canonical_crate(self):+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.side_effect = [+ _response(200, _crate_detail("serde")),+ _response(200, {"users": [{"id": 3618, "login": "dtolnay", "kind": "user"}]}),+ ]++ batches = list(get_rows("owners", ["serde"], structlog.get_logger()))++ assert batches == [[{"id": 3618, "login": "dtolnay", "kind": "user", "crate": "serde"}]]++ def test_chunks_large_version_history(self, monkeypatch):+ # A crate with a large version history must not be yielded as one oversized list; it's+ # split into bounded chunks so downstream Arrow conversion stays capped.+ monkeypatch.setattr(f"{MODULE}.MAX_ROWS_PER_BATCH", 2)+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:+ mock_session.return_value.get.return_value = _response(+ 200, _versions_page(["1.0.2", "1.0.1", "1.0.0"], next_page=None)+ )++ batches = list(get_rows("versions", ["serde"], structlog.get_logger()))++ # Three versions at 2 rows per chunk is [2, 1].+ assert [len(b) for b in batches] == [2, 1]+++class TestCratesIOSourceResponse:+ @pytest.mark.parametrize("endpoint", list(CRATES_IO_ENDPOINTS))+ def test_source_response_shape(self, endpoint):+ response = crates_io_source(endpoint, "serde", structlog.get_logger())++ assert response.name == endpoint+ assert response.primary_keys == CRATES_IO_ENDPOINTS[endpoint].primary_keys+ assert response.sort_mode == "asc"++ def test_only_streams_with_stable_dates_are_partitioned(self):+ # `versions` has a stable publish timestamp and `downloads` a stable day; `crates` and+ # `owners` have no stable datetime column.+ versions = crates_io_source("versions", "serde", structlog.get_logger())+ downloads = crates_io_source("downloads", "serde", structlog.get_logger())+ crates = crates_io_source("crates", "serde", structlog.get_logger())+ owners = crates_io_source("owners", "serde", structlog.get_logger())++ assert versions.partition_mode == "datetime"+ assert versions.partition_keys == ["created_at"]+ assert downloads.partition_mode == "datetime"+ assert downloads.partition_keys == ["date"]+ assert crates.partition_mode is None+ assert crates.partition_keys is None+ assert owners.partition_mode is None+ assert owners.partition_keys is None++ def test_invalid_crates_raise(self):+ with pytest.raises(ValueError):+ crates_io_source("crates", "", structlog.get_logger())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io_source.pynew file mode 100644index 000000000000..745297017dad--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/crates_io/tests/test_crates_io_source.py@@ -0,0 +1,127 @@+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.crates_io.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.source import CratesIOSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CratesIOSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(schema_name: str = "crates") -> 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 TestCratesIOSource:+ def setup_method(self):+ self.source = CratesIOSource()+ self.team_id = 123+ self.config = CratesIOSourceConfig(crates="serde\ntokio")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.CRATESIO++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "CratesIO"+ assert config.label == "crates.io"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/crates-io"+ # 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) == {"crates"}++ crates_field = by_name["crates"]+ assert crates_field.type == SourceFieldInputConfigType.TEXTAREA+ assert crates_field.required is True+ # No auth, so the field carries no secret.+ assert crates_field.secret is False++ def test_get_schemas_lists_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)++ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_get_schemas_full_refresh_only(self, endpoint):+ # crates.io exposes no server-side timestamp filter, so no stream is incremental or append.+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert schemas[endpoint].supports_incremental is False+ assert schemas[endpoint].supports_append is False++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["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, "Crate 'x' was not found on crates.io."), False, "Crate 'x' was not found on crates.io."),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.source.validate_crates_io_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id, "crates")++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with(self.config.crates)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.crates_io.source.crates_io_source")+ def test_source_for_pipeline_plumbs_args(self, mock_crates_io_source):+ inputs = _make_inputs(schema_name="downloads")++ self.source.source_for_pipeline(self.config, inputs)++ mock_crates_io_source.assert_called_once_with(+ endpoint="downloads",+ crates_raw="serde\ntokio",+ logger=inputs.logger,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex a5885e9d64e5..e2b09ce607d1 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@@ -1042,7 +1042,7 @@ class CoverallsSourceConfig(config.Config):@config.configclass CratesIOSourceConfig(config.Config):- pass+ crates: str@config.config