:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse): implement azure cosmos db source (#118145)
Daniel RCbcb7eb8fe5ed
diff --git a/frontend/public/services/cosmosdb.png b/frontend/public/services/cosmosdb.pngindex 044436a9d92c..93113c83c135 100644Binary files a/frontend/public/services/cosmosdb.png and b/frontend/public/services/cosmosdb.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 9871b8e836a8..0cdf1aef2130 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -256,6 +256,7 @@ the row lists both.| copper | HTTP | requests | ✅ || coralogix | HTTP | requests | ✅ || cortex | HTTP | requests + `rest_source.RESTClient` | ✅ |+| cosmosdb | HTTP | requests | ✅ || coupa | HTTP | requests | ✅ || courier | HTTP | requests + `rest_source.RESTClient` | ✅ || coveralls | HTTP | requests | ✅ |@@ -1097,7 +1098,6 @@ doesn't conflict with concurrent PRs.- contentsquare- convonite- copper-- cosmosdb- couchbase- crowdstrike_falcon- cube_clouddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/cosmosdb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/cosmosdb.pynew file mode 100644index 000000000000..d8d464bfab39--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/cosmosdb.py@@ -0,0 +1,482 @@+import hmac+import json+import time+import base64+import hashlib+import binascii+from collections.abc import Callable, Iterator+from datetime import UTC, datetime+from email.utils import format_datetime+from typing import Any, ClassVar, Optional+from urllib.parse import quote, urlparse++import requests+import structlog+from structlog.types import FilteringBoundLogger+from urllib3.util.retry import Retry++from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager+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.interruptible_wait import (+ interruptible_wait,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cosmosdb.settings import (+ PAGE_SIZE,+ PARTITION_KEY_COLUMN,+ PRIMARY_KEYS,+ TIMESTAMP_FIELD,+)++REQUEST_TIMEOUT_SECONDS = (30, 120)+# Throttles (429) are bounded by the time budget only: Cosmos throttles in bursts of millisecond waits.+MAX_SERVER_ERROR_ATTEMPTS = 5+MAX_BACKOFF_SECONDS = 60.0+# One request with its retries and waits holds the worker for five minutes at most (the source+# contract), so a retry only starts when the wait and a full-length attempt still fit.+RETRY_BUDGET_SECONDS = 300.0+MAX_REQUEST_SECONDS = float(sum(REQUEST_TIMEOUT_SECONDS))+# Rows arrive unordered across partitions, so the next run rereads from before this run started.+TS_FLOOR_MARGIN_SECONDS = 5 * 60+INVALID_KEY_MESSAGE = "Azure Cosmos DB account key is not valid base64"+# Any account key can read the account, so a 403 comes from network rules or disabled key auth.+FORBIDDEN_MESSAGE = (+ "Azure Cosmos DB refused the request. Check that the account's firewall allows PostHog's IP addresses, "+ "that public network access is on, and that key-based authentication isn't turned off."+)+++class CosmosDBRetryableError(Exception):+ """Throttled (429) or a gateway failure (5xx) that outlived the retry budget."""++ pass+++@frozen+class CosmosDBResumeConfig:+ # A continuation token is only valid for the exact query it came from.+ continuation: str | None = None+ ts_floor: int | None = None+ next_ts_floor: int | None = None+++@frozen+class CosmosDBTsCursor:+ """Where the next incremental run starts reading `_ts`."""++ cursor_kind: ClassVar[str] = "cosmosdb_ts_floor"+ ts_floor: int+++@frozen+class CosmosDBCollection:+ id: str+ partition_key_paths: tuple[str, ...] = ()+++def normalize_account_endpoint(endpoint: str) -> str:+ """Trim a user-entered endpoint to `https://host[:port]`.++ The value becomes the base of every credentialed request, so anything that could carry the+ request elsewhere (a path, a query, userinfo, a non-https scheme) is rejected.+ """+ raw = (endpoint or "").strip()+ if "://" not in raw:+ raw = f"https://{raw}"+ parsed = urlparse(raw)+ if parsed.scheme != "https" or not parsed.hostname or "@" in parsed.netloc:+ raise ValueError(+ "Azure Cosmos DB account endpoint must be an https:// URL such as https://<account>.documents.azure.com"+ )+ if parsed.path not in ("", "/") or parsed.params or parsed.query or parsed.fragment:+ raise ValueError("Azure Cosmos DB account endpoint must not include a path or query string")+ return f"https://{parsed.netloc}"+++def hostname_of(endpoint: str) -> str:+ return urlparse(normalize_account_endpoint(endpoint)).hostname or ""+++def decode_account_key(key: str) -> bytes:+ try:+ return base64.b64decode(key.strip(), validate=True)+ except (binascii.Error, ValueError):+ raise ValueError(INVALID_KEY_MESSAGE)+++def master_key_signature(key: bytes, verb: str, resource_type: str, resource_link: str, date: str) -> str:+ """The `Authorization` header for a master-key request.++ Verb, resource type and date are lowercased; the resource link keeps the casing the database+ and container were created with, as the REST auth docs require.+ """+ text = f"{verb.lower()}\n{resource_type.lower()}\n{resource_link}\n{date.lower()}\n\n"+ digest = hmac.new(key, text.encode("utf-8"), hashlib.sha256).digest()+ signature = base64.b64encode(digest).decode("ascii")+ return quote(f"type=master&ver=1.0&sig={signature}", safe="")+++def _error_description(response: requests.Response) -> str:+ # Cosmos errors look like {"code": "Unauthorized", "message": "..."}.+ try:+ body = response.json()+ except ValueError:+ return ""+ if isinstance(body, dict) and isinstance(body.get("message"), str):+ return f" — {body['message']}"+ return ""+++def _retry_after_seconds(response: requests.Response) -> Optional[float]:+ # Not capped: retrying before Cosmos said to only earns another 429.+ for header, scale in (("x-ms-retry-after-ms", 1000.0), ("Retry-After", 1.0)):+ raw = response.headers.get(header)+ if raw is None:+ continue+ try:+ seconds = float(raw) / scale+ except (TypeError, ValueError):+ continue+ if seconds >= 0:+ return seconds+ return None+++def _backoff_seconds(response: requests.Response | None, attempt: int) -> float:+ retry_after = _retry_after_seconds(response) if response is not None else None+ if retry_after is not None:+ return retry_after+ return min(2.0**attempt, MAX_BACKOFF_SECONDS)+++class CosmosDBClient:+ """Master-key client for the Cosmos DB for NoSQL REST API.++ Transport retries are off (`Retry(total=0)`): the document query is a POST, which the default+ retry never covers, and Cosmos reports its throttle wait in `x-ms-retry-after-ms`, which the+ transport cannot read. Backoff is handled once, here.+ """++ def __init__(+ self,+ endpoint: str,+ key: str,+ api_version: str,+ logger: FilteringBoundLogger,+ safe_point: Callable[[], None] | None = None,+ ) -> None:+ self._base_url = normalize_account_endpoint(endpoint)+ self._key = decode_account_key(key)+ self._api_version = api_version+ self._logger = logger+ self._safe_point = safe_point+ # The endpoint is user-supplied, so a redirect must never carry the signed request elsewhere.+ self._session = make_tracked_session(retry=Retry(total=0), redact_values=(key,), allow_redirects=False)++ def request(+ self,+ method: str,+ resource_type: str,+ resource_link: str,+ path: str,+ body: str | None = None,+ headers: dict[str, str] | None = None,+ ) -> requests.Response:+ url = f"{self._base_url}/{path}"+ attempt = 0+ server_errors = 0+ started = time.monotonic()++ while True:+ date = format_datetime(datetime.now(UTC), usegmt=True)+ request_headers = {+ "Authorization": master_key_signature(self._key, method, resource_type, resource_link, date),+ "x-ms-date": date,+ "x-ms-version": self._api_version,+ "Accept": "application/json",+ **(headers or {}),+ }+ response: requests.Response | None+ try:+ response = self._session.request(+ method, url, data=body, headers=request_headers, timeout=REQUEST_TIMEOUT_SECONDS+ )+ status = str(response.status_code)+ except (requests.ConnectionError, requests.Timeout) as error:+ # Every call reads, so a dropped connection or a timeout is safe to send again.+ response = None+ status = type(error).__name__++ if response is None or response.status_code in (408, 429) or response.status_code >= 500:+ attempt += 1+ if response is None or response.status_code != 429:+ server_errors += 1+ delay = _backoff_seconds(response, attempt)+ elapsed = time.monotonic() - started+ if (+ server_errors >= MAX_SERVER_ERROR_ATTEMPTS+ or elapsed + delay + MAX_REQUEST_SECONDS > RETRY_BUDGET_SECONDS+ ):+ raise CosmosDBRetryableError(f"Azure Cosmos DB error (retryable): status={status}, path={path}")+ self._logger.debug(f"Azure Cosmos DB retry: status={status}, sleeping {delay}s (attempt {attempt})")+ interruptible_wait(delay, safe_point=self._safe_point)+ continue++ if not response.ok:+ raise requests.HTTPError(+ f"{response.status_code} Client Error: {response.reason} for url: {url}{_error_description(response)}",+ response=response,+ )++ return response++ def list_collections(self, database: str) -> list[CosmosDBCollection]:+ link = f"dbs/{database}"+ path = f"dbs/{quote(database, safe='')}/colls"+ collections: list[CosmosDBCollection] = []+ continuation: str | None = None++ while True:+ headers = {"x-ms-continuation": continuation} if continuation else {}+ response = self.request("GET", "colls", link, path, headers=headers)+ for item in response.json().get("DocumentCollections") or []:+ collections.append(_collection_from_payload(item))+ continuation = response.headers.get("x-ms-continuation") or None+ if not continuation:+ return collections++ def get_collection(self, database: str, collection: str) -> CosmosDBCollection:+ link = f"dbs/{database}/colls/{collection}"+ path = f"dbs/{quote(database, safe='')}/colls/{quote(collection, safe='')}"+ return _collection_from_payload(self.request("GET", "colls", link, path).json())++ def query_page(+ self,+ database: str,+ collection: str,+ query: str,+ parameters: list[dict[str, Any]],+ continuation: str | None,+ ) -> tuple[list[dict[str, Any]], str | None]:+ link = f"dbs/{database}/colls/{collection}"+ path = f"dbs/{quote(database, safe='')}/colls/{quote(collection, safe='')}/docs"+ headers = {+ "Content-Type": "application/query+json",+ "x-ms-documentdb-isquery": "True",+ "x-ms-documentdb-query-enablecrosspartition": "True",+ "x-ms-max-item-count": str(PAGE_SIZE),+ }+ if continuation:+ headers["x-ms-continuation"] = continuation+ response = self.request(+ "POST", "docs", link, path, body=json.dumps({"query": query, "parameters": parameters}), headers=headers+ )+ documents = response.json().get("Documents") or []+ return documents, response.headers.get("x-ms-continuation") or None+++def _collection_from_payload(item: dict[str, Any]) -> CosmosDBCollection:+ partition_key = item.get("partitionKey") or {}+ paths = partition_key.get("paths") or []+ return CosmosDBCollection(id=str(item["id"]), partition_key_paths=tuple(str(path) for path in paths))+++_MISSING = object()+++def split_path(path: str) -> list[str]:+ """Split a Cosmos JSON path such as `/address/"zip/code"` into its property names.++ A double-quoted segment may hold `/` and backslash-escaped quotes, so splitting on `/` alone+ would resolve the wrong property.+ """+ segments: list[str] = []+ current: list[str] = []+ quoted = False+ escaped = False+ for char in path:+ if escaped:+ current.append(char)+ escaped = False+ elif quoted and char == "\\":+ escaped = True+ elif char == '"':+ quoted = not quoted+ elif char == "/" and not quoted:+ if current:+ segments.append("".join(current))+ current = []+ else:+ current.append(char)+ if current:+ segments.append("".join(current))+ return segments+++def _resolve_path(document: dict[str, Any], path: str) -> Any:+ value: Any = document+ for segment in split_path(path):+ if not isinstance(value, dict) or segment not in value:+ return _MISSING+ value = value[segment]+ return value+++def _encode_partition_key_part(value: Any) -> str:+ # JSON keeps types apart (`"1"` vs `1`), and JSON never encodes to "", so "" is free to mean+ # Cosmos's undefined partition (no value at the path).+ return "" if value is _MISSING else json.dumps(value, separators=(",", ":"), sort_keys=True)+++def partition_key_value(document: dict[str, Any], paths: tuple[str, ...]) -> str:+ """The document's partition key as one string column that is distinct for distinct keys.++ A single key is its JSON encoding, or "" when the document has no value at the path. A+ hierarchical key is the JSON list of its encoded parts.+ """+ parts = [_encode_partition_key_part(_resolve_path(document, path)) for path in paths]+ if not parts:+ return ""+ if len(parts) == 1:+ return parts[0]+ return json.dumps(parts, separators=(",", ":"))+++def shape_document(document: dict[str, Any], paths: tuple[str, ...]) -> dict[str, Any]:+ row = dict(document)+ row[PARTITION_KEY_COLUMN] = partition_key_value(document, paths)+ return row+++def build_query(ts_floor: int | None) -> tuple[str, list[dict[str, Any]]]:+ # No ORDER BY: the REST gateway refuses a cross-partition ORDER BY (the SDKs plan it client-side),+ # so rows arrive in partition order. No upper bound: it would skip a document rewritten every few seconds.+ if ts_floor is None:+ return "SELECT * FROM c", []+ return f"SELECT * FROM c WHERE c.{TIMESTAMP_FIELD} >= @floor", [{"name": "@floor", "value": ts_floor}]+++def validate_credentials(endpoint: str, key: str, database: str, api_version: str) -> tuple[bool, Optional[str]]:+ """Mint nothing: one signed list of the database's containers proves the endpoint, key and+ database at once."""+ try:+ client = CosmosDBClient(endpoint, key, api_version, structlog.get_logger(__name__))+ except ValueError as error:+ return False, _validation_message_for_value_error(error)++ try:+ client.list_collections(database)+ except requests.HTTPError as error:+ status = getattr(error.response, "status_code", None)+ if status == 401:+ return (+ False,+ "Azure Cosmos DB rejected the account key. Copy a key from the account's Keys page and try again.",+ )+ if status == 403:+ return False, FORBIDDEN_MESSAGE + _error_description(error.response)+ if status == 404:+ return False, f"No database named {database} exists in this account. Check the database name."+ return False, f"Azure Cosmos DB returned an error: {error}"+ except (CosmosDBRetryableError, requests.RequestException):+ return False, "Could not reach the Azure Cosmos DB account endpoint. Check the endpoint URL and try again."++ return True, None+++def _validation_message_for_value_error(error: ValueError) -> str:+ if str(error) == INVALID_KEY_MESSAGE:+ return "The account key is not valid. Copy the primary or secondary key from the account's Keys page."+ return str(error)+++def get_rows(+ client: CosmosDBClient,+ database: str,+ collection: CosmosDBCollection,+ ts_floor: int | None,+ next_ts_floor: int | None,+ resumable_source_manager: ResumableSourceManager[CosmosDBResumeConfig],+ cursor_manager: SourceCursorManager[CosmosDBTsCursor] | None,+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ continuation: str | None = None+ if resume is not None and resume.continuation:+ continuation = resume.continuation+ ts_floor = resume.ts_floor+ next_ts_floor = resume.next_ts_floor+ logger.debug(f"Azure Cosmos DB: resuming {collection.id} from a saved continuation token")++ if cursor_manager is not None and next_ts_floor is not None:+ cursor_manager.stage(CosmosDBTsCursor(ts_floor=next_ts_floor))++ query, parameters = build_query(ts_floor)++ while True:+ documents, continuation = client.query_page(database, collection.id, query, parameters, continuation)+ if continuation:+ # Staged before the yield it covers: the pipeline commits it once this page is written.+ resumable_source_manager.save_state(+ CosmosDBResumeConfig(continuation=continuation, ts_floor=ts_floor, next_ts_floor=next_ts_floor)+ )+ rows = [shape_document(document, collection.partition_key_paths) for document in documents]+ if rows:+ yield rows+ else:+ # Cosmos hands back empty pages while it crosses physical partitions, and the pipeline+ # only sees a shutdown when an item or a safe point arrives.+ resumable_source_manager.safe_point()+ if not continuation:+ return+++def cosmosdb_source(+ endpoint: str,+ key: str,+ database: str,+ collection_name: str,+ api_version: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CosmosDBResumeConfig],+ cursor_manager: SourceCursorManager[CosmosDBTsCursor] | None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ client = CosmosDBClient(endpoint, key, api_version, logger, safe_point=resumable_source_manager.safe_point)++ ts_floor: int | None = None+ next_ts_floor: int | None = None+ if should_use_incremental_field:+ stored = cursor_manager.load() if cursor_manager is not None else None+ if stored is not None:+ ts_floor = stored.ts_floor+ elif db_incremental_field_last_value is not None:+ ts_floor = int(db_incremental_field_last_value)+ next_ts_floor = int(time.time()) - TS_FLOOR_MARGIN_SECONDS++ def items() -> Iterator[list[dict[str, Any]]]:+ collection = client.get_collection(database, collection_name)+ yield from get_rows(+ client,+ database,+ collection,+ ts_floor,+ next_ts_floor,+ resumable_source_manager,+ cursor_manager,+ logger,+ )++ return SourceResponse(+ name=collection_name,+ items=items,+ primary_keys=PRIMARY_KEYS,+ # Rows arrive in partition order, not `_ts` order. `desc` makes the pipeline promote the+ # watermark only when the run completes; the next run starts from the source cursor anyway.+ sort_mode="desc",+ on_complete=resumable_source_manager.clear_state,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/settings.pynew file mode 100644index 000000000000..126a3c3d20f0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/settings.py@@ -0,0 +1,21 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Newest version Microsoft lists for the Cosmos DB REST API; sent as `x-ms-version` on every call.+API_VERSION = "2018-12-31"+PAGE_SIZE = 500+# Written on every row: the document's partition key value, so `id` (unique only within a logical+# partition) becomes a table-wide key with it.+PARTITION_KEY_COLUMN = "_partition_key"+PRIMARY_KEYS = ["id", PARTITION_KEY_COLUMN]+# Cosmos stamps `_ts` (epoch seconds) on every write, so it is the one server-side cursor every+# container has.+TIMESTAMP_FIELD = "_ts"+INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": TIMESTAMP_FIELD,+ "type": IncrementalFieldType.Integer,+ "field": TIMESTAMP_FIELD,+ "field_type": IncrementalFieldType.Integer,+ "is_indexed": True,+ }+]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/source.pyindex 8ef2f56cece5..de173ee7dea8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/source.py@@ -1,8 +1,35 @@-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+import structlog++from products.warehouse_sources.backend.facade.codebase_detection import detect+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import CursorSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cosmosdb.cosmosdb import (+ FORBIDDEN_MESSAGE,+ CosmosDBClient,+ CosmosDBResumeConfig,+ CosmosDBTsCursor,+ cosmosdb_source,+ hostname_of,+ validate_credentials as validate_cosmosdb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cosmosdb.settings import (+ API_VERSION,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cosmosdb import (CosmosDBSourceConfig,)@@ -10,19 +37,174 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CosmosDBSource(SimpleSource[CosmosDBSourceConfig]):+class CosmosDBSource(+ ResumableSource[CosmosDBSourceConfig, CosmosDBResumeConfig],+ CursorSource[CosmosDBTsCursor],+ ValidateDatabaseHostMixin,+):+ codebase_detection = detect(+ env=("^(AZURE_COSMOS|COSMOS_DB|COSMOSDB)_",),+ npm=("@azure/cosmos",),+ pypi=("azure-cosmos",),+ go=("github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos",),+ maven=("com.azure:azure-cosmos",),+ )++ supported_versions = (API_VERSION,)+ default_version = API_VERSION+ api_docs_url = "https://learn.microsoft.com/en-us/rest/api/cosmos-db/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COSMOSDB+ @property+ def connection_host_fields(self) -> list[str]:+ # The stored key signs every request to this endpoint, so retargeting it must re-require the key.+ return ["account_endpoint"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.COSMOSDB,category=DataWarehouseSourceCategory.DATABASES,- keywords=["azure cosmos"],+ keywords=["azure cosmos", "documentdb"],label="Azure Cosmos DB",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Sync the containers of an Azure Cosmos DB for NoSQL database into the PostHog Data warehouse. Each container becomes a table, and incremental syncs use the `_ts` system property Cosmos stamps on every write.++Enter the account endpoint (`https://<account>.documents.azure.com`), a read-only or read-write key from the account's **Keys** page, and the database to sync. Only the NoSQL API is supported.""",iconPath="/static/services/cosmosdb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/cosmosdb",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="account_endpoint",+ label="Account endpoint",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://<account>.documents.azure.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="key",+ label="Account key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="database",+ label="Database",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="",+ secret=False,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url:": "Azure Cosmos DB rejected the account key. Copy a current key from the account's Keys page and reconnect.",+ "403 Client Error: Forbidden for url:": FORBIDDEN_MESSAGE,+ "404 Client Error:": "The database or container no longer exists in this Cosmos DB account. Check the source settings and the table list.",+ "Azure Cosmos DB account key is not valid base64": "The account key is not valid. Copy the primary or secondary key from the account's Keys page and reconnect.",+ }++ def get_retryable_errors(self) -> set[str]:+ return {"Azure Cosmos DB error (retryable)"}++ def _check_host(self, config: CosmosDBSourceConfig, team_id: int) -> tuple[bool, str | None]:+ try:+ host = hostname_of(config.account_endpoint)+ except ValueError as error:+ return False, str(error)+ return self.is_database_host_valid(host, team_id)++ def get_schemas(+ self,+ config: CosmosDBSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ host_valid, host_error = self._check_host(config, team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Azure Cosmos DB account endpoint")++ client = CosmosDBClient(+ config.account_endpoint, config.key, self.resolve_api_version(api_version), structlog.get_logger(__name__)+ )+ schemas = [+ SourceSchema(+ name=collection.id,+ supports_incremental=True,+ # The `>=` watermark re-reads its boundary second, which only merge dedupes.+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS,+ )+ for collection in client.list_collections(config.database)+ ]++ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]++ return schemas++ def validate_credentials(+ self,+ config: CosmosDBSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ host_valid, host_error = self._check_host(config, team_id)+ if not host_valid:+ return False, host_error++ return validate_cosmosdb_credentials(+ endpoint=config.account_endpoint,+ key=config.key,+ database=config.database,+ api_version=self.resolve_api_version(api_version),+ )++ def cursor_class(self) -> type[CosmosDBTsCursor]:+ return CosmosDBTsCursor++ def merge_cursors(self, current: CosmosDBTsCursor, candidate: CosmosDBTsCursor) -> CosmosDBTsCursor:+ return candidate if candidate.ts_floor >= current.ts_floor else current++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CosmosDBResumeConfig]:+ return ResumableSourceManager[CosmosDBResumeConfig](inputs, CosmosDBResumeConfig)++ def source_for_pipeline(+ self,+ config: CosmosDBSourceConfig,+ resumable_source_manager: ResumableSourceManager[CosmosDBResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ host_valid, host_error = self._check_host(config, inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Azure Cosmos DB account endpoint")++ return cosmosdb_source(+ endpoint=config.account_endpoint,+ key=config.key,+ database=config.database,+ collection_name=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ # The pipeline always builds one for a cursor source; the test drivers do not.+ cursor_manager=inputs.source_cursor,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/tests/test_cosmosdb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/tests/test_cosmosdb.pynew file mode 100644index 000000000000..7095dc74edd8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cosmosdb/tests/test_cosmosdb.py@@ -0,0 +1,381 @@+from collections.abc import Iterator+from datetime import UTC, datetime+from typing import Any+from urllib.parse import unquote++import pytest+import time_machine++from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,+ ScriptedResponse,+ SourceDriver,+ scripted_network,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.cosmosdb.cosmosdb import (+ CosmosDBResumeConfig,+ CosmosDBRetryableError,+ CosmosDBTsCursor,+ decode_account_key,+ master_key_signature,+ normalize_account_endpoint,+ partition_key_value,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.cosmosdb.source import CosmosDBSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.cosmosdb import (+ CosmosDBSourceConfig,+)++# A syntactically valid 64-byte key, as the Azure portal issues them (the value itself is made up).+ACCOUNT_KEY = "QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVowMTIzNDU2Nzg5YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU2Nzg5"+ENDPOINT = "https://unit-test.documents.azure.com"+# Each run reads documents written before now minus five minutes.+NOW = datetime(2023, 11, 14, 22, 18, 20, tzinfo=UTC)+CURSOR_FLOOR = 1700000000+COLLECTION = {"id": "orders", "partitionKey": {"paths": ["/tenantId"], "kind": "Hash"}}+++def _driver() -> SourceDriver:+ return SourceDriver(+ CosmosDBSource(), CosmosDBSourceConfig(account_endpoint=ENDPOINT, key=ACCOUNT_KEY, database="shop")+ )+++def _collection() -> ScriptedResponse:+ return ScriptedResponse(json=COLLECTION)+++def _page(documents: list[dict[str, Any]], continuation: str | None = None) -> ScriptedResponse:+ headers = {"x-ms-continuation": continuation} if continuation else {}+ return ScriptedResponse(json={"_rid": "rid", "Documents": documents, "_count": len(documents)}, headers=headers)+++class TestMasterKeySignature:+ def test_matches_the_worked_example_from_the_rest_auth_docs(self) -> None:+ key = decode_account_key(+ "dsZQi3KtZmCv1ljt3VNWNm7sQUF1y5rJfC6kv5JiwvW0EndXdDku/dkKBp8/ufDToSxLzR4y+O/0H/t4bQtVNw=="+ )+ signature = master_key_signature(key, "GET", "dbs", "dbs/ToDoList", "Thu, 27 Apr 2017 00:51:12 GMT")++ assert unquote(signature) == "type=master&ver=1.0&sig=c09PEVJrgp2uQRkr934kFbTqhByc7TVr3OHyqlu+c+c="+++class TestNormalizeAccountEndpoint:+ @pytest.mark.parametrize(+ ("endpoint", "expected"),+ [+ ("https://acme.documents.azure.com", "https://acme.documents.azure.com"),+ ("https://acme.documents.azure.com:443/", "https://acme.documents.azure.com:443"),+ (" acme.documents.azure.com ", "https://acme.documents.azure.com"),+ ],+ )+ def test_trims_to_scheme_and_host(self, endpoint: str, expected: str) -> None:+ assert normalize_account_endpoint(endpoint) == expected++ @pytest.mark.parametrize(+ "endpoint",+ [+ "http://acme.documents.azure.com",+ "https://acme.documents.azure.com/dbs/other",+ "https://acme.documents.azure.com?x=1",+ "https://user:[email protected]",+ "",+ ],+ )+ def test_rejects_anything_that_could_repoint_the_signed_request(self, endpoint: str) -> None:+ with pytest.raises(ValueError):+ normalize_account_endpoint(endpoint)+++class TestPartitionKeyValue:+ @pytest.mark.parametrize(+ ("document", "paths", "expected"),+ [+ ({"tenantId": "t-1"}, ("/tenantId",), '"t-1"'),+ ({"tenantId": "1"}, ("/tenantId",), '"1"'),+ ({"tenantId": 1}, ("/tenantId",), "1"),+ ({"tenantId": True}, ("/tenantId",), "true"),+ ({"tenantId": None}, ("/tenantId",), "null"),+ ({"tenantId": ""}, ("/tenantId",), '""'),+ ({"id": "x"}, ("/tenantId",), ""),+ ({"address": {"city": "Oslo"}}, ("/address/city",), '"Oslo"'),+ ({"address": "flat"}, ("/address/city",), ""),+ ({"tenant/key": "t-1"}, ('/"tenant/key"',), '"t-1"'),+ ({"a": {'say "hi"': 2}}, ('/a/"say \\"hi\\""',), "2"),+ ({"tenantId": "t-1", "region": "eu"}, ("/tenantId", "/region"), '["\\"t-1\\"","\\"eu\\""]'),+ ({"tenantId": "t-1"}, ("/tenantId", "/region"), '["\\"t-1\\"",""]'),+ ({"tenantId": "t-1", "region": None}, ("/tenantId", "/region"), '["\\"t-1\\"","null"]'),+ ({"id": "x"}, (), ""),+ ],+ )+ def test_resolves_the_path_to_one_string(self, document: dict[str, Any], paths: tuple[str, ...], expected: str):+ assert partition_key_value(document, paths) == expected++ def test_keys_that_differ_in_type_or_presence_stay_distinct(self) -> None:+ documents: list[dict[str, Any]] = [{"k": "1"}, {"k": 1}, {"k": ""}, {"k": None}, {}, {"k": True}, {"k": "true"}]++ assert len({partition_key_value(document, ("/k",)) for document in documents}) == len(documents)+++class _SourceWithCursor(CosmosDBSource):+ """Hands the source a cursor manager, as the pipeline does for a cursor source."""++ def __init__(self, stored: CosmosDBTsCursor | None = None) -> None:+ super().__init__()+ self.cursor_manager = SourceCursorManager(CosmosDBTsCursor, stored, self)++ def source_for_pipeline(+ self,+ config: CosmosDBSourceConfig,+ resumable_source_manager: ResumableSourceManager[CosmosDBResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ inputs.source_cursor = self.cursor_manager+ return super().source_for_pipeline(config, resumable_source_manager, inputs)+++def _config() -> CosmosDBSourceConfig:+ return CosmosDBSourceConfig(account_endpoint=ENDPOINT, key=ACCOUNT_KEY, database="shop")+++class TestQueryDocuments:+ @pytest.fixture(autouse=True)+ def _frozen_clock(self) -> Iterator[None]:+ with time_machine.travel(NOW, tick=False):+ yield++ def test_walks_continuation_tokens_and_stages_each_before_its_page(self) -> None:+ result = _driver().run(+ "orders",+ [+ _collection(),+ _page([{"id": "1", "tenantId": "a", "_ts": 10}], continuation="tok-2"),+ _page([{"id": "2", "tenantId": "b", "_ts": 11}], continuation="tok-3"),+ _page([{"id": "3", "tenantId": "a", "_ts": 12}]),+ ],+ )++ assert result.raised is None+ assert result.paths == ["/dbs/shop/colls/orders"] + ["/dbs/shop/colls/orders/docs"] * 3+ assert [request.headers.get("x-ms-continuation") for request in result.requests[1:]] == [None, "tok-2", "tok-3"]+ assert [row["id"] for row in result.rows] == ["1", "2", "3"]+ assert [row["_partition_key"] for row in result.rows] == ['"a"', '"b"', '"a"']+ assert result.saved_states == [+ CosmosDBResumeConfig(continuation="tok-2"),+ CosmosDBResumeConfig(continuation="tok-3"),+ ]+ assert result.committed_states == result.saved_states+ assert result.completed_state is None++ @pytest.mark.parametrize(+ ("stored", "inputs", "expected_floor", "expected_staged"),+ [+ (None, {}, None, None),+ (+ CosmosDBTsCursor(ts_floor=1699995000),+ {+ "incremental_field": "_ts",+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": 1,+ },+ None,+ None,+ ),+ (None, {"incremental_field": "_ts"}, None, CosmosDBTsCursor(ts_floor=CURSOR_FLOOR)),+ (+ None,+ {"incremental_field": "_ts", "db_incremental_field_last_value": 1699990000},+ 1699990000,+ CosmosDBTsCursor(ts_floor=CURSOR_FLOOR),+ ),+ (+ CosmosDBTsCursor(ts_floor=1699995000),+ {"incremental_field": "_ts", "db_incremental_field_last_value": 1699999999},+ 1699995000,+ CosmosDBTsCursor(ts_floor=CURSOR_FLOOR),+ ),+ ],+ )+ def test_incremental_runs_read_from_the_cursor_with_no_upper_bound(+ self,+ stored: CosmosDBTsCursor | None,+ inputs: dict[str, Any],+ expected_floor: int | None,+ expected_staged: CosmosDBTsCursor | None,+ ) -> None:+ source = _SourceWithCursor(stored)+ result = SourceDriver(source, _config()).run(+ "orders", [_collection(), _page([{"id": "1", "tenantId": "a", "_ts": 1}])], **inputs+ )++ assert result.raised is None+ query_request = result.requests[1]+ if expected_floor is None:+ assert query_request.json() == {"query": "SELECT * FROM c", "parameters": []}+ else:+ assert query_request.json() == {+ "query": "SELECT * FROM c WHERE c._ts >= @floor",+ "parameters": [{"name": "@floor", "value": expected_floor}],+ }+ assert query_request.headers["x-ms-documentdb-query-enablecrosspartition"] == "True"+ assert query_request.headers["x-ms-version"] == "2018-12-31"+ assert source.cursor_manager.staged == expected_staged++ def test_resume_replays_the_saved_token_and_hands_on_the_first_attempts_floor(self) -> None:+ source = _SourceWithCursor(CosmosDBTsCursor(ts_floor=30))+ result = SourceDriver(source, _config()).run(+ "orders",+ [_collection(), _page([{"id": "9", "tenantId": "a", "_ts": 50}])],+ resume_state=CosmosDBResumeConfig(continuation="tok-7", ts_floor=40, next_ts_floor=90),+ incremental_field="_ts",+ )++ assert result.raised is None+ query_request = result.requests[1]+ assert query_request.headers["x-ms-continuation"] == "tok-7"+ assert query_request.json()["parameters"] == [{"name": "@floor", "value": 40}]+ assert source.cursor_manager.staged == CosmosDBTsCursor(ts_floor=90)++ def test_empty_pages_with_a_token_keep_walking(self) -> None:+ result = _driver().run(+ "orders",+ [+ _collection(),+ _page([], continuation="tok-2"),+ _page([], continuation="tok-3"),+ _page([{"id": "1", "tenantId": "a", "_ts": 1}]),+ ],+ )++ assert result.raised is None+ assert len(result.requests) == 4+ assert [row["id"] for row in result.rows] == ["1"]++ def test_throttle_honours_retry_after_ms_then_succeeds(self) -> None:+ throttled = ScriptedResponse(+ status=429,+ json={"code": "TooManyRequests", "message": "Request rate is large."},+ headers={"x-ms-retry-after-ms": "250"},+ )+ answers = iter([_collection(), *[throttled] * 7, _page([{"id": "1", "tenantId": "a", "_ts": 1}])])++ def respond(_request: RecordedRequest) -> ScriptedResponse:+ return next(answers)++ result = _driver().run("orders", respond)++ assert result.raised is None+ assert len(result.requests) == 9+ assert [row["id"] for row in result.rows] == ["1"]++ def test_a_dropped_connection_is_retried_within_the_budget(self) -> None:+ result = _driver().run(+ "orders",+ [_collection(), ConnectionResetError(), _page([{"id": "1", "tenantId": "a", "_ts": 1}])],+ )++ assert result.raised is None+ assert len(result.requests) == 3+ assert [row["id"] for row in result.rows] == ["1"]++ def test_a_throttle_wait_longer_than_the_budget_fails_without_retrying(self) -> None:+ def respond(request: RecordedRequest) -> ScriptedResponse:+ if request.path == "/dbs/shop/colls/orders":+ return _collection()+ return ScriptedResponse(status=429, json={"code": "TooManyRequests"}, headers={"Retry-After": "86400"})++ result = _driver().run("orders", respond)++ assert isinstance(result.raised, CosmosDBRetryableError)+ assert len(result.requests) == 2++ def test_retries_stop_before_a_full_attempt_would_overrun_five_minutes(self) -> None:+ unavailable = ScriptedResponse(status=503, json={"code": "ServiceUnavailable"}, headers={"Retry-After": "60"})++ def respond(request: RecordedRequest) -> ScriptedResponse:+ return _collection() if request.path == "/dbs/shop/colls/orders" else unavailable++ result = _driver().run("orders", respond)++ assert isinstance(result.raised, CosmosDBRetryableError)+ # Waits of 60 s at 0 s and 60 s still leave room for a full 150 s attempt; a third does not.+ assert len(result.requests) == 1 + 3++ def test_bad_key_surfaces_the_vendor_error(self) -> None:+ result = _driver().run(+ "orders",+ [+ ScriptedResponse(+ status=401,+ json={+ "code": "Unauthorized",+ "message": "The input authorization token can't serve the request. The wrong key is being used or the expected payload is not built as per the protocol.",+ },+ )+ ],+ )++ assert result.raised is not None+ assert "401 Client Error: Unauthorized for url:" in str(result.raised)+ assert "The wrong key is being used" in str(result.raised)+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("response", "expected_ok", "expected_fragment"),+ [+ (ScriptedResponse(json={"DocumentCollections": [COLLECTION], "_count": 1}), True, None),+ (+ ScriptedResponse(+ status=401,+ json={"code": "Unauthorized", "message": "The input authorization token can't serve the request."},+ ),+ False,+ "rejected the account key",+ ),+ (+ ScriptedResponse(+ status=403,+ json={+ "code": "Forbidden",+ "message": "Request originated from IP 203.0.113.7 through public internet. This is blocked by your Cosmos DB account firewall settings.",+ },+ ),+ False,+ "blocked by your Cosmos DB account firewall",+ ),+ (+ ScriptedResponse(+ status=404,+ json={"code": "NotFound", "message": "Entity with the specified id does not exist in the system."},+ ),+ False,+ "No database named shop",+ ),+ ],+ )+ def test_maps_the_collection_probe_to_a_message(+ self, response: ScriptedResponse, expected_ok: bool, expected_fragment: str | None+ ) -> None:+ with scripted_network([response]) as network:+ ok, message = validate_credentials(ENDPOINT, ACCOUNT_KEY, "shop", "2018-12-31")++ assert ok is expected_ok+ if expected_fragment is None:+ assert message is None+ else:+ assert message is not None and expected_fragment in message+ assert network.requests_log[0].path == "/dbs/shop/colls"+ assert network.requests_log[0].headers["authorization"].startswith("type%3Dmaster%26ver%3D1.0%26sig%3D")++ def test_rejects_a_key_that_is_not_base64_without_a_request(self) -> None:+ with scripted_network([]) as network:+ ok, message = validate_credentials(ENDPOINT, "not a key", "shop", "2018-12-31")++ assert ok is False+ assert message is not None and "not valid" in message+ assert network.requests_log == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cosmosdb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cosmosdb.pyindex e4a7bce41821..74e8598e39a5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cosmosdb.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/cosmosdb.py@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CosmosDBSourceConfig(config.Config):- pass+ account_endpoint: str+ key: str+ database: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txtindex 31fd1f33a60a..fa989654a162 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/source_contract_baseline.txt@@ -186,6 +186,7 @@ Convex not-checkable:schemasCopper fail:stall-budgetCoralogix fail:stall-budgetCortex fail:stall-budget+CosmosDB not-checkable:schemasCoupa fail:rate-limit-budget,stall-budgetCourier fail:stall-budgetCoveralls not-checkable:no-request