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 the cloudinary import source (#108035)

Tom Owers88baca584e29
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 313d47a23b99..06d0a3977fb1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -170,6 +170,7 @@ the row lists both.
| clever | HTTP | requests + `rest_source.RESTClient` | ✅ |
| cliniko | HTTP | requests + `rest_source.RESTClient` | ✅ |
| cloudability | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| cloudinary | HTTP | requests + `rest_source.RESTClient` | ✅ |
| cloudzero | HTTP | requests + `rest_source.RESTClient` | ✅ |
| coassemble | HTTP | requests | ✅ |
| coda | HTTP | requests | ✅ |
@@ -970,7 +971,6 @@ doesn't conflict with concurrent PRs.
- clio
- clip
- cloudbeds
-- cloudinary
- clover
- coassemble
- cockroachdb
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/canonical_descriptions.py
new file mode 100644
index 000000000000..b00fd41e46ea
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/canonical_descriptions.py
@@ -0,0 +1,70 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_ASSET_COLUMNS = {
+ "asset_id": "Unique identifier for the asset, stable across renames.",
+ "public_id": "Identifier used to build the asset's delivery URL, including its folder path.",
+ "folder": "Folder the asset sits in.",
+ "format": "File format, such as jpg, png, or mp4.",
+ "version": "Version number, which changes each time the asset is overwritten.",
+ "resource_type": "Asset type: image, video, or raw.",
+ "type": "Delivery type, such as upload, private, or authenticated.",
+ "created_at": "Date and time the asset was uploaded.",
+ "uploaded_at": "Date and time the current version was uploaded.",
+ "bytes": "File size in bytes.",
+ "width": "Width in pixels.",
+ "height": "Height in pixels.",
+ "url": "HTTP delivery URL for the asset.",
+ "secure_url": "HTTPS delivery URL for the asset.",
+ "tags": "Tags applied to the asset.",
+ "context": "Contextual metadata key-value pairs stored on the asset.",
+ "access_mode": "Whether the asset is publicly accessible or restricted.",
+ "backup_bytes": "Size of the asset's backed-up versions in bytes.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "images": {
+ "description": "An image in the Cloudinary media library, with its delivery URLs, size, and metadata.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_resources",
+ "columns": dict(_ASSET_COLUMNS),
+ },
+ "videos": {
+ "description": "A video in the Cloudinary media library, with its delivery URLs, size, and metadata.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_resources",
+ "columns": {**_ASSET_COLUMNS, "duration": "Length of the video in seconds."},
+ },
+ "raw_files": {
+ "description": "A raw file in the Cloudinary media library, meaning one stored without image or video processing.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_resources",
+ "columns": dict(_ASSET_COLUMNS),
+ },
+ "folders": {
+ "description": "A folder in the Cloudinary media library.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_folders",
+ "columns": {
+ "name": "Folder name.",
+ "path": "Full path of the folder, including its parents.",
+ "external_id": "Cloudinary's identifier for the folder.",
+ },
+ },
+ "transformations": {
+ "description": "A stored transformation, meaning a named recipe Cloudinary applies when delivering an asset.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_transformations",
+ "columns": {
+ "name": "Transformation name, either the named transformation or its parameter string.",
+ "named": "Whether the transformation was given a name rather than generated from parameters.",
+ "allowed_for_strict": "Whether the transformation is allowed when strict transformations are on.",
+ "used": "Whether the transformation has been used to deliver an asset.",
+ },
+ },
+ "upload_presets": {
+ "description": "An upload preset, meaning a saved set of upload options that clients can apply by name.",
+ "docs_url": "https://cloudinary.com/documentation/admin_api#get_upload_presets",
+ "columns": {
+ "name": "Preset name, used by clients when uploading.",
+ "unsigned": "Whether the preset allows unsigned uploads from the browser.",
+ "settings": "Upload options the preset applies, such as folder, tags, and transformations.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/cloudinary.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/cloudinary.py
new file mode 100644
index 000000000000..9cfe1c9a8920
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/cloudinary.py
@@ -0,0 +1,112 @@
+import dataclasses
+from typing import Any, Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.settings import CLOUDINARY_ENDPOINTS
+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.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+CLOUDINARY_API_HOSTS = {
+ "global": "https://api.cloudinary.com",
+ "eu": "https://api-eu.cloudinary.com",
+ "ap": "https://api-ap.cloudinary.com",
+}
+REQUEST_TIMEOUT_SECONDS = 30
+
+
[email protected](frozen=True)
+class CloudinaryResumeConfig:
+ cursor: str
+
+
+def base_url(cloud_name: str, region: str) -> str:
+ host = CLOUDINARY_API_HOSTS.get(region, CLOUDINARY_API_HOSTS["global"])
+ return f"{host}/v1_1/{cloud_name}"
+
+
+def get_resource(endpoint: str) -> EndpointResource:
+ config = CLOUDINARY_ENDPOINTS[endpoint]
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "primary_key": config.primary_key,
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": f"{config.data_key}[*]",
+ "path": config.path,
+ "params": dict(config.params),
+ },
+ "table_format": "delta",
+ }
+
+
+def cloudinary_source(
+ cloud_name: str,
+ api_key: str,
+ api_secret: str,
+ region: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[CloudinaryResumeConfig],
+):
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": base_url(cloud_name, region),
+ "auth": {"type": "http_basic", "username": api_key, "password": api_secret},
+ "paginator": JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="next_cursor"),
+ },
+ "resource_defaults": {"write_disposition": "replace"},
+ "resources": [get_resource(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 = {"cursor": resume_config.cursor}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state and state.get("cursor"):
+ resumable_source_manager.save_state(CloudinaryResumeConfig(cursor=str(state["cursor"])))
+
+ return rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def validate_credentials(cloud_name: str, api_key: str, api_secret: str, region: str) -> tuple[bool, Optional[str]]:
+ """Ping is the one Admin API call that costs nothing against the hourly quota."""
+ try:
+ response = make_tracked_session(redact_values=(api_secret,)).get(
+ f"{base_url(cloud_name, region)}/ping",
+ auth=(api_key, api_secret),
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ return False, "Could not reach the Cloudinary API. Check your connection and try again."
+
+ if response.ok:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, (
+ "Cloudinary rejected these credentials. Check the API key and secret in your Cloudinary console, "
+ "under Settings then API Keys."
+ )
+ if response.status_code == 404:
+ return False, "Cloudinary does not recognize this cloud name. Copy it from your Cloudinary console."
+ if response.status_code == 420 or response.status_code == 429:
+ return False, "This Cloudinary account has hit its hourly Admin API limit. Wait for the limit to reset."
+ return False, f"Cloudinary returned an unexpected error ({response.status_code}) while checking these credentials."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/settings.py
new file mode 100644
index 000000000000..9bb5b453db5c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/settings.py
@@ -0,0 +1,77 @@
+from dataclasses import field
+from typing import Any, Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+
+@frozen
+class CloudinaryEndpointConfig:
+ name: str
+ path: str
+ # Key the rows sit under in the response envelope.
+ data_key: str
+ primary_key: str
+ params: dict[str, Any] = field(default_factory=dict)
+ partition_key: Optional[str] = None
+
+
+# Cloudinary caps a page at 500 rows and counts every call against an hourly quota, so ask for the
+# largest page it allows.
+MAX_RESULTS = 500
+
+CLOUDINARY_ENDPOINTS: dict[str, CloudinaryEndpointConfig] = {
+ "images": CloudinaryEndpointConfig(
+ name="images",
+ path="/resources/image",
+ data_key="resources",
+ primary_key="asset_id",
+ params={"max_results": MAX_RESULTS, "context": "true", "tags": "true"},
+ partition_key="created_at",
+ ),
+ "videos": CloudinaryEndpointConfig(
+ name="videos",
+ path="/resources/video",
+ data_key="resources",
+ primary_key="asset_id",
+ params={"max_results": MAX_RESULTS, "context": "true", "tags": "true"},
+ partition_key="created_at",
+ ),
+ "raw_files": CloudinaryEndpointConfig(
+ name="raw_files",
+ path="/resources/raw",
+ data_key="resources",
+ primary_key="asset_id",
+ params={"max_results": MAX_RESULTS, "context": "true", "tags": "true"},
+ partition_key="created_at",
+ ),
+ "folders": CloudinaryEndpointConfig(
+ name="folders",
+ path="/folders",
+ data_key="folders",
+ primary_key="path",
+ params={"max_results": MAX_RESULTS},
+ ),
+ "transformations": CloudinaryEndpointConfig(
+ name="transformations",
+ path="/transformations",
+ data_key="transformations",
+ primary_key="name",
+ params={"max_results": MAX_RESULTS},
+ ),
+ "upload_presets": CloudinaryEndpointConfig(
+ name="upload_presets",
+ path="/upload_presets",
+ data_key="presets",
+ primary_key="name",
+ params={"max_results": MAX_RESULTS},
+ ),
+}
+
+ENDPOINTS = tuple(CLOUDINARY_ENDPOINTS.keys())
+
+# Cloudinary's only time filter on the asset lists is `start_at`, which selects on update time while
+# the list itself is ordered by creation time. A watermark built on it would skip rows, so every
+# table is a full refresh until that ordering can be verified against a live account.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/source.py
index d3d466af0e89..6dda597987fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/source.py
@@ -1,8 +1,34 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.cloudinary import (
+ CloudinaryResumeConfig,
+ cloudinary_source,
+ validate_credentials as validate_cloudinary_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.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, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudinary import (
CloudinarySourceConfig,
)
@@ -10,19 +36,127 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CloudinarySource(SimpleSource[CloudinarySourceConfig]):
+class CloudinarySource(ResumableSource[CloudinarySourceConfig, CloudinaryResumeConfig]):
+ supported_versions = ("v1_1",)
+ default_version = "v1_1"
+ api_docs_url = "https://cloudinary.com/documentation/admin_api"
+
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CLOUDINARY
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api": "Cloudinary rejected these credentials. Check the API key and secret in your Cloudinary console and reconnect the source.",
+ "403 Client Error: Forbidden for url: https://api": "These Cloudinary credentials cannot read this data. Check the key's permissions and reconnect the source.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.CLOUDINARY,
category=DataWarehouseSourceCategory.FILE_STORAGE,
label="Cloudinary",
- keywords=["cloudinary.com"],
+ caption="""Enter your Cloudinary cloud name, API key, and API secret to sync your media library metadata into the PostHog Data warehouse: images, videos, raw files, folders, transformations, and upload presets.
+
+Find all three in your Cloudinary console under Settings, then API Keys. The source only reads metadata, so a key with read access is enough. Media files themselves are never downloaded.
+
+Cloudinary limits Admin API calls per hour, 500 on free plans, so a first sync of a large media library can take a while.""",
iconPath="/static/services/cloudinary.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/cloudinary",
+ keywords=["cloudinary.com", "media", "images", "cdn"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="cloud_name",
+ label="Cloud name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-cloud",
+ secret=False,
+ caption="Shown at the top of your Cloudinary console.",
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_secret",
+ label="API secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="global",
+ options=[
+ SourceFieldSelectConfigOption(label="Global (api.cloudinary.com)", value="global"),
+ SourceFieldSelectConfigOption(label="Europe (api-eu.cloudinary.com)", value="eu"),
+ SourceFieldSelectConfigOption(label="Asia Pacific (api-ap.cloudinary.com)", value="ap"),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: CloudinarySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: CloudinarySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_cloudinary_credentials(config.cloud_name, config.api_key, config.api_secret, config.region)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CloudinaryResumeConfig]:
+ return ResumableSourceManager[CloudinaryResumeConfig](inputs, CloudinaryResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CloudinarySourceConfig,
+ resumable_source_manager: ResumableSourceManager[CloudinaryResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in ENDPOINTS:
+ raise ValueError(f"Unknown Cloudinary endpoint: {inputs.schema_name}")
+
+ return cloudinary_source(
+ cloud_name=config.cloud_name,
+ api_key=config.api_key,
+ api_secret=config.api_secret,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary.py
new file mode 100644
index 000000000000..62be7f0a6209
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary.py
@@ -0,0 +1,168 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.cloudinary import (
+ CloudinaryResumeConfig,
+ base_url,
+ cloudinary_source,
+ get_resource,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.settings import (
+ CLOUDINARY_ENDPOINTS,
+ MAX_RESULTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponseCursorPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+
+_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.cloudinary"
+
+
+def _manager(resume_state: CloudinaryResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(status_code: int = 200) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ return response
+
+
+def _source(endpoint: str = "images", region: str = "global", manager: mock.MagicMock | None = None) -> Resource:
+ return cloudinary_source("my-cloud", "key", "secret", region, endpoint, 1, "job", manager or _manager())
+
+
+class TestCloudinaryRegions:
+ @pytest.mark.parametrize(
+ "region,expected",
+ [
+ ("global", "https://api.cloudinary.com/v1_1/my-cloud"),
+ ("eu", "https://api-eu.cloudinary.com/v1_1/my-cloud"),
+ ("ap", "https://api-ap.cloudinary.com/v1_1/my-cloud"),
+ ("not-a-region", "https://api.cloudinary.com/v1_1/my-cloud"),
+ ],
+ )
+ def test_each_region_maps_to_its_host(self, region: str, expected: str) -> None:
+ assert base_url("my-cloud", region) == expected
+
+
+class TestCloudinaryResources:
+ @pytest.mark.parametrize("endpoint", sorted(CLOUDINARY_ENDPOINTS))
+ def test_rows_are_selected_from_the_endpoints_own_envelope(self, endpoint: str) -> None:
+ config = CLOUDINARY_ENDPOINTS[endpoint]
+ resource = get_resource(endpoint)
+ endpoint_config = resource["endpoint"]
+ assert endpoint_config is not None and not isinstance(endpoint_config, str)
+ assert endpoint_config["data_selector"] == f"{config.data_key}[*]"
+ assert resource["primary_key"] == config.primary_key
+
+ @pytest.mark.parametrize("endpoint", sorted(CLOUDINARY_ENDPOINTS))
+ def test_every_endpoint_asks_for_the_largest_page(self, endpoint: str) -> None:
+ # Cloudinary counts each call against an hourly quota, so a small page multiplies the cost.
+ endpoint_config = get_resource(endpoint)["endpoint"]
+ assert endpoint_config is not None and not isinstance(endpoint_config, str)
+ params = endpoint_config["params"]
+ assert params is not None
+ assert params["max_results"] == MAX_RESULTS
+
+ @pytest.mark.parametrize("endpoint", ["images", "videos", "raw_files"])
+ def test_asset_tables_ask_for_tags_and_context(self, endpoint: str) -> None:
+ # Cloudinary omits both unless asked, and they are the fields users join on.
+ endpoint_config = get_resource(endpoint)["endpoint"]
+ assert endpoint_config is not None and not isinstance(endpoint_config, str)
+ params = endpoint_config["params"]
+ assert params is not None
+ assert params["tags"] == "true"
+ assert params["context"] == "true"
+
+
+class TestCloudinarySource:
+ def test_pages_are_walked_with_cloudinarys_cursor_field(self) -> None:
+ with mock.patch(f"{_MODULE}.rest_api_resource") as rest_api_resource:
+ _source()
+
+ paginator = rest_api_resource.call_args.args[0]["client"]["paginator"]
+ assert isinstance(paginator, JSONResponseCursorPaginator)
+ assert paginator.cursor_path == "next_cursor"
+ assert paginator.cursor_param == "next_cursor"
+
+ def test_the_key_and_secret_ride_basic_auth(self) -> None:
+ with mock.patch(f"{_MODULE}.rest_api_resource") as rest_api_resource:
+ _source()
+
+ assert rest_api_resource.call_args.args[0]["client"]["auth"] == {
+ "type": "http_basic",
+ "username": "key",
+ "password": "secret",
+ }
+
+ def test_a_saved_cursor_seeds_the_paginator(self) -> None:
+ with mock.patch(f"{_MODULE}.rest_api_resource") as rest_api_resource:
+ _source(manager=_manager(CloudinaryResumeConfig(cursor="page-2")))
+
+ assert rest_api_resource.call_args.kwargs["initial_paginator_state"] == {"cursor": "page-2"}
+
+ def test_only_a_real_cursor_is_checkpointed(self) -> None:
+ manager = _manager()
+ with mock.patch(f"{_MODULE}.rest_api_resource") as rest_api_resource:
+ _source(manager=manager)
+
+ resume_hook = rest_api_resource.call_args.kwargs["resume_hook"]
+ resume_hook({})
+ resume_hook(None)
+ assert manager.save_state.call_args_list == []
+
+ resume_hook({"cursor": "next"})
+ assert manager.save_state.call_args_list == [mock.call(CloudinaryResumeConfig(cursor="next"))]
+
+
+class TestCloudinaryCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected_valid",
+ [(200, True), (401, False), (403, False), (404, False), (420, False), (429, False), (500, False)],
+ )
+ def test_status_maps_to_a_verdict(self, status_code: int, expected_valid: bool) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = _response(status_code)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ valid, message = validate_credentials("my-cloud", "key", "secret", "global")
+
+ assert valid is expected_valid
+ assert (message is None) is expected_valid
+
+ def test_an_unknown_cloud_name_is_called_out(self) -> None:
+ session = mock.MagicMock()
+ session.get.return_value = _response(404)
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ _, message = validate_credentials("my-cloud", "key", "secret", "global")
+
+ assert message is not None and "cloud name" in message
+
+ def test_the_probe_costs_nothing_against_the_quota(self) -> None:
+ # /ping is the one Admin API call Cloudinary does not bill to the hourly limit.
+ session = mock.MagicMock()
+ session.get.return_value = _response()
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ validate_credentials("my-cloud", "key", "secret", "eu")
+
+ assert session.get.call_args.args[0] == "https://api-eu.cloudinary.com/v1_1/my-cloud/ping"
+ assert session.get.call_args.kwargs["auth"] == ("key", "secret")
+
+ def test_an_unreachable_api_is_reported_rather_than_raised(self) -> None:
+ session = mock.MagicMock()
+ session.get.side_effect = ConnectionError("no route")
+
+ with mock.patch(f"{_MODULE}.make_tracked_session", return_value=session):
+ valid, message = validate_credentials("my-cloud", "key", "secret", "global")
+
+ assert valid is False
+ assert message is not None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary_source.py
new file mode 100644
index 000000000000..453ca8d43b3a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cloudinary/tests/test_cloudinary_source.py
@@ -0,0 +1,32 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.source import CloudinarySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cloudinary import (
+ CloudinarySourceConfig,
+)
+
+_SOURCE = "products.warehouse_sources.backend.temporal.data_imports.sources.cloudinary.source"
+
+
+def _config() -> CloudinarySourceConfig:
+ return CloudinarySourceConfig(cloud_name="my-cloud", api_key="key", api_secret="secret", region="eu")
+
+
+class TestCloudinarySourceClass:
+ def test_an_unknown_schema_fails_before_any_request_goes_out(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_cloudinary_table"
+
+ with pytest.raises(ValueError, match="Unknown Cloudinary endpoint"):
+ CloudinarySource().source_for_pipeline(_config(), mock.MagicMock(), inputs)
+
+ def test_the_configured_region_reaches_the_transport(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "images"
+
+ with mock.patch(f"{_SOURCE}.cloudinary_source") as cloudinary_source:
+ CloudinarySource().source_for_pipeline(_config(), mock.MagicMock(), inputs)
+
+ assert cloudinary_source.call_args.kwargs["region"] == "eu"
+ assert cloudinary_source.call_args.kwargs["cloud_name"] == "my-cloud"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudinary.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudinary.py
index 6c63f90263cb..8fe723fe96e4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudinary.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cloudinary.py
@@ -1,9 +1,14 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@config.config
class CloudinarySourceConfig(config.Config):
- pass
+ cloud_name: str
+ api_key: str
+ api_secret: str
+ region: Literal["global", "eu", "ap"] = config.value(default="global")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
index 2d51b2096c76..4e01ccefce1d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
@@ -48,6 +48,7 @@ CREDENTIAL_FIELD = re.compile(r"api[_-]?key|access[_-]?key|token|secret|password
# ending in `_id`/`_ids` is exempt for the same reason without needing an entry here.
PUBLIC_CREDENTIAL_HALVES = {
"Adjust.app_tokens",
+ "Cloudinary.api_key",
"ConfluentCloud.api_key",
"Fleetio.account_token",
"Gong.access_key",