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 shutterstock import source (#72629)

Tom Owersc75b2adcba49
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 9ccee29dbd83..7859ee5677d1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -483,6 +483,7 @@ the row lists both.
| shopwired | HTTP | requests | ✅ |
| shortcut | HTTP | requests | ✅ |
| shortio | HTTP | requests | ✅ |
+| shutterstock | HTTP | requests + `rest_source.RESTClient` | ✅ |
| signoz | HTTP | requests | ✅ |
| simfin | HTTP | requests | ✅ |
| simplecast | HTTP | requests | ✅ |
@@ -926,7 +927,6 @@ doesn't conflict with concurrent PRs.
- shopware
- shopwired
- shortio
-- shutterstock
- sigma_computing
- signnow
- sim
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shutterstock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shutterstock.py
index d317f768a1f8..d920fba43738 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shutterstock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/shutterstock.py
@@ -1,9 +1,19 @@
# 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
+class ShutterstockAuthMethodConfig(config.Config):
+ selection: Literal["api_key", "access_token"] = "api_key"
+ consumer_key: str | None = None
+ consumer_secret: str | None = None
+ access_token: str | None = None
+
+
@config.config
class ShutterstockSourceConfig(config.Config):
- pass
+ auth_method: ShutterstockAuthMethodConfig
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/canonical_descriptions.py
new file mode 100644
index 000000000000..3b879e09a63b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/canonical_descriptions.py
@@ -0,0 +1,94 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_CATEGORY_COLUMNS = {
+ "id": "Category ID.",
+ "name": "Category name.",
+}
+
+_UPDATED_MEDIA_COLUMNS = {
+ "id": "ID of the media item that was updated.",
+ "updated_time": "Date that the media item was updated.",
+ "updates": "Types of updates that were made to the media item (addition, deletion, or edit).",
+}
+
+_COLLECTION_COLUMNS = {
+ "id": "The collection ID.",
+ "name": "The name of the collection.",
+ "created_time": "When the collection was created.",
+ "updated_time": "The last time the collection itself was updated (other than changes to the items in it).",
+ "items_updated_time": "The last time this collection's items were updated.",
+ "total_item_count": "The number of items in the collection.",
+ "cover_item": "The media item shown as the collection's cover.",
+ "share_code": "A code that can be used to share the collection.",
+ "share_url": "The browser URL that can be used to share the collection.",
+}
+
+_LICENSE_COLUMNS = {
+ "id": "ID of the download event.",
+ "download_time": "Date the media was downloaded the first time.",
+ "license": "The name of the license of this download.",
+ "is_downloadable": "Whether the media is still downloadable via its downloads endpoint.",
+ "metadata": "The metadata that was passed in the original licensing request.",
+ "subscription_id": "ID of the subscription used to perform this download.",
+ "user": "The user that performed the download.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "image_categories": {
+ "description": "Categories that Shutterstock images can belong to.",
+ "docs_url": "https://api-reference.shutterstock.com/#images-list-image-categories",
+ "columns": _CATEGORY_COLUMNS,
+ },
+ "video_categories": {
+ "description": "Categories that Shutterstock videos can belong to.",
+ "docs_url": "https://api-reference.shutterstock.com/#videos-list-video-categories",
+ "columns": _CATEGORY_COLUMNS,
+ },
+ "images_updated": {
+ "description": "Images that were recently added, deleted, or edited in the Shutterstock catalog.",
+ "docs_url": "https://api-reference.shutterstock.com/#images-list-updated-images",
+ "columns": _UPDATED_MEDIA_COLUMNS,
+ },
+ "videos_updated": {
+ "description": "Videos that were recently added, deleted, or edited in the Shutterstock catalog.",
+ "docs_url": "https://api-reference.shutterstock.com/#videos-list-updated-videos",
+ "columns": _UPDATED_MEDIA_COLUMNS,
+ },
+ "image_collections": {
+ "description": "The account's image collections (lightboxes).",
+ "docs_url": "https://api-reference.shutterstock.com/#images-list-image-collections",
+ "columns": _COLLECTION_COLUMNS,
+ },
+ "video_collections": {
+ "description": "The account's video collections (clipboxes).",
+ "docs_url": "https://api-reference.shutterstock.com/#videos-list-video-collections",
+ "columns": _COLLECTION_COLUMNS,
+ },
+ "image_licenses": {
+ "description": "The account's image license history: one row per image download event.",
+ "docs_url": "https://api-reference.shutterstock.com/#images-list-image-licenses",
+ "columns": {**_LICENSE_COLUMNS, "image": "Details of the licensed image."},
+ },
+ "video_licenses": {
+ "description": "The account's video license history: one row per video download event.",
+ "docs_url": "https://api-reference.shutterstock.com/#videos-list-video-licenses",
+ "columns": {**_LICENSE_COLUMNS, "video": "Details of the licensed video."},
+ },
+ "subscriptions": {
+ "description": "The account's Shutterstock subscriptions and their download allotments.",
+ "docs_url": "https://api-reference.shutterstock.com/#users-list-user-subscriptions",
+ "columns": {
+ "id": "Unique internal identifier for the subscription.",
+ "description": "Description of the subscription.",
+ "license": "Internal identifier for the type of subscription.",
+ "asset_type": "Type of assets associated with this subscription (images, videos, audio, editorial).",
+ "expiration_time": "Date the subscription ends.",
+ "formats": "List of formats that are licensable for the subscription.",
+ "allotment": "Download credit allotment: credits remaining, total credits, and the subscription period.",
+ "metadata": "Metadata fields the subscription requires with each licensing request.",
+ "price_per_download": "Price per download for the subscription.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/settings.py
new file mode 100644
index 000000000000..ce710e4abc73
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/settings.py
@@ -0,0 +1,144 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class ShutterstockEndpointConfig:
+ name: str
+ # Path under https://api.shutterstock.com.
+ path: str
+ incremental_fields: list[IncrementalField]
+ # Page size for page-number paginated endpoints; None = single unpaginated response.
+ page_size: Optional[int] = None
+ # Stable datetime field used for datetime partitioning. Only set where the field is
+ # present on every row (never a mutable `updated_*` field — those rewrite partitions).
+ partition_key: Optional[str] = None
+ # Cursor field the API's `start_date` server-side filter narrows on. When set, the
+ # request also passes `sort=oldest` so rows arrive in ascending cursor order and the
+ # incremental watermark advances correctly.
+ cursor_field: Optional[str] = None
+ # True only where Shutterstock exposes a genuine server-side `start_date` filter.
+ supports_incremental: bool = False
+ # OAuth scope needed by this endpoint. Endpoints with a scope require an OAuth access
+ # token; the consumer key/secret (HTTP Basic) auth method cannot reach them.
+ required_scope: Optional[str] = None
+ # For the `updated` feeds: with no `start_date` the API defaults to a 1-hour interval,
+ # so the first sync bounds its window to this many days back instead.
+ default_lookback_days: Optional[int] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# Shutterstock v2 REST API (https://api-reference.shutterstock.com/).
+#
+# Catalog-wide search endpoints are deliberately excluded: they enumerate Shutterstock's
+# whole media library, not the customer's account data. Incremental support is set only
+# for resources that document a server-side `start_date` filter narrowing on a stable
+# timestamp (`updated` feeds -> updated_time, license history -> download_time); those
+# endpoints also accept `sort=oldest` for ascending cursor order. Everything else is
+# full refresh.
+SHUTTERSTOCK_ENDPOINTS: dict[str, ShutterstockEndpointConfig] = {
+ "image_categories": ShutterstockEndpointConfig(
+ name="image_categories",
+ path="/v2/images/categories",
+ incremental_fields=[],
+ ),
+ "video_categories": ShutterstockEndpointConfig(
+ name="video_categories",
+ path="/v2/videos/categories",
+ incremental_fields=[],
+ ),
+ "images_updated": ShutterstockEndpointConfig(
+ name="images_updated",
+ path="/v2/images/updated",
+ page_size=500,
+ cursor_field="updated_time",
+ supports_incremental=True,
+ default_lookback_days=30,
+ incremental_fields=[
+ {
+ "label": "updated_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "videos_updated": ShutterstockEndpointConfig(
+ name="videos_updated",
+ path="/v2/videos/updated",
+ page_size=500,
+ cursor_field="updated_time",
+ supports_incremental=True,
+ default_lookback_days=30,
+ incremental_fields=[
+ {
+ "label": "updated_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updated_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "image_collections": ShutterstockEndpointConfig(
+ name="image_collections",
+ path="/v2/images/collections",
+ page_size=100,
+ required_scope="collections.view",
+ incremental_fields=[],
+ ),
+ "video_collections": ShutterstockEndpointConfig(
+ name="video_collections",
+ path="/v2/videos/collections",
+ page_size=100,
+ required_scope="collections.view",
+ incremental_fields=[],
+ ),
+ "image_licenses": ShutterstockEndpointConfig(
+ name="image_licenses",
+ path="/v2/images/licenses",
+ page_size=200,
+ partition_key="download_time",
+ cursor_field="download_time",
+ supports_incremental=True,
+ required_scope="licenses.view",
+ incremental_fields=[
+ {
+ "label": "download_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "download_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "video_licenses": ShutterstockEndpointConfig(
+ name="video_licenses",
+ path="/v2/videos/licenses",
+ page_size=200,
+ partition_key="download_time",
+ cursor_field="download_time",
+ supports_incremental=True,
+ required_scope="licenses.view",
+ incremental_fields=[
+ {
+ "label": "download_time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "download_time",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "subscriptions": ShutterstockEndpointConfig(
+ name="subscriptions",
+ path="/v2/user/subscriptions",
+ required_scope="purchases.view",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(SHUTTERSTOCK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SHUTTERSTOCK_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/shutterstock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/shutterstock.py
new file mode 100644
index 000000000000..b6d9bd83fcba
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/shutterstock.py
@@ -0,0 +1,226 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+from requests.auth import HTTPBasicAuth
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ AuthConfig,
+ Endpoint,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.settings import (
+ SHUTTERSTOCK_ENDPOINTS,
+)
+
+SHUTTERSTOCK_BASE_URL = "https://api.shutterstock.com"
+
+# Hard cap so a runaway pagination loop (e.g. the API never returning an empty page) can't
+# scan forever. Page sizes are 100-500, so this bounds a single endpoint sync.
+MAX_PAGES = 100_000
+
+
+class ShutterstockResumeConfig:
+ # Next 1-indexed page to fetch.
+ page: int
+
+
[email protected](frozen=True)
+class ShutterstockAuth:
+ """Either an app consumer key/secret pair (HTTP Basic) or an OAuth access token
+ (Bearer). Account-scoped endpoints (collections, licenses, subscriptions) require the
+ OAuth token; the catalog feeds work with either."""
+
+ consumer_key: str | None = None
+ consumer_secret: str | None = None
+ access_token: str | None = None
+
+
+def _auth_config(auth: ShutterstockAuth) -> AuthConfig:
+ # Framework auth so the credential values are redacted from logs/samples.
+ if auth.access_token:
+ return {"type": "bearer", "token": auth.access_token}
+ return {
+ "type": "http_basic",
+ "username": auth.consumer_key or "",
+ "password": auth.consumer_secret or "",
+ }
+
+
+def _format_start_date(value: Any) -> str | None:
+ """Format an incremental cursor value as the ISO 8601 `start_date` the API filters on.
+
+ Second precision, UTC offset form (the docs' examples use offset datetimes). Flooring
+ to the second re-fetches boundary rows at worst; the merge dedupes them on the
+ primary key.
+ """
+ if isinstance(value, datetime):
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=UTC)
+ return value.astimezone(UTC).replace(microsecond=0).isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ if isinstance(value, str) and value:
+ return value
+ return None
+
+
+def validate_credentials(auth: ShutterstockAuth) -> bool:
+ """Confirm the credentials are genuine by hitting a cheap endpoint every valid
+ credential type can reach (image categories accepts both Basic and Bearer auth with
+ no scopes)."""
+ ok, _status = _probe_endpoint(auth, "/v2/images/categories")
+ return ok
+
+
+def check_endpoint_access(auth: ShutterstockAuth, endpoint: str) -> str | None:
+ """Per-endpoint scope probe for the schema picker. Only a real denial (401/403) counts
+ as a missing scope — throttles, 5xx, or network blips must not mark a table
+ unreachable, so anything else reads as reachable."""
+ config = SHUTTERSTOCK_ENDPOINTS[endpoint]
+ ok, status = _probe_endpoint(auth, config.path)
+ if ok or status not in (401, 403):
+ return None
+ if config.required_scope:
+ return (
+ f"This table needs an OAuth access token with the `{config.required_scope}` scope. "
+ "Consumer key/secret authentication cannot access account-level data."
+ )
+ return "Your Shutterstock credentials were rejected for this table."
+
+
+def _probe_endpoint(auth: ShutterstockAuth, path: str) -> tuple[bool, int | None]:
+ redact = tuple(v for v in (auth.consumer_key, auth.consumer_secret, auth.access_token) if v)
+ headers = {"Accept": "application/json"}
+ request_auth = None
+ if auth.access_token:
+ headers["Authorization"] = f"Bearer {auth.access_token}"
+ else:
+ request_auth = HTTPBasicAuth(auth.consumer_key or "", auth.consumer_secret or "")
+ return validate_via_probe(
+ lambda: make_tracked_session(redact_values=redact),
+ f"{SHUTTERSTOCK_BASE_URL}{path}?per_page=1&page=1",
+ headers=headers,
+ auth=request_auth,
+ )
+
+
+def get_rows(
+ auth: ShutterstockAuth,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ShutterstockResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SHUTTERSTOCK_ENDPOINTS[endpoint]
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ initial_paginator_state: Optional[dict[str, Any]] = {"page": resume.page} if resume is not None else None
+
+ params: dict[str, Any] = {}
+ if config.page_size is not None:
+ params["per_page"] = config.page_size
+ if config.cursor_field:
+ # Ascending on the cursor field so the pipeline watermark advances safely and
+ # full-refresh pages don't skip/duplicate rows inserted mid-sync. The API's sort
+ # enum is newest/oldest, not a field name.
+ params["sort"] = "oldest"
+
+ use_watermark = (
+ config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value is not None
+ )
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ # All list responses wrap rows in a `data` array; a missing/empty key reads as an
+ # empty page and ends pagination.
+ "data_selector": "data",
+ "params": params,
+ "paginator": PageNumberPaginator(base_page=1, page_param="page", maximum_page=MAX_PAGES)
+ if config.page_size is not None
+ else SinglePagePaginator(),
+ }
+ if use_watermark:
+ endpoint_config["incremental"] = {
+ "start_param": "start_date",
+ "cursor_path": str(config.cursor_field),
+ "convert": _format_start_date,
+ }
+ elif config.default_lookback_days is not None:
+ # The `updated` feeds default to a 1-hour interval when no `start_date` is passed,
+ # so an unwatermarked sync (first incremental run or full refresh) would silently
+ # return almost nothing. Bound the window explicitly instead. Whether the API
+ # honors arbitrarily old start dates is undocumented, so the window stays modest.
+ window_start = datetime.now(UTC) - timedelta(days=config.default_lookback_days)
+ params["start_date"] = _format_start_date(window_start)
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ "base_url": SHUTTERSTOCK_BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": _auth_config(auth),
+ },
+ "resources": [{"name": endpoint, "endpoint": endpoint_config}],
+ }
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Called by the framework AFTER a page is yielded, so a crash re-pulls from the
+ # next page rather than losing the page we just handed off; the merge dedupes any
+ # overlap on the primary key.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(ShutterstockResumeConfig(page=int(state["page"])))
+
+ yield from rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value if use_watermark else None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+
+def shutterstock_source(
+ auth: ShutterstockAuth,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[ShutterstockResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SHUTTERSTOCK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ auth=auth,
+ endpoint=endpoint,
+ team_id=team_id,
+ job_id=job_id,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/source.py
index 5121c3e179b6..732af0da4f3c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/source.py
@@ -1,21 +1,64 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.shutterstock import (
ShutterstockSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SHUTTERSTOCK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.shutterstock import (
+ ShutterstockAuth,
+ ShutterstockResumeConfig,
+ check_endpoint_access,
+ shutterstock_source,
+ validate_credentials as validate_shutterstock_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+def _auth_from_config(config: ShutterstockSourceConfig) -> ShutterstockAuth:
+ if config.auth_method.selection == "access_token":
+ return ShutterstockAuth(access_token=config.auth_method.access_token)
+ return ShutterstockAuth(
+ consumer_key=config.auth_method.consumer_key,
+ consumer_secret=config.auth_method.consumer_secret,
+ )
+
+
@SourceRegistry.register
-class ShutterstockSource(SimpleSource[ShutterstockSourceConfig]):
+class ShutterstockSource(ResumableSource[ShutterstockSourceConfig, ShutterstockResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ supported_versions = ("v2",)
+ default_version = "v2"
+ api_docs_url = "https://api-reference.shutterstock.com/"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SHUTTERSTOCK
@@ -26,7 +69,139 @@ class ShutterstockSource(SimpleSource[ShutterstockSourceConfig]):
name=SchemaExternalDataSourceType.SHUTTERSTOCK,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Shutterstock",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["stock photos", "stock media"],
+ caption="""Pull your Shutterstock media catalog and account data into the PostHog Data warehouse.
+
+Authenticate with your app's consumer key and secret (from [your Shutterstock apps page](https://www.shutterstock.com/account/developers/apps)) to sync the catalog feeds: categories and recently updated images and videos.
+
+To also sync account-level tables, use an OAuth access token instead. Collections need the `collections.view` scope, license history needs `licenses.view`, and subscriptions need `purchases.view`. Note that Shutterstock invalidates OAuth tokens when the account password changes, so you may need to reconnect after a password change.""",
iconPath="/static/services/shutterstock.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/shutterstock",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="auth_method",
+ label="Authentication type",
+ required=True,
+ defaultValue="api_key",
+ options=[
+ SourceFieldSelectConfigOption(
+ label="Consumer key and secret",
+ value="api_key",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="consumer_key",
+ label="Consumer key",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="consumer_secret",
+ label="Consumer secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ SourceFieldSelectConfigOption(
+ label="OAuth access token",
+ value="access_token",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Bad, revoked, or password-invalidated credentials surface as HTTPErrors from
+ # `raise_for_status()`. Retrying can never fix a credential problem. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.shutterstock.com": "Your Shutterstock credentials are invalid or expired. OAuth tokens are invalidated when the account password changes. Reconnect with fresh credentials.",
+ "403 Client Error: Forbidden for url: https://api.shutterstock.com": "Your Shutterstock credentials do not have access to this data. Account-level tables (collections, licenses, subscriptions) need an OAuth access token with the matching scope.",
+ }
+
+ def get_schemas(
+ self,
+ config: ShutterstockSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self, config: ShutterstockSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ auth = _auth_from_config(config)
+ if schema_name is not None and schema_name in SHUTTERSTOCK_ENDPOINTS:
+ reason = check_endpoint_access(auth, schema_name)
+ if reason is not None:
+ return False, reason
+ return True, None
+
+ if validate_shutterstock_credentials(auth):
+ return True, None
+
+ return False, "Invalid Shutterstock credentials"
+
+ def get_endpoint_permissions(
+ self, config: ShutterstockSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ auth = _auth_from_config(config)
+ return {
+ endpoint: check_endpoint_access(auth, endpoint) if endpoint in SHUTTERSTOCK_ENDPOINTS else None
+ for endpoint in endpoints
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ShutterstockResumeConfig]:
+ return ResumableSourceManager[ShutterstockResumeConfig](inputs, ShutterstockResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ShutterstockSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ShutterstockResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return shutterstock_source(
+ auth=_auth_from_config(config),
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py
new file mode 100644
index 000000000000..297f7610b423
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock.py
@@ -0,0 +1,303 @@
+import json
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.settings import (
+ ENDPOINTS,
+ SHUTTERSTOCK_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.shutterstock import (
+ ShutterstockAuth,
+ ShutterstockResumeConfig,
+ _format_start_date,
+ check_endpoint_access,
+ get_rows,
+ shutterstock_source,
+ validate_credentials,
+)
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# The credential/scope probes build their own tracked session in the shutterstock module.
+PROBE_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.shutterstock.make_tracked_session"
+)
+
+BASIC_AUTH = ShutterstockAuth(consumer_key="ck", consumer_secret="cs")
+TOKEN_AUTH = ShutterstockAuth(access_token="tok")
+
+
+def _response(body: dict[str, Any]) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
+def _page(items: list[dict[str, Any]]) -> Response:
+ return _response({"data": items, "page": 1, "per_page": 100, "total_count": 999})
+
+
+def _make_manager(resume_state: ShutterstockResumeConfig | 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 _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and snapshot each request AT PREPARE TIME.
+
+ ``request.params`` is a single dict mutated in place across pages, so inspecting it
+ after the run shows only the final state — snapshot a copy per request instead.
+ """
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _collect(
+ endpoint: str,
+ responses: list[Response],
+ MockSession: mock.MagicMock,
+ manager: mock.MagicMock | None = None,
+ auth: ShutterstockAuth = BASIC_AUTH,
+ **kwargs: Any,
+) -> tuple[list[list[dict[str, Any]]], list[dict[str, Any]], mock.MagicMock]:
+ session = MockSession.return_value
+ snapshots = _wire(session, responses)
+ manager = manager if manager is not None else _make_manager()
+ batches = list(get_rows(auth, endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs))
+ return batches, snapshots, manager
+
+
+class TestFormatStartDate:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (datetime(2026, 3, 4, 22, 13, 20, 123456, tzinfo=UTC), "2026-03-04T22:13:20+00:00"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("2026-03-04T22:13:20+00:00", "2026-03-04T22:13:20+00:00"),
+ ("", None),
+ ],
+ )
+ def test_format_start_date(self, value: Any, expected: str | None) -> None:
+ assert _format_start_date(value) == expected
+
+
+class TestCredentialProbes:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(PROBE_SESSION_PATCH)
+ def test_validate_credentials_status_mapping(
+ self, mock_session: mock.MagicMock, status_code: int, expected: bool
+ ) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ assert validate_credentials(BASIC_AUTH) is expected
+
+ @mock.patch(PROBE_SESSION_PATCH)
+ def test_validate_credentials_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials(BASIC_AUTH) is False
+
+ @pytest.mark.parametrize(
+ "endpoint, status_code, expect_reason, expect_scope",
+ [
+ ("image_licenses", 200, False, None),
+ ("image_licenses", 403, True, "licenses.view"),
+ ("image_collections", 401, True, "collections.view"),
+ ("subscriptions", 403, True, "purchases.view"),
+ ("images_updated", 401, True, None),
+ # A throttle or server blip is not a missing scope — the table stays selectable.
+ ("image_licenses", 429, False, None),
+ ("image_licenses", 500, False, None),
+ ],
+ )
+ @mock.patch(PROBE_SESSION_PATCH)
+ def test_check_endpoint_access(
+ self,
+ mock_session: mock.MagicMock,
+ endpoint: str,
+ status_code: int,
+ expect_reason: bool,
+ expect_scope: str | None,
+ ) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ reason = check_endpoint_access(BASIC_AUTH, endpoint)
+
+ if not expect_reason:
+ assert reason is None
+ else:
+ assert reason is not None
+ if expect_scope:
+ assert expect_scope in reason
+
+
+class TestGetRows:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_paginates_until_empty_page_and_checkpoints(self, MockSession: mock.MagicMock) -> None:
+ batches, snapshots, manager = _collect(
+ "images_updated",
+ [
+ _page([{"id": "1"}, {"id": "2"}]),
+ _page([]),
+ ],
+ MockSession,
+ )
+
+ assert [item["id"] for batch in batches for item in batch] == ["1", "2"]
+ assert snapshots[0]["params"]["page"] == 1
+ assert snapshots[0]["params"]["per_page"] == 500
+ assert snapshots[1]["params"]["page"] == 2
+ # State saved once (after page 1, pointing at page 2); the empty page ends the run.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == ShutterstockResumeConfig(page=2)
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_page(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ _, snapshots, _ = _collect(
+ "images_updated",
+ [_page([])],
+ MockSession,
+ manager=_make_manager(ShutterstockResumeConfig(page=7)),
+ )
+
+ assert session.send.call_count == 1
+ assert snapshots[0]["params"]["page"] == 7
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_basic_auth_uses_consumer_key_and_secret(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect("images_updated", [_page([])], MockSession, auth=BASIC_AUTH)
+
+ assert snapshots[0]["auth"].username == "ck"
+ assert snapshots[0]["auth"].password == "cs"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_access_token_uses_bearer_auth(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect("image_licenses", [_page([])], MockSession, auth=TOKEN_AUTH)
+
+ assert snapshots[0]["auth"].token == "tok"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_incremental_request_carries_watermark_and_ascending_sort(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "image_licenses",
+ [_page([])],
+ MockSession,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ assert snapshots[0]["params"]["start_date"] == "2026-01-01T00:00:00+00:00"
+ assert snapshots[0]["params"]["sort"] == "oldest"
+ assert snapshots[0]["params"]["per_page"] == 200
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_licenses_full_refresh_fetches_full_history(self, MockSession: mock.MagicMock) -> None:
+ _, snapshots, _ = _collect(
+ "image_licenses",
+ [_page([])],
+ MockSession,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+
+ # No lookback default for license history: a full refresh walks all of it, still
+ # ascending so pages don't skip/duplicate rows inserted mid-sync.
+ assert "start_date" not in snapshots[0]["params"]
+ assert snapshots[0]["params"]["sort"] == "oldest"
+
+ @freeze_time("2026-01-31 00:00:00")
+ @pytest.mark.parametrize("should_use_incremental_field", [True, False])
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_updated_feed_defaults_to_bounded_lookback_without_watermark(
+ self, MockSession: mock.MagicMock, should_use_incremental_field: bool
+ ) -> None:
+ # The updated feeds return only the last hour when no start_date is passed, so an
+ # unwatermarked sync must bound the window explicitly or it silently syncs nothing.
+ _, snapshots, _ = _collect(
+ "images_updated",
+ [_page([])],
+ MockSession,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=None,
+ )
+
+ assert snapshots[0]["params"]["start_date"] == "2026-01-01T00:00:00+00:00"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_unpaginated_endpoint_makes_a_single_request(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ batches, snapshots, manager = _collect(
+ "subscriptions",
+ [_page([{"id": "s1"}, {"id": "s2"}])],
+ MockSession,
+ )
+
+ assert session.send.call_count == 1
+ assert [item["id"] for batch in batches for item in batch] == ["s1", "s2"]
+ assert "page" not in snapshots[0]["params"]
+ assert "per_page" not in snapshots[0]["params"]
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_missing_data_key_reads_as_end_of_data(self, MockSession: mock.MagicMock) -> None:
+ batches, _, manager = _collect("images_updated", [_response({"message": "no results"})], MockSession)
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+
+class TestShutterstockSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = SHUTTERSTOCK_ENDPOINTS[endpoint]
+ response = shutterstock_source(
+ BASIC_AUTH, endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ )
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(SHUTTERSTOCK_ENDPOINTS.values()))
+ def test_incremental_endpoints_sort_ascending_on_their_cursor(self, config: Any) -> None:
+ # An incremental endpoint must sort ascending on its cursor so the watermark advances.
+ if config.supports_incremental:
+ assert config.cursor_field is not None
+ assert config.incremental_fields
+ assert config.incremental_fields[0]["field"] == config.cursor_field
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock_source.py
new file mode 100644
index 000000000000..8f0d267b112b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/shutterstock/tests/test_shutterstock_source.py
@@ -0,0 +1,226 @@
+from typing import Literal
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.shutterstock import (
+ ShutterstockAuthMethodConfig,
+ ShutterstockSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.shutterstock import (
+ ShutterstockResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source import (
+ ShutterstockSource,
+ _auth_from_config,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _basic_config(**auth_overrides: str) -> ShutterstockSourceConfig:
+ return ShutterstockSourceConfig(
+ auth_method=ShutterstockAuthMethodConfig(
+ selection="api_key", consumer_key="ck", consumer_secret="cs", **auth_overrides
+ )
+ )
+
+
+class TestShutterstockSource:
+ def setup_method(self) -> None:
+ self.source = ShutterstockSource()
+ self.team_id = 123
+ self.config = _basic_config()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SHUTTERSTOCK
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Shutterstock"
+ assert config.label == "Shutterstock"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/shutterstock"
+
+ def test_auth_select_offers_both_credential_types_with_secret_inputs(self) -> None:
+ config = self.source.get_source_config
+ select = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig))
+
+ assert select.name == "auth_method"
+ assert [option.value for option in select.options] == ["api_key", "access_token"]
+ secret_fields = {
+ field.name for option in select.options for field in option.fields or [] if getattr(field, "secret", False)
+ }
+ assert secret_fields == {"consumer_secret", "access_token"}
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.shutterstock.com/v2/images/updated?page=1",
+ "403 Client Error: Forbidden for url: https://api.shutterstock.com/v2/images/licenses",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.shutterstock.com/v2/images/updated",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_server_side_filter_endpoints_are_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ incremental = {name for name, s in schemas.items() if s.supports_incremental}
+ # Only the updated feeds and license history expose Shutterstock's server-side
+ # `start_date` filter.
+ assert incremental == {"images_updated", "videos_updated", "image_licenses", "video_licenses"}
+
+ def test_incremental_schemas_advertise_their_fields(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["image_licenses"].incremental_fields == INCREMENTAL_FIELDS["image_licenses"]
+ assert schemas["subscriptions"].incremental_fields == []
+ assert schemas["subscriptions"].supports_append is False
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["image_licenses"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "image_licenses"
+
+ def test_get_canonical_descriptions_keys_match_endpoints(self) -> None:
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical).issubset(set(ENDPOINTS))
+
+ @pytest.mark.parametrize(
+ "selection, expected",
+ [
+ ("api_key", {"consumer_key": "ck", "consumer_secret": "cs", "access_token": None}),
+ ("access_token", {"consumer_key": None, "consumer_secret": None, "access_token": "tok"}),
+ ],
+ )
+ def test_auth_from_config_routes_by_selection(
+ self, selection: Literal["api_key", "access_token"], expected: dict[str, str | None]
+ ) -> None:
+ config = ShutterstockSourceConfig(
+ auth_method=ShutterstockAuthMethodConfig(
+ selection=selection, consumer_key="ck", consumer_secret="cs", access_token="tok"
+ )
+ )
+ auth = _auth_from_config(config)
+ assert auth.consumer_key == expected["consumer_key"]
+ assert auth.consumer_secret == expected["consumer_secret"]
+ assert auth.access_token == expected["access_token"]
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Shutterstock credentials"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source.validate_shutterstock_credentials"
+ )
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source.check_endpoint_access"
+ )
+ def test_validate_credentials_with_schema_name_reports_scope_reason(self, mock_check: mock.MagicMock) -> None:
+ mock_check.return_value = "needs licenses.view"
+
+ is_valid, error_message = self.source.validate_credentials(
+ self.config, self.team_id, schema_name="image_licenses"
+ )
+
+ assert is_valid is False
+ assert error_message == "needs licenses.view"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source.check_endpoint_access"
+ )
+ def test_get_endpoint_permissions_probes_known_endpoints_only(self, mock_check: mock.MagicMock) -> None:
+ mock_check.side_effect = lambda auth, endpoint: "blocked" if endpoint == "subscriptions" else None
+
+ permissions = self.source.get_endpoint_permissions(
+ self.config, self.team_id, ["subscriptions", "image_categories", "not_an_endpoint"]
+ )
+
+ assert permissions == {"subscriptions": "blocked", "image_categories": None, "not_an_endpoint": None}
+
+ 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 ShutterstockResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source.shutterstock_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_shutterstock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "image_licenses"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_shutterstock_source.call_args.kwargs
+ assert kwargs["auth"].consumer_key == "ck"
+ assert kwargs["auth"].consumer_secret == "cs"
+ assert kwargs["endpoint"] == "image_licenses"
+ assert kwargs["team_id"] is inputs.team_id
+ assert kwargs["job_id"] is inputs.job_id
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.shutterstock.source.shutterstock_source"
+ )
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(
+ self, mock_shutterstock_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "subscriptions"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_shutterstock_source.call_args.kwargs["db_incremental_field_last_value"] is None