:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): add CompanyCam import source (#84361)
Tom Owerseba3adea02b2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/canonical_descriptions.pynew file mode 100644index 000000000000..1b8f4177043b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/canonical_descriptions.py@@ -0,0 +1,137 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "Projects": {+ "description": "A jobsite or work location where photos, videos, and documents are organized.",+ "docs_url": "https://docs.companycam.com/reference/listprojects",+ "columns": {+ "id": "A unique identifier for the Project.",+ "company_id": "A unique identifier for the Company the Project belongs to.",+ "creator_id": "The id of the entity that created the Project.",+ "creator_type": "The type of the entity that created the Project.",+ "creator_name": "The display name of the entity that created the Project.",+ "status": "Indicates the status of the Project (active or deleted).",+ "archived": "Indicates whether the Project is archived.",+ "name": "The title of the Project.",+ "project_url": "The URL to the Project in the web app.",+ "embedded_project_url": "The URL to an embeddable photo feed for the Project.",+ "slug": "A unique identifier for the Project used to construct some public URLs.",+ "public": "Indicates whether the Project's timeline and other public features are enabled.",+ "notepad": "Notes or description of the project.",+ "created_at": "Timestamp when the Project was created.",+ "updated_at": "Timestamp when the Project was updated.",+ },+ },+ "Photos": {+ "description": "A photo captured at a Project, with metadata and links to the image assets.",+ "docs_url": "https://docs.companycam.com/reference/listphotos",+ "columns": {+ "id": "The unique ID for the photo.",+ "company_id": "A unique identifier for the Company the Photo belongs to.",+ "creator_id": "The id of the entity that created the Photo.",+ "creator_type": "The type of the entity that created the Photo.",+ "creator_name": "The display name of the entity that created the Photo.",+ "project_id": "The unique ID of the project the Photo was captured at.",+ "processing_status": "Indicates the Photo's processing status.",+ "status": "The status of the Photo (active or deleted).",+ "hash": "The MD5 hash of the photo.",+ "description": "A description of the photo.",+ "internal": "Indicates whether the photo is for internal use only.",+ "photo_url": "The link to the photo in the web app.",+ "captured_at": "Timestamp when the Photo was captured.",+ "created_at": "Timestamp when the photo was created on the server. May differ from captured_at.",+ "updated_at": "Timestamp when the photo was last updated.",+ },+ },+ "Videos": {+ "description": "A video captured at a Project, with metadata and a link to the playback URL.",+ "docs_url": "https://docs.companycam.com/reference/listvideos",+ "columns": {+ "id": "The unique ID for the video.",+ "company_id": "A unique identifier for the Company the Video belongs to.",+ "creator_id": "The id of the entity that created the Video.",+ "creator_type": "The type of the entity that created the Video.",+ "creator_name": "The display name of the entity that created the Video.",+ "project_id": "The unique ID of the project the Video was captured at.",+ "status": "The video's processing status.",+ "internal": "Indicates whether the video is for internal use only.",+ "captured_at": "Unix timestamp when the Video was captured.",+ "created_at": "Unix timestamp when the video record was created on the server.",+ "updated_at": "Unix timestamp when the video was last updated.",+ "playback_url": "The HLS manifest URL once processed, or the raw upload URL before that.",+ "format": "The video format, e.g. m3u8 once processed.",+ "duration": "Length of the video in seconds.",+ },+ },+ "Users": {+ "description": "A user (team member) on the CompanyCam account.",+ "docs_url": "https://docs.companycam.com/reference/listusers",+ "columns": {+ "id": "A unique identifier for the User.",+ "company_id": "A unique identifier for the Company the User belongs to.",+ "email_address": "The User's email address.",+ "status": "Indicates the status of the User (active or deleted).",+ "first_name": "The User's first name.",+ "last_name": "The User's last name.",+ "phone_number": "The User's phone number.",+ "created_at": "Timestamp when the User was created.",+ "updated_at": "Timestamp when the User was last updated.",+ "user_url": "The link to the user in the web app.",+ },+ },+ "Tags": {+ "description": "A label that can be applied to photos or videos for organization and search.",+ "docs_url": "https://docs.companycam.com/reference/listtags",+ "columns": {+ "id": "A unique ID for the Tag.",+ "company_id": "A unique ID for the Company the Tag belongs to.",+ "display_value": "The display value of the Tag, used to display to the user.",+ "value": "The lowercase version of display_value, useful for searching and sorting.",+ "created_at": "Timestamp when the Tag was created on the server.",+ "updated_at": "Timestamp when the Tag was last updated.",+ },+ },+ "Groups": {+ "description": "A group of users on the CompanyCam account, e.g. a crew.",+ "docs_url": "https://docs.companycam.com/reference/listgroups",+ "columns": {+ "id": "A unique ID for the Group.",+ "company_id": "A unique ID for the Company the Group belongs to.",+ "name": "The title of the Group.",+ "status": "Indicates the status of the Group (active or deleted).",+ "group_url": "The link to the group in the web app.",+ "created_at": "Timestamp when the Group was created on the server.",+ "updated_at": "Timestamp when the Group was last updated.",+ },+ },+ "Checklists": {+ "description": "A checklist filled out at a Project, optionally created from a ChecklistTemplate.",+ "docs_url": "https://docs.companycam.com/reference/listchecklists",+ "columns": {+ "id": "The unique ID for the Checklist.",+ "company_id": "A unique identifier for the Company the Checklist belongs to.",+ "project_id": "A unique identifier for the Project the Checklist belongs to.",+ "name": "The name for the Checklist.",+ "created_at": "Timestamp when the Checklist was created on the server.",+ "updated_at": "Timestamp when the Checklist was last updated.",+ "completed_at": "Timestamp when the Checklist was completed.",+ "creator_id": "A unique identifier for the creator of the Checklist.",+ "checklist_template_id": "A unique identifier for the template used to create the Checklist.",+ "is_populating": "Flag indicating whether the Checklist is still being created.",+ },+ },+ "ChecklistTemplates": {+ "description": "A reusable checklist template that can be used to create Checklists on Projects.",+ "docs_url": "https://docs.companycam.com/reference/listchecklisttemplates",+ "columns": {+ "id": "The unique ID for the ChecklistTemplate.",+ "company_id": "A unique identifier for the Company the ChecklistTemplate belongs to.",+ "name": "The name for the ChecklistTemplate.",+ "description": "The description for the ChecklistTemplate.",+ "created_at": "Timestamp when the ChecklistTemplate was created on the server.",+ "updated_at": "Timestamp when the ChecklistTemplate was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/companycam.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/companycam.pynew file mode 100644index 000000000000..a31827e90042--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/companycam.py@@ -0,0 +1,238 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from requests import Request, Response++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 (+ BasePaginator,+ PageNumberPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+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.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.settings import (+ COMPANYCAM_ENDPOINTS,+ PER_PAGE,+)+++def base_url(api_version: str) -> str:+ return f"https://api.companycam.com/{api_version}"++[email protected](frozen=True)+class CompanycamResumeConfig:+ # Next 1-indexed page to fetch, for page/per_page-paginated endpoints.+ page: Optional[int] = None+ # Next forward cursor (from `X-Next-Cursor`), for Photos.+ cursor: Optional[str] = None+++def _to_iso8601(value: Any) -> Optional[str]:+ """Format an incremental cursor as the ISO8601 string CompanyCam's `modified_since` expects."""+ if value is None:+ return None+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ if isinstance(value, int | float):+ return datetime.fromtimestamp(value, tz=UTC).isoformat()+ return str(value)+++def _to_unix_timestamp(value: Any) -> Optional[str]:+ """Format an incremental cursor as the unix timestamp string CompanyCam's `start_date` expects."""+ if value is None:+ return None+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return str(int(aware.timestamp()))+ if isinstance(value, date):+ return str(int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp()))+ if isinstance(value, int | float):+ return str(int(value))+ return str(value)+++_CONVERTERS = {+ "modified_since": _to_iso8601,+ "start_date": _to_unix_timestamp,+}+++class CompanycamCursorPaginator(BasePaginator):+ """Forward cursor pagination for `/photos`, driven by the `X-Next-Cursor` response header.++ CompanyCam's cursor is a bare token carried in a response header, not a full next-page URL or+ a body field, so none of the framework's built-in paginators fit: it isn't a `Link` header+ (`HeaderLinkPaginator`), a JSON body cursor (`JSONResponseCursorPaginator`), or a full URL+ (`BaseNextUrlPaginator`). `page` and `after` are mutually exclusive, so this paginator never+ sends `page`.+ """++ def __init__(self, per_page: int) -> None:+ super().__init__()+ self._per_page = per_page+ self._cursor: Optional[str] = None++ def init_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["per_page"] = self._per_page+ if self._cursor is not None:+ request.params["after"] = self._cursor++ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:+ has_next = response.headers.get("X-Has-Next")+ next_cursor = response.headers.get("X-Next-Cursor")+ if has_next is not None:+ self._has_next_page = has_next.lower() == "true" and bool(next_cursor)+ else:+ self._has_next_page = bool(next_cursor)+ self._cursor = next_cursor or None++ def update_request(self, request: Request) -> None:+ if request.params is None:+ request.params = {}+ request.params["per_page"] = self._per_page+ if self._cursor is not None:+ request.params["after"] = self._cursor++ def get_resume_state(self) -> Optional[dict[str, Any]]:+ return {"cursor": self._cursor} if self._has_next_page and self._cursor else None++ def set_resume_state(self, state: dict[str, Any]) -> None:+ cursor = state.get("cursor")+ if cursor is not None:+ self._cursor = str(cursor)+ self._has_next_page = True++ def __str__(self) -> str:+ return f"CompanycamCursorPaginator(cursor={self._cursor})"+++def _paginator_for(endpoint: str) -> BasePaginator:+ config = COMPANYCAM_ENDPOINTS[endpoint]+ if not config.paginated:+ return SinglePagePaginator()+ if config.cursor_paginated:+ return CompanycamCursorPaginator(per_page=PER_PAGE)+ return PageNumberPaginator(base_page=1, page_param="page")+++def get_resource(+ endpoint: str,+ should_use_incremental_field: bool,+) -> EndpointResource:+ config = COMPANYCAM_ENDPOINTS[endpoint]++ params: dict[str, Any] = {}+ if config.paginated and not config.cursor_paginated:+ params["per_page"] = PER_PAGE+ if config.incremental_query_param and should_use_incremental_field:+ params[config.incremental_query_param] = {+ "type": "incremental",+ "cursor_path": config.incremental_fields[0]["field"],+ "initial_value": None,+ "convert": _CONVERTERS[config.incremental_query_param],+ }++ return {+ "name": endpoint,+ "table_name": endpoint.lower(),+ "write_disposition": {"disposition": "merge", "strategy": "upsert"}+ if should_use_incremental_field+ else "replace",+ "endpoint": {+ "data_selector": "$",+ "path": config.path,+ "params": params,+ },+ "table_format": "delta",+ }+++def companycam_source(+ api_key: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[CompanycamResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ api_version: str,+) -> SourceResponse:+ endpoint_config = COMPANYCAM_ENDPOINTS[endpoint]++ rest_config: RESTAPIConfig = {+ "client": {+ "base_url": base_url(api_version),+ "auth": {"type": "bearer", "token": api_key},+ "paginator": _paginator_for(endpoint),+ # capture=False: project notes, photo/video metadata, and other free-text fields+ # can carry customer-authored (potentially sensitive) content the name-based HTTP+ # sample scrubbers aren't guaranteed to catch, same as the other PII-heavy sources.+ "capture": False,+ },+ "resources": [get_resource(endpoint, should_use_incremental_field)],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ if endpoint_config.cursor_paginated and resume_config.cursor is not None:+ initial_paginator_state = {"cursor": resume_config.cursor}+ elif resume_config.page is not None:+ initial_paginator_state = {"page": resume_config.page}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when there's a next page/cursor to resume to. Save AFTER a page is+ # yielded so a crash re-yields the last page (merge dedupes) rather than skipping it.+ if not state:+ return+ if endpoint_config.cursor_paginated and state.get("cursor"):+ resumable_source_manager.save_state(CompanycamResumeConfig(cursor=str(state["cursor"])))+ elif state.get("page") is not None:+ resumable_source_manager.save_state(CompanycamResumeConfig(page=int(state["page"])))++ resource = rest_api_resource(+ rest_config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=endpoint_config.primary_keys,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode=endpoint_config.sort_mode if should_use_incremental_field else "asc",+ column_hints=resource.column_hints,+ )+++def validate_credentials(api_key: str, api_version: str) -> bool:+ # capture=False: `/company` returns the customer's company record, which can carry+ # free-text fields the name-based HTTP sample scrubbers aren't guaranteed to catch.+ is_valid, _status_code = validate_via_probe(+ lambda: make_tracked_session(redact_values=(api_key,), capture=False),+ f"{base_url(api_version)}/company",+ headers={"Authorization": f"Bearer {api_key}"},+ )+ return is_validdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/settings.pynew file mode 100644index 000000000000..6e52b15d310b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/settings.py@@ -0,0 +1,94 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# CompanyCam's documented ceiling for `per_page` is 100 (default 50). Requesting the max on+# every endpoint minimises round trips; endpoints without a documented cap accept it too.+PER_PAGE = 100+++@dataclass(frozen=True)+class CompanycamEndpointConfig:+ name: str+ path: str # Path under https://api.companycam.com/v2+ # Field CompanyCam filters on server-side for this endpoint (`modified_since` on Projects,+ # `start_date` on Photos/Videos), or None when the endpoint has no time filter.+ incremental_query_param: Optional[str] = None+ # The rows come back newest-first for every incremental-capable list endpoint here, so the+ # watermark can only be finalized once a full sync completes (see SourceResponse.sort_mode).+ sort_mode: SortMode = "desc"+ # Stable field to partition by. Capture time for photos/videos, creation time otherwise.+ partition_key: Optional[str] = "created_at"+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Whether this endpoint's cursor pagination comes from the `X-Next-Cursor` response header+ # (Photos) rather than `page`/`per_page`.+ cursor_paginated: bool = False+ # False for endpoints the docs show no page/per_page params for (ChecklistTemplates returns+ # a company's full template list in one response).+ paginated: bool = True+++def _incremental_field(field_name: str) -> list[IncrementalField]:+ return [+ {+ "label": field_name,+ "type": IncrementalFieldType.DateTime,+ "field": field_name,+ "field_type": IncrementalFieldType.Integer,+ },+ ]+++COMPANYCAM_ENDPOINTS: dict[str, CompanycamEndpointConfig] = {+ "Projects": CompanycamEndpointConfig(+ name="Projects",+ path="/projects",+ incremental_query_param="modified_since",+ incremental_fields=_incremental_field("updated_at"),+ ),+ "Photos": CompanycamEndpointConfig(+ name="Photos",+ path="/photos",+ incremental_query_param="start_date",+ incremental_fields=_incremental_field("captured_at"),+ partition_key="captured_at",+ cursor_paginated=True,+ ),+ "Videos": CompanycamEndpointConfig(+ name="Videos",+ path="/videos",+ incremental_query_param="start_date",+ incremental_fields=_incremental_field("captured_at"),+ partition_key="captured_at",+ ),+ "Users": CompanycamEndpointConfig(+ name="Users",+ path="/users",+ ),+ "Tags": CompanycamEndpointConfig(+ name="Tags",+ path="/tags",+ ),+ "Groups": CompanycamEndpointConfig(+ name="Groups",+ path="/groups",+ ),+ "Checklists": CompanycamEndpointConfig(+ name="Checklists",+ path="/checklists",+ ),+ "ChecklistTemplates": CompanycamEndpointConfig(+ name="ChecklistTemplates",+ path="/templates/checklists",+ paginated=False,+ ),+}++ENDPOINTS = tuple(COMPANYCAM_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in COMPANYCAM_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/source.pyindex 1aac58fd91a1..7fde9687ae5c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/source.py@@ -1,13 +1,34 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.companycam import (+ CompanycamResumeConfig,+ companycam_source,+ validate_credentials as validate_companycam_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.companycam import (CompanycamSourceConfig,)@@ -15,18 +36,98 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class CompanycamSource(SimpleSource[CompanycamSourceConfig]):+class CompanycamSource(ResumableSource[CompanycamSourceConfig, CompanycamResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ supported_versions = ("v2",)+ default_version = "v2"+ api_docs_url = "https://docs.companycam.com/changelog"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.COMPANYCAM+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your CompanyCam API key is invalid or expired. "+ "Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url": "Your CompanyCam API key does not have permission "+ "to access this data.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: CompanycamSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: CompanycamSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if validate_companycam_credentials(config.api_key, self.resolve_api_version(api_version)):+ return True, None++ return False, "Invalid credentials"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CompanycamResumeConfig]:+ return ResumableSourceManager[CompanycamResumeConfig](inputs, CompanycamResumeConfig)++ def source_for_pipeline(+ self,+ config: CompanycamSourceConfig,+ resumable_source_manager: ResumableSourceManager[CompanycamResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return companycam_source(+ api_key=config.api_key,+ 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,+ api_version=self.resolve_api_version(inputs.api_version),+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.COMPANYCAM,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="CompanyCam",+ caption="Sync projects, photos, videos, and team data from your CompanyCam account. "+ "Generate an API key from your [CompanyCam account settings](https://docs.companycam.com/reference/authentication).",+ docsUrl="https://posthog.com/docs/cdp/sources/companycam",+ releaseStatus=ReleaseStatus.ALPHA,iconPath="/static/services/companycam.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam.pynew file mode 100644index 000000000000..c3bbaeeb6056--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam.py@@ -0,0 +1,375 @@+import json+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Request, Response++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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.companycam import (+ CompanycamCursorPaginator,+ CompanycamResumeConfig,+ _paginator_for,+ _to_iso8601,+ _to_unix_timestamp,+ companycam_source,+ get_resource,+ validate_credentials,+)+++class TestCompanycamCursorPaginator:+ def test_initial_state(self) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ assert paginator._cursor is None+ assert paginator.has_next_page is True++ def test_init_request_sends_per_page_and_no_cursor_when_fresh(self) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ request = Request(method="GET", url="https://api.companycam.com/v2/photos")+ paginator.init_request(request)+ assert request.params == {"per_page": 100}++ def test_init_request_seeds_after_cursor_when_resumed(self) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ paginator.set_resume_state({"cursor": "cursor-abc"})+ request = Request(method="GET", url="https://api.companycam.com/v2/photos")+ paginator.init_request(request)+ assert request.params == {"per_page": 100, "after": "cursor-abc"}++ @pytest.mark.parametrize(+ ("has_next_header", "next_cursor_header", "expected_has_next"),+ [+ ("true", "cursor-1", True),+ ("false", "", False),+ (None, "cursor-2", True),+ (None, "", False),+ ("true", "", False), # header says more but no cursor to fetch it with+ ],+ )+ def test_update_state(self, has_next_header: str | None, next_cursor_header: str, expected_has_next: bool) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ response = MagicMock()+ headers = {"X-Next-Cursor": next_cursor_header}+ if has_next_header is not None:+ headers["X-Has-Next"] = has_next_header+ response.headers = headers++ paginator.update_state(response)++ assert paginator.has_next_page is expected_has_next++ def test_get_resume_state_round_trip(self) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ response = MagicMock()+ response.headers = {"X-Has-Next": "true", "X-Next-Cursor": "cursor-9"}+ paginator.update_state(response)++ assert paginator.get_resume_state() == {"cursor": "cursor-9"}++ def test_get_resume_state_none_on_terminal_page(self) -> None:+ paginator = CompanycamCursorPaginator(per_page=100)+ response = MagicMock()+ response.headers = {"X-Has-Next": "false", "X-Next-Cursor": ""}+ paginator.update_state(response)++ assert paginator.get_resume_state() is None+++class TestPaginatorFor:+ def test_photos_uses_cursor_paginator(self) -> None:+ assert isinstance(_paginator_for("Photos"), CompanycamCursorPaginator)++ def test_checklist_templates_uses_single_page_paginator(self) -> None:+ assert isinstance(_paginator_for("ChecklistTemplates"), SinglePagePaginator)++ @pytest.mark.parametrize("endpoint", ["Projects", "Videos", "Users", "Tags", "Groups", "Checklists"])+ def test_other_endpoints_use_page_number_paginator(self, endpoint: str) -> None:+ assert isinstance(_paginator_for(endpoint), PageNumberPaginator)+++class TestConverters:+ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (1700000000, "2023-11-14T22:13:20+00:00"),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), "2023-11-14T22:13:20+00:00"),+ (None, None),+ ],+ )+ def test_to_iso8601(self, value: Any, expected: str | None) -> None:+ assert _to_iso8601(value) == expected++ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ (1700000000, "1700000000"),+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), "1700000000"),+ (None, None),+ ],+ )+ def test_to_unix_timestamp(self, value: Any, expected: str | None) -> None:+ assert _to_unix_timestamp(value) == expected+++class TestGetResource:+ def test_full_refresh_uses_replace_disposition(self) -> None:+ resource = cast(dict[str, Any], get_resource("Users", should_use_incremental_field=False))+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["params"] == {"per_page": 100}++ def test_incremental_endpoint_sets_merge_disposition_and_incremental_param(self) -> None:+ resource = cast(dict[str, Any], get_resource("Projects", should_use_incremental_field=True))+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}+ assert "modified_since" in resource["endpoint"]["params"]+ assert resource["endpoint"]["params"]["modified_since"]["type"] == "incremental"++ def test_incremental_endpoint_without_incremental_flag_has_no_incremental_param(self) -> None:+ resource = cast(dict[str, Any], get_resource("Projects", should_use_incremental_field=False))+ assert "modified_since" not in resource["endpoint"]["params"]++ def test_full_refresh_endpoint_never_gets_incremental_param(self) -> None:+ # Users has no incremental_query_param at all, regardless of should_use_incremental_field.+ resource = cast(dict[str, Any], get_resource("Users", should_use_incremental_field=True))+ assert "modified_since" not in resource["endpoint"]["params"]+ assert "start_date" not in resource["endpoint"]["params"]++ def test_cursor_paginated_endpoint_has_no_static_per_page_param(self) -> None:+ # Photos' per_page is injected by CompanycamCursorPaginator itself.+ resource = cast(dict[str, Any], get_resource("Photos", should_use_incremental_field=False))+ assert "per_page" not in resource["endpoint"]["params"]+++def _make_http_response(+ body: list[dict[str, Any]], headers: dict[str, str] | None = None, status_code: int = 200+) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ for key, value in (headers or {}).items():+ resp.headers[key] = value+ return resp+++class TestCompanycamSourceResumeBehavior:+ """End-to-end resume behaviour of ``companycam_source`` via ``rest_api_resource``."""++ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[MagicMock, list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ return next(response_iter)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.side_effect = fake_send++ resource = companycam_source(+ api_key="test-key",+ endpoint=endpoint,+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ api_version="v2",+ )+ list(cast(Iterable[Any], resource.items()))+ return mock_session, sent_params++ def test_page_number_endpoint_saves_page_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response([{"id": "1"}]),+ _make_http_response([{"id": "2"}]),+ _make_http_response([]),+ ]+ _, sent_params = self._drive("Users", manager, responses)++ pages_sent = [p.get("page") for p in sent_params]+ assert pages_sent == [1, 2, 3]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [+ CompanycamResumeConfig(page=2),+ CompanycamResumeConfig(page=3),+ ]++ def test_page_number_endpoint_resumes_from_saved_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CompanycamResumeConfig(page=5)++ responses = [_make_http_response([])]+ _, sent_params = self._drive("Users", manager, responses)++ assert sent_params[0]["page"] == 5++ def test_cursor_endpoint_saves_cursor_after_each_non_terminal_page(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [+ _make_http_response([{"id": "p1"}], headers={"X-Has-Next": "true", "X-Next-Cursor": "cursor-1"}),+ _make_http_response([{"id": "p2"}], headers={"X-Has-Next": "false", "X-Next-Cursor": ""}),+ ]+ _, sent_params = self._drive("Photos", manager, responses)++ cursors_sent = [p.get("after") for p in sent_params]+ assert cursors_sent == [None, "cursor-1"]++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [CompanycamResumeConfig(cursor="cursor-1")]++ def test_cursor_endpoint_resumes_from_saved_cursor(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = CompanycamResumeConfig(cursor="cursor-resumed")++ responses = [_make_http_response([], headers={"X-Has-Next": "false"})]+ _, sent_params = self._drive("Photos", manager, responses)++ assert sent_params[0]["after"] == "cursor-resumed"++ def test_single_page_endpoint_never_saves_state(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([{"id": "t1"}])]+ self._drive("ChecklistTemplates", manager, responses)++ manager.save_state.assert_not_called()++ def test_incremental_sync_omits_filter_param_on_first_sync(self) -> None:+ # No watermark yet (first sync): the framework drops a None-valued param entirely,+ # so the request is an unfiltered full pull.+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([])]+ _, sent_params = self._drive("Projects", manager, responses, should_use_incremental_field=True)++ assert "modified_since" not in sent_params[0]++ def test_incremental_sync_sends_filter_param_once_watermark_exists(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([])]+ _, sent_params = self._drive(+ "Projects",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )++ assert sent_params[0]["modified_since"] == "2023-11-14T22:13:20+00:00"++ def test_incremental_sync_sends_unix_timestamp_filter_for_photos(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ responses = [_make_http_response([], headers={"X-Has-Next": "false"})]+ _, sent_params = self._drive(+ "Photos",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1700000000,+ )++ assert sent_params[0]["start_date"] == "1700000000"++ def test_source_response_sort_mode(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.return_value = _make_http_response([])++ response = companycam_source(+ api_key="test-key",+ endpoint="Projects",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ api_version="v2",+ )+ assert response.sort_mode == "desc"+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]++ def test_source_response_sort_mode_defaults_to_asc_on_full_refresh(self) -> None:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"+ ) as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.prepare_request.side_effect = lambda req: req+ mock_session.send.return_value = _make_http_response([])++ response = companycam_source(+ api_key="test-key",+ endpoint="Projects",+ team_id=123,+ job_id="test_job",+ resumable_source_manager=manager,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ api_version="v2",+ )+ assert response.sort_mode == "asc"+++class TestValidateCredentials:+ @pytest.mark.parametrize(("status_code", "expected"), [(200, True), (401, False), (403, False)])+ def test_validate_credentials(self, status_code: int, expected: bool) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.companycam.companycam.make_tracked_session"+ ) as mock_make_session:+ mock_session = mock_make_session.return_value+ mock_session.get.return_value = MagicMock(status_code=status_code)++ assert validate_credentials("test-key", "v2") is expected++ def test_validate_credentials_transport_error_returns_false(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.companycam.companycam.make_tracked_session"+ ) as mock_make_session:+ mock_make_session.return_value.get.side_effect = ConnectionError("boom")++ assert validate_credentials("test-key", "v2") is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam_source.pynew file mode 100644index 000000000000..da54083c6a5a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/companycam/tests/test_companycam_source.py@@ -0,0 +1,161 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.companycam import (+ CompanycamResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.settings import (+ COMPANYCAM_ENDPOINTS,+ ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.companycam.source import CompanycamSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.companycam import (+ CompanycamSourceConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_INCREMENTAL_ENDPOINTS = {"Projects", "Photos", "Videos"}+_FULL_REFRESH_ENDPOINTS = {"Users", "Tags", "Groups", "Checklists", "ChecklistTemplates"}+++class TestCompanycamSource:+ def setup_method(self) -> None:+ self.source = CompanycamSource()+ self.team_id = 123+ self.config = CompanycamSourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.COMPANYCAM++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Companycam"+ assert config.label == "CompanyCam"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/companycam.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/companycam"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://api.companycam.com/v2/projects?page=1",+ "403 Client Error: Forbidden for url: https://api.companycam.com/v2/photos?page=1",+ ],+ )+ 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",+ [+ "429 Client Error: Too Many Requests for url: https://api.companycam.com/v2/photos",+ "500 Server Error: Internal Server Error for url: https://api.companycam.com/v2/photos",+ "HTTPSConnectionPool(host='api.companycam.com', port=443): Read timed out.",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient(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_match_endpoints_with_correct_sync_modes(self) -> None:+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ for name in _INCREMENTAL_ENDPOINTS:+ assert schemas[name].supports_incremental is True+ assert schemas[name].supports_append is True+ assert len(schemas[name].incremental_fields) == 1+ for name in _FULL_REFRESH_ENDPOINTS:+ assert schemas[name].supports_incremental is False+ assert schemas[name].supports_append is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Projects"])+ assert len(schemas) == 1+ assert schemas[0].name == "Projects"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self) -> None:+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self) -> None:+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(COMPANYCAM_ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected_valid, expected_message",+ [+ (True, True, None),+ (False, False, "Invalid credentials"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.companycam.source.validate_companycam_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_validate.assert_called_once_with("test-key", "v2")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert manager._data_class is CompanycamResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.companycam.source.companycam_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_companycam_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Projects"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = 1700000000+ inputs.api_version = None+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_companycam_source.assert_called_once()+ kwargs = mock_companycam_source.call_args.kwargs+ assert kwargs["api_key"] == "test-key"+ assert kwargs["endpoint"] == "Projects"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["db_incremental_field_last_value"] == 1700000000+ assert kwargs["api_version"] == "v2"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.companycam.source.companycam_source")+ def test_source_for_pipeline_omits_cursor_when_not_incremental(+ self, mock_companycam_source: mock.MagicMock+ ) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "Users"+ 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_companycam_source.call_args.kwargs["db_incremental_field_last_value"] is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/companycam.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/companycam.pyindex 8d995e0d81d5..0489f6d67ebf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/companycam.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/companycam.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass CompanycamSourceConfig(config.Config):- pass+ api_key: str