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): implement nuget import source (#71216)

Tom Owers7fdffa52eaf0
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 a3332232ba24..ac5cd027f197 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -360,6 +360,7 @@ the row lists both.
| northflank | HTTP | requests | ✅ |
| northpass_lms | HTTP | requests | ✅ |
| notion | HTTP | requests | ✅ |
+| nuget | HTTP | requests | ✅ |
| omnisend | HTTP | requests | ✅ |
| octopus_deploy | HTTP | requests | ✅ |
| oncehub | HTTP | requests | ✅ |
@@ -814,7 +815,6 @@ doesn't conflict with concurrent PRs.
- ninjaone_rmm
- nocrm
- northpass_lms
-- nuget
- nutshell
- nylas
- octolens
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.py
index fceccdd41872..c7bf4057915c 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
@@ -2941,7 +2941,7 @@ class NotionSourceConfig(config.Config):
@config.config
class NugetSourceConfig(config.Config):
- pass
+ package_ids: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/canonical_descriptions.py
new file mode 100644
index 000000000000..1793d86ab8c1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/canonical_descriptions.py
@@ -0,0 +1,81 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "packages": {
+ "description": (
+ "One row per tracked package from the NuGet search service, carrying package-level metadata "
+ "and the all-time total download count as of the sync."
+ ),
+ "docs_url": "https://learn.microsoft.com/en-us/nuget/api/search-query-service-resource",
+ "columns": {
+ "id": "The package ID, the case-insensitive unique identifier of the package.",
+ "version": "The latest full SemVer 2.0.0 version of the package (including prereleases).",
+ "title": "The display title of the package's latest version.",
+ "description": "The description of the package's latest version.",
+ "summary": "The summary of the package's latest version.",
+ "authors": "The authors of the package, as declared in the package manifest.",
+ "owners": "The nuget.org accounts that own the package.",
+ "tags": "The tags of the package's latest version.",
+ "iconUrl": "URL of the package's icon.",
+ "licenseUrl": "URL of the package's license.",
+ "projectUrl": "URL of the package's project homepage.",
+ "registration": "URL of the package's registration index.",
+ "totalDownloads": "The all-time total number of downloads across every version of the package.",
+ "verified": "Whether the package ID is verified (owned under a reserved ID prefix).",
+ "packageTypes": "The package types declared by the latest version (e.g. Dependency, DotnetTool).",
+ "vulnerabilities": "Known vulnerabilities affecting the package's latest version.",
+ },
+ },
+ "package_versions": {
+ "description": (
+ "One row per published version of each tracked package from the NuGet registration index, "
+ "with the per-version download count merged in from the search service."
+ ),
+ "docs_url": "https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource",
+ "columns": {
+ "id": "The package ID this version belongs to.",
+ "version": "The full SemVer 2.0.0 version string of this package version.",
+ "published": (
+ "When this version was published. NuGet rewrites this to the year 1900 while a version is unlisted."
+ ),
+ "listed": "Whether this version is listed (visible in search results and version lists).",
+ "downloads": "The all-time number of downloads of this specific version, from the search service.",
+ "authors": "The authors of this version, as declared in the package manifest.",
+ "description": "The description of this version.",
+ "summary": "The summary of this version.",
+ "title": "The display title of this version.",
+ "tags": "The tags of this version.",
+ "iconUrl": "URL of this version's icon.",
+ "licenseUrl": "URL of this version's license.",
+ "licenseExpression": "The SPDX license expression of this version, when declared.",
+ "projectUrl": "URL of this version's project homepage.",
+ "packageContent": "URL of the .nupkg file for this version.",
+ "minClientVersion": "The minimum NuGet client version required to install this version.",
+ "requireLicenseAcceptance": "Whether installing this version requires accepting the license.",
+ "language": "The language declared in the package manifest.",
+ "dependencyGroups": "The dependencies of this version, grouped by target framework.",
+ "deprecation": "Deprecation metadata for this version, when it has been deprecated.",
+ "vulnerabilities": "Known vulnerabilities affecting this version.",
+ },
+ },
+ "catalog_events": {
+ "description": (
+ "Publish, edit, and delete events for the tracked packages, from the append-only NuGet "
+ "catalog. One row per catalog leaf (event)."
+ ),
+ "docs_url": "https://learn.microsoft.com/en-us/nuget/api/catalog-resource",
+ "columns": {
+ "catalog_leaf_url": "URL of the catalog leaf document describing this event. Unique per event.",
+ "event_type": (
+ "The event type: nuget:PackageDetails for a package version being published or edited, "
+ "nuget:PackageDelete for a version being hard-deleted."
+ ),
+ "commit_id": "ID of the catalog commit this event belongs to.",
+ "commit_timestamp": "When the event was committed to the catalog. The incremental sync cursor.",
+ "package_id": "The package ID the event applies to.",
+ "package_version": "The package version the event applies to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/nuget.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/nuget.py
new file mode 100644
index 000000000000..a8b338905cc1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/nuget.py
@@ -0,0 +1,426 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote, urlencode
+
+import requests
+from dateutil import parser as dateutil_parser
+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.nuget.settings import (
+ NUGET_ENDPOINTS,
+ SERVICE_INDEX_URL,
+)
+
+# Yield registration/catalog rows in chunks of this size; the pipeline batches further downstream.
+ROWS_PER_YIELD = 500
+
+# Cap the per-package existence probes at source-create so a huge pasted list can't stall the request.
+MAX_VALIDATED_PACKAGES = 20
+
+# Hard cap on the configured package count. Each package costs one or more requests per enabled
+# stream on every sync, so bound the config to keep a single source from tying up a resumable worker.
+MAX_PACKAGES = 500
+
+# Preference order per service-index resource; the index lists several versioned variants of each.
+# RegistrationsBaseUrl/3.6.0 is the gzipped SemVer 2.0.0 view, which includes every package.
+_SEARCH_TYPES = ("SearchQueryService/3.5.0", "SearchQueryService")
+_REGISTRATION_TYPES = ("RegistrationsBaseUrl/3.6.0", "RegistrationsBaseUrl")
+_CATALOG_TYPES = ("Catalog/3.0.0",)
+
+PACKAGE_NOT_FOUND_PREFIX = "NuGet package not found"
+
+
+class NugetRetryableError(Exception):
+ pass
+
+
+class NugetPackageNotFoundError(Exception):
+ pass
+
+
+class NugetResumeConfig:
+ # catalog_events: commitTimeStamp (ISO string) of the last fully processed catalog page.
+ commit_cursor: str | None = None
+ # packages / package_versions: package id whose rows were fully yielded last.
+ last_package_id: str | None = None
+
+
+def parse_package_ids(raw: str) -> list[str]:
+ """Split the user's comma/newline-separated package id list, deduping case-insensitively.
+
+ NuGet package ids are case-insensitive; the first spelling entered is kept for display.
+ Raises ``ValueError`` when no ids remain so the caller can surface a precise message.
+ """
+ ids: list[str] = []
+ seen: set[str] = set()
+ for chunk in raw.replace("\n", ",").split(","):
+ package_id = chunk.strip()
+ if package_id and package_id.lower() not in seen:
+ seen.add(package_id.lower())
+ ids.append(package_id)
+ if len(ids) > MAX_PACKAGES:
+ raise ValueError(f"Too many NuGet package IDs: at most {MAX_PACKAGES} are allowed per source.")
+ if not ids:
+ raise ValueError("Enter at least one NuGet package ID (comma-separated).")
+ return ids
+
+
+def _parse_timestamp(value: str) -> datetime:
+ # NuGet timestamps carry 7 fractional digits; dateutil truncates to microseconds, which only
+ # widens the re-fetch window slightly (merge dedupes the overlap).
+ return dateutil_parser.isoparse(value)
+
+
+def _coerce_cursor(value: Any) -> datetime | None:
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ if isinstance(value, str):
+ try:
+ return _coerce_cursor(_parse_timestamp(value))
+ except ValueError:
+ return None
+ return None
+
+
+def _resolve_resource(service_index: dict[str, Any], preferred_types: tuple[str, ...]) -> str:
+ for preferred in preferred_types:
+ for resource in service_index.get("resources", []):
+ if resource.get("@type") == preferred:
+ return str(resource["@id"])
+ raise ValueError(f"NuGet service index has no resource of type {preferred_types[0]}")
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (NugetRetryableError, requests.ReadTimeout, requests.ConnectionError, requests.exceptions.ChunkedEncodingError)
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_json(session: requests.Session, url: str, logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, timeout=60)
+
+ # nuget.org has no hard rate limit but asks for fair use; back off on throttles and transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise NugetRetryableError(f"NuGet API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"NuGet API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _search_package(
+ session: requests.Session, search_url: str, package_id: str, logger: FilteringBoundLogger
+) -> dict | None:
+ """Look up a single package by exact id. Returns None when search has no hit (unknown or unlisted)."""
+ params = {"q": f"packageid:{package_id}", "prerelease": "true", "semVerLevel": "2.0.0"}
+ data = _fetch_json(session, f"{search_url}?{urlencode(params)}", logger)
+ docs = data.get("data", [])
+ return docs[0] if docs else None
+
+
+def _registration_index_url(registration_base_url: str, package_id: str) -> str:
+ # Registration paths are keyed by the lowercased package id.
+ return f"{registration_base_url}{quote(package_id.lower())}/index.json"
+
+
+def _iter_registration_leaves(
+ session: requests.Session, registration_base_url: str, package_id: str, logger: FilteringBoundLogger
+) -> Iterator[dict]:
+ """Yield every registration leaf for a package, following linked pages when not inlined."""
+ try:
+ index = _fetch_json(session, _registration_index_url(registration_base_url, package_id), logger)
+ except requests.HTTPError as exc:
+ if exc.response is not None and exc.response.status_code == 404:
+ raise NugetPackageNotFoundError(
+ f"{PACKAGE_NOT_FOUND_PREFIX}: no NuGet package with id '{package_id}' exists"
+ ) from exc
+ raise
+
+ for page in index.get("items", []):
+ # Packages with few versions inline their leaves; larger ones link out to per-page documents.
+ leaves = page.get("items")
+ if leaves is None:
+ leaves = _fetch_json(session, page["@id"], logger).get("items", [])
+ yield from leaves
+
+
+def _normalize_version(version: str) -> str:
+ # SemVer build metadata (`+sha`) is not part of version identity; search strips it.
+ return version.split("+", 1)[0].lower()
+
+
+def _version_downloads(search_doc: dict | None) -> dict[str, Any]:
+ if not search_doc:
+ return {}
+ return {
+ _normalize_version(entry["version"]): entry.get("downloads")
+ for entry in search_doc.get("versions", [])
+ if entry.get("version")
+ }
+
+
+def _package_row(search_doc: dict) -> dict:
+ # `versions` is materialized as the package_versions table; the JSON-LD `@` keys aren't data.
+ return {key: value for key, value in search_doc.items() if key != "versions" and not key.startswith("@")}
+
+
+def _package_version_row(leaf: dict, downloads_by_version: dict[str, Any]) -> dict:
+ entry = leaf.get("catalogEntry", {})
+ row = {key: value for key, value in entry.items() if not key.startswith("@")}
+ row["downloads"] = downloads_by_version.get(_normalize_version(row.get("version", "")))
+ return row
+
+
+def _catalog_event_row(item: dict) -> dict:
+ return {
+ "catalog_leaf_url": item["@id"],
+ # "nuget:PackageDetails" (publish/edit) or "nuget:PackageDelete".
+ "event_type": item["@type"],
+ "commit_id": item.get("commitId"),
+ "commit_timestamp": _parse_timestamp(item["commitTimeStamp"]),
+ "package_id": item.get("nuget:id"),
+ "package_version": item.get("nuget:version"),
+ }
+
+
+def _remaining_packages(
+ package_ids: list[str],
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ """Resolve the saved package-id bookmark to the packages still to process.
+
+ A stable id bookmark (not a positional index) so a config edit between a crash and the retry
+ can't resume into the wrong package. An unknown bookmark restarts from the first package —
+ merge dedupes the re-pulled rows.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is None or resume.last_package_id is None:
+ return package_ids
+ lowered = [package_id.lower() for package_id in package_ids]
+ if resume.last_package_id.lower() not in lowered:
+ return package_ids
+ remaining = package_ids[lowered.index(resume.last_package_id.lower()) + 1 :]
+ logger.debug(f"NuGet: resuming after package {resume.last_package_id}")
+ return remaining
+
+
+def _get_package_rows(
+ session: requests.Session,
+ search_url: str,
+ package_ids: list[str],
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict]]:
+ remaining = _remaining_packages(package_ids, resumable_source_manager, logger)
+ for index, package_id in enumerate(remaining):
+ search_doc = _search_package(session, search_url, package_id, logger)
+ if search_doc is None:
+ # Unlisted packages are hidden from search; the package_versions table still covers them.
+ logger.warning(f"NuGet: package {package_id} not returned by search, skipping")
+ else:
+ yield [_package_row(search_doc)]
+ # Save AFTER yielding (and only while more packages remain) so a crash re-yields the last
+ # package rather than skipping it — merge dedupes on the primary key.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(NugetResumeConfig(last_package_id=package_id))
+
+
+def _get_package_version_rows(
+ session: requests.Session,
+ search_url: str,
+ registration_base_url: str,
+ package_ids: list[str],
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict]]:
+ remaining = _remaining_packages(package_ids, resumable_source_manager, logger)
+ for index, package_id in enumerate(remaining):
+ # Per-version download counts only live in the search view, not the registration leaves.
+ downloads_by_version = _version_downloads(_search_package(session, search_url, package_id, logger))
+
+ rows: list[dict] = []
+ for leaf in _iter_registration_leaves(session, registration_base_url, package_id, logger):
+ rows.append(_package_version_row(leaf, downloads_by_version))
+ if len(rows) >= ROWS_PER_YIELD:
+ yield rows
+ rows = []
+ if rows:
+ yield rows
+
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(NugetResumeConfig(last_package_id=package_id))
+
+
+def _get_catalog_event_rows(
+ session: requests.Session,
+ catalog_index_url: str,
+ package_ids: list[str],
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ logger: FilteringBoundLogger,
+ cursor: datetime | None,
+) -> Iterator[list[dict]]:
+ """Walk the catalog with the standard NuGet cursor protocol, filtered to the tracked packages.
+
+ A page's commitTimeStamp is the max of its items and pages fill sequentially, so pages at or
+ below the cursor hold nothing new and are skipped without fetching. The index's page list and
+ each page's items are NOT time-ordered (verified against the live API), so both are sorted
+ client-side — that's what makes the stream globally ascending and sort_mode="asc" truthful.
+ """
+ wanted = {package_id.lower() for package_id in package_ids}
+
+ index = _fetch_json(session, catalog_index_url, logger)
+ pages = sorted(index.get("items", []), key=lambda page: _parse_timestamp(page["commitTimeStamp"]))
+
+ skipped = 0
+ for page_entry in pages:
+ if cursor is not None and _parse_timestamp(page_entry["commitTimeStamp"]) <= cursor:
+ skipped += 1
+ continue
+
+ page = _fetch_json(session, page_entry["@id"], logger)
+ items = sorted(page.get("items", []), key=lambda item: _parse_timestamp(item["commitTimeStamp"]))
+ rows = [
+ _catalog_event_row(item)
+ for item in items
+ if (cursor is None or _parse_timestamp(item["commitTimeStamp"]) > cursor)
+ and (item.get("nuget:id") or "").lower() in wanted
+ ]
+ if rows:
+ yield rows
+ # Save AFTER yielding so a crash re-processes this page — merge dedupes the re-yielded rows.
+ resumable_source_manager.save_state(NugetResumeConfig(commit_cursor=page_entry["commitTimeStamp"]))
+
+ if skipped:
+ logger.debug(f"NuGet: skipped {skipped} catalog pages at or below the cursor")
+
+
+def _effective_catalog_cursor(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ resume: NugetResumeConfig | None,
+) -> datetime | None:
+ """Combine the incremental watermark and any saved resume checkpoint; the later one wins."""
+ candidates: list[datetime] = []
+ if should_use_incremental_field:
+ coerced = _coerce_cursor(db_incremental_field_last_value)
+ if coerced is not None:
+ candidates.append(coerced)
+ if resume is not None and resume.commit_cursor:
+ candidates.append(_parse_timestamp(resume.commit_cursor))
+ return max(candidates) if candidates else None
+
+
+def get_rows(
+ package_ids_raw: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict]]:
+ package_ids = parse_package_ids(package_ids_raw)
+ # One session reused across every request so urllib3 keeps connections alive.
+ session = make_tracked_session()
+ service_index = _fetch_json(session, SERVICE_INDEX_URL, logger)
+
+ if endpoint == "packages":
+ yield from _get_package_rows(
+ session, _resolve_resource(service_index, _SEARCH_TYPES), package_ids, resumable_source_manager, logger
+ )
+ elif endpoint == "package_versions":
+ yield from _get_package_version_rows(
+ session,
+ _resolve_resource(service_index, _SEARCH_TYPES),
+ _resolve_resource(service_index, _REGISTRATION_TYPES),
+ package_ids,
+ resumable_source_manager,
+ logger,
+ )
+ elif endpoint == "catalog_events":
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ cursor = _effective_catalog_cursor(should_use_incremental_field, db_incremental_field_last_value, resume)
+ yield from _get_catalog_event_rows(
+ session,
+ _resolve_resource(service_index, _CATALOG_TYPES),
+ package_ids,
+ resumable_source_manager,
+ logger,
+ cursor,
+ )
+ else:
+ raise ValueError(f"Unknown NuGet endpoint: {endpoint}")
+
+
+def nuget_source(
+ package_ids: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = NUGET_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ package_ids_raw=package_ids,
+ endpoint=endpoint,
+ 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,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_nuget_connection(package_ids_raw: str) -> tuple[bool, str | None]:
+ """Probe the service index and each configured package's registration index.
+
+ The public NuGet V3 API is anonymous, so "credentials" are just the package id list —
+ validation checks the ids actually exist (a 404 on the registration index means they don't).
+ Throttles and transient 5xx during the per-package probes must not block source creation.
+ Raises ``ValueError`` when the id list is empty so the caller can surface a precise message.
+ """
+ package_ids = parse_package_ids(package_ids_raw)
+ session = make_tracked_session()
+
+ try:
+ response = session.get(SERVICE_INDEX_URL, timeout=10)
+ response.raise_for_status()
+ registration_base_url = _resolve_resource(response.json(), _REGISTRATION_TYPES)
+ except Exception:
+ return False, "Could not reach the NuGet API. Please try again."
+
+ unknown: list[str] = []
+ for package_id in package_ids[:MAX_VALIDATED_PACKAGES]:
+ try:
+ probe = session.get(_registration_index_url(registration_base_url, package_id), timeout=10)
+ except Exception:
+ return False, "Could not reach the NuGet API. Please try again."
+ if probe.status_code == 404:
+ unknown.append(package_id)
+
+ if unknown:
+ return False, f"These package IDs were not found on NuGet: {', '.join(unknown)}"
+ return True, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/settings.py
new file mode 100644
index 000000000000..135edcb00eeb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/settings.py
@@ -0,0 +1,71 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# The well-known entry point of the public NuGet V3 API. Every other base URL (search,
+# registrations, catalog) is discovered from this document at run time, per the API contract.
+SERVICE_INDEX_URL = "https://api.nuget.org/v3/index.json"
+
+
+@dataclass
+class NugetEndpointConfig:
+ name: str
+ # True only for the catalog: its index exposes per-page commitTimeStamps, so a cursor can skip
+ # already-synced pages server-side. Search and registrations are keyed by package id, not time.
+ supports_incremental: bool
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable field to partition by. Only the catalog qualifies: its leaves are append-only and
+ # immutable. `published` on package versions is NOT stable (unlisting rewrites it to 1900).
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ should_sync_default: bool = True
+ description: str | None = None
+
+
+NUGET_ENDPOINTS: dict[str, NugetEndpointConfig] = {
+ "packages": NugetEndpointConfig(
+ name="packages",
+ supports_incremental=False,
+ description=(
+ "One row per tracked package from NuGet search, including the total download count and "
+ "verification status. Download totals are re-polled on every sync. Unlisted packages are "
+ "hidden from NuGet search and skipped"
+ ),
+ ),
+ "package_versions": NugetEndpointConfig(
+ name="package_versions",
+ supports_incremental=False,
+ primary_keys=["id", "version"],
+ description=(
+ "One row per version of each tracked package from the NuGet registration index, with "
+ "per-version download counts merged in from search"
+ ),
+ ),
+ "catalog_events": NugetEndpointConfig(
+ name="catalog_events",
+ supports_incremental=True,
+ partition_key="commit_timestamp",
+ primary_keys=["catalog_leaf_url"],
+ should_sync_default=False,
+ description=(
+ "Publish, edit, and delete events for the tracked packages from the append-only NuGet "
+ "catalog. The first sync walks the full nuget.org catalog (tens of thousands of pages) and "
+ "can take several hours; incremental syncs afterwards only read new catalog pages"
+ ),
+ incremental_fields=[
+ {
+ "label": "commit_timestamp",
+ "type": IncrementalFieldType.DateTime,
+ "field": "commit_timestamp",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(NUGET_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in NUGET_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/source.py
index d314b89383dc..31c0402fa0aa 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/source.py
@@ -1,19 +1,43 @@
-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.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 SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NugetSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.nuget import (
+ PACKAGE_NOT_FOUND_PREFIX,
+ NugetResumeConfig,
+ nuget_source,
+ validate_nuget_connection,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.settings import (
+ INCREMENTAL_FIELDS,
+ NUGET_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class NugetSource(SimpleSource[NugetSourceConfig]):
+class NugetSource(ResumableSource[NugetSourceConfig, NugetResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.NUGET
@@ -23,8 +47,93 @@ class NugetSource(SimpleSource[NugetSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.NUGET,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="NuGet (Microsoft / .NET Foundation)",
+ label="NuGet",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["dotnet", ".net", "csharp", "package registry"],
+ caption="""Track adoption of .NET libraries over time: package metadata, per-version download counts, and publish/delete events for the NuGet packages you care about.
+
+The public NuGet V3 API allows anonymous read access, so no API key is needed. Enter the package IDs you want to track, separated by commas or new lines — e.g. `Newtonsoft.Json, Serilog`.
+""",
iconPath="/static/services/nuget.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/nuget",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="package_ids",
+ label="Package IDs",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="Newtonsoft.Json, Serilog, Microsoft.Extensions.Logging",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Raised when a configured package id has no registration index (404). Retrying can never
+ # make a nonexistent package appear, so stop the sync with an actionable message.
+ PACKAGE_NOT_FOUND_PREFIX: "One of the configured package IDs does not exist on NuGet. Check the spelling of your package IDs and update the source.",
+ }
+
+ def get_schemas(
+ self,
+ config: NugetSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ # Catalog leaves are immutable events, so append-only sync is also safe there.
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ description=endpoint_config.description,
+ )
+ for endpoint, endpoint_config in NUGET_ENDPOINTS.items()
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [schema for schema in schemas if schema.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: NugetSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ return validate_nuget_connection(config.package_ids)
+ except ValueError as e:
+ return False, str(e)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NugetResumeConfig]:
+ return ResumableSourceManager[NugetResumeConfig](inputs, NugetResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: NugetSourceConfig,
+ resumable_source_manager: ResumableSourceManager[NugetResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return nuget_source(
+ package_ids=config.package_ids,
+ endpoint=inputs.schema_name,
+ 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/nuget/tests/test_nuget.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/tests/test_nuget.py
new file mode 100644
index 000000000000..ba3b17a2cadd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/tests/test_nuget.py
@@ -0,0 +1,384 @@
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget import nuget
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.nuget import (
+ MAX_PACKAGES,
+ MAX_VALIDATED_PACKAGES,
+ NugetPackageNotFoundError,
+ NugetResumeConfig,
+ _resolve_resource,
+ get_rows,
+ parse_package_ids,
+ validate_nuget_connection,
+)
+
+SERVICE_INDEX_URL = "https://api.nuget.org/v3/index.json"
+SEARCH_URL = "https://azuresearch-usnc.nuget.org/query"
+REGISTRATION_URL = "https://api.nuget.org/v3/registration5-gz-semver2/"
+CATALOG_INDEX_URL = "https://api.nuget.org/v3/catalog0/index.json"
+
+SERVICE_INDEX = {
+ "resources": [
+ {"@id": SEARCH_URL, "@type": "SearchQueryService"},
+ {"@id": SEARCH_URL, "@type": "SearchQueryService/3.5.0"},
+ {"@id": "https://api.nuget.org/v3/registration5-semver1/", "@type": "RegistrationsBaseUrl"},
+ {"@id": REGISTRATION_URL, "@type": "RegistrationsBaseUrl/3.6.0"},
+ {"@id": CATALOG_INDEX_URL, "@type": "Catalog/3.0.0"},
+ ]
+}
+
+
+def _search_query_url(package_id: str) -> str:
+ return f"{SEARCH_URL}?q=packageid%3A{package_id}&prerelease=true&semVerLevel=2.0.0"
+
+
+def _search_doc(package_id: str, **overrides: Any) -> dict:
+ doc = {
+ "@id": f"{REGISTRATION_URL}{package_id.lower()}/index.json",
+ "@type": "Package",
+ "id": package_id,
+ "version": "2.0.0",
+ "totalDownloads": 100,
+ "verified": True,
+ "versions": [
+ {"version": "1.0.0", "downloads": 40},
+ {"version": "2.0.0+sha123", "downloads": 60},
+ ],
+ }
+ doc.update(overrides)
+ return doc
+
+
+class _FakeResumableManager:
+ def __init__(self, state: NugetResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[NugetResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> NugetResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: NugetResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> dict:
+ fetched.append(url)
+ if url not in pages:
+ raise AssertionError(f"Unexpected fetch: {url}")
+ return pages[url]
+
+ monkeypatch.setattr(nuget, "_fetch_json", fake_fetch)
+ return fetched
+
+
+def _collect(manager: _FakeResumableManager, endpoint: str, package_ids: str = "Foo.Bar", **kwargs: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in get_rows(
+ package_ids_raw=package_ids,
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestParsePackageIds:
+ @parameterized.expand(
+ [
+ ("commas", "Newtonsoft.Json, Serilog", ["Newtonsoft.Json", "Serilog"]),
+ ("newlines", "Newtonsoft.Json\nSerilog\n", ["Newtonsoft.Json", "Serilog"]),
+ ("case_insensitive_dedupe", "Serilog, serilog, SERILOG", ["Serilog"]),
+ ("whitespace_and_empty_chunks", " Foo.Bar , , \n Baz ", ["Foo.Bar", "Baz"]),
+ ]
+ )
+ def test_valid_lists(self, _name: str, raw: str, expected: list[str]) -> None:
+ assert parse_package_ids(raw) == expected
+
+ @parameterized.expand([("empty", ""), ("only_separators", " , \n , ")])
+ def test_empty_raises(self, _name: str, raw: str) -> None:
+ with pytest.raises(ValueError):
+ parse_package_ids(raw)
+
+ def test_too_many_raises(self) -> None:
+ with pytest.raises(ValueError):
+ parse_package_ids(",".join(f"pkg{i}" for i in range(MAX_PACKAGES + 1)))
+
+ def test_at_limit_ok(self) -> None:
+ assert len(parse_package_ids(",".join(f"pkg{i}" for i in range(MAX_PACKAGES)))) == MAX_PACKAGES
+
+
+class TestResolveResource:
+ def test_prefers_versioned_type(self) -> None:
+ assert _resolve_resource(SERVICE_INDEX, ("RegistrationsBaseUrl/3.6.0", "RegistrationsBaseUrl")) == (
+ REGISTRATION_URL
+ )
+
+ def test_falls_back_to_unversioned_type(self) -> None:
+ assert _resolve_resource(SERVICE_INDEX, ("SearchQueryService/9.9.9", "SearchQueryService")) == SEARCH_URL
+
+ def test_missing_resource_raises(self) -> None:
+ with pytest.raises(ValueError):
+ _resolve_resource({"resources": []}, ("Catalog/3.0.0",))
+
+
+class TestPackagesEndpoint:
+ def test_yields_row_without_versions_or_jsonld_keys(self, monkeypatch: Any) -> None:
+ _patch_fetch(
+ monkeypatch,
+ {SERVICE_INDEX_URL: SERVICE_INDEX, _search_query_url("Foo.Bar"): {"data": [_search_doc("Foo.Bar")]}},
+ )
+ rows = _collect(_FakeResumableManager(), "packages")
+
+ assert len(rows) == 1
+ assert rows[0]["id"] == "Foo.Bar"
+ assert rows[0]["totalDownloads"] == 100
+ assert "versions" not in rows[0]
+ assert "@id" not in rows[0]
+ assert "@type" not in rows[0]
+
+ def test_search_miss_skips_package_and_continues(self, monkeypatch: Any) -> None:
+ # Unlisted packages are hidden from search; the sync must not fail, just move on.
+ _patch_fetch(
+ monkeypatch,
+ {
+ SERVICE_INDEX_URL: SERVICE_INDEX,
+ _search_query_url("Gone.Pkg"): {"data": []},
+ _search_query_url("Foo.Bar"): {"data": [_search_doc("Foo.Bar")]},
+ },
+ )
+ rows = _collect(_FakeResumableManager(), "packages", package_ids="Gone.Pkg, Foo.Bar")
+
+ assert [row["id"] for row in rows] == ["Foo.Bar"]
+
+ def test_saves_resume_state_between_packages_only(self, monkeypatch: Any) -> None:
+ _patch_fetch(
+ monkeypatch,
+ {
+ SERVICE_INDEX_URL: SERVICE_INDEX,
+ _search_query_url("A"): {"data": [_search_doc("A")]},
+ _search_query_url("B"): {"data": [_search_doc("B")]},
+ },
+ )
+ manager = _FakeResumableManager()
+ _collect(manager, "packages", package_ids="A, B")
+
+ assert manager.saved == [NugetResumeConfig(last_package_id="A")]
+
+ def test_resumes_after_bookmarked_package(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(
+ monkeypatch,
+ {SERVICE_INDEX_URL: SERVICE_INDEX, _search_query_url("B"): {"data": [_search_doc("B")]}},
+ )
+ rows = _collect(_FakeResumableManager(NugetResumeConfig(last_package_id="a")), "packages", package_ids="A, B")
+
+ assert [row["id"] for row in rows] == ["B"]
+ assert _search_query_url("A") not in fetched
+
+
+class TestPackageVersionsEndpoint:
+ def _pages(self) -> dict[str, Any]:
+ leaf_1 = {"catalogEntry": {"@id": "leaf1", "id": "Foo.Bar", "version": "1.0.0", "listed": True}}
+ leaf_2 = {"catalogEntry": {"@id": "leaf2", "id": "Foo.Bar", "version": "2.0.0+sha123", "listed": True}}
+ return {
+ SERVICE_INDEX_URL: SERVICE_INDEX,
+ _search_query_url("Foo.Bar"): {"data": [_search_doc("Foo.Bar")]},
+ f"{REGISTRATION_URL}foo.bar/index.json": {
+ "items": [
+ {"items": [leaf_1]}, # inlined page
+ {"@id": f"{REGISTRATION_URL}foo.bar/page/2.json"}, # linked page
+ ]
+ },
+ f"{REGISTRATION_URL}foo.bar/page/2.json": {"items": [leaf_2]},
+ }
+
+ def test_walks_inlined_and_linked_pages_and_merges_downloads(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(_FakeResumableManager(), "package_versions")
+
+ assert [(row["id"], row["version"]) for row in rows] == [("Foo.Bar", "1.0.0"), ("Foo.Bar", "2.0.0+sha123")]
+ # Downloads come from search, matched with SemVer build metadata stripped.
+ assert [row["downloads"] for row in rows] == [40, 60]
+ assert all("@id" not in row for row in rows)
+
+ def test_unknown_package_raises_not_found(self, monkeypatch: Any) -> None:
+ def fake_fetch(session: Any, url: str, logger: Any) -> dict:
+ if url == SERVICE_INDEX_URL:
+ return SERVICE_INDEX
+ if url == _search_query_url("Nope"):
+ return {"data": []}
+ response = MagicMock(status_code=404)
+ raise requests.HTTPError(response=response)
+
+ monkeypatch.setattr(nuget, "_fetch_json", fake_fetch)
+
+ with pytest.raises(NugetPackageNotFoundError):
+ _collect(_FakeResumableManager(), "package_versions", package_ids="Nope")
+
+
+def _catalog_item(package_id: str, version: str, timestamp: str, event_type: str = "nuget:PackageDetails") -> dict:
+ return {
+ "@id": f"https://api.nuget.org/v3/catalog0/data/{timestamp}/{package_id.lower()}.{version}.json",
+ "@type": event_type,
+ "commitId": f"commit-{timestamp}",
+ "commitTimeStamp": timestamp,
+ "nuget:id": package_id,
+ "nuget:version": version,
+ }
+
+
+class TestCatalogEventsEndpoint:
+ PAGE_1_URL = "https://api.nuget.org/v3/catalog0/page1.json"
+ PAGE_2_URL = "https://api.nuget.org/v3/catalog0/page2.json"
+
+ def _pages(self) -> dict[str, Any]:
+ # The live index lists pages out of time order; items within a page are unsorted too.
+ return {
+ SERVICE_INDEX_URL: SERVICE_INDEX,
+ CATALOG_INDEX_URL: {
+ "items": [
+ {"@id": self.PAGE_2_URL, "commitTimeStamp": "2026-02-01T00:00:00.0000000Z"},
+ {"@id": self.PAGE_1_URL, "commitTimeStamp": "2026-01-01T00:00:00.0000000Z"},
+ ]
+ },
+ self.PAGE_1_URL: {
+ "items": [
+ _catalog_item("Foo.Bar", "1.1.0", "2026-01-01T00:00:00.0000000Z"),
+ _catalog_item("Foo.Bar", "1.0.0", "2025-12-01T00:00:00.0000000Z"),
+ _catalog_item("Other.Pkg", "9.0.0", "2025-12-15T00:00:00.0000000Z"),
+ ]
+ },
+ self.PAGE_2_URL: {
+ "items": [
+ _catalog_item("Foo.Bar", "2.0.0", "2026-02-01T00:00:00.0000000Z", "nuget:PackageDelete"),
+ ]
+ },
+ }
+
+ def test_first_sync_walks_pages_in_ascending_commit_order(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(_FakeResumableManager(), "catalog_events")
+
+ # Unsorted index/page items must come out globally ascending (sort_mode="asc" contract),
+ # filtered to the tracked package.
+ assert [row["package_version"] for row in rows] == ["1.0.0", "1.1.0", "2.0.0"]
+ assert [row["package_id"] for row in rows] == ["Foo.Bar"] * 3
+ assert rows[0]["commit_timestamp"] == datetime(2025, 12, 1, tzinfo=UTC)
+ assert rows[2]["event_type"] == "nuget:PackageDelete"
+ assert fetched.index(self.PAGE_1_URL) < fetched.index(self.PAGE_2_URL)
+
+ def test_incremental_cursor_skips_whole_pages_without_fetching(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(
+ _FakeResumableManager(),
+ "catalog_events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert self.PAGE_1_URL not in fetched
+ assert [row["package_version"] for row in rows] == ["2.0.0"]
+
+ def test_cursor_filters_items_within_a_refetched_page(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(
+ _FakeResumableManager(),
+ "catalog_events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2025, 12, 20, tzinfo=UTC),
+ )
+
+ assert [row["package_version"] for row in rows] == ["1.1.0", "2.0.0"]
+
+ def test_saves_state_after_each_processed_page(self, monkeypatch: Any) -> None:
+ _patch_fetch(monkeypatch, self._pages())
+ manager = _FakeResumableManager()
+ _collect(manager, "catalog_events")
+
+ assert [state.commit_cursor for state in manager.saved] == [
+ "2026-01-01T00:00:00.0000000Z",
+ "2026-02-01T00:00:00.0000000Z",
+ ]
+
+ def test_resume_checkpoint_acts_as_cursor(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(
+ _FakeResumableManager(NugetResumeConfig(commit_cursor="2026-01-01T00:00:00.0000000Z")),
+ "catalog_events",
+ )
+
+ assert self.PAGE_1_URL not in fetched
+ assert [row["package_version"] for row in rows] == ["2.0.0"]
+
+ def test_later_of_watermark_and_resume_checkpoint_wins(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, self._pages())
+ rows = _collect(
+ _FakeResumableManager(NugetResumeConfig(commit_cursor="2026-02-01T00:00:00.0000000Z")),
+ "catalog_events",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2025, 12, 20, tzinfo=UTC),
+ )
+
+ assert rows == []
+ assert self.PAGE_1_URL not in fetched
+ assert self.PAGE_2_URL not in fetched
+
+
+class TestValidateNugetConnection:
+ def _session(self, registration_status: int = 200) -> MagicMock:
+ session = MagicMock()
+
+ def fake_get(url: str, timeout: int = 10) -> MagicMock:
+ if url == SERVICE_INDEX_URL:
+ return MagicMock(status_code=200, json=lambda: SERVICE_INDEX, raise_for_status=lambda: None)
+ return MagicMock(status_code=registration_status)
+
+ session.get.side_effect = fake_get
+ return session
+
+ def test_valid_packages(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(nuget, "make_tracked_session", lambda: self._session())
+ assert validate_nuget_connection("Foo.Bar, Baz") == (True, None)
+
+ def test_unknown_packages_named_in_error(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(nuget, "make_tracked_session", lambda: self._session(registration_status=404))
+ ok, message = validate_nuget_connection("Nope.One, Nope.Two")
+
+ assert ok is False
+ assert "Nope.One" in (message or "")
+ assert "Nope.Two" in (message or "")
+
+ def test_transient_probe_errors_do_not_block_creation(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(nuget, "make_tracked_session", lambda: self._session(registration_status=503))
+ assert validate_nuget_connection("Foo.Bar") == (True, None)
+
+ def test_unreachable_service_index(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = ConnectionError("boom")
+ monkeypatch.setattr(nuget, "make_tracked_session", lambda: session)
+
+ ok, message = validate_nuget_connection("Foo.Bar")
+ assert ok is False
+ assert "Could not reach the NuGet API" in (message or "")
+
+ def test_probe_count_capped(self, monkeypatch: Any) -> None:
+ session = self._session()
+ monkeypatch.setattr(nuget, "make_tracked_session", lambda: session)
+ validate_nuget_connection(", ".join(f"pkg{i}" for i in range(MAX_VALIDATED_PACKAGES + 10)))
+
+ # 1 service-index fetch + at most MAX_VALIDATED_PACKAGES probes.
+ assert session.get.call_count == 1 + MAX_VALIDATED_PACKAGES
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/tests/test_nuget_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/tests/test_nuget_source.py
new file mode 100644
index 000000000000..f1cda7db6401
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/nuget/tests/test_nuget_source.py
@@ -0,0 +1,137 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NugetSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.nuget import NugetResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.settings import ENDPOINTS, NUGET_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.nuget.source import NugetSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestNugetSource:
+ def setup_method(self):
+ self.source = NugetSource()
+ self.team_id = 123
+ self.config = NugetSourceConfig(package_ids="Newtonsoft.Json, Serilog")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.NUGET
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Nuget"
+ assert config.label == "NuGet"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/nuget.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/nuget"
+
+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert [f.name for f in fields] == ["package_ids"]
+ assert fields[0].type == SourceFieldInputConfigType.TEXTAREA
+ assert fields[0].required is True
+ assert fields[0].secret is False
+
+ def test_get_schemas_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ # Only the catalog exposes a server-side time cursor; search/registrations are id-keyed.
+ assert schemas["catalog_events"].supports_incremental is True
+ assert schemas["catalog_events"].supports_append is True
+ assert [f["field"] for f in schemas["catalog_events"].incremental_fields] == ["commit_timestamp"]
+ assert schemas["catalog_events"].should_sync_default is False
+ for name in ("packages", "package_versions"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+ assert schemas[name].should_sync_default is True
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["packages"])
+ assert [schema.name for schema in schemas] == ["packages"]
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list must render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ assert set(self.source.get_canonical_descriptions()) == set(NUGET_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [
+ (True, None),
+ (False, "These package IDs were not found on NuGet: Nope.One"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.nuget.source.validate_nuget_connection"
+ )
+ def test_validate_credentials_plumbs_result(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ assert self.source.validate_credentials(self.config, self.team_id) == mock_return
+ mock_validate.assert_called_once_with("Newtonsoft.Json, Serilog")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.nuget.source.validate_nuget_connection"
+ )
+ def test_validate_credentials_surfaces_empty_package_list(self, mock_validate):
+ mock_validate.side_effect = ValueError("Enter at least one NuGet package ID (comma-separated).")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "at least one NuGet package ID" in (error_message or "")
+
+ def test_non_retryable_errors_match_package_not_found(self):
+ observed = "NuGet package not found: no NuGet package with id 'Nope.One' exists"
+ assert any(key in observed for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "transient_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.nuget.org/v3/catalog0/index.json",
+ "500 Server Error: Internal Server Error for url: https://azuresearch-usnc.nuget.org/query",
+ "HTTPSConnectionPool(host='api.nuget.org', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, transient_error):
+ assert not any(key in transient_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert manager._data_class is NugetResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.nuget.source.nuget_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_nuget_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "catalog_events"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_nuget_source.call_args.kwargs
+ assert kwargs["package_ids"] == "Newtonsoft.Json, Serilog"
+ assert kwargs["endpoint"] == "catalog_events"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.nuget.source.nuget_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_nuget_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "packages"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_nuget_source.call_args.kwargs["db_incremental_field_last_value"] is None