: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): implement opuswatch import source (#72637)
Tom Owers1b0cce866c3b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 75f61172d0b5..12ea6bdec15f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -382,6 +382,7 @@ the row lists both.| openai | HTTP | requests | ✅ || openai_ads | HTTP | requests + `rest_source.RESTClient` | ✅ || opinion_stage | HTTP | requests | ✅ |+| opuswatch | HTTP | requests + `rest_source.RESTClient` | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ || orca_security | HTTP (POST query DSL) | requests | ✅ || openaq | HTTP | requests | ✅ |@@ -836,7 +837,6 @@ doesn't conflict with concurrent PRs.- onehundredms- onesignal- open_data_dc-- opuswatch- oracle- oracle_ebs- oracle_fusiondiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opuswatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opuswatch.pyindex 6a6dc669bbeb..a2a56dd8cf1f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opuswatch.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/opuswatch.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass OPUSWatchSourceConfig(config.Config):- pass+ api_key: str+ start_date: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/canonical_descriptions.pynew file mode 100644index 000000000000..74cae1b4f772--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/canonical_descriptions.py@@ -0,0 +1,143 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_COMMON_COLUMNS = {+ "id": "Unique identifier of the record.",+ "name": "Display name of the record.",+ "createdTimestamp": "When the record was created.",+ "updatedTimestamp": "When the record was last updated.",+ "isArchived": "Whether the record has been archived.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "client": {+ "description": "The OPUSWatch client (company account) the API key belongs to.",+ "columns": {+ "name": "Display name of the client account.",+ "updatedTimestamp": "When the client record was last updated.",+ },+ },+ "locations": {+ "description": "Locations or areas within the greenhouse or nursery.",+ "columns": {+ **_COMMON_COLUMNS,+ "externalId": "Identifier of the location in an external system.",+ "layoutIds": "Identifiers of the layouts defined for this location.",+ },+ },+ "rows": {+ "description": "Physical rows or sections where plants are cultivated.",+ "columns": {+ **_COMMON_COLUMNS,+ "locationId": "Identifier of the location this row belongs to.",+ "layoutId": "Identifier of the layout this row belongs to.",+ "varietyId": "Identifier of the plant variety cultivated in this row.",+ "labelIds": "Identifiers of the labels attached to this row.",+ "latestWorkerId": "Identifier of the worker who most recently worked this row.",+ "rowNumber": "Number of the row within its location.",+ "rowLength": "Length of the row.",+ "rowWidth": "Width of the row.",+ "rowFloorArea": "Floor area of the row.",+ },+ },+ "users": {+ "description": "People with access to the OPUSWatch system.",+ "columns": {+ **_COMMON_COLUMNS,+ "email": "Email address of the user.",+ "role": "Role of the user within the OPUSWatch system.",+ "language": "Preferred language of the user.",+ "associatedWorkerId": "Identifier of the worker record associated with this user.",+ },+ },+ "workers": {+ "description": "Workforce members registered in OPUSWatch.",+ "columns": {+ **_COMMON_COLUMNS,+ "workerCode": "Code identifying the worker.",+ "workerGroupId": "Identifier of the worker group this worker belongs to.",+ "externalId": "Identifier of the worker in an external system (e.g. payroll).",+ "hourlyRate": "Hourly rate of the worker.",+ "startTimestamp": "When the worker started.",+ "endTimestamp": "When the worker ended.",+ "locationIds": "Identifiers of the locations this worker is assigned to.",+ "labelIds": "Identifiers of the labels attached to this worker.",+ "leftHanded": "Whether the worker is left-handed.",+ },+ },+ "worker_groups": {+ "description": "Groupings of workers.",+ "columns": _COMMON_COLUMNS,+ },+ "tasks": {+ "description": "Tasks workers can register their work against.",+ "columns": {+ **_COMMON_COLUMNS,+ "externalId": "Identifier of the task in an external system.",+ "function": "Function of the task.",+ "taskGroupIds": "Identifiers of the task groups this task belongs to.",+ "locationIds": "Identifiers of the locations this task applies to.",+ },+ },+ "task_groups": {+ "description": "Groupings of tasks.",+ "columns": _COMMON_COLUMNS,+ },+ "labels": {+ "description": "Labels used to categorize workers, rows, and varieties.",+ "columns": _COMMON_COLUMNS,+ },+ "varieties": {+ "description": "Plant varieties cultivated at the client's locations.",+ "columns": {+ **_COMMON_COLUMNS,+ "externalId": "Identifier of the variety in an external system.",+ "assignedLocationIds": "Identifiers of the locations this variety is assigned to.",+ "labelIds": "Identifiers of the labels attached to this variety.",+ },+ },+ "registrations": {+ "description": "Individual work registrations recorded by workers on their OPUSWatch.",+ "columns": {+ "id": "Unique identifier of the registration.",+ "workerId": "Identifier of the worker who made the registration.",+ "worker": "Name of the worker who made the registration.",+ "workerGroupId": "Identifier of the worker's group.",+ "taskId": "Identifier of the task the registration is for.",+ "task": "Name of the task the registration is for.",+ "taskType": "Type of the task the registration is for.",+ "locationId": "Identifier of the location the work took place at.",+ "startTimestamp": "When the registered work started.",+ "endTimestamp": "When the registered work ended.",+ "updatedTimestamp": "When the registration was last updated.",+ "laborCost": "Labor cost of the registered work.",+ "stepCounter": "Steps counted by the watch during the registration.",+ "deviceNumber": "Number of the OPUSWatch device used.",+ "isArchived": "Whether the registration has been archived.",+ },+ },+ "sessions": {+ "description": "Work sessions with productivity metrics such as counts, performance, and labor cost.",+ "columns": {+ "id": "Unique identifier of the session.",+ "workerId": "Identifier of the worker for the session.",+ "worker": "Name of the worker for the session.",+ "rowId": "Identifier of the row worked during the session.",+ "varietyId": "Identifier of the plant variety worked during the session.",+ "locationId": "Identifier of the location the session took place at.",+ "startTimestampGross": "When the session started, including breaks.",+ "endTimestampGross": "When the session ended, including breaks.",+ "startTimestampNet": "When the session started, excluding breaks.",+ "endTimestampNet": "When the session ended, excluding breaks.",+ "updatedTimestamp": "When the session was last updated.",+ "count": "Units counted during the session.",+ "correctedCount": "Corrected unit count for the session.",+ "performanceGross": "Performance over the gross session duration.",+ "performanceNet": "Performance over the net session duration.",+ "laborCost": "Labor cost of the session.",+ "deviceNumber": "Number of the OPUSWatch device used.",+ "isArchived": "Whether the session has been archived.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/opuswatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/opuswatch.pynew file mode 100644index 000000000000..f5339e4b1dba--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/opuswatch.py@@ -0,0 +1,182 @@+import dataclasses+from datetime import UTC, date, datetime+from typing import Any, Optional++from dateutil import parser++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 (+ OffsetPaginator,+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.settings import (+ BASE_URL,+ DEFAULT_START_DATE,+ OPUSWATCH_ENDPOINTS,+ PAGE_SIZE,+)+++class OPUSWatchResumeConfig:+ offset: int+++def parse_start_date(start_date: Optional[str]) -> date:+ value = (start_date or "").strip() or DEFAULT_START_DATE+ return datetime.strptime(value, "%Y%m%d").date()+++def _window_start(last_value: Any) -> Optional[date]:+ if isinstance(last_value, datetime):+ return last_value.date()+ if isinstance(last_value, date):+ return last_value+ if isinstance(last_value, str):+ try:+ return parser.parse(last_value).date()+ except (ValueError, OverflowError):+ return None+ return None+++def build_date_window_params(+ start_date: Optional[str],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ today: Optional[date] = None,+) -> dict[str, str]:+ """Server-side date-window filter params for the transactional endpoints.++ The API filters by whole days: `date` (YYYYMMDD) + `days_from_date` select a+ window starting at `date`, while `days_till_date` selects a window of the last+ N days; `filter_date_by` picks which timestamp (CREATED or UPDATED) the window+ applies to. There is no cursor token, so incremental syncs re-read from the+ watermark's day (a `days_till_date` window over UPDATED — the same request+ shape the vendor's own connector uses for recent updates) and rely on the+ merge on `id` to dedupe the overlap.+ """+ if today is None:+ today = datetime.now(UTC).date()++ params = {"return_breaks": "true", "return_leaves": "true", "return_archived": "true"}++ watermark = _window_start(db_incremental_field_last_value) if should_use_incremental_field else None+ if watermark is not None:+ params["filter_date_by"] = "UPDATED"+ params["days_till_date"] = str(max((today - watermark).days + 1, 1))+ else:+ window_start = parse_start_date(start_date)+ params["filter_date_by"] = "CREATED"+ params["date"] = window_start.strftime("%Y%m%d")+ params["days_from_date"] = str(max((today - window_start).days + 1, 1))++ return params+++def get_resource(+ name: str,+ should_use_incremental_field: bool,+ start_date: Optional[str],+ db_incremental_field_last_value: Any,+) -> EndpointResource:+ endpoint_config = OPUSWATCH_ENDPOINTS[name]++ endpoint: Endpoint = {"path": endpoint_config.path}++ if endpoint_config.paginated:+ # Transactional responses wrap rows in {"data": [...]}; no total count is+ # returned, so pagination stops on a short or empty page.+ endpoint["data_selector"] = "data"+ endpoint["paginator"] = OffsetPaginator(limit=PAGE_SIZE, total_path=None)+ else:+ endpoint["paginator"] = SinglePagePaginator()++ if endpoint_config.supports_date_window:+ endpoint["params"] = dict(+ build_date_window_params(start_date, should_use_incremental_field, db_incremental_field_last_value)+ )++ return {+ "name": endpoint_config.name,+ "table_name": endpoint_config.name,+ "write_disposition": {+ "disposition": "merge",+ "strategy": "upsert",+ }+ if should_use_incremental_field+ else "replace",+ "endpoint": endpoint,+ "table_format": "delta",+ }+++def opuswatch_source(+ api_key: str,+ start_date: Optional[str],+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[OPUSWatchResumeConfig],+ db_incremental_field_last_value: Optional[Any],+ should_use_incremental_field: bool = False,+) -> Resource:+ endpoint_config = OPUSWATCH_ENDPOINTS[endpoint]++ config: RESTAPIConfig = {+ "client": {+ "base_url": BASE_URL,+ # The API key rides in a bare `key` header, not an Authorization header.+ "auth": {"type": "api_key", "name": "key", "api_key": api_key, "location": "header"},+ # Pin every request to the fixed API host and reject cross-host redirects —+ # `requests` only strips `Authorization` on redirects, so the custom `key`+ # header would otherwise be replayed off-host. `allowed_hosts=[]` means+ # "same host as base_url only".+ "allowed_hosts": [],+ "allow_redirects": False,+ },+ "resources": [+ get_resource(endpoint, should_use_incremental_field, start_date, db_incremental_field_last_value)+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ resume_hook = None++ if endpoint_config.paginated:+ if resumable_source_manager.can_resume():+ resume_config = resumable_source_manager.load_state()+ if resume_config is not None:+ initial_paginator_state = {"offset": resume_config.offset}++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state and state.get("offset") is not None:+ resumable_source_manager.save_state(OPUSWatchResumeConfig(offset=int(state["offset"])))++ resume_hook = save_checkpoint++ return rest_api_resource(+ config,+ team_id,+ job_id,+ db_incremental_field_last_value,+ resume_hook=resume_hook,+ initial_paginator_state=initial_paginator_state,+ )+++def validate_credentials(api_key: str) -> bool:+ # `allow_redirects=False` keeps the `key` header from being replayed to a redirect target.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ response = session.get(f"{BASE_URL}master/workers", headers={"key": api_key}, timeout=30)+ return response.status_code == 200diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/settings.pynew file mode 100644index 000000000000..c5791605e06f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/settings.py@@ -0,0 +1,61 @@+from dataclasses import dataclass++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField++BASE_URL = "https://api.opuswatch.nl/ext/"+DEFAULT_START_DATE = "20250101"+PAGE_SIZE = 10000+++@dataclass(frozen=True)+class OPUSWatchEndpointConfig:+ name: str+ path: str+ primary_key: str = "id"+ # Stable datetime field used for Delta partitioning; None disables partitioning+ # (master-data tables are small enough not to need it).+ partition_key: str | None = None+ # Transactional endpoints paginate with offset/limit and accept the+ # filter_date_by date-window params; master-data endpoints return the full+ # list (or a single object, for `client`) in one response.+ paginated: bool = False+ supports_date_window: bool = False+++OPUSWATCH_ENDPOINTS: dict[str, OPUSWatchEndpointConfig] = {+ # The client endpoint returns the account itself, which has no id field.+ "client": OPUSWatchEndpointConfig(name="client", path="master/client", primary_key="name"),+ "locations": OPUSWatchEndpointConfig(name="locations", path="master/locations"),+ "rows": OPUSWatchEndpointConfig(name="rows", path="master/rows"),+ "users": OPUSWatchEndpointConfig(name="users", path="master/users"),+ "workers": OPUSWatchEndpointConfig(name="workers", path="master/workers"),+ "worker_groups": OPUSWatchEndpointConfig(name="worker_groups", path="master/workergroups"),+ "tasks": OPUSWatchEndpointConfig(name="tasks", path="master/tasks"),+ "task_groups": OPUSWatchEndpointConfig(name="task_groups", path="master/taskgroups"),+ "labels": OPUSWatchEndpointConfig(name="labels", path="master/labels"),+ "varieties": OPUSWatchEndpointConfig(name="varieties", path="master/varieties"),+ "registrations": OPUSWatchEndpointConfig(+ name="registrations",+ path="transactional/registrations",+ partition_key="startTimestamp",+ paginated=True,+ supports_date_window=True,+ ),+ "sessions": OPUSWatchEndpointConfig(+ name="sessions",+ path="transactional/sessions",+ partition_key="startTimestampGross",+ paginated=True,+ supports_date_window=True,+ ),+}++ENDPOINTS = tuple(OPUSWATCH_ENDPOINTS.keys())++# Only the transactional endpoints accept a server-side date-window filter+# (filter_date_by=UPDATED); master-data endpoints are full refresh only.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "registrations": [incremental_field("updatedTimestamp")],+ "sessions": [incremental_field("updatedTimestamp")],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/source.pyindex ffbddd1351db..365b61fff4ad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/source.py@@ -1,32 +1,169 @@-from typing import cast+import re+from datetime import datetime+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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.opuswatch import (OPUSWatchSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.opuswatch import (+ OPUSWatchResumeConfig,+ opuswatch_source,+ validate_credentials as validate_opuswatch_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.settings import (+ DEFAULT_START_DATE,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ OPUSWATCH_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+_START_DATE_RE = re.compile(r"^\d{8}$")+@SourceRegistry.register-class OPUSWatchSource(SimpleSource[OPUSWatchSourceConfig]):+class OPUSWatchSource(ResumableSource[OPUSWatchSourceConfig, OPUSWatchResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+ # OPUS Solutions publishes no versioned API reference; the ext API base URL is the+ # closest stable pointer to the API surface.+ api_docs_url = "https://api.opuswatch.nl/ext/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.OPUSWATCH+ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url": "Your OPUSWatch API key is invalid or has been revoked. Please check the key and reconnect.",+ "403 Client Error: Forbidden for url": "Your OPUSWatch API key does not have permission to access this data. Please check the key and reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: OPUSWatchSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self, config: OPUSWatchSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ start_date = (config.start_date or "").strip()+ if start_date:+ if not _START_DATE_RE.match(start_date):+ return False, "Start date must be in YYYYMMDD format, e.g. 20250101"+ try:+ datetime.strptime(start_date, "%Y%m%d")+ except ValueError:+ return False, "Start date is not a valid date"++ if validate_opuswatch_credentials(config.api_key):+ return True, None++ return False, "Invalid OPUSWatch API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OPUSWatchResumeConfig]:+ return ResumableSourceManager[OPUSWatchResumeConfig](inputs, OPUSWatchResumeConfig)++ def source_for_pipeline(+ self,+ config: OPUSWatchSourceConfig,+ resumable_source_manager: ResumableSourceManager[OPUSWatchResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ endpoint_config = OPUSWATCH_ENDPOINTS[inputs.schema_name]+ resource = opuswatch_source(+ api_key=config.api_key,+ start_date=config.start_date,+ 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,+ )+ has_partitioning = endpoint_config.partition_key is not None+ return SourceResponse(+ name=resource.name,+ items=lambda: resource,+ primary_keys=[endpoint_config.primary_key],+ partition_count=1 if has_partitioning else None,+ partition_size=1 if has_partitioning else None,+ partition_mode="datetime" if has_partitioning else None,+ partition_format="month" if has_partitioning else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ # The API documents no ordering for the offset-paginated transactional+ # endpoints, so treat rows as unordered: "desc" defers the incremental+ # watermark to job completion instead of checkpointing it per batch.+ sort_mode="desc" if endpoint_config.supports_date_window else "asc",+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.OPUS_WATCH,category=DataWarehouseSourceCategory.HR___RECRUITING,label="OPUSWatch",+ caption="Import master data, work registrations, and productivity sessions from OPUSWatch by OPUS Solutions.",+ docsUrl="https://posthog.com/docs/cdp/sources/opuswatch",iconPath="/static/services/opuswatch.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ caption="The API key for the OPUSWatch external API, issued by OPUS Solutions.",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="start_date",+ label="Start date",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder=DEFAULT_START_DATE,+ caption=f"Sync registrations and sessions created from this date, in YYYYMMDD format. Defaults to {DEFAULT_START_DATE}.",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch.pynew file mode 100644index 000000000000..d90e40cc5cb9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch.py@@ -0,0 +1,189 @@+import json+from collections.abc import Iterable+from datetime import date, datetime+from typing import Any, Optional, cast++import pytest+from unittest.mock import MagicMock, patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.opuswatch import (+ OPUSWatchResumeConfig,+ build_date_window_params,+ opuswatch_source,+)++TODAY = date(2025, 1, 10)+++class TestBuildDateWindowParams:+ @pytest.mark.parametrize(+ ("start_date", "should_use_incremental_field", "last_value", "expected"),+ [+ # Full refresh: CREATED window from the configured start date up to today.+ ("20250101", False, None, {"filter_date_by": "CREATED", "date": "20250101", "days_from_date": "10"}),+ # Blank start date falls back to the default.+ (None, False, None, {"filter_date_by": "CREATED", "date": "20250101", "days_from_date": "10"}),+ (" ", False, None, {"filter_date_by": "CREATED", "date": "20250101", "days_from_date": "10"}),+ # First incremental run has no watermark yet -> CREATED window.+ ("20250101", True, None, {"filter_date_by": "CREATED", "date": "20250101", "days_from_date": "10"}),+ # Incremental with a watermark: UPDATED window covering watermark day -> today.+ ("20250101", True, datetime(2025, 1, 8, 15, 30), {"filter_date_by": "UPDATED", "days_till_date": "3"}),+ ("20250101", True, "2025-01-08T15:30:00Z", {"filter_date_by": "UPDATED", "days_till_date": "3"}),+ # Watermark on today's date still requests at least one day.+ ("20250101", True, datetime(2025, 1, 10, 1, 0), {"filter_date_by": "UPDATED", "days_till_date": "1"}),+ # An unparseable watermark falls back to the CREATED window rather than failing.+ ("20250101", True, "not-a-date", {"filter_date_by": "CREATED", "date": "20250101", "days_from_date": "10"}),+ ],+ )+ def test_window_params(+ self,+ start_date: Optional[str],+ should_use_incremental_field: bool,+ last_value: Any,+ expected: dict[str, str],+ ):+ params = build_date_window_params(start_date, should_use_incremental_field, last_value, today=TODAY)++ for key in ("return_breaks", "return_leaves", "return_archived"):+ assert params.pop(key) == "true"+ assert params == expected+++def _make_http_response(body: Any, status_code: int = 200) -> Response:+ resp = Response()+ resp.status_code = status_code+ resp._content = json.dumps(body).encode()+ resp.headers["Content-Type"] = "application/json"+ return resp+++def _fresh_manager() -> MagicMock:+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager+++class TestOPUSWatchSourceTransport:+ def _drive(+ self,+ endpoint: str,+ manager: MagicMock,+ responses: list[Response],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:+ sent_params: list[dict[str, Any]] = []+ sent_headers: list[dict[str, Any]] = []+ rows: list[dict[str, Any]] = []+ response_iter = iter(responses)++ def fake_prepare(request: Any) -> Any:+ # Apply the auth callable like a real session would, so the test observes+ # the header the API key is injected under.+ if request.auth is not None:+ request.auth(request)+ return request++ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:+ sent_params.append(dict(request.params or {}))+ sent_headers.append(dict(request.headers 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 = fake_prepare+ mock_session.send.side_effect = fake_send++ resource = opuswatch_source(+ api_key="test-key",+ start_date="20250101",+ endpoint=endpoint,+ team_id=1,+ job_id="job",+ resumable_source_manager=manager,+ db_incremental_field_last_value=db_incremental_field_last_value,+ should_use_incremental_field=should_use_incremental_field,+ )+ for page in cast(Iterable[list[dict[str, Any]]], resource):+ rows.extend(page)++ return rows, sent_params, sent_headers++ def test_master_endpoint_fetches_single_root_list_page(self):+ manager = _fresh_manager()+ responses = [_make_http_response([{"id": "w1"}, {"id": "w2"}])]++ rows, sent_params, sent_headers = self._drive("workers", manager, responses)++ assert rows == [{"id": "w1"}, {"id": "w2"}]+ assert len(sent_params) == 1+ # Master endpoints take no pagination or date-window params.+ assert sent_params[0] == {}+ assert sent_headers[0]["key"] == "test-key"+ manager.load_state.assert_not_called()+ manager.save_state.assert_not_called()++ def test_client_endpoint_wraps_single_object_as_one_row(self):+ manager = _fresh_manager()+ responses = [_make_http_response({"name": "Acme Nursery", "updatedTimestamp": "2025-01-05T00:00:00Z"})]++ rows, _, _ = self._drive("client", manager, responses)++ assert rows == [{"name": "Acme Nursery", "updatedTimestamp": "2025-01-05T00:00:00Z"}]++ @pytest.mark.parametrize("endpoint", ["registrations", "sessions"])+ def test_transactional_pagination_advances_offset_and_checkpoints(self, endpoint: str):+ manager = _fresh_manager()++ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.opuswatch.PAGE_SIZE", 2):+ responses = [+ _make_http_response({"data": [{"id": "1"}, {"id": "2"}]}),+ _make_http_response({"data": [{"id": "3"}, {"id": "4"}]}),+ _make_http_response({"data": [{"id": "5"}]}),+ ]+ rows, sent_params, _ = self._drive(endpoint, manager, responses)++ assert [row["id"] for row in rows] == ["1", "2", "3", "4", "5"]+ assert [p.get("offset") for p in sent_params] == [0, 2, 4]+ assert [p.get("limit") for p in sent_params] == [2, 2, 2]+ # Full refresh requests the CREATED window from the start date on every page.+ assert all(p["filter_date_by"] == "CREATED" for p in sent_params)+ assert all(p["date"] == "20250101" for p in sent_params)++ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert saved == [OPUSWatchResumeConfig(offset=2), OPUSWatchResumeConfig(offset=4)]++ def test_incremental_run_requests_updated_window(self):+ manager = _fresh_manager()+ responses = [_make_http_response({"data": [{"id": "1", "updatedTimestamp": "2025-01-09T10:00:00Z"}]})]++ _, sent_params, _ = self._drive(+ "registrations",+ manager,+ responses,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2025, 1, 8, 12, 0),+ )++ assert sent_params[0]["filter_date_by"] == "UPDATED"+ assert "days_till_date" in sent_params[0]+ assert "date" not in sent_params[0]++ def test_resume_seeds_paginator_with_saved_offset(self):+ manager = MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = True+ manager.load_state.return_value = OPUSWatchResumeConfig(offset=4)++ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.opuswatch.PAGE_SIZE", 2):+ responses = [_make_http_response({"data": [{"id": "5"}]})]+ _, sent_params, _ = self._drive("registrations", manager, responses)++ assert [p.get("offset") for p in sent_params] == [4]+ manager.load_state.assert_called_once()+ manager.save_state.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch_source.pynew file mode 100644index 000000000000..d7a2c825f062--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opuswatch/tests/test_opuswatch_source.py@@ -0,0 +1,169 @@+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.opuswatch import (+ OPUSWatchSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.opuswatch import OPUSWatchResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.source import OPUSWatchSource++INCREMENTAL_ENDPOINT_NAMES = {"registrations", "sessions"}+++def _make_inputs(+ schema_name: str,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-id",+ source_id="source-id",+ team_id=1,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ db_incremental_field_earliest_value=None,+ incremental_field="updatedTimestamp" if should_use_incremental_field else None,+ incremental_field_type=None,+ job_id="job-id",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestOPUSWatchSource:+ def setup_method(self):+ self.source = OPUSWatchSource()++ def test_get_schemas_only_transactional_endpoints_support_incremental(self):+ schemas = {s.name: s for s in self.source.get_schemas(OPUSWatchSourceConfig(api_key="k"), team_id=1)}++ assert set(schemas.keys()) == set(ENDPOINTS)+ for name, schema in schemas.items():+ if name in INCREMENTAL_ENDPOINT_NAMES:+ assert schema.supports_incremental is True+ assert [f["field"] for f in schema.incremental_fields] == ["updatedTimestamp"]+ else:+ # Master-data endpoints have no server-side timestamp filter, so they+ # must stay full refresh.+ assert schema.supports_incremental is False+ assert schema.incremental_fields == []++ @pytest.mark.parametrize(+ ("start_date", "expected_error_fragment"),+ [+ ("2025-01-01", "YYYYMMDD"),+ ("2025011", "YYYYMMDD"),+ ("20251301", "not a valid date"),+ ("20250230", "not a valid date"),+ ],+ )+ def test_validate_credentials_rejects_bad_start_date_without_calling_api(+ self, start_date: str, expected_error_fragment: str+ ):+ config = OPUSWatchSourceConfig(api_key="k", start_date=start_date)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.source.validate_opuswatch_credentials"+ ) as mock_validate:+ valid, error = self.source.validate_credentials(config, team_id=1)++ assert valid is False+ assert error is not None and expected_error_fragment in error+ mock_validate.assert_not_called()++ @pytest.mark.parametrize(+ ("start_date", "api_result", "expected_valid"),+ [+ ("20250101", True, True),+ (None, True, True),+ (" ", True, True),+ ("20250101", False, False),+ ],+ )+ def test_validate_credentials_probes_api(self, start_date: Optional[str], api_result: bool, expected_valid: bool):+ config = OPUSWatchSourceConfig(api_key="the-key", start_date=start_date)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.source.validate_opuswatch_credentials",+ return_value=api_result,+ ) as mock_validate:+ valid, error = self.source.validate_credentials(config, team_id=1)++ assert valid is expected_valid+ assert (error is None) is expected_valid+ mock_validate.assert_called_once_with("the-key")++ def test_get_resumable_source_manager_is_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(_make_inputs("registrations"))++ assert manager._data_class is OPUSWatchResumeConfig++ @pytest.mark.parametrize(+ ("endpoint", "expected_primary_keys", "expected_partition_keys", "expected_sort_mode"),+ [+ ("workers", ["id"], None, "asc"),+ ("client", ["name"], None, "asc"),+ ("registrations", ["id"], ["startTimestamp"], "desc"),+ ("sessions", ["id"], ["startTimestampGross"], "desc"),+ ],+ )+ def test_source_for_pipeline_response_shape(+ self,+ endpoint: str,+ expected_primary_keys: list[str],+ expected_partition_keys: Optional[list[str]],+ expected_sort_mode: str,+ ):+ config = OPUSWatchSourceConfig(api_key="k", start_date="20250101")+ inputs = _make_inputs(endpoint)+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.source.opuswatch_source"+ ) as mock_source:+ mock_source.return_value.name = endpoint+ response = self.source.source_for_pipeline(config, manager, inputs)++ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ assert response.partition_keys == expected_partition_keys+ assert response.sort_mode == expected_sort_mode+ if expected_partition_keys:+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"+ else:+ assert response.partition_mode is None++ @pytest.mark.parametrize(+ ("should_use_incremental_field", "expected_last_value"),+ [+ (True, "2025-01-05T00:00:00Z"),+ (False, None),+ ],+ )+ def test_source_for_pipeline_forwards_watermark_only_for_incremental_syncs(+ self, should_use_incremental_field: bool, expected_last_value: Optional[str]+ ):+ config = OPUSWatchSourceConfig(api_key="k")+ inputs = _make_inputs(+ "registrations",+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value="2025-01-05T00:00:00Z",+ )+ manager = MagicMock()++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.opuswatch.source.opuswatch_source"+ ) as mock_source:+ mock_source.return_value.name = "registrations"+ self.source.source_for_pipeline(config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is should_use_incremental_field+ assert kwargs["db_incremental_field_last_value"] == expected_last_value+ assert kwargs["resumable_source_manager"] is manager