Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement my_hours import source (#68594)

Tom Owersef9a42430f78
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index e1a5f8687b67..60e643541084 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -230,6 +230,7 @@ the row lists both.
| mongodb | DB protocol | pymongo | ➖ |
| mssql | DB protocol | pyodbc / pymssql | ➖ |
| mux | HTTP | requests | ✅ |
+| my_hours | HTTP | requests | ✅ |
| mysql | DB protocol | pymysql | ➖ |
| n8n | HTTP | requests | ✅ |
| new_york_times | HTTP | requests | ✅ |
@@ -536,7 +537,6 @@ doesn't conflict with concurrent PRs.
- miro
- missive
- mode
-- my_hours
- nasa
- navan
- nebius_ai
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 8fa7ce34346f..0231cc378b6f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2091,7 +2091,7 @@ class MuxSourceConfig(config.Config):
@config.config
class MyHoursSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py
new file mode 100644
index 000000000000..de1051f06de6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/canonical_descriptions.py
@@ -0,0 +1,80 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the My Hours API v1.1 docs (https://documenter.getpostman.com/view/8879268/TVmV4YYU)
+# and the My Hours connector reference. Partial coverage is fine — uncovered columns fall back to
+# LLM enrichment.
+_DOCS_URL = "https://documenter.getpostman.com/view/8879268/TVmV4YYU"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "clients": {
+ "description": "A client (customer) that projects and time logs can be billed against.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the client.",
+ "name": "The client's name.",
+ "contactName": "The client's primary contact person.",
+ "contactEmail": "The client's contact email address.",
+ "customId": "A user-defined external identifier for the client.",
+ "archived": "Whether the client has been archived.",
+ "dateArchived": "When the client was archived, if applicable.",
+ },
+ },
+ "projects": {
+ "description": "A project that time is tracked against, optionally linked to a client.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the project.",
+ "name": "The project name.",
+ "clientId": "The ID of the client this project belongs to.",
+ "clientName": "The name of the client this project belongs to.",
+ "customId": "A user-defined external identifier for the project.",
+ "billable": "Whether time logged to the project is billable by default.",
+ "budgetType": "The project's budget type.",
+ "budgetValue": "The configured budget amount for the project.",
+ "budgetSpent": "How much of the project's budget has been used.",
+ "budgetSpentPercentage": "The share of the project's budget used, as a percentage.",
+ "totalTimeLogged": "Total time logged to the project, in seconds.",
+ "billableTimeLogged": "Billable time logged to the project, in seconds.",
+ "totalAmount": "Total billable amount accrued on the project.",
+ "totalCost": "Total labor cost accrued on the project.",
+ "laborCost": "Labor cost accrued on the project.",
+ "roundType": "How logged time is rounded on the project.",
+ "roundInterval": "The rounding interval applied to logged time.",
+ "dateCreated": "When the project was created.",
+ "archived": "Whether the project has been archived.",
+ "dateArchived": "When the project was archived, if applicable.",
+ },
+ },
+ "tags": {
+ "description": "A label used to categorise time logs.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the tag.",
+ "name": "The tag name.",
+ "hexColor": "The tag's display colour, as a hex code.",
+ "archived": "Whether the tag has been archived.",
+ "dateArchived": "When the tag was archived, if applicable.",
+ },
+ },
+ "users": {
+ "description": "A member of the My Hours account (team member) who logs time.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "The unique ID of the user.",
+ "name": "The user's full name.",
+ "email": "The user's email address.",
+ "active": "Whether the user is currently active.",
+ "accountOwner": "Whether the user owns the account.",
+ "admin": "Whether the user has administrator privileges.",
+ "isProjectManager": "Whether the user is a project manager.",
+ "roleType": "The user's role type.",
+ "rate": "The user's labor rate.",
+ "billableRate": "The user's billable rate.",
+ "customId": "A user-defined external identifier for the user.",
+ "archived": "Whether the user has been archived.",
+ "dateArchived": "When the user was archived, if applicable.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py
new file mode 100644
index 000000000000..0dec3b326ab2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/my_hours.py
@@ -0,0 +1,102 @@
+from collections.abc import Iterator
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import MY_HOURS_ENDPOINTS
+
+MY_HOURS_BASE_URL = "https://api2.myhours.com/api"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Cheap list endpoint used to confirm an API key is genuine. The key is account-wide, so one probe
+# validates access to every list endpoint.
+DEFAULT_PROBE_PATH = "/Clients"
+
+
+class MyHoursRetryableError(Exception):
+ pass
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ # My Hours expects the literal `apikey ` prefix before the key; omitting it (or using `Bearer`)
+ # returns 400/401.
+ return {"Authorization": f"apikey {api_key}", "Accept": "application/json"}
+
+
+@retry(
+ retry=retry_if_exception_type((MyHoursRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(session: requests.Session, path: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ response = session.get(f"{MY_HOURS_BASE_URL}{path}", timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 429 (the API throttles at ~100 calls/60s) and transient 5xx are retryable; back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise MyHoursRetryableError(f"My Hours API error (retryable): status={response.status_code}, path={path}")
+
+ if not response.ok:
+ logger.error(f"My Hours API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # My Hours list endpoints return a bare JSON array of records.
+ if not isinstance(data, list):
+ raise MyHoursRetryableError(f"My Hours returned an unexpected payload for {path}: {type(data).__name__}")
+ return data
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ config = MY_HOURS_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+
+ # The list endpoints are unpaginated, so a single request returns the whole collection.
+ items = _fetch(session, config.path, logger)
+ if items:
+ yield items
+
+
+def my_hours_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+) -> SourceResponse:
+ config = MY_HOURS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(api_key=api_key, endpoint=endpoint, logger=logger),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ )
+
+
+def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to validate the API key.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))
+ try:
+ response = session.get(f"{MY_HOURS_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to My Hours: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"My Hours returned HTTP {response.status_code}"
+
+ return 200, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
new file mode 100644
index 000000000000..14f808c3cea9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/settings.py
@@ -0,0 +1,25 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class MyHoursEndpointConfig:
+ name: str
+ path: str
+ # My Hours object IDs are unique within an account, so `id` is a safe primary key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# My Hours REST API list endpoints. All are full-refresh only: the API exposes no row-level
+# pagination and no updated-since cursor, so there is no incremental cursor to advance. The
+# per-user activity report (`Reports/activity`) is intentionally excluded — it requires a
+# mandatory `DateFrom`/`DateTo` window rather than being a plain top-level list.
+MY_HOURS_ENDPOINTS: dict[str, MyHoursEndpointConfig] = {
+ "clients": MyHoursEndpointConfig(name="clients", path="/Clients"),
+ "projects": MyHoursEndpointConfig(name="projects", path="/Projects/getAll"),
+ "tags": MyHoursEndpointConfig(name="tags", path="/Tags"),
+ "users": MyHoursEndpointConfig(name="users", path="/Users/getAll"),
+}
+
+ENDPOINTS = tuple(MY_HOURS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
index f003997dd4c1..07aba497159f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/source.py
@@ -1,19 +1,40 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+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, SimpleSource
+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.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MyHoursSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.my_hours import (
+ check_access,
+ my_hours_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import (
+ ENDPOINTS,
+ MY_HOURS_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class MyHoursSource(SimpleSource[MyHoursSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MYHOURS
@@ -24,7 +45,82 @@ class MyHoursSource(SimpleSource[MyHoursSourceConfig]):
name=SchemaExternalDataSourceType.MY_HOURS,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="My Hours",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your My Hours API key to pull your time-tracking data into the PostHog Data warehouse.
+
+API keys are available on paid plans. Create one under **Settings → Integrations → API keys** in your [My Hours account](https://app.myhours.com/). The key is tied to the user who created it, so it stops working if that user is archived or removed. The key grants read access to your clients, projects, tags, and users.
+""",
iconPath="/static/services/my_hours.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/my-hours",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api2.myhours.com": "Your My Hours API key is invalid or has been revoked. Generate a new key under Settings → Integrations → API keys, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api2.myhours.com": "Your My Hours API key does not have access to this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: MyHoursSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Every endpoint is full refresh only — My Hours list endpoints expose no server-side
+ # timestamp filter, so there is no incremental cursor to advance.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ )
+ for endpoint in ENDPOINTS
+ ]
+ 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: MyHoursSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # The API key is account-wide, so a single probe validates access to every schema.
+ status, message = check_access(config.api_key)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, "Invalid My Hours API key"
+ return False, message or "Could not validate My Hours API key"
+
+ def source_for_pipeline(self, config: MyHoursSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ if inputs.schema_name not in MY_HOURS_ENDPOINTS:
+ raise ValueError(f"Unknown My Hours schema '{inputs.schema_name}'")
+
+ return my_hours_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py
new file mode 100644
index 000000000000..7feadc39508c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours.py
@@ -0,0 +1,143 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours import my_hours
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.my_hours import (
+ MyHoursRetryableError,
+ check_access,
+ get_rows,
+ my_hours_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import (
+ ENDPOINTS,
+ MY_HOURS_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_unwrapped = my_hours._fetch.__wrapped__ # type: ignore[attr-defined]
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(monkeypatch: Any, items: list[dict], endpoint: str = "clients") -> list[dict]:
+ def fake_fetch(session: Any, path: str, logger: Any) -> list[dict]:
+ return items
+
+ monkeypatch.setattr(my_hours, "_fetch", fake_fetch)
+ monkeypatch.setattr(my_hours, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(api_key="mh-key", endpoint=endpoint, logger=MagicMock()):
+ rows.extend(batch)
+ return rows
+
+ def test_yields_the_full_array_once(self, monkeypatch: Any) -> None:
+ rows = self._collect(monkeypatch, [{"id": 1}, {"id": 2}])
+ assert rows == [{"id": 1}, {"id": 2}]
+
+ def test_empty_array_yields_nothing(self, monkeypatch: Any) -> None:
+ rows = self._collect(monkeypatch, [])
+ assert rows == []
+
+
+class TestFetch:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else []
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(MyHoursRetryableError):
+ _fetch_unwrapped(session, "/Clients", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_unwrapped(session, "/Clients", MagicMock())
+
+ def test_success_returns_list_body(self) -> None:
+ body = [{"id": 1}]
+ session = self._session_returning(200, body)
+ assert _fetch_unwrapped(session, "/Clients", MagicMock()) == body
+
+ def test_non_list_body_is_retryable(self) -> None:
+ session = self._session_returning(200, {"error": "nope"})
+ with pytest.raises(MyHoursRetryableError):
+ _fetch_unwrapped(session, "/Clients", MagicMock())
+
+ def test_request_targets_the_expected_url(self) -> None:
+ session = self._session_returning(200, [])
+ _fetch_unwrapped(session, "/Projects/getAll", MagicMock())
+ args, _ = session.get.call_args
+ assert args[0] == "https://api2.myhours.com/api/Projects/getAll"
+
+
+class TestAuthHeader:
+ def test_uses_apikey_prefix(self) -> None:
+ # My Hours rejects requests that omit the literal `apikey ` prefix, so this is load-bearing.
+ assert my_hours._headers("mh-key")["Authorization"] == "apikey mh-key"
+
+
+class TestCheckAccess:
+ def _patch_session(self, monkeypatch: Any, response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ monkeypatch.setattr(my_hours, "make_tracked_session", lambda **kwargs: session)
+ return session
+
+ @parameterized.expand(
+ [
+ ("reachable", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "My Hours returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(
+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with pytest.MonkeyPatch().context() as mp:
+ self._patch_session(mp, response)
+ assert check_access("mh-key") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self, monkeypatch: Any) -> None:
+ self._patch_session(monkeypatch, requests.ConnectionError("boom"))
+ status, message = check_access("mh-key")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestMyHoursSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = my_hours_source(api_key="mh-key", endpoint=endpoint, logger=MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ # The list endpoints carry no stable timestamp, so we don't partition.
+ assert response.partition_mode is None
+
+ def test_every_endpoint_uses_id_primary_key(self) -> None:
+ assert all(config.primary_keys == ["id"] for config in MY_HOURS_ENDPOINTS.values())
+ assert set(MY_HOURS_ENDPOINTS) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours_source.py
new file mode 100644
index 000000000000..f110401b92a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/my_hours/tests/test_my_hours_source.py
@@ -0,0 +1,155 @@
+import pytest
+from unittest import mock
+
+import structlog
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import MyHoursSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.source import MyHoursSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(schema_name: str = "clients") -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=123,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=structlog.get_logger(),
+ reset_pipeline=False,
+ )
+
+
+class TestMyHoursSource:
+ def setup_method(self) -> None:
+ self.source = MyHoursSource()
+ self.team_id = 123
+ self.config = MyHoursSourceConfig(api_key="mh-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.MYHOURS
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "MyHours"
+ assert config.label == "My Hours"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/my-hours"
+
+ 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
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API key; the base URL is hardcoded, so there is no non-secret
+ # field an editor could retarget to reuse a preserved key against another account.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ assert all(s.supports_incremental is False for s in schemas)
+ assert all(s.supports_append is False for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ 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_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assert all("Full refresh" in t["sync_methods"] for t in tables)
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions) == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api2.myhours.com/api/Clients"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api2.myhours.com/api/Projects/getAll"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name: str, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("server_error", "500 Server Error: Internal Server Error for url: https://api2.myhours.com/api/Clients"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api2.myhours.com/api/Tags"),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, _name: str, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("reachable", 200, True, None),
+ ("unauthorized", 401, False, "Invalid My Hours API key"),
+ ("forbidden", 403, False, "Invalid My Hours API key"),
+ ("server_error", 500, False, "My Hours returned HTTP 500"),
+ ("connection_error", 0, False, "Could not connect to My Hours: boom"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.source.check_access")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ message = (
+ "My Hours returned HTTP 500"
+ if status == 500
+ else ("Could not connect to My Hours: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.my_hours.source.my_hours_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="clients")
+
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "mh-key"
+ assert kwargs["endpoint"] == "clients"
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = _make_inputs(schema_name="not_a_table")
+ with pytest.raises(ValueError, match="Unknown My Hours schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, inputs)