Skip to content

: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.

feat(data-warehouse): add RubyGems.org source (#73201)

Tom Owers457f19b648db
diff --git a/frontend/public/services/rubygems.png b/frontend/public/services/rubygems.png
index c5736e43b50d..b569bf8442e1 100644
Binary files a/frontend/public/services/rubygems.png and b/frontend/public/services/rubygems.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index afdd7a81f42b..008c8d088b25 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -480,6 +480,7 @@ the row lists both.
| rollbar | HTTP | requests | ✅ |
| rootly | HTTP | requests | ✅ |
| rss | HTTP | requests | ✅ |
+| rubygems | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
| runpod | HTTP | requests | ✅ |
| safetyculture | HTTP | requests | ✅ |
@@ -1224,7 +1225,6 @@ doesn't conflict with concurrent PRs.
- rocket_matter
- rocketlane
- rss
-- rubygems
- rudderstack
- safetyculture
- sage_intacct
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rubygems.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rubygems.py
index 22f017f8ce44..518949193403 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rubygems.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/rubygems.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class RubygemsSourceConfig(config.Config):
- pass
+ gems: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/canonical_descriptions.py
new file mode 100644
index 000000000000..f01f0b99d9eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/canonical_descriptions.py
@@ -0,0 +1,60 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_API_DOCS = "https://guides.rubygems.org/rubygems-org-api/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "gems": {
+ "description": "Current metadata and cumulative download count for each configured gem, one row per gem.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "name": "Gem name, as registered on RubyGems.org.",
+ "downloads": "Total cumulative downloads of the gem across all versions and platforms.",
+ "version": "Latest published version number.",
+ "version_created_at": "Timestamp the latest version was published.",
+ "version_downloads": "Cumulative downloads of the latest version.",
+ "platform": "Platform of the latest version (e.g. ruby, java).",
+ "authors": "Comma-separated list of gem authors.",
+ "info": "Gem description/summary text.",
+ "licenses": "List of licenses declared by the gem.",
+ "metadata": "Free-form metadata map declared in the gemspec (changelog/source/docs URIs, etc.).",
+ "yanked": "Whether the latest version has been yanked.",
+ "sha": "SHA-256 checksum of the latest version's `.gem` file.",
+ "project_uri": "Canonical RubyGems.org page for the gem.",
+ "gem_uri": "Direct download URL for the latest version's `.gem` file.",
+ "homepage_uri": "Project homepage URL, if declared.",
+ "wiki_uri": "Project wiki URL, if declared.",
+ "documentation_uri": "Hosted documentation URL, if declared.",
+ "mailing_list_uri": "Mailing list URL, if declared.",
+ "source_code_uri": "Source code repository URL, if declared.",
+ "bug_tracker_uri": "Issue tracker URL, if declared.",
+ "changelog_uri": "Changelog URL, if declared.",
+ "funding_uri": "Funding/sponsorship URL, if declared.",
+ "dependencies": "Runtime and development dependencies of the latest version.",
+ },
+ },
+ "versions": {
+ "description": "Every published version of each configured gem, including per-version download counts.",
+ "docs_url": _API_DOCS,
+ "columns": {
+ "gem_name": "Gem the version belongs to (injected by the connector).",
+ "number": "Version number (e.g. 1.2.3).",
+ "platform": "Build platform this version was published for (e.g. ruby, java, x86_64-linux).",
+ "created_at": "Timestamp the version was published; used as the partition key.",
+ "built_at": "Timestamp the version's gemspec reports as its build time.",
+ "summary": "Short one-line summary of the gem at this version.",
+ "description": "Long description of the gem at this version.",
+ "authors": "Comma-separated list of authors at this version.",
+ "licenses": "List of licenses declared at this version.",
+ "downloads_count": "Cumulative downloads of this specific version.",
+ "metadata": "Free-form metadata map declared in the gemspec at this version.",
+ "ruby_version": "Ruby version requirement declared at this version, if any.",
+ "rubygems_version": "RubyGems version requirement declared at this version, if any.",
+ "prerelease": "Whether this version is a prerelease.",
+ "requirements": "Native extension build requirements, if any.",
+ "sha": "SHA-256 checksum of this version's `.gem` file.",
+ "spec_sha": "SHA-256 checksum of this version's gemspec.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/rubygems.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/rubygems.py
new file mode 100644
index 000000000000..d76dbcd2e0a4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/rubygems.py
@@ -0,0 +1,223 @@
+import re
+from collections.abc import Callable, Iterator
+from typing import Any
+from urllib.parse import quote
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.settings import (
+ RUBYGEMS_ENDPOINTS,
+ RubyGemsEndpointConfig,
+)
+
+RUBYGEMS_BASE_URL = "https://rubygems.org/api/v1"
+
+REQUEST_TIMEOUT_SECONDS = 30
+MAX_RETRY_ATTEMPTS = 5
+
+# Each configured gem costs one request per enabled stream on every sync (full refresh, no bulk
+# enumeration endpoint exists), so cap the config to bound worker time and outbound fan-out.
+MAX_GEMS = 500
+
+_HEADERS = {"Accept": "application/json"}
+
+# Rows for a single gem are yielded in bounded chunks so a gem with a very large 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
+
+
+class RubyGemsRetryableError(Exception):
+ pass
+
+
+def parse_gems(raw: str | None) -> list[str]:
+ """Parse the user's free-text ``gems`` field into a list of gem names.
+
+ Accepts one gem 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 while preserving order.
+ """
+ if not raw:
+ raise ValueError("At least one gem name is required.")
+
+ gems: list[str] = []
+ seen: set[str] = set()
+ for token in re.split(r"[\n,]", raw):
+ name = token.strip()
+ if not name:
+ continue
+ if name not in seen:
+ seen.add(name)
+ gems.append(name)
+
+ if len(gems) > MAX_GEMS:
+ raise ValueError(f"Too many gems: at most {MAX_GEMS} are allowed per source.")
+
+ if not gems:
+ raise ValueError("At least one gem name is required.")
+
+ return gems
+
+
+def _gem_url(gem: str) -> str:
+ # RubyGems.org resolves the gem name as-is; percent-encode the path segment so an odd
+ # character can't break out of the path.
+ return f"{RUBYGEMS_BASE_URL}/gems/{quote(gem, safe='')}.json"
+
+
+def _versions_url(gem: str) -> str:
+ return f"{RUBYGEMS_BASE_URL}/versions/{quote(gem, safe='')}.json"
+
+
+@retry(
+ retry=retry_if_exception_type((RubyGemsRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, url: str, gem: str, logger: FilteringBoundLogger) -> Any | None:
+ """Fetch a single JSON document.
+
+ Returns ``None`` for a 404 (gem not found) so a typo'd or unpublished gem is skipped rather
+ than failing the whole sync. Transient 429/5xx raise a retryable error; other client errors
+ raise ``requests.HTTPError``.
+ """
+ response = session.get(url, headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 404:
+ logger.warning(f"RubyGems: gem {gem!r} not found, skipping")
+ return None
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise RubyGemsRetryableError(f"RubyGems API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"RubyGems API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _gem_rows(gem: str, document: dict[str, Any]) -> Iterator[dict[str, Any]]:
+ """One row per gem: the full `/gems/{name}.json` document, stamped with the requested name."""
+ row = dict(document)
+ # `name` is the primary key; fall back to the requested gem if the API omits it.
+ row.setdefault("name", gem)
+ yield row
+
+
+def _version_rows(gem: str, versions: list[Any]) -> Iterator[dict[str, Any]]:
+ """One row per published version of a gem, stamped with the parent `gem_name`.
+
+ `gem_name` completes the `[gem_name, number, platform]` primary key: version numbers repeat
+ across platforms (e.g. native-extension gems publishing separate `ruby`/`java` builds) and rows
+ aggregate across every configured gem.
+ """
+ for version in versions:
+ if not isinstance(version, dict):
+ continue
+ # `number` and `platform` are part of the primary key; a version object missing either
+ # would merge with a null key component, so skip it rather than emit an unmergeable row.
+ if not version.get("number") or not version.get("platform"):
+ continue
+ row = dict(version)
+ row["gem_name"] = gem
+ yield row
+
+
+_ROW_BUILDERS: dict[str, Callable[[str, Any], Iterator[dict[str, Any]]]] = {
+ "gems": _gem_rows,
+ "versions": _version_rows,
+}
+
+
+def validate_credentials(gems_raw: str | None) -> tuple[bool, str | None]:
+ """Confirm the config is usable by probing the first configured gem.
+
+ RubyGems.org's read APIs are unauthenticated, so there is no key to check; instead we confirm
+ at least one gem is configured and that it resolves (200). A 404 means the gem name is wrong.
+ """
+ try:
+ gems = parse_gems(gems_raw)
+ except ValueError as exc:
+ return False, str(exc)
+
+ gem = gems[0]
+ try:
+ response = make_tracked_session().get(_gem_url(gem), headers=_HEADERS, timeout=REQUEST_TIMEOUT_SECONDS)
+ except Exception:
+ return False, "Could not reach the RubyGems.org API. Please try again."
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 404:
+ return False, f"Gem '{gem}' was not found on RubyGems.org. Check the spelling and try again."
+
+ return False, f"RubyGems.org API returned an unexpected status code: {response.status_code}"
+
+
+def get_rows(
+ endpoint: str,
+ gems: list[str],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ # One session reused across every gem so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ for gem in gems:
+ if endpoint == "gems":
+ document = _fetch(session, _gem_url(gem), gem, logger)
+ if document is None:
+ continue
+ source_data: Any = document
+ else:
+ versions = _fetch(session, _versions_url(gem), gem, logger)
+ if versions is None:
+ continue
+ source_data = versions if isinstance(versions, list) else []
+
+ build_rows = _ROW_BUILDERS[endpoint]
+ # Stream the builder into bounded chunks: a gem 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(gem, source_data):
+ chunk.append(row)
+ if len(chunk) >= MAX_ROWS_PER_BATCH:
+ yield chunk
+ chunk = []
+ if chunk:
+ yield chunk
+
+
+def rubygems_source(
+ endpoint: str,
+ gems_raw: str | None,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config: RubyGemsEndpointConfig = RUBYGEMS_ENDPOINTS[endpoint]
+ gems = parse_gems(gems_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, gems=gems, logger=logger),
+ primary_keys=config.primary_keys,
+ # No server-side ordering to rely on; rows are grouped per gem as fetched.
+ sort_mode="asc",
+ **partition_kwargs,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/settings.py
new file mode 100644
index 000000000000..8c51e6ab9afb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/settings.py
@@ -0,0 +1,55 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# A version's `created_at` never changes once published, so it's a stable partition key for the
+# versions stream. `gems` has no comparable stable timestamp (its `downloads`/`version` fields
+# mutate as new releases land), so it's left unpartitioned.
+_CREATED_AT_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass
+class RubyGemsEndpointConfig:
+ 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
+
+
+RUBYGEMS_ENDPOINTS: dict[str, RubyGemsEndpointConfig] = {
+ "gems": RubyGemsEndpointConfig(
+ name="gems",
+ # Gem names are globally unique on RubyGems.org.
+ primary_keys=["name"],
+ description="Current metadata and cumulative download count for each configured gem, from "
+ "GET /api/v1/gems/{name}.json.",
+ ),
+ "versions": RubyGemsEndpointConfig(
+ name="versions",
+ # A version `number` is unique per gem, but can repeat across platforms (e.g. a native
+ # extension gem publishing separate `ruby` and `java` builds of the same version), and
+ # rows aggregate across every configured gem, so all three fields together form the key.
+ primary_keys=["gem_name", "number", "platform"],
+ incremental_fields=list(_CREATED_AT_INCREMENTAL_FIELDS),
+ partition_key="created_at",
+ description="Every published version of each configured gem, including per-version download "
+ "counts, from GET /api/v1/versions/{name}.json.",
+ ),
+}
+
+ENDPOINTS = tuple(RUBYGEMS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in RUBYGEMS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/source.py
index 03254d848e35..2abc8fc44a49 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/source.py
@@ -1,21 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from 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.generated_configs.rubygems import (
RubygemsSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.rubygems import (
+ rubygems_source,
+ validate_credentials as validate_rubygems_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ RUBYGEMS_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class RubygemsSource(SimpleSource[RubygemsSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://guides.rubygems.org/rubygems-org-api/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RUBYGEMS
@@ -26,7 +49,86 @@ class RubygemsSource(SimpleSource[RubygemsSourceConfig]):
name=SchemaExternalDataSourceType.RUBYGEMS,
category=DataWarehouseSourceCategory.ANALYTICS,
label="RubyGems.org",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Pull gem metadata and version/download history from [RubyGems.org](https://rubygems.org) into the PostHog Data warehouse.
+
+RubyGems.org's read APIs are public, so no credentials are required. There is no list endpoint, so enter the gem names you want to track, one per line (or comma-separated). For example:
+
+```
+rails
+rspec
+devise
+```
+
+Each sync fetches the current metadata and full version history for every configured gem. RubyGems.org has no server-side "changed since" filter, so all tables sync as a full refresh.""",
iconPath="/static/services/rubygems.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/rubygems",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="gems",
+ label="Gems",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="rails\nrspec\ndevise",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # RubyGems.org's read APIs are unauthenticated, so there are no credential errors to
+ # permanently fail on. A missing gem surfaces as a 404 and is skipped per-gem during sync.
+ return {}
+
+ def get_schemas(
+ self,
+ config: RubygemsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # RubyGems.org 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=RUBYGEMS_ENDPOINTS[endpoint].should_sync_default,
+ description=RUBYGEMS_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: RubygemsSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_rubygems_credentials(config.gems)
+
+ def source_for_pipeline(self, config: RubygemsSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return rubygems_source(
+ endpoint=inputs.schema_name,
+ gems_raw=config.gems,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems.py
new file mode 100644
index 000000000000..9889b0db5ecf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems.py
@@ -0,0 +1,305 @@
+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.rubygems.rubygems import (
+ MAX_GEMS,
+ RUBYGEMS_BASE_URL,
+ RubyGemsRetryableError,
+ _fetch,
+ _gem_rows,
+ _gem_url,
+ _version_rows,
+ _versions_url,
+ get_rows,
+ parse_gems,
+ rubygems_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.settings import RUBYGEMS_ENDPOINTS
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.rubygems"
+
+
+def _response(status: int = 200, body: Optional[Any] = None) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status
+ resp.ok = 200 <= status < 300
+ resp.json.return_value = body if body is not None else {}
+ resp.text = json.dumps(body if body is not None else {})
+ if not resp.ok:
+ resp.raise_for_status.side_effect = requests.HTTPError(
+ f"{status} Client Error for url: {RUBYGEMS_BASE_URL}", response=requests.Response()
+ )
+ return resp
+
+
+def _gem_document(name: str = "rails") -> dict[str, Any]:
+ return {
+ "name": name,
+ "downloads": 766763345,
+ "version": "8.1.3",
+ "version_downloads": 10458162,
+ "platform": "ruby",
+ "authors": "David Heinemeier Hansson",
+ "licenses": ["MIT"],
+ }
+
+
+def _versions_document(name: str = "rails") -> list[Any]:
+ return [
+ {
+ "number": "8.1.3",
+ "platform": "ruby",
+ "created_at": "2026-03-24T20:27:42.098Z",
+ "downloads_count": 10463551,
+ "authors": name,
+ },
+ {
+ "number": "8.1.2.1",
+ "platform": "ruby",
+ "created_at": "2026-03-23T19:45:37.709Z",
+ "downloads_count": 1093372,
+ },
+ "not-a-dict",
+ {"number": "8.1.2.1", "platform": None}, # missing platform: unmergeable, must be dropped
+ {"number": None, "platform": "ruby"}, # missing number: unmergeable, must be dropped
+ ]
+
+
+class TestParseGems:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("rails", ["rails"]),
+ ("rails\nrspec", ["rails", "rspec"]),
+ ("rails, rspec", ["rails", "rspec"]),
+ (" rails , rspec \n devise ", ["rails", "rspec", "devise"]),
+ # De-duplicated while preserving order so the primary key never sees the same gem twice.
+ ("rails\nrails\nrspec", ["rails", "rspec"]),
+ ("rails\n\n \nrspec", ["rails", "rspec"]),
+ ],
+ )
+ def test_valid(self, raw, expected):
+ assert parse_gems(raw) == expected
+
+ @pytest.mark.parametrize("raw", [None, "", " \n ", " , , "])
+ def test_empty_raises(self, raw):
+ with pytest.raises(ValueError):
+ parse_gems(raw)
+
+ def test_rejects_too_many_gems(self):
+ raw = "\n".join(f"gem{i}" for i in range(MAX_GEMS + 1))
+ with pytest.raises(ValueError, match="Too many gems"):
+ parse_gems(raw)
+
+ def test_allows_max_gems(self):
+ raw = "\n".join(f"gem{i}" for i in range(MAX_GEMS))
+ assert len(parse_gems(raw)) == MAX_GEMS
+
+
+class TestUrls:
+ def test_gem_url_encodes_path_segment(self):
+ assert _gem_url("rails") == f"{RUBYGEMS_BASE_URL}/gems/rails.json"
+ assert "/" not in _gem_url("a/b").removeprefix(f"{RUBYGEMS_BASE_URL}/gems/").removesuffix(".json")
+
+ def test_versions_url_encodes_path_segment(self):
+ assert _versions_url("rails") == f"{RUBYGEMS_BASE_URL}/versions/rails.json"
+
+
+class TestGemRows:
+ def test_single_row_stamped_with_name(self):
+ rows = list(_gem_rows("rails", _gem_document()))
+
+ assert len(rows) == 1
+ assert rows[0]["name"] == "rails"
+ assert rows[0]["downloads"] == 766763345
+
+ def test_name_falls_back_to_requested_when_missing(self):
+ rows = list(_gem_rows("rails", {"downloads": 1}))
+
+ assert rows[0]["name"] == "rails"
+
+
+class TestVersionRows:
+ def test_one_row_per_version_stamped_with_gem_name(self):
+ rows = list(_version_rows("rails", _versions_document()))
+
+ # The malformed string entry and both entries missing number/platform are skipped.
+ assert len(rows) == 2
+ keys = {(r["gem_name"], r["number"], r["platform"]) for r in rows}
+ assert ("rails", "8.1.3", "ruby") in keys
+ assert ("rails", "8.1.2.1", "ruby") in keys
+ assert all(r["gem_name"] == "rails" for r in rows)
+
+ def test_handles_empty_versions(self):
+ assert list(_version_rows("rails", [])) == []
+
+ def test_skips_versions_missing_number_or_platform(self):
+ versions = [
+ {"number": "1.0.0", "platform": "ruby"},
+ {"number": "1.0.0", "platform": None},
+ {"number": None, "platform": "ruby"},
+ {"number": "", "platform": "ruby"},
+ ]
+
+ rows = list(_version_rows("rails", versions))
+
+ assert [r["number"] for r in rows] == ["1.0.0"]
+
+
+# tenacity exposes the undecorated function via `__wrapped__` so status classification can be
+# asserted without waiting through retry backoff.
+_fetch_once = _fetch.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestFetch:
+ def test_ok_returns_body(self):
+ session = mock.MagicMock()
+ session.get.return_value = _response(200, {"name": "rails"})
+
+ assert _fetch_once(session, f"{RUBYGEMS_BASE_URL}/gems/rails.json", "rails", structlog.get_logger()) == {
+ "name": "rails"
+ }
+
+ def test_404_returns_none(self):
+ # A typo'd or unpublished gem must be skipped, not fail the whole sync.
+ session = mock.MagicMock()
+ session.get.return_value = _response(404)
+
+ assert _fetch_once(session, f"{RUBYGEMS_BASE_URL}/gems/nope.json", "nope", structlog.get_logger()) is None
+
+ @pytest.mark.parametrize("status", [429, 500, 503])
+ def test_retryable_statuses_raise_retryable(self, status):
+ session = mock.MagicMock()
+ session.get.return_value = _response(status)
+
+ with pytest.raises(RubyGemsRetryableError):
+ _fetch_once(session, f"{RUBYGEMS_BASE_URL}/gems/rails.json", "rails", 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, f"{RUBYGEMS_BASE_URL}/gems/rails.json", "rails", 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("rails")
+
+ assert is_valid is expected_valid
+
+ def test_empty_gems_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("rails")
+
+ assert is_valid is False
+ assert message is not None
+
+ def test_probes_first_gem(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200)
+
+ validate_credentials("rails\nrspec")
+
+ called_url = mock_session.return_value.get.call_args[0][0]
+
+ assert called_url == f"{RUBYGEMS_BASE_URL}/gems/rails.json"
+
+
+class TestGetRows:
+ def test_yields_a_batch_per_gem_and_skips_404(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = [
+ _response(200, _gem_document(name="rails")),
+ _response(404),
+ _response(200, _gem_document(name="rspec")),
+ ]
+
+ batches = list(get_rows("gems", ["rails", "nope", "rspec"], structlog.get_logger()))
+
+ # The 404 gem is skipped, so only two batches come back.
+ assert len(batches) == 2
+ assert batches[0][0]["name"] == "rails"
+ assert batches[1][0]["name"] == "rspec"
+
+ def test_versions_endpoint_flattens_versions(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, _versions_document(name="rails"))
+
+ batches = list(get_rows("versions", ["rails"], structlog.get_logger()))
+
+ assert len(batches) == 1
+ assert len(batches[0]) == 2
+
+ def test_non_list_versions_response_yields_nothing(self):
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, {"unexpected": "shape"})
+
+ batches = list(get_rows("versions", ["rails"], structlog.get_logger()))
+
+ assert batches == []
+
+ def test_chunks_large_version_history(self, monkeypatch):
+ # A gem 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", 1)
+ with mock.patch(f"{MODULE}.make_tracked_session") as mock_session:
+ mock_session.return_value.get.return_value = _response(200, _versions_document(name="rails"))
+
+ batches = list(get_rows("versions", ["rails"], structlog.get_logger()))
+
+ # The document has 2 valid version rows; at 1 row per chunk that's [1, 1].
+ assert [len(b) for b in batches] == [1, 1]
+
+
+class TestRubyGemsSource:
+ @pytest.mark.parametrize("endpoint", list(RUBYGEMS_ENDPOINTS))
+ def test_source_response_shape(self, endpoint):
+ response = rubygems_source(endpoint, "rails", structlog.get_logger())
+
+ assert response.name == endpoint
+ assert response.primary_keys == RUBYGEMS_ENDPOINTS[endpoint].primary_keys
+ assert response.sort_mode == "asc"
+
+ def test_only_versions_is_partitioned(self):
+ # `versions` has a stable created_at timestamp; `gems` has no stable datetime column.
+ versions = rubygems_source("versions", "rails", structlog.get_logger())
+ gems = rubygems_source("gems", "rails", structlog.get_logger())
+
+ assert versions.partition_mode == "datetime"
+ assert versions.partition_keys == ["created_at"]
+ assert gems.partition_mode is None
+ assert gems.partition_keys is None
+
+ def test_invalid_gems_raise(self):
+ with pytest.raises(ValueError):
+ rubygems_source("gems", "", structlog.get_logger())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems_source.py
new file mode 100644
index 000000000000..fbe235569ec9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/rubygems/tests/test_rubygems_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.generated_configs.rubygems import (
+ RubygemsSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.source import RubygemsSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "gems") -> 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 TestRubygemsSource:
+ def setup_method(self):
+ self.source = RubygemsSource()
+ self.team_id = 123
+ self.config = RubygemsSourceConfig(gems="rails\nrspec")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.RUBYGEMS
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Rubygems"
+ assert config.label == "RubyGems.org"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/rubygems"
+
+ 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) == {"gems"}
+
+ gems_field = by_name["gems"]
+ assert gems_field.type == SourceFieldInputConfigType.TEXTAREA
+ assert gems_field.required is True
+ # No auth, so the field carries no secret.
+ assert gems_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):
+ # RubyGems.org 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, "Gem 'x' was not found on RubyGems.org."), False, "Gem 'x' was not found on RubyGems.org."),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.source.validate_rubygems_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, "gems")
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.gems)
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.rubygems.source.rubygems_source")
+ def test_source_for_pipeline_plumbs_args(self, mock_rubygems_source):
+ inputs = _make_inputs(schema_name="versions")
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_rubygems_source.assert_called_once_with(
+ endpoint="versions",
+ gems_raw="rails\nrspec",
+ logger=inputs.logger,
+ )