:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add Cloudsmith source (#77132)
Tom Owers3cecbb7a23d1
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 6bd3d553ff3a..ec5274777b65 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -177,6 +177,7 @@ the row lists both.| clockodo | HTTP | requests | ✅ || close | HTTP | requests + `rest_source.RESTClient` | ✅ || cloudbeds | HTTP | requests | ✅ |+| cloudsmith | HTTP | requests + `rest_source.RESTClient` | ✅ || convertkit | HTTP | requests | ✅ || convex | HTTP | requests | ✅ || copper | HTTP | requests | ✅ |@@ -867,7 +868,6 @@ doesn't conflict with concurrent PRs.- clip- cloudability- cloudbeds-- cloudsmith- clover- coassemble- cockroachdbdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/canonical_descriptions.pynew file mode 100644index 000000000000..a0fa1a67bfda--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/canonical_descriptions.py@@ -0,0 +1,214 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "repositories": {+ "description": "A repository in the workspace: the container that packages are pushed to and installed from.",+ "docs_url": "https://help.cloudsmith.io/reference/repos_namespace_list",+ "columns": {+ "slug_perm": "Permanent identifier for the repository. It never changes once the repository is created.",+ "slug": "The slug that identifies the repository in URLs. Can be renamed.",+ "name": "A descriptive name for the repository.",+ "namespace": "Workspace the repository belongs to.",+ "description": "A description of the repository's purpose or contents.",+ "created_at": "The time the repository was created.",+ "deleted_at": "The time the repository was manually deleted, if it was.",+ "size": "The calculated size of the repository in bytes.",+ "size_str": "The calculated size of the repository, human readable.",+ "package_count": "The number of packages in the repository.",+ "package_group_count": "The number of package groups in the repository.",+ "num_downloads": "The number of downloads for packages in the repository.",+ "num_policy_violated_packages": "Number of packages in the repository that violate a policy.",+ "num_quarantined_packages": "Number of quarantined packages in the repository.",+ "repository_type_str": "Whether the repository is public or private.",+ "is_private": "Whether the repository is private.",+ "is_public": "Whether the repository is public.",+ "is_open_source": "Whether the repository is an open source repository.",+ "storage_region": "The Cloudsmith region in which package files are stored.",+ "content_kind": "Whether the repository holds packages or distributes other repositories.",+ "use_vulnerability_scanning": "Whether vulnerability scanning is enabled for supported packages in the repository.",+ "cdn_url": "Base URL from which packages and other artifacts are downloaded.",+ "self_html_url": "Website URL for the repository.",+ },+ },+ "packages": {+ "description": "A package (artifact) stored in a repository, with its version, size, download count and synchronisation status.",+ "docs_url": "https://help.cloudsmith.io/reference/packages_list",+ "columns": {+ "repository_slug": "Slug of the repository the package was listed from. Added by PostHog so packages stay distinguishable across repositories.",+ "slug_perm": "Permanent identifier for the package within its repository.",+ "slug": "The public identifier for the package.",+ "identifier_perm": "Unique and permanent identifier for the package.",+ "name": "The name of the package.",+ "version": "The raw version of the package.",+ "version_orig": "The version exactly as it was supplied at upload time.",+ "epoch": "The epoch of the package version, if any.",+ "release": "The release of the package version, if any.",+ "format": "The package format, for example deb, docker, maven or python.",+ "subtype": "The package subtype, where the format has one.",+ "filename": "The name of the package file.",+ "filepath": "Full path to the file, including the filename.",+ "extension": "The file extension of the package file.",+ "size": "The calculated size of the package in bytes.",+ "freeable_storage": "Amount of storage that would be freed if the package were deleted.",+ "num_files": "The number of files in the package.",+ "downloads": "The number of times the package has been downloaded.",+ "uploaded_at": "The time the package was uploaded. Does not change afterwards.",+ "uploader": "The user who uploaded the package.",+ "repository": "The repository the package belongs to.",+ "namespace": "The workspace the package belongs to.",+ "status": "The synchronisation status of the package, as a numeric code.",+ "status_str": "The synchronisation status of the package, as text.",+ "status_reason": "A textual description of the synchronisation status reason, if any.",+ "status_updated_at": "The time the package status was last updated.",+ "stage": "The synchronisation stage of the package, as a numeric code.",+ "stage_str": "The synchronisation stage of the package, as text.",+ "stage_updated_at": "The time the package stage was last updated.",+ "sync_finished_at": "The time the package sync finished.",+ "sync_progress": "Synchronisation progress, from 0 to 100.",+ "is_quarantined": "Whether the package is quarantined.",+ "is_sync_completed": "Whether the package finished synchronising.",+ "is_sync_failed": "Whether the package failed to synchronise.",+ "policy_violated": "Whether the package violates any policy.",+ "security_scan_status": "The status of the package's security scan.",+ "security_scan_started_at": "The time security scanning started.",+ "security_scan_completed_at": "The time security scanning completed.",+ "security_scan_status_updated_at": "The time the security scan status was last updated.",+ "license": "The license of the package.",+ "raw_license": "The license string exactly as it appears in the package metadata.",+ "spdx_license": "The SPDX license identifier for the package.",+ "osi_approved": "Whether the package's SPDX license is OSI-approved.",+ "checksum_sha256": "SHA256 checksum of the package file.",+ "checksum_md5": "MD5 checksum of the package file.",+ "architectures": "The architectures the package targets.",+ "distro": "The distribution the package targets.",+ "distro_version": "The distribution version the package targets.",+ "tags": "Tags applied to the package.",+ "description": "A textual description of the package.",+ "summary": "A one-line synopsis of the package.",+ "cdn_url": "URL the package file is downloaded from.",+ "self_html_url": "Website URL for the package.",+ },+ },+ "entitlements": {+ "description": "An entitlement token for a repository: a download credential with its own usage limits and counters. The token value itself is never synced.",+ "docs_url": "https://help.cloudsmith.io/reference/entitlements_list",+ "columns": {+ "repository_slug": "Slug of the repository the entitlement belongs to. Added by PostHog so entitlements stay distinguishable across repositories.",+ "slug_perm": "Permanent identifier for the entitlement token.",+ "name": "Name of the entitlement token.",+ "created_at": "The time the token was created.",+ "created_by": "The user who created the token.",+ "updated_at": "The time the token was last updated.",+ "updated_by": "The user who last updated the token.",+ "is_active": "Whether the token can currently be used to download.",+ "default": "Whether this is the default token for the repository.",+ "downloads": "Number of downloads made with the token.",+ "clients": "Number of unique clients that have used the token.",+ "has_limits": "Whether any usage limit is configured on the token.",+ "is_limited": "Whether the token has hit one of its limits.",+ "limit_bandwidth": "Maximum download bandwidth allowed for the token.",+ "limit_bandwidth_unit": "Unit the bandwidth limit is expressed in.",+ "limit_num_downloads": "Maximum number of downloads allowed for the token.",+ "limit_num_clients": "Maximum number of unique clients allowed for the token.",+ "limit_date_range_from": "The date and time the token can be used from.",+ "limit_date_range_to": "The date and time the token can be used until.",+ "limit_package_query": "Package search query restricting what the token can download.",+ "scheduled_reset_at": "The time the scheduled reset period elapses and the limits reset.",+ "scheduled_reset_period": "How often the token's usage limits reset.",+ "eula_required": "Whether accepting a EULA is required to use the token.",+ "eula_accepted_at": "The time the EULA was accepted.",+ "user": "The user the token belongs to, for user-specific tokens.",+ "metadata": "Arbitrary metadata stored against the token.",+ },+ },+ "webhooks": {+ "description": "A webhook configured on a repository, including the events it fires on and the delivery health of its most recent request. The destination URL and request-body templates are not synced, since either can embed a delivery credential.",+ "docs_url": "https://help.cloudsmith.io/reference/webhooks_list",+ "columns": {+ "repository_slug": "Slug of the repository the webhook belongs to. Added by PostHog so webhooks stay distinguishable across repositories.",+ "slug_perm": "Permanent identifier for the webhook.",+ "events": "The events the webhook is subscribed to, for example package.created.",+ "package_query": "Package search query that a package must match for the webhook to fire.",+ "is_active": "Whether the webhook fires on subscribed events.",+ "created_at": "The time the webhook was created.",+ "created_by": "The user who created the webhook.",+ "updated_at": "The time the webhook was last updated.",+ "updated_by": "The user who last updated the webhook.",+ "num_sent": "Number of webhook requests sent.",+ "last_response_status": "HTTP status code of the most recent webhook request.",+ "last_response_status_str": "HTTP status of the most recent webhook request, as text.",+ "is_last_response_bad": "Whether the most recent webhook request failed.",+ "disable_reason": "Why the webhook was disabled, as a numeric code.",+ "disable_reason_str": "Why the webhook was disabled, as text.",+ "request_body_format_str": "The payload format used for webhook requests.",+ "request_content_type": "The value sent for the Content-Type header.",+ "secret_header": "The header the predefined secret is sent in. The secret value itself is not returned.",+ "verify_ssl": "Whether SSL certificates are verified when the webhook is sent.",+ },+ },+ "vulnerabilities": {+ "description": "The result of a vulnerability scan of a package in the workspace, with the number of findings and the highest severity found.",+ "docs_url": "https://help.cloudsmith.io/reference/vulnerabilities_namespace_list",+ "columns": {+ "identifier": "Identifier for the scan result.",+ "created_at": "The time the scan result was stored.",+ "has_vulnerabilities": "Whether the results contain any known vulnerabilities.",+ "num_vulnerabilities": "Number of vulnerabilities found.",+ "max_severity": "Highest severity found, one of Unknown, Low, Medium, High or Critical.",+ "package": "The package that was scanned, with its name, version and identifier.",+ "scan_id": "Deprecated. A number that identified a scan within a repository. Use identifier instead.",+ },+ },+ "audit_log": {+ "description": "An audit log entry for the workspace: who did what, to which object, and when. Availability depends on your Cloudsmith plan.",+ "docs_url": "https://help.cloudsmith.io/reference/audit_log_namespace_list",+ "columns": {+ "uuid": "Identifier for the audit log entry.",+ "event": "The event that was recorded.",+ "event_at": "The time the event happened.",+ "context": "The context the event happened in.",+ "actor": "The user or service that performed the action.",+ "actor_kind": "Whether the actor was a user, a service or something else.",+ "actor_slug_perm": "Permanent identifier for the actor.",+ "actor_ip_address": "IP address the action came from.",+ "actor_location": "Geographic location resolved from the actor's IP address.",+ "object": "The object the action was performed on.",+ "object_kind": "The kind of object the action was performed on.",+ "object_slug_perm": "Permanent identifier for the object.",+ "target": "The target the action applied to.",+ "target_kind": "The kind of target the action applied to.",+ "target_slug_perm": "Permanent identifier for the target.",+ },+ },+ "members": {+ "description": "A member of the Cloudsmith organization, with their role, team memberships and login activity.",+ "docs_url": "https://help.cloudsmith.io/reference/orgs_members_list",+ "columns": {+ "user_id": "Identifier for the user.",+ "user": "The user's slug.",+ "user_name": "The user's display name.",+ "email": "The user's email address.",+ "role": "The member's role in the organization: Owner, Manager, Member or Collaborator.",+ "is_active": "Whether the membership is active.",+ "joined_at": "The time the user joined the organization.",+ "last_login_at": "The time the user last logged in.",+ "last_login_method": "How the user last logged in, for example Password, SAML or OIDC.",+ "has_two_factor": "Whether the user has two-factor authentication enabled.",+ "teams": "The teams within the organization the user belongs to.",+ "visibility": "Whether the membership is public or private.",+ },+ },+ "teams": {+ "description": "A team within the Cloudsmith organization. Teams group members so repository privileges can be granted in bulk.",+ "docs_url": "https://help.cloudsmith.io/reference/orgs_teams_list",+ "columns": {+ "slug_perm": "Permanent identifier for the team.",+ "slug": "The slug that identifies the team in URLs.",+ "name": "A descriptive name for the team.",+ "description": "A detailed description of the team.",+ "visibility": "Whether the team is visible or hidden.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/cloudsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/cloudsmith.pynew file mode 100644index 000000000000..28dd38bf926c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/cloudsmith.py@@ -0,0 +1,278 @@+import re+import dataclasses+from collections.abc import Callable, Iterable+from typing import Any, Optional, cast++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.settings import (+ CLOUDSMITH_BASE_URL,+ CLOUDSMITH_ENDPOINTS,+ PAGE_TOTAL_HEADER,+ CloudsmithEndpointConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (+ coerce_datetime_to_utc,+)+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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+ IncrementalConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse++# Cloudsmith workspace (namespace) slugs, per the API schema's slug pattern. Enforced before the+# slug is interpolated into a request path.+WORKSPACE_SLUG_RE = re.compile(r"^[-a-zA-Z0-9_]+$")++INVALID_WORKSPACE_ERROR = "Enter a valid Cloudsmith workspace slug (letters, numbers, dashes and underscores only)."++# The lower bound sent on a first incremental sync: old enough to select every package, and a+# value the `uploaded` filter parses (a bare `None` would be rejected as an unknown expression).+INCREMENTAL_INITIAL_VALUE = "1970-01-01T00:00:00Z"+++class CloudsmithResumeConfig:+ # Opaque framework checkpoint (the page number for top-level endpoints, per-parent fan-out+ # state for repository-scoped ones), round-tripped into `initial_paginator_state` on resume.+ paginator_state: dict[str, Any]+++class CloudsmithPaginator(PageNumberPaginator):+ """Page-number paginator that stops on Cloudsmith's page-count response header.++ Cloudsmith reports the number of pages in `X-Pagination-PageTotal` rather than the response+ body, and answers a page past the last one with a 404 rather than an empty page - so the+ inherited empty-page check would only fire after a request that has already failed.+ """++ def __init__(self, page_size: int, page: int = 1) -> None:+ super().__init__(base_page=1, page=page, page_param="page")+ self.page_size = page_size++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ if not data:+ self._has_next_page = False+ return++ self.page += 1++ raw_page_total = response.headers.get(PAGE_TOTAL_HEADER)+ if raw_page_total is not None:+ try:+ self._has_next_page = self.page <= int(raw_page_total)+ return+ except ValueError:+ pass++ # Header absent or unparseable: fall back to stopping on a short page, since asking for+ # the page after the last one is an error rather than an empty page.+ self._has_next_page = len(data) >= self.page_size++ def __str__(self) -> str:+ return f"CloudsmithPaginator(page={self.page}, page_size={self.page_size})"+++def _format_uploaded_filter(value: Any) -> str:+ """Build the `query` search expression that bounds a package list by upload time.++ Truncates to whole seconds, which rounds the lower bound *down* - so a sync re-reads at most+ a few boundary packages (the merge dedupes them) rather than skipping any package uploaded in+ the same second as the watermark.+ """+ normalized_value = coerce_datetime_to_utc(value)+ formatted = normalized_value.strftime("%Y-%m-%dT%H:%M:%SZ") if normalized_value is not None else str(value)+ return f"uploaded:>={formatted}"+++def _cloudsmith_incremental_window(cursor_path: str) -> IncrementalConfig:+ # `query` is a server-side search filter that applies to every page, so pagination stays+ # bounded by the filtered set and terminates at the watermark.+ return {+ "cursor_path": cursor_path,+ "start_param": "query",+ "initial_value": INCREMENTAL_INITIAL_VALUE,+ "convert": _format_uploaded_filter,+ }+++def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:+ for name in fields:+ row.pop(name, None)+ return row++ return _mapper+++def _client_config(api_key: str) -> ClientConfig:+ return {+ "base_url": CLOUDSMITH_BASE_URL,+ "headers": {"Accept": "application/json"},+ # Cloudsmith API keys authenticate via the `X-Api-Key` header (HTTP basic also works, but+ # the header is the documented default and keeps the key out of the URL userinfo).+ "auth": {"type": "api_key", "name": "X-Api-Key", "api_key": api_key, "location": "header"},+ # `capture=False` keeps raw responses out of HTTP sample storage: member emails, audit-log+ # IP addresses and webhook targets ride in these bodies, and the name-based scrubber can't+ # recognise them. Traffic is still metered and logged, with the API key redacted.+ "session": make_tracked_session(redact_values=(api_key,), capture=False),+ }+++def validate_credentials(api_key: str, workspace: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:+ """Confirm the API key is genuine and the workspace is reachable with one cheap probe.++ `GET /namespaces/{slug}/` validates both halves of the config at once: a bad key is a 401 and+ a workspace the key cannot see is a 404.+ """+ if not WORKSPACE_SLUG_RE.match(workspace):+ return False, INVALID_WORKSPACE_ERROR++ response = make_tracked_session(redact_values=(api_key,), capture=False).get(+ f"{CLOUDSMITH_BASE_URL}/namespaces/{workspace}/",+ headers={"X-Api-Key": api_key, "Accept": "application/json"},+ timeout=10,+ )+ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Cloudsmith rejected the API key. Check the key in your Cloudsmith user settings and try again."+ if response.status_code == 403:+ # A Cloudsmith API key inherits its owner's permissions, which vary per repository. Let+ # source creation through so the user can still sync the tables they do have access to,+ # and only fail when a specific table is being checked.+ if schema_name is None:+ return True, None+ return False, "Your Cloudsmith API key does not have permission to read this data."+ if response.status_code == 404:+ return False, f"Cloudsmith workspace '{workspace}' was not found, or this API key cannot see it."+ return False, f"Cloudsmith returned an unexpected response (HTTP {response.status_code})."+++def get_resource(config: CloudsmithEndpointConfig, workspace: str) -> EndpointResource:+ if config.fanout:+ raise ValueError(f"Fan-out endpoint '{config.name}' must use the fan-out path")++ endpoint_config: Endpoint = {+ "path": config.path.replace("{owner}", workspace),+ "params": {"page_size": config.page_size, **config.params},+ "paginator": CloudsmithPaginator(page_size=config.page_size),+ # Every Cloudsmith list endpoint returns a bare JSON array; anything else is a shape+ # change we would rather fail on than silently sync as a single row.+ "data_selector_required": True,+ }++ resource: EndpointResource = {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+ if config.strip_fields:+ resource["data_map"] = _drop_fields(config.strip_fields)+ return resource+++def _make_source_response(config: CloudsmithEndpointConfig, items_fn: Callable[[], Any]) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=config.primary_key if isinstance(config.primary_key, list) else [config.primary_key],+ sort_mode=config.sort_mode,+ 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 cloudsmith_source(+ api_key: str,+ workspace: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CloudsmithResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ if not WORKSPACE_SLUG_RE.match(workspace):+ raise ValueError(INVALID_WORKSPACE_ERROR)++ endpoint_config = CLOUDSMITH_ENDPOINTS[endpoint]++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = resume_config.paginator_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Only persist when there's somewhere to resume to; the Redis TTL handles cleanup.+ if state:+ resumable_source_manager.save_state(CloudsmithResumeConfig(paginator_state=dict(state)))++ if endpoint_config.fanout is not None:+ parent_config = CLOUDSMITH_ENDPOINTS[endpoint_config.fanout.parent_name]+ dependent_resource: Any = build_dependent_resource(+ endpoint_configs=CLOUDSMITH_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=endpoint_config.fanout,+ client_config=_client_config(api_key),+ path_format_values={"owner": workspace},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ incremental_field=incremental_field,+ incremental_config_factory=_cloudsmith_incremental_window,+ page_size_param="page_size",+ parent_endpoint_extra={+ "paginator": CloudsmithPaginator(page_size=parent_config.page_size),+ "data_selector_required": True,+ },+ child_endpoint_extra={+ "paginator": CloudsmithPaginator(page_size=endpoint_config.page_size),+ "data_selector_required": True,+ },+ child_params_extra=dict(endpoint_config.params) if endpoint_config.params else None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ if endpoint_config.strip_fields:+ dependent_resource = dependent_resource.add_map(_drop_fields(endpoint_config.strip_fields))+ items = cast(Iterable[Any], dependent_resource)+ return _make_source_response(endpoint_config, lambda: items)++ config: RESTAPIConfig = {+ "client": _client_config(api_key),+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(endpoint_config, workspace)],+ }++ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ return _make_source_response(endpoint_config, lambda: resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/settings.pynew file mode 100644index 000000000000..2700f7fce3ff--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/settings.py@@ -0,0 +1,153 @@+from dataclasses import dataclass, field+from typing import Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++CLOUDSMITH_BASE_URL = "https://api.cloudsmith.io/v1"++# Cloudsmith's list endpoints default to 30 results per page. 100 is the largest size the docs+# advertise, and it keeps the number of round trips down on repositories with many packages.+PAGE_SIZE = 100++# Cloudsmith reports the number of pages in a response header rather than the body, and returns+# 404 "Invalid page." for a page past the last one, so pagination has to stop on this header.+PAGE_TOTAL_HEADER = "X-Pagination-PageTotal"++UPLOADED_AT_INCREMENTAL: IncrementalField = {+ "label": "uploaded_at",+ "type": IncrementalFieldType.DateTime,+ "field": "uploaded_at",+ "field_type": IncrementalFieldType.DateTime,+}+++@dataclass+class CloudsmithEndpointConfig:+ name: str+ path: str+ primary_key: str | list[str]+ # Query params sent on every request for this endpoint, on top of pagination. Used to pin an+ # explicit sort so page boundaries stay stable while rows are inserted mid-walk.+ params: dict[str, str] = field(default_factory=dict)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ # Stable creation-time field used for datetime partitioning. None where the resource has no+ # non-mutating creation timestamp.+ partition_key: str | None = None+ page_size: int = PAGE_SIZE+ # Only meaningful for an endpoint with incremental fields, since it drives when the pipeline+ # checkpoints the watermark. Every other endpoint here is full refresh, so the default is+ # inert for them rather than a claim about the order Cloudsmith returns rows in.+ sort_mode: Literal["asc", "desc"] = "asc"+ fanout: DependentEndpointConfig | None = None+ # Response fields dropped from every row before it is yielded.+ strip_fields: tuple[str, ...] = ()+++# Every repository-scoped endpoint fans out from the workspace's repository list, binding the+# repository slug into `{repo}`. `{owner}` is pre-formatted from the configured workspace.+_REPOSITORY_FANOUT = DependentEndpointConfig(+ parent_name="repositories",+ resolve_param="repo",+ resolve_field="slug",+ include_from_parent=["slug"],+ # The framework injects the parent value as `_repositories_slug`; renaming it to+ # `repository_slug` gives every child table an explicit, stable parent column that does not+ # collide with a resource's own `repository` field.+ parent_field_renames={"slug": "repository_slug"},+ # Repositories are listed oldest-first so the parent walk is not reordered by activity+ # (`-created_at` is the API default, and `downloads`/`package_count` would shift mid-walk).+ parent_params={"sort": "created_at"},+)+++CLOUDSMITH_ENDPOINTS: dict[str, CloudsmithEndpointConfig] = {+ "repositories": CloudsmithEndpointConfig(+ name="repositories",+ path="/repos/{owner}/",+ primary_key="slug_perm",+ params={"sort": "created_at"},+ partition_key="created_at",+ ),+ "packages": CloudsmithEndpointConfig(+ name="packages",+ path="/packages/{owner}/{repo}/",+ # `slug_perm` is Cloudsmith's permanent package identifier, but the docs only promise it+ # is unique within its repository, and this table aggregates packages from every+ # repository in the workspace — so the parent repository is part of the key.+ primary_key=["repository_slug", "slug_perm"],+ # `date` is the ascending form of the endpoint's `-date` default and sorts on upload+ # time, which never changes — so pages do not shift as new packages are uploaded.+ params={"sort": "date"},+ # The `query` search filter accepts `uploaded:>=<datetime>`, a real server-side filter+ # that bounds the pages fetched. It only tracks upload time: a package whose status,+ # download count or scan result changes later keeps its original `uploaded_at`, so+ # those updates need a full refresh.+ incremental_fields=[UPLOADED_AT_INCREMENTAL],+ default_incremental_field="uploaded_at",+ partition_key="uploaded_at",+ # Fan-out interleaves repositories, so rows are never globally ascending by+ # `uploaded_at` even though each repository's own page walk is. Declaring `desc` makes+ # the pipeline persist the incremental watermark only once the whole sync completes, so+ # a partial run cannot advance it past repositories it never reached.+ sort_mode="desc",+ fanout=_REPOSITORY_FANOUT,+ ),+ "entitlements": CloudsmithEndpointConfig(+ name="entitlements",+ path="/entitlements/{owner}/{repo}/",+ primary_key=["repository_slug", "slug_perm"],+ params={"sort": "name"},+ partition_key="created_at",+ fanout=_REPOSITORY_FANOUT,+ # `token` is the download credential the entitlement hands out. Cloudsmith only fills it+ # in when `show_tokens=true` (which we never send), but it is stripped anyway so a future+ # API default change cannot copy live credentials into a queryable warehouse table.+ strip_fields=("token",),+ ),+ "webhooks": CloudsmithEndpointConfig(+ name="webhooks",+ path="/webhooks/{owner}/{repo}/",+ primary_key=["repository_slug", "slug_perm"],+ partition_key="created_at",+ fanout=_REPOSITORY_FANOUT,+ # `target_url` can embed an auth token in its path, query or userinfo, and `templates`+ # carries the rendered request bodies - both are credentials a project member could+ # replay from a warehouse table, so neither is synced.+ strip_fields=("target_url", "templates"),+ ),+ "vulnerabilities": CloudsmithEndpointConfig(+ name="vulnerabilities",+ path="/vulnerabilities/{owner}/",+ primary_key="identifier",+ partition_key="created_at",+ ),+ "audit_log": CloudsmithEndpointConfig(+ name="audit_log",+ path="/audit-log/{owner}/",+ primary_key="uuid",+ partition_key="event_at",+ ),+ "members": CloudsmithEndpointConfig(+ name="members",+ path="/orgs/{owner}/members/",+ primary_key="user_id",+ params={"sort": "user_name"},+ partition_key="joined_at",+ ),+ "teams": CloudsmithEndpointConfig(+ name="teams",+ path="/orgs/{owner}/teams/",+ primary_key="slug_perm",+ params={"sort": "name"},+ ),+}++ENDPOINTS = tuple(CLOUDSMITH_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in CLOUDSMITH_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/source.pyindex dc7ff0228bcc..7161844d2447 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/source.py@@ -1,13 +1,34 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith import (+ CloudsmithResumeConfig,+ cloudsmith_source,+ validate_credentials as validate_cloudsmith_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudsmith import (CloudsmithSourceConfig,)@@ -15,18 +36,112 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CloudsmithSource(SimpleSource[CloudsmithSourceConfig]):+class CloudsmithSource(ResumableSource[CloudsmithSourceConfig, CloudsmithResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog, safe for public docs+ # `/v1` is the only API Cloudsmith publishes and it is not a version the caller selects, so+ # the framework's unversioned default applies.+ api_docs_url = "https://help.cloudsmith.io/reference/introduction"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.CLOUDSMITH+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Cloudsmith rejected your API key. Create a new key in your Cloudsmith user settings and reconnect.",+ "403 Client Error": "Your Cloudsmith API key does not have permission to read this data. Check the key owner's repository access and reconnect.",+ "402 Client Error": "This table is not included in your Cloudsmith plan. The audit log is only available on some plans.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CloudsmithSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ # packages is merge-only: the `uploaded` filter is inclusive at its lower bound, so each+ # incremental run re-reads the boundary packages and append mode would duplicate them.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=("packages",))++ def validate_credentials(+ self,+ config: CloudsmithSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_cloudsmith_credentials(+ api_key=config.api_key,+ workspace=config.workspace,+ schema_name=schema_name,+ )++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloudsmithResumeConfig]:+ return ResumableSourceManager[CloudsmithResumeConfig](inputs, CloudsmithResumeConfig)++ def source_for_pipeline(+ self,+ config: CloudsmithSourceConfig,+ resumable_source_manager: ResumableSourceManager[CloudsmithResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return cloudsmith_source(+ api_key=config.api_key,+ workspace=config.workspace,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ 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,+ incremental_field=inputs.incremental_field,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.CLOUDSMITH,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cloudsmith",+ caption="""Sync your Cloudsmith repositories, packages, entitlements, webhooks, vulnerability scans, audit log, members and teams.++Create an API key in Cloudsmith under **Account settings → API settings**. The key inherits your own access, so use a key from a user who can see every repository you want to sync. The workspace is the slug in your Cloudsmith URLs, for example `acme` in `https://cloudsmith.io/~acme/`.+""",+ keywords=["package registry", "artifacts", "supply chain"],+ docsUrl="https://posthog.com/docs/cdp/sources/cloudsmith",iconPath="/static/services/cloudsmith.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="workspace",+ label="Workspace",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="acme",+ secret=False,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith.pynew file mode 100644index 000000000000..b81a8e63bdc9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith.py@@ -0,0 +1,407 @@+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith import (+ INVALID_WORKSPACE_ERROR,+ CloudsmithPaginator,+ CloudsmithResumeConfig,+ _cloudsmith_incremental_window,+ _format_uploaded_filter,+ cloudsmith_source,+ get_resource,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.settings import CLOUDSMITH_ENDPOINTS+++class _FakeResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++def _make_manager(resume_state: CloudsmithResumeConfig | None = None) -> Mock:+ manager = Mock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(page_total: str | None) -> Mock:+ response = Mock()+ response.headers = {} if page_total is None else {"X-Pagination-PageTotal": page_total}+ return response+++class TestCloudsmithTransport:+ @parameterized.expand(+ [+ # Cloudsmith answers a page past the last one with 404, so the header - not an+ # empty page - has to be what stops the walk.+ ("more_pages", "3", 100, True),+ ("last_page", "1", 100, False),+ ("empty_page", "5", 0, False),+ # Header missing or unparseable: fall back to the short-page heuristic.+ ("no_header_full_page", None, 100, True),+ ("no_header_short_page", None, 42, False),+ ("garbage_header_full_page", "not-a-number", 100, True),+ ("garbage_header_short_page", "not-a-number", 7, False),+ ]+ )+ def test_paginator_termination(self, _name, page_total, row_count, expected_has_next) -> None:+ paginator = CloudsmithPaginator(page_size=100)+ request = Mock()+ request.params = {}+ paginator.init_request(request)+ assert request.params["page"] == 1++ data = [{"slug_perm": str(i)} for i in range(row_count)]+ paginator.update_state(_response(page_total), data=data)++ assert paginator.has_next_page is expected_has_next++ def test_paginator_advances_page_number(self) -> None:+ paginator = CloudsmithPaginator(page_size=100)+ request = Mock()+ request.params = {"sort": "date"}+ paginator.init_request(request)++ paginator.update_state(_response("3"), data=[{"slug_perm": str(i)} for i in range(100)])+ paginator.update_request(request)++ assert request.params["page"] == 2+ assert request.params["sort"] == "date"++ def test_paginator_stops_after_walking_every_page(self) -> None:+ # A full last page still has to stop the walk: requesting the page after it is a 404,+ # not an empty page, so the inherited empty-page check never gets a chance to fire.+ paginator = CloudsmithPaginator(page_size=100)+ full_page = [{"slug_perm": str(i)} for i in range(100)]++ paginator.update_state(_response("2"), data=full_page)+ assert paginator.has_next_page is True++ paginator.update_state(_response("2"), data=full_page)+ assert paginator.has_next_page is False++ def test_paginator_resume_state_roundtrip(self) -> None:+ paginator = CloudsmithPaginator(page_size=100)+ paginator.update_state(_response("9"), data=[{"slug_perm": str(i)} for i in range(100)])++ state = paginator.get_resume_state()+ assert state == {"page": 2}++ resumed = CloudsmithPaginator(page_size=100)+ resumed.set_resume_state(cast(dict[str, Any], state))+ request = Mock()+ request.params = {}+ resumed.init_request(request)+ assert request.params["page"] == 2++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45, 999999), "uploaded:>=2026-03-01T12:30:45Z"),+ ("aware_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "uploaded:>=2026-03-01T12:30:45Z"),+ ("passthrough_string", "1970-01-01T00:00:00Z", "uploaded:>=1970-01-01T00:00:00Z"),+ ]+ )+ def test_format_uploaded_filter(self, _name, value, expected) -> None:+ # Cloudsmith rejects an unparseable search expression with a 400, and truncating to+ # whole seconds keeps the lower bound inclusive rather than skipping a package+ # uploaded in the same second as the watermark.+ assert _format_uploaded_filter(value) == expected++ def test_incremental_window_filters_server_side_via_query(self) -> None:+ # The filter only bounds the fetched pages if it rides the `query` search param;+ # any other param name is silently ignored and every sync refetches everything.+ window = _cloudsmith_incremental_window("uploaded_at")+ assert window["start_param"] == "query"+ assert window["cursor_path"] == "uploaded_at"+ assert window["convert"] is _format_uploaded_filter+ assert window["initial_value"] == "1970-01-01T00:00:00Z"++ @parameterized.expand(+ [+ (200, None, True, None),+ (+ 401,+ None,+ False,+ "Cloudsmith rejected the API key. Check the key in your Cloudsmith user settings and try again.",+ ),+ # A key only has access to some repositories, so a 403 must not block source+ # creation - only a per-table check.+ (403, None, True, None),+ (403, "packages", False, "Your Cloudsmith API key does not have permission to read this data."),+ (404, None, False, "Cloudsmith workspace 'acme' was not found, or this API key cannot see it."),+ (500, None, False, "Cloudsmith returned an unexpected response (HTTP 500)."),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.make_tracked_session"+ )+ def test_validate_credentials_status_mapping(+ self, status, schema_name, expected_valid, expected_message, mock_session+ ) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status)++ result = validate_credentials(api_key="key", workspace="acme", schema_name=schema_name)++ assert result == (expected_valid, expected_message)+ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://api.cloudsmith.io/v1/namespaces/acme/"+ assert call.kwargs["headers"]["X-Api-Key"] == "key"++ @parameterized.expand([("../../user", None), ("acme/repo", None), ("", None), ("with space", None)])+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.make_tracked_session"+ )+ def test_validate_credentials_rejects_unsafe_workspace(self, workspace, _unused, mock_session) -> None:+ # The workspace is interpolated straight into the request path, so a slug carrying+ # path separators has to be rejected before any request is made.+ assert validate_credentials(api_key="key", workspace=workspace) == (False, INVALID_WORKSPACE_ERROR)+ mock_session.assert_not_called()++ def test_cloudsmith_source_rejects_unsafe_workspace(self) -> None:+ with pytest.raises(ValueError, match="valid Cloudsmith workspace slug"):+ cloudsmith_source(+ api_key="key",+ workspace="../other",+ endpoint="repositories",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ @parameterized.expand(+ [+ ("repositories", "/repos/acme/", {"sort": "created_at"}),+ ("vulnerabilities", "/vulnerabilities/acme/", {}),+ ("audit_log", "/audit-log/acme/", {}),+ ("members", "/orgs/acme/members/", {"sort": "user_name"}),+ ("teams", "/orgs/acme/teams/", {"sort": "name"}),+ ]+ )+ def test_get_resource_binds_workspace_into_path(self, endpoint, expected_path, expected_extra_params) -> None:+ resource = cast(dict[str, Any], get_resource(CLOUDSMITH_ENDPOINTS[endpoint], "acme"))++ assert resource["name"] == endpoint+ assert resource["write_disposition"] == "replace"+ assert resource["table_format"] == "delta"+ assert resource["endpoint"]["path"] == expected_path+ assert resource["endpoint"]["params"] == {"page_size": 100, **expected_extra_params}+ assert isinstance(resource["endpoint"]["paginator"], CloudsmithPaginator)+ assert resource["endpoint"]["data_selector_required"] is True++ @parameterized.expand([("packages",), ("entitlements",), ("webhooks",)])+ def test_get_resource_rejects_fanout_endpoints(self, endpoint) -> None:+ with pytest.raises(ValueError, match="Fan-out endpoint"):+ get_resource(CLOUDSMITH_ENDPOINTS[endpoint], "acme")++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.rest_api_resource")+ def test_top_level_source_response(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()++ response = cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint="repositories",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert response.name == "repositories"+ assert response.primary_keys == ["slug_perm"]+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.rest_api_resource")+ def test_top_level_source_resumes_from_saved_state(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager(CloudsmithResumeConfig(paginator_state={"page": 4}))++ cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint="repositories",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ assert mock_rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"page": 4}++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.rest_api_resource")+ def test_source_saves_checkpoints_after_batches(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ manager = _make_manager()++ cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint="repositories",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ resume_hook = mock_rest_api_resource.call_args.kwargs["resume_hook"]+ resume_hook({"page": 3})+ manager.save_state.assert_called_once_with(CloudsmithResumeConfig(paginator_state={"page": 3}))++ # A terminal (None) checkpoint is not persisted - the Redis TTL handles cleanup.+ manager.save_state.reset_mock()+ resume_hook(None)+ manager.save_state.assert_not_called()++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_packages_fanout_row_format(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeResource("repositories", [{"slug": "prod"}]),+ _FakeResource("packages", [{"slug_perm": "abc", "name": "tool", "_repositories_slug": "prod"}]),+ ]++ response = cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint="packages",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert list(cast(Any, response.items())) == [{"slug_perm": "abc", "name": "tool", "repository_slug": "prod"}]+ # `slug_perm` is only documented as unique within a repository, and this table+ # aggregates every repository in the workspace.+ assert response.primary_keys == ["repository_slug", "slug_perm"]+ assert response.partition_keys == ["uploaded_at"]+ # Fan-out interleaves repositories, so rows never arrive globally ascending: desc mode+ # keeps a partial run from advancing the watermark past repositories it never reached.+ assert response.sort_mode == "desc"++ @parameterized.expand(+ [+ # The entitlement token is a live download credential.+ (+ "entitlements",+ {"slug_perm": "tok", "name": "ci", "token": "secret", "_repositories_slug": "prod"},+ {"slug_perm": "tok", "name": "ci", "repository_slug": "prod"},+ ),+ # `target_url` can embed an auth token and `templates` carries rendered request bodies.+ (+ "webhooks",+ {+ "slug_perm": "wh",+ "target_url": "https://example.com/hook?token=secret",+ "templates": [{"event": "package.created", "template": "{}"}],+ "is_active": True,+ "_repositories_slug": "prod",+ },+ {"slug_perm": "wh", "is_active": True, "repository_slug": "prod"},+ ),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_fanout_strips_secret_fields(self, endpoint, raw_row, expected_row, mock_rest_api_resources) -> None:+ # Credential-bearing fields must never land in a warehouse table any project member can query.+ mock_rest_api_resources.return_value = [+ _FakeResource("repositories", [{"slug": "prod"}]),+ _FakeResource(endpoint, [raw_row]),+ ]++ response = cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ )++ assert list(cast(Any, response.items())) == [expected_row]++ @parameterized.expand(+ [+ ("packages", {"sort": "date"}),+ ("entitlements", {"sort": "name"}),+ ("webhooks", None),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.build_dependent_resource"+ )+ def test_fanout_wiring(self, endpoint, expected_child_params, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = _FakeResource(endpoint, [])+ manager = _make_manager(CloudsmithResumeConfig(paginator_state={"completed": [], "current": None}))++ cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint=endpoint,+ team_id=1,+ job_id="job-1",+ resumable_source_manager=manager,+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["child_endpoint"] == endpoint+ assert kwargs["page_size_param"] == "page_size"+ # `{owner}` has to be pre-formatted: the fan-out helper only substitutes `{repo}`.+ assert kwargs["path_format_values"] == {"owner": "acme"}+ assert kwargs["fanout"].resolve_param == "repo"+ assert kwargs["fanout"].resolve_field == "slug"+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], CloudsmithPaginator)+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], CloudsmithPaginator)+ assert kwargs["child_params_extra"] == expected_child_params+ assert kwargs["incremental_config_factory"] is _cloudsmith_incremental_window+ assert kwargs["resume_hook"] is not None+ assert kwargs["initial_paginator_state"] == {"completed": [], "current": None}++ @parameterized.expand(+ [+ ("incremental", True, datetime(2026, 3, 1, tzinfo=UTC)),+ ("first_sync", True, None),+ ("non_incremental", False, datetime(2026, 3, 1, tzinfo=UTC)),+ ]+ )+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith.build_dependent_resource"+ )+ def test_packages_passes_watermark(+ self, _name, should_use_incremental_field, last_value, mock_build_dependent_resource+ ) -> None:+ mock_build_dependent_resource.return_value = _FakeResource("packages", [])++ cloudsmith_source(+ api_key="key",+ workspace="acme",+ endpoint="packages",+ team_id=1,+ job_id="job-1",+ resumable_source_manager=_make_manager(),+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=last_value,+ incremental_field="uploaded_at",+ )++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field+ assert kwargs["db_incremental_field_last_value"] == last_value+ assert kwargs["incremental_field"] == "uploaded_at"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith_source.pynew file mode 100644index 000000000000..07c62c30f193--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudsmith/tests/test_cloudsmith_source.py@@ -0,0 +1,161 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.cloudsmith import (+ CloudsmithResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.settings import (+ CLOUDSMITH_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.source import CloudsmithSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudsmith import (+ CloudsmithSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestCloudsmithSource:+ def setup_method(self) -> None:+ self.source = CloudsmithSource()+ self.team_id = 123+ self.config = CloudsmithSourceConfig(api_key="cloudsmith-key", workspace="acme")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.CLOUDSMITH++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Cloudsmith"+ assert config.label == "Cloudsmith"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The source ships visible: unreleasedSource hides the connector from every user.+ assert not config.unreleasedSource+ assert config.iconPath == "/static/services/cloudsmith.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/cloudsmith"++ @pytest.mark.parametrize(+ "name,expected_type,expected_secret",+ [+ ("api_key", SourceFieldInputConfigType.PASSWORD, True),+ ("workspace", SourceFieldInputConfigType.TEXT, False),+ ],+ )+ def test_source_fields(self, name, expected_type, expected_secret) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == name)+ assert field.type == expected_type+ assert field.secret is expected_secret+ assert field.required is True++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_incremental_semantics(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}++ # Only the packages list has a server-side time filter (`query=uploaded:>=...`);+ # everything else would have to fetch every page anyway, so it stays full refresh.+ for name in ("repositories", "entitlements", "webhooks", "vulnerabilities", "audit_log", "members", "teams"):+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ # packages is merge-only: the `uploaded` bound is inclusive, so each run re-reads the+ # boundary packages and append mode would duplicate them.+ assert schemas["packages"].supports_incremental is True+ assert schemas["packages"].supports_append is False+ assert [f["field"] for f in schemas["packages"].incremental_fields] == ["uploaded_at"]++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["packages"])+ assert [s.name for s in schemas] == ["packages"]++ @pytest.mark.parametrize(+ "endpoint",+ ["packages", "entitlements", "webhooks"],+ )+ def test_fanout_primary_keys_include_parent_repository(self, endpoint) -> None:+ # These tables aggregate rows from every repository in the workspace, and Cloudsmith+ # only documents `slug_perm` as unique within a repository - a key without the parent+ # would seed duplicate rows that every later merge multi-matches.+ assert CLOUDSMITH_ENDPOINTS[endpoint].primary_key == ["repository_slug", "slug_perm"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.cloudsmith.io/v1/repos/acme/",+ "403 Client Error: Forbidden for url: https://api.cloudsmith.io/v1/packages/acme/prod/",+ "402 Client Error: Payment Required for url: https://api.cloudsmith.io/v1/audit-log/acme/",+ ],+ )+ def test_non_retryable_errors_match_permanent_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient_failures(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(+ key in "500 Server Error for url: https://api.cloudsmith.io/v1/repos/acme/" for key in non_retryable+ )++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.source.validate_cloudsmith_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="packages")++ assert result == (True, None)+ mock_validate.assert_called_once_with(api_key="cloudsmith-key", workspace="acme", schema_name="packages")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is CloudsmithResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.source.cloudsmith_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_cloudsmith_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "packages"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"+ inputs.should_use_incremental_field = True+ inputs.incremental_field = "uploaded_at"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_cloudsmith_source.call_args.kwargs+ assert kwargs["api_key"] == "cloudsmith-key"+ assert kwargs["workspace"] == "acme"+ assert kwargs["endpoint"] == "packages"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["incremental_field"] == "uploaded_at"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.cloudsmith.source.cloudsmith_source")+ def test_source_for_pipeline_omits_watermark_when_not_incremental(+ self, mock_cloudsmith_source: mock.MagicMock+ ) -> None:+ 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_cloudsmith_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ assert set(self.source.get_canonical_descriptions().keys()) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudsmith.pyindex b29aea56c601..c50e47d1a561 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudsmith.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudsmith.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CloudsmithSourceConfig(config.Config):- pass+ api_key: str+ workspace: str