: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
"""Thin RevenueCat API v2 client used by the data warehouse source.
Spec: https://www.revenuecat.com/docs/api-v2
Everything in this module routes through ``make_tracked_session`` so outbound
calls show up in our HTTP logs, OTel metrics, and sample-capture pipeline.
"""
import dataclasses
from collections.abc import Iterator
from typing import Any, Optional
from urllib.parse import urlencode, urljoin
import requests
import structlog
from products.warehouse_sources.sources.revenuecat.constants import (
REVENUECAT_API_BASE_URL,
REVENUECAT_AUTO_WEBHOOK_NAME,
)
from products.warehouse_sources.sources.revenuecat.settings import REVENUECAT_API_ENDPOINTS
from products.warehouse_sources.sources.sdk import (
ExternalWebhookInfo,
JSONResponsePaginator,
Resource,
RESTAPIConfig,
ResumableSourceManager,
SourceResponse,
WebhookCreationResult,
WebhookDeletionResult,
make_tracked_session,
rest_api_resource,
)
LOGGER = structlog.get_logger(__name__)
DEFAULT_PAGE_SIZE = 100
REQUEST_TIMEOUT_SECONDS = 30
@dataclasses.dataclass
class RevenueCatResumeConfig:
"""Cursor state for resumable list iteration.
``endpoint`` scopes the cursor to a single endpoint so we never replay a customers cursor
against products. ``next_url`` is the resolved RevenueCat ``next_page`` link the run resumes
from. ``starting_after`` (the last item's id) is retained so resume state written by the
pre-framework implementation still parses; new runs resume from ``next_url``.
"""
endpoint: str
starting_after: str | None = None
next_url: str | None = None
def _auth_headers(api_key: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Content-Type": "application/json",
}
def _session(api_key: str) -> requests.Session:
return make_tracked_session(headers=_auth_headers(api_key))
def _project_path(project_id: str, suffix: str) -> str:
return f"/projects/{project_id}{suffix}"
# How many accessible project ids we list back when an entered id 404s. Most keys
# see a single project, so this is really just a guard against a wall of text.
MAX_SUGGESTED_PROJECTS = 5
def _normalize_project_id(raw: str | None) -> str:
"""Best-effort cleanup of a user-entered RevenueCat project id.
The setup form points users at their dashboard URL
(``app.revenuecat.com/projects/<project_id>``) to find the id, so a large
share of connection failures come from pasting the whole URL, a
``projects/<id>`` path fragment, a value with stray whitespace, or the bare
id with its ``proj`` prefix dropped. Pull the id back out, trim it, and
restore a missing prefix so those copy-paste mistakes don't become a 404.
"""
if not raw:
return ""
value = raw.strip()
# Pasted a full or partial dashboard URL / `.../projects/<id>/...` path. The
# marker has no leading slash so it matches both `/projects/x` and the
# bare `projects/x` form.
marker = "projects/"
if marker in value:
value = value.split(marker, 1)[1]
# Keep only the first path segment, dropping any trailing `/overview`,
# query string, or fragment that rode along with the paste.
value = value.split("/", 1)[0].split("?", 1)[0].split("#", 1)[0].strip()
# RevenueCat project ids are always `proj`-prefixed (e.g. `proj1a2b3c4d`),
# but the setup form points users at the dashboard where the id is shown
# without the prefix, so a large share of failures are bare ids like
# `1a2b3c4d`. Restore the prefix so that copy-paste slip isn't a dead-end
# 404 — the membership check against the live project list still rejects
# anything that isn't a real, reachable project.
if value and not value.startswith("proj"):
value = f"proj{value}"
return value
def _accessible_project_ids(payload: dict[str, Any] | None) -> list[str]:
"""Pull the project ids out of a ``GET /v2/projects`` response page.
We deliberately keep only the ids (opaque ``proj...`` tokens), never the
project names — the error string built from this is captured into our
analytics, and names can carry a customer's app/company identity.
"""
items = (payload or {}).get("items")
if not isinstance(items, list):
return []
return [str(item["id"]) for item in items if isinstance(item, dict) and item.get("id")]
def _list_accessible_project_ids(session: requests.Session) -> list[str] | None:
"""Return every project id the key can see, following cursor pages.
Returns ``None`` when a page comes back 200 but unparseable — callers can't
distinguish "no projects" from "couldn't read the list", and the two demand
opposite treatment, so we surface the difference. HTTP/network errors
propagate to the caller.
"""
ids: list[str] = []
url = f"{REVENUECAT_API_BASE_URL}/projects"
params: dict[str, Any] | None = {"limit": DEFAULT_PAGE_SIZE}
while True:
response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
response.raise_for_status()
try:
payload = response.json() or {}
except (ValueError, requests.exceptions.JSONDecodeError):
return None
ids.extend(_accessible_project_ids(payload))
next_page = payload.get("next_page")
if not next_page:
return ids
# next_page already carries its own query string, so re-send it as-is with no extra params.
url = next_page if next_page.startswith("http") else urljoin(REVENUECAT_API_BASE_URL, next_page)
params = None
def _project_not_found_error(entered_project_id: str, accessible_ids: list[str]) -> str:
"""Turn an opaque 404 into an actionable message naming the reachable project ids."""
if not accessible_ids:
return (
f"RevenueCat could not find the project '{entered_project_id}', and this API key "
"can't see any projects. Generate a v2 secret API key in the RevenueCat project you "
"want to sync, then re-enter its Project ID."
)
if len(accessible_ids) == 1:
only = accessible_ids[0]
return (
f"RevenueCat has no project '{entered_project_id}' for this API key. The key has access to "
f"one project — '{only}'. Set the Project ID to '{only}' and reconnect."
)
shown = accessible_ids[:MAX_SUGGESTED_PROJECTS]
listed = ", ".join(f"'{pid}'" for pid in shown)
overflow = len(accessible_ids) - MAX_SUGGESTED_PROJECTS
more = f" (+{overflow} more)" if overflow > 0 else ""
return (
f"RevenueCat has no project '{entered_project_id}' for this API key. The key has access to: "
f"{listed}{more}. Copy the exact Project ID from your RevenueCat dashboard and reconnect."
)
UNSUPPORTED_KEY_CHARACTER_MESSAGE = (
"Your RevenueCat API key contains an unsupported character, such as a curly quote, a line break, "
"or an invisible character pasted from another app. Copy the key again from RevenueCat and paste "
"only the key."
)
# A transport failure leaves the key unjudged, so it must not read as a credential problem.
UNREACHABLE_MESSAGE = "PostHog couldn't reach RevenueCat. Wait a few minutes and try again."
def _format_http_error(error: requests.HTTPError, forbidden_hint: str | None = None) -> str:
response = error.response
status_code = response.status_code if response is not None else None
if status_code == 401:
return (
"RevenueCat rejected your API key. Generate a new v2 secret API key under "
"Project settings > API keys, then reconnect."
)
if status_code == 403:
# This formatter also serves webhook create/delete, which need write scope, so the default
# stays scope-neutral. Read-only callers pass a read-specific hint.
detail = forbidden_hint or "Give your v2 secret API key the permissions this request needs, then reconnect."
return f"RevenueCat denied the request. {detail}"
if status_code == 404:
return (
"RevenueCat could not find the project. Check the project id in your RevenueCat dashboard, then reconnect."
)
if status_code == 429:
return "RevenueCat rate-limited the request. Try again in a few seconds."
return "RevenueCat could not complete the request. Try again in a few minutes, and check the RevenueCat status page if it keeps failing."
_READ_FORBIDDEN_HINT = "Give your v2 secret API key read permission for the data you want to sync, then reconnect."
def _validate_project_read_access(session: requests.Session, project_id: str) -> tuple[bool, str | None]:
"""Accept the key when it can read at least one endpoint the sync uses in ``project_id``."""
last_forbidden: requests.HTTPError | None = None
for endpoint in REVENUECAT_API_ENDPOINTS.values():
url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, endpoint.path_suffix)}"
try:
response = session.get(url, params={"limit": 1}, timeout=REQUEST_TIMEOUT_SECONDS)
response.raise_for_status()
except requests.HTTPError as e:
if e.response is not None and e.response.status_code == 403:
last_forbidden = e
continue
return False, _format_http_error(e, forbidden_hint=_READ_FORBIDDEN_HINT)
except requests.RequestException as e:
LOGGER.warning("Could not reach RevenueCat to validate credentials", error=str(e))
return False, UNREACHABLE_MESSAGE
return True, None
if last_forbidden is not None:
return False, _format_http_error(last_forbidden, forbidden_hint=_READ_FORBIDDEN_HINT)
return True, None
def validate_credentials(api_key: str, project_id: str | None) -> tuple[bool, str | None]:
"""Confirm the key works and (when set) that it can reach ``project_id``.
``GET /v2/projects`` both validates the key and tells us every project the
key can see, so the project check is a membership test against that list.
There is no ``GET /v2/projects/{id}`` endpoint in the RevenueCat v2 API —
probing it 404s even for a perfectly valid id, so never "verify" a project
that way. The entered id is normalized first so a pasted dashboard URL or
stray whitespace doesn't masquerade as a missing project; on a miss, the
error names the project ids the key *can* reach instead of a dead-end
"double-check the project id".
"""
# The key rides in the Authorization header, which http.client encodes as latin-1, so a
# non-ASCII character raises UnicodeEncodeError mid-request. A line break is ASCII but makes
# requests raise InvalidHeader, which would otherwise read as RevenueCat being unreachable.
if not api_key.isascii() or "\r" in api_key or "\n" in api_key:
return False, UNSUPPORTED_KEY_CHARACTER_MESSAGE
session = _session(api_key)
normalized_project_id = _normalize_project_id(project_id)
try:
accessible_ids = _list_accessible_project_ids(session)
except requests.HTTPError as e:
# Listing projects needs a projects permission the sync never uses, so a key scoped to just
# the synced resources is denied here. Check the project's own endpoints instead.
if normalized_project_id and e.response is not None and e.response.status_code == 403:
return _validate_project_read_access(session, normalized_project_id)
return False, _format_http_error(e, forbidden_hint=_READ_FORBIDDEN_HINT)
except requests.RequestException as e:
LOGGER.warning("Could not reach RevenueCat to validate credentials", error=str(e))
return False, UNREACHABLE_MESSAGE
if not normalized_project_id:
return True, None
# The list came back 200 but unreadable — the key itself is good, and we
# have no way to check the project, so fail open rather than block setup.
if accessible_ids is None:
return True, None
if normalized_project_id in accessible_ids:
return True, None
return False, _project_not_found_error(normalized_project_id, accessible_ids)
def _ms_to_seconds(value: Any) -> Any:
"""Convert a millisecond epoch int to a Unix-seconds int.
RevenueCat returns timestamps as millisecond epochs (e.g. ``1658399423658``),
but the warehouse partition layer interprets bare ints as Unix *seconds*
(``datetime.datetime.fromtimestamp(date)``). Normalize to seconds so a
datetime partition on ``created_at`` produces sane bucket dates, matching
the convention used by other sources (Stripe's ``created`` is already in
seconds).
"""
if isinstance(value, int) and not isinstance(value, bool):
return value // 1000
return value
class RevenueCatCursorPaginator(JSONResponsePaginator):
"""Follows RevenueCat's ``next_page`` body link.
RevenueCat returns the link as a root-relative path
(``/v2/projects/{id}/customers?starting_after=ID&limit=100``), and the base paginator assigns
it verbatim as the next request URL — which ``requests`` needs to be absolute. Resolve it
against the API host the same way the pre-framework client did
(``urljoin(REVENUECAT_API_BASE_URL, next_page)``) before it becomes the next request.
"""
def __init__(self) -> None:
super().__init__(next_url_path="next_page")
def update_state(self, response: requests.Response, data: Optional[list[Any]] = None) -> None:
super().update_state(response, data)
if self._has_next_page and self._next_url and not self._next_url.startswith("http"):
self._next_url = urljoin(REVENUECAT_API_BASE_URL, self._next_url)
def _normalize_timestamps(row: dict[str, Any], timestamp_fields: tuple[str, ...]) -> dict[str, Any]:
"""Divide the endpoint's ms-epoch partition field(s) down to Unix seconds.
The partition layer treats bare ints as Unix seconds, so RevenueCat's ms epochs must be
scaled or a datetime partition buckets every row far in the future. Only the partition
field is touched (``created_at`` for most endpoints, ``first_seen_at`` for customers); other
ms fields such as ``last_seen_at`` are left as-is. See ``_ms_to_seconds``.
"""
for field in timestamp_fields:
if field in row:
row[field] = _ms_to_seconds(row[field])
return row
def revenuecat_api_source(
api_key: str,
project_id: str,
schema_name: str,
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager["RevenueCatResumeConfig"],
) -> SourceResponse:
"""Build the ``rest_source`` resource for a RevenueCat v2 list endpoint.
RevenueCat returns ``{"items": [...], "next_page": "/v2/path?starting_after=ID"}`` and
paginates via that cursor link; a null/absent ``next_page`` ends the list. The key rides the
framework ``auth`` config so it is redacted from logs and raised error messages.
"""
endpoint = REVENUECAT_API_ENDPOINTS[schema_name]
normalized_project_id = _normalize_project_id(project_id)
timestamp_fields = tuple(endpoint.partition_keys)
params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
# Only honor saved state for the endpoint that wrote it — replaying a customers cursor against
# products would skip rows.
if resume is not None and resume.endpoint != schema_name:
resume = None
initial_paginator_state: Optional[dict[str, Any]] = None
if resume is not None:
if resume.next_url:
initial_paginator_state = {"next_url": resume.next_url}
elif resume.starting_after:
# Legacy pre-framework state stored only the cursor id; reproduce the old resumed first
# request (`?starting_after=<id>&limit=100`) so an in-flight sync still advances.
params["starting_after"] = resume.starting_after
def normalize(row: dict[str, Any]) -> dict[str, Any]:
return _normalize_timestamps(row, timestamp_fields)
rest_config: RESTAPIConfig = {
"client": {
"base_url": REVENUECAT_API_BASE_URL,
"headers": {"Accept": "application/json", "Content-Type": "application/json"},
"auth": {"type": "bearer", "token": api_key},
"paginator": RevenueCatCursorPaginator(),
},
"resource_defaults": {},
"resources": [
{
"name": schema_name,
"endpoint": {
"path": _project_path(normalized_project_id, endpoint.path_suffix),
"params": params,
# A 200 without `items` is a legit empty page (not an error) — leave the
# selector non-required so it terminates rather than failing loud.
"data_selector": "items",
},
"data_map": normalize,
}
],
}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
# Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields
# the last page (merge dedupes on the primary key) rather than skipping it.
if state and state.get("next_url"):
resumable_source_manager.save_state(
RevenueCatResumeConfig(endpoint=schema_name, next_url=state["next_url"])
)
resource = rest_api_resource(
rest_config,
team_id,
job_id,
None,
resume_hook=save_checkpoint,
initial_paginator_state=initial_paginator_state,
)
def dict_rows() -> Iterator[list[dict[str, Any]]]:
# The framework passes non-dict page entries through untouched (data_map only runs on
# dicts), so drop them here — matching the old client's per-row dict guard — before a
# malformed row can reach the delta writer.
for page in resource:
yield [row for row in page if isinstance(row, dict)]
# The framework staged the cursor after this page before it handed the page on, and the
# guard holds no rows, so the run can stop here.
resumable_source_manager.safe_point()
# As a `Resource` the guard also keeps the framework's safe points before each retry wait.
pages = Resource(dict_rows, name=schema_name, hints=resource._hints)
return SourceResponse(
items=lambda: pages,
primary_keys=endpoint.primary_keys,
name=schema_name,
partition_keys=endpoint.partition_keys,
partition_mode="datetime",
partition_format="week",
partition_count=1,
partition_size=1,
)
def _update_webhook_integration(api_key: str, project_id: str, webhook_id: str, updates: dict[str, Any]) -> None:
"""Update fields on an existing webhook integration in place.
RevenueCat models updates as a POST to the integration's own path
(``POST /v2/projects/{project_id}/integrations/webhooks/{id}``); only the
fields present in the body change.
"""
url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, f'/integrations/webhooks/{webhook_id}')}"
response = _session(api_key).post(url, json=updates, timeout=REQUEST_TIMEOUT_SECONDS)
response.raise_for_status()
def create_webhook(
api_key: str,
project_id: str,
webhook_url: str,
authorization_header_value: str | None = None,
) -> WebhookCreationResult:
"""Register a webhook integration in RevenueCat pointing at ``webhook_url``.
``POST /v2/projects/{project_id}/integrations/webhooks`` — note the plural
``webhooks``; the singular path is a 404 ("Resource not found") that our
error formatter would misreport as a bad project id. ``event_types`` is
deliberately omitted from the body: a null filter subscribes the
integration to every event type, including ones RevenueCat adds later,
which is exactly what the single ``events`` warehouse table wants.
Auth-header note: the integration ships an ``Authorization`` header on
every delivery whose value the user sets (the API field is
``authorization_header``). We let callers pass that value through so we can
later verify it in the Hog template. If not supplied, the integration is
created without an auth header and the user finishes setup by adding one
via the webhook fields (handled by the surrounding warehouse-source flow).
When a webhook for this URL already exists, a supplied header is bound to
it in place via the update endpoint.
"""
project_id = _normalize_project_id(project_id)
logger = LOGGER.bind(project_id=project_id)
body: dict[str, Any] = {
"name": REVENUECAT_AUTO_WEBHOOK_NAME,
"url": webhook_url,
}
if authorization_header_value:
body["authorization_header"] = authorization_header_value
url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhooks')}"
try:
existing = _find_webhook_integration(api_key, project_id, webhook_url)
if existing is not None:
if authorization_header_value:
webhook_id = existing.get("id")
if not webhook_id:
return WebhookCreationResult(
success=False,
error="RevenueCat returned a webhook without an id; please recreate it manually.",
)
# Resend name and url alongside the header. The update input's
# fields are all optional (patch semantics), but echoing the
# delivery-critical fields costs nothing and keeps the webhook
# pointed at us even if the endpoint ever replaces instead of
# patches. `event_types` is deliberately not echoed: the list
# response may contain event types newer than the update
# enum, which would fail validation.
_update_webhook_integration(
api_key,
project_id,
str(webhook_id),
{
"name": str(existing.get("name") or REVENUECAT_AUTO_WEBHOOK_NAME),
"url": webhook_url,
"authorization_header": authorization_header_value,
},
)
return WebhookCreationResult(success=True)
# No auth header supplied yet — treat the existing webhook as
# success so the user can finish setup by entering the header
# value. RevenueCat omits the configured header from list
# responses, so we can't tell whether one is already set.
return WebhookCreationResult(success=True, pending_inputs=["authorization_header"])
response = _session(api_key).post(url, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
response.raise_for_status()
except requests.HTTPError as e:
logger.warning("Failed to register RevenueCat webhook integration", error=str(e))
return WebhookCreationResult(
success=False,
error=_format_http_error(
e,
# The read-only hint the validate path passes doesn't fit here: registering the
# integration needs write scope, and the failure screen offers manual setup.
forbidden_hint=(
"Give your v2 secret API key write permission for integrations, or follow the manual setup below."
),
),
)
except requests.RequestException as e:
logger.warning("Could not reach RevenueCat to register webhook", error=str(e))
return WebhookCreationResult(success=False, error=UNREACHABLE_MESSAGE)
pending: list[str] = []
if not authorization_header_value:
pending.append("authorization_header")
return WebhookCreationResult(success=True, pending_inputs=pending)
def _list_webhook_integrations(api_key: str, project_id: str) -> list[dict[str, Any]]:
"""Iterate the webhook integrations under a project, following cursor pages."""
items: list[dict[str, Any]] = []
session = _session(api_key)
params: dict[str, Any] = {"limit": DEFAULT_PAGE_SIZE}
url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, '/integrations/webhooks')}"
while True:
# Build the URL with explicit query encoding so the call signature stays
# stable across pages and we never accidentally pass duplicate `limit`s.
request_url = f"{url}?{urlencode(params)}" if params else url
response = session.get(request_url, timeout=REQUEST_TIMEOUT_SECONDS)
response.raise_for_status()
payload = response.json() or {}
page = payload.get("items") or []
if isinstance(page, list):
for hook in page:
if isinstance(hook, dict):
items.append(hook)
next_page = payload.get("next_page")
if not next_page:
return items
url = next_page if next_page.startswith("http") else urljoin(REVENUECAT_API_BASE_URL, next_page)
params = {}
def _find_webhook_integration(api_key: str, project_id: str, webhook_url: str) -> dict[str, Any] | None:
try:
integrations = _list_webhook_integrations(api_key, project_id)
except requests.RequestException:
return None
for hook in integrations:
if hook.get("url") == webhook_url:
return hook
return None
def delete_webhook(api_key: str, project_id: str, webhook_url: str) -> WebhookDeletionResult:
project_id = _normalize_project_id(project_id)
logger = LOGGER.bind(project_id=project_id)
try:
integrations = _list_webhook_integrations(api_key, project_id)
except requests.HTTPError as e:
logger.warning("Failed to list RevenueCat webhook integrations", error=str(e))
return WebhookDeletionResult(success=False, error=_format_http_error(e))
except requests.RequestException as e:
logger.warning("Could not reach RevenueCat to list webhooks", error=str(e))
return WebhookDeletionResult(success=False, error=UNREACHABLE_MESSAGE)
target = next((hook for hook in integrations if hook.get("url") == webhook_url), None)
if target is None:
# Nothing to delete is a success — keep delete idempotent.
return WebhookDeletionResult(success=True)
webhook_id = target.get("id")
if not webhook_id:
return WebhookDeletionResult(
success=False,
error="RevenueCat returned a webhook without an id; please delete it manually.",
)
url = f"{REVENUECAT_API_BASE_URL}{_project_path(project_id, f'/integrations/webhooks/{webhook_id}')}"
try:
response = _session(api_key).delete(url, timeout=REQUEST_TIMEOUT_SECONDS)
if response.status_code == 404:
return WebhookDeletionResult(success=True)
response.raise_for_status()
except requests.HTTPError as e:
logger.warning("Failed to delete RevenueCat webhook integration", error=str(e))
return WebhookDeletionResult(success=False, error=_format_http_error(e))
except requests.RequestException as e:
logger.warning("Could not reach RevenueCat to delete webhook", error=str(e))
return WebhookDeletionResult(success=False, error=UNREACHABLE_MESSAGE)
return WebhookDeletionResult(success=True)
def get_external_webhook_info(api_key: str, project_id: str, webhook_url: str) -> ExternalWebhookInfo:
project_id = _normalize_project_id(project_id)
try:
integrations = _list_webhook_integrations(api_key, project_id)
except requests.HTTPError as e:
return ExternalWebhookInfo(exists=False, error=_format_http_error(e))
except requests.RequestException as e:
LOGGER.warning("Could not reach RevenueCat to look up the webhook", error=str(e))
return ExternalWebhookInfo(exists=False, error=UNREACHABLE_MESSAGE)
target = next((hook for hook in integrations if hook.get("url") == webhook_url), None)
if target is None:
return ExternalWebhookInfo(exists=False)
# `event_types` is null when the integration subscribes to every event type
# (the default for integrations we create).
events_value = target.get("event_types")
enabled_events = events_value if isinstance(events_value, list) else None
created_at_raw = target.get("created_at")
created_at = str(created_at_raw) if created_at_raw is not None else None
return ExternalWebhookInfo(
exists=True,
url=target.get("url"),
enabled_events=enabled_events,
# RevenueCat doesn't expose an enabled/disabled state on the integration
# object — once created, it's active. Report "enabled" to surface that.
status="enabled",
description=target.get("name"),
created_at=created_at,
)