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 hubplanner import source (#67818)

Tom Owers2e0a8215ec46
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 2d67a60055f2..15e6370692a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -175,6 +175,7 @@ the row lists both.
| guru | HTTP | requests | ✅ |
| hellobaton | HTTP | requests | ✅ |
| hibob | HTTP | requests | ✅ |
+| hubplanner | HTTP | requests | ✅ |
| hubspot | HTTP | requests | ✅ |
| hugging_face | HTTP | requests | ✅ |
| incident_io | HTTP | requests | ✅ |
@@ -467,6 +468,7 @@ doesn't conflict with concurrent PRs.
- hightouch
- hoorayhr
- hubplanner
+- hugging_face
- humanitix
- huntr
- ikas
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 fb19fe365c83..a6f8f1f54a2e 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
@@ -1554,7 +1554,7 @@ class HoorayHRSourceConfig(config.Config):
@config.config
class HubplannerSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/canonical_descriptions.py
new file mode 100644
index 000000000000..34539ff59bd4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/canonical_descriptions.py
@@ -0,0 +1,164 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the official Hub Planner API docs (https://github.com/hubplanner/API).
+# Keys are the endpoint names returned by `get_schemas` (see settings.ENDPOINTS).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "Projects scheduled in Hub Planner, including budget, status and assigned resources/managers.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/project.md",
+ "columns": {
+ "_id": "Unique identifier for the project.",
+ "name": "Project name.",
+ "note": "Free-text note on the project.",
+ "projectCode": "User-defined project code.",
+ "status": "Project status (e.g. STATUS_ACTIVE, STATUS_ARCHIVED).",
+ "budgetHours": "Project budget expressed in hours.",
+ "budgetCashAmount": "Project budget expressed as a cash amount.",
+ "budgetCurrency": "Currency of the cash budget.",
+ "projectManagers": "IDs of the resources managing the project.",
+ "resources": "IDs of the resources assigned to the project.",
+ "start": "Project start date.",
+ "end": "Project end date.",
+ "createdDate": "Date the project was created.",
+ "updatedDate": "Date the project was last updated.",
+ },
+ },
+ "resources": {
+ "description": "Resources (people or assets) that can be scheduled, with role, status and contact details.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/resource.md",
+ "columns": {
+ "_id": "Unique identifier for the resource.",
+ "firstName": "Resource first name.",
+ "lastName": "Resource last name.",
+ "email": "Resource email address.",
+ "role": "Resource role.",
+ "status": "Resource status (e.g. STATUS_ACTIVE, STATUS_ARCHIVED).",
+ "createdDate": "Date the resource was created.",
+ "updatedDate": "Date the resource was last updated.",
+ },
+ },
+ "bookings": {
+ "description": "Scheduled bookings allocating a resource to a project over a date range.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/bookings.md",
+ "columns": {
+ "_id": "Unique identifier for the booking.",
+ "title": "Booking title.",
+ "state": "Booking state (STATE_DAY_MINUTE, STATE_PERCENTAGE, STATE_TOTAL_MINUTE).",
+ "type": "Booking type (SCHEDULED, APPROVED, WAITING_FOR_APPROVAL, REJECTED).",
+ "stateValue": "Value interpreted according to the booking state.",
+ "start": "Booking start date.",
+ "end": "Booking end date.",
+ "resource": "ID of the booked resource.",
+ "project": "ID of the project the booking is for.",
+ "note": "Booking note.",
+ "createdDate": "Date the booking was created.",
+ "updatedDate": "Date the booking was last updated.",
+ },
+ },
+ "time_entries": {
+ "description": "Timesheet entries logging time a resource spent on a project.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/timesheets.md",
+ "columns": {
+ "_id": "Unique identifier for the time entry.",
+ "resource": "ID of the resource who logged the time.",
+ "project": "ID of the project the time was logged against.",
+ "status": "Entry status (UNSUBMITTED, SUBMITTED, APPROVED, REJECTED, PENDING).",
+ "createdDate": "Server date when the entry was created.",
+ "updatedDate": "Server date when the entry was last updated.",
+ },
+ },
+ "events": {
+ "description": "Custom events in the scheduler (e.g. training, meetings) not tied to a project.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/events.md",
+ "columns": {
+ "_id": "Unique identifier for the event.",
+ "name": "Event name.",
+ "eventCode": "User-defined event code.",
+ "createdDate": "Date the event was created.",
+ "updatedDate": "Date the event was last updated.",
+ },
+ },
+ "clients": {
+ "description": "Clients that projects can be associated with.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/clients.md",
+ "columns": {
+ "_id": "Unique identifier for the client.",
+ "name": "Client name.",
+ "createdDate": "Date the client was created.",
+ "updatedDate": "Date the client was last updated.",
+ },
+ },
+ "milestones": {
+ "description": "Project milestones with a target date.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/milestones.md",
+ "columns": {
+ "_id": "Unique identifier for the milestone.",
+ "name": "Milestone name.",
+ "date": "Milestone date.",
+ "project": "ID of the project the milestone belongs to.",
+ },
+ },
+ "project_groups": {
+ "description": "Groups used to organise projects.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/groups.md",
+ "columns": {
+ "_id": "Unique identifier for the group.",
+ "createdDate": "Date the group was created.",
+ "updatedDate": "Date the group was last updated.",
+ },
+ },
+ "resource_groups": {
+ "description": "Groups used to organise resources.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/groups.md",
+ "columns": {
+ "_id": "Unique identifier for the group.",
+ "createdDate": "Date the group was created.",
+ "updatedDate": "Date the group was last updated.",
+ },
+ },
+ "billing_rates": {
+ "description": "Billing rates that can be applied to bookings and projects.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/billingrate.md",
+ "columns": {
+ "_id": "Unique identifier for the billing rate.",
+ "label": "Billing rate label.",
+ "currency": "Currency of the rate.",
+ "createdDate": "Date the billing rate was created.",
+ "updatedDate": "Date the billing rate was last updated.",
+ },
+ },
+ "holidays": {
+ "description": "Public holidays configured in Hub Planner.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/holidays.md",
+ "columns": {
+ "_id": "Unique identifier for the holiday.",
+ "name": "Holiday name.",
+ "createdDate": "Date the holiday was created.",
+ "updatedDate": "Date the holiday was last updated.",
+ },
+ },
+ "vacations": {
+ "description": "Vacation and time-off entries per resource.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/vacation.md",
+ "columns": {
+ "_id": "Unique identifier for the vacation entry.",
+ "title": "Vacation title.",
+ "start": "Vacation start date.",
+ "end": "Vacation end date.",
+ "resource": "ID of the resource the vacation belongs to.",
+ "type": "Vacation type (e.g. APPROVED, REJECTED).",
+ "state": "Vacation state.",
+ },
+ },
+ "project_managers": {
+ "description": "Resources designated as project managers.",
+ "docs_url": "https://github.com/hubplanner/API/blob/master/Sections/project-manager.md",
+ "columns": {
+ "_id": "Unique identifier for the project manager record.",
+ "createdDate": "Date the record was created.",
+ "updatedDate": "Date the record was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/hubplanner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/hubplanner.py
new file mode 100644
index 000000000000..5dae367d40bc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/hubplanner.py
@@ -0,0 +1,223 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import orjson
+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.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.settings import (
+ HUBPLANNER_ENDPOINTS,
+ HubPlannerEndpointConfig,
+)
+
+HUBPLANNER_BASE_URL = "https://api.hubplanner.com/v1"
+
+# Hub Planner caps `limit` at 1000; a limit of 0 or >1000 returns a 400. Bookings and time
+# entries default to 20 rows/page, so we always request the max to minimise round-trips.
+PAGE_SIZE = 1000
+
+
+class HubPlannerRetryableError(Exception):
+ pass
+
+
+class HubPlannerResumeConfig:
+ # Next 0-indexed page to fetch. Pagination is page-number based, so the page index is the
+ # only cursor we need to persist to resume mid-endpoint after a heartbeat timeout.
+ page: int = 0
+
+
+def _format_value(value: Any) -> str:
+ """Format an incremental cursor value as an ISO-8601 string Hub Planner accepts.
+
+ The API's `updatedDate` search filter compares against ISO timestamps (e.g.
+ `2018-09-04T08:15:11.487Z`), so datetimes are emitted in UTC with a `Z` suffix.
+ """
+ if isinstance(value, datetime):
+ utc_dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ # Despite Hub Planner's docs calling this an "OAuth 2.0 Bearer Token", the API key is placed
+ # raw in the Authorization header with no `Bearer ` prefix (verified against the live API).
+ return {
+ "Authorization": api_key,
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(base_url: str, params: dict[str, Any]) -> str:
+ if not params:
+ return base_url
+ return f"{base_url}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ # One cheap probe: list a single project. A valid key returns 200; an invalid or
+ # insufficiently-permissioned key returns 403 (Hub Planner keys are account-wide, not
+ # per-resource scoped, so a reachable /project confirms the whole token).
+ url = _build_url(f"{HUBPLANNER_BASE_URL}/project", {"page": 0, "limit": 1})
+ try:
+ response = make_tracked_session(redact_values=(api_key,)).get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ HubPlannerRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ # Hub Planner returns 429 with a Retry-After header on burst (50 req / 5s) or daily
+ # (6000/day) limits; exponential jitter keeps us comfortably under both without parsing it.
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ body: Optional[dict[str, Any]],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ data = orjson.dumps(body) if body is not None else None
+ response = session.request(method, url, headers=headers, data=data, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HubPlannerRetryableError(f"Hub Planner API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Never log the response body: Hub Planner echoes the supplied API key back in auth-error
+ # bodies, so logging it would leak the credential.
+ logger.error(f"Hub Planner API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ payload = response.json()
+ # Every list/search endpoint returns a bare JSON array; guard against an unexpected object.
+ if not isinstance(payload, list):
+ logger.warning(f"Hub Planner: expected a list response, got {type(payload).__name__} from url={url}")
+ return []
+ return payload
+
+
+def _build_request_plan(
+ config: HubPlannerEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> tuple[str, str, Optional[dict[str, Any]], Optional[str]]:
+ """Resolve (http_method, path, body, sort_field) for an endpoint's list request.
+
+ Incremental endpoints (and search-only endpoints like milestones) POST to `<path>/search`;
+ everything else GETs `<path>`.
+ """
+ incremental_active = bool(config.incremental_search_field and should_use_incremental_field)
+
+ if config.list_via_search or incremental_active:
+ body: dict[str, Any] = {}
+ sort_field: Optional[str] = None
+ field_name = config.incremental_search_field
+ if incremental_active and field_name is not None:
+ # Sort ascending on the cursor field so rows arrive oldest-first and the pipeline's
+ # incremental watermark advances safely (matches SourceResponse.sort_mode="asc").
+ sort_field = field_name
+ if db_incremental_field_last_value is not None:
+ body = {field_name: {"$gte": _format_value(db_incremental_field_last_value)}}
+ return "POST", f"{config.path}/search", body, sort_field
+
+ # Full-refresh GET. We deliberately don't pass a `sort` here: the API rejects an unsupported
+ # sort field with a 400 that would fail the whole sync, and not every endpoint's sortable
+ # fields are verifiable up front. A full refresh replaces the table each run, so the worst case
+ # of unsorted paging (a row shifting across a page boundary mid-sync) self-heals next sync.
+ return "GET", config.path, None, None
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HubPlannerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = HUBPLANNER_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = make_tracked_session(redact_values=(api_key,))
+
+ method, path, body, sort_field = _build_request_plan(
+ config, should_use_incremental_field, db_incremental_field_last_value
+ )
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page = resume.page if resume else 0
+
+ while True:
+ params: dict[str, Any] = {"page": page, "limit": PAGE_SIZE}
+ if sort_field:
+ params["sort"] = sort_field
+ url = _build_url(f"{HUBPLANNER_BASE_URL}{path}", params)
+
+ items = _fetch_page(session, method, url, headers, body, logger)
+
+ if items:
+ yield items
+
+ # A short page (fewer rows than requested) is the last page — the API has no next-page
+ # token, so we page until the server returns less than the limit.
+ if len(items) < PAGE_SIZE:
+ break
+
+ page += 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; the
+ # delta merge dedupes the re-pulled rows on the primary key.
+ resumable_source_manager.save_state(HubPlannerResumeConfig(page=page))
+
+
+def hubplanner_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HubPlannerResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = HUBPLANNER_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/settings.py
new file mode 100644
index 000000000000..81f171086f02
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/settings.py
@@ -0,0 +1,130 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class HubPlannerEndpointConfig:
+ name: str
+ path: str # e.g. "/booking" (base path, joined onto https://api.hubplanner.com/v1)
+ incremental_fields: list[IncrementalField]
+ primary_keys: list[str] = field(default_factory=lambda: ["_id"])
+ # Stable creation-time field used for datetime partitioning. Never a mutable field
+ # (`updatedDate`) — those rewrite partitions on every sync. None => no partitioning.
+ partition_key: Optional[str] = None
+ # Some resources have no GET-all endpoint and can only be listed via POST /<path>/search
+ # with an empty body (e.g. milestones). When True, list through search instead of GET.
+ list_via_search: bool = False
+ # Server-side incremental filter field. It MUST be a *searchable* property on the
+ # /<path>/search endpoint (Hub Planner only filters searchable fields). None => full
+ # refresh only. Only `bookings` and `time_entries` expose a searchable `updatedDate`,
+ # so they're the only incremental endpoints; every other area's search omits it.
+ incremental_search_field: Optional[str] = None
+ should_sync_default: bool = True
+
+
+def _updated_date_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "updatedDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedDate",
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+HUBPLANNER_ENDPOINTS: dict[str, HubPlannerEndpointConfig] = {
+ # Full-refresh core catalog resources. GET /project and GET /resource return every row
+ # (Hub Planner ignores pagination on them), but we still page defensively at limit=1000.
+ "projects": HubPlannerEndpointConfig(
+ name="projects",
+ path="/project",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ "resources": HubPlannerEndpointConfig(
+ name="resources",
+ path="/resource",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ # Bookings and time entries default to 20 rows per page and MUST be paginated. Both expose
+ # a searchable `updatedDate`, so they support server-side incremental sync via POST search.
+ "bookings": HubPlannerEndpointConfig(
+ name="bookings",
+ path="/booking",
+ partition_key="createdDate",
+ incremental_search_field="updatedDate",
+ incremental_fields=_updated_date_incremental_fields(),
+ ),
+ "time_entries": HubPlannerEndpointConfig(
+ name="time_entries",
+ path="/timeentry",
+ partition_key="createdDate",
+ incremental_search_field="updatedDate",
+ incremental_fields=_updated_date_incremental_fields(),
+ ),
+ "events": HubPlannerEndpointConfig(
+ name="events",
+ path="/event",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ "clients": HubPlannerEndpointConfig(
+ name="clients",
+ path="/client",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ # Milestones have no GET-all endpoint — list them via POST /milestone/search with {}.
+ "milestones": HubPlannerEndpointConfig(
+ name="milestones",
+ path="/milestone",
+ list_via_search=True,
+ incremental_fields=[],
+ ),
+ "project_groups": HubPlannerEndpointConfig(
+ name="project_groups",
+ path="/projectgroup",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ "resource_groups": HubPlannerEndpointConfig(
+ name="resource_groups",
+ path="/resourcegroup",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ "billing_rates": HubPlannerEndpointConfig(
+ name="billing_rates",
+ path="/billingRate",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ "holidays": HubPlannerEndpointConfig(
+ name="holidays",
+ path="/holiday",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+ # Vacations carry no creation timestamp (start/end only), so we don't partition them.
+ "vacations": HubPlannerEndpointConfig(
+ name="vacations",
+ path="/vacation",
+ incremental_fields=[],
+ ),
+ "project_managers": HubPlannerEndpointConfig(
+ name="project_managers",
+ path="/project-manager",
+ partition_key="createdDate",
+ incremental_fields=[],
+ ),
+}
+
+ENDPOINTS = tuple(HUBPLANNER_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HUBPLANNER_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/source.py
index ef1904d4acac..9a20221c5859 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/source.py
@@ -1,19 +1,43 @@
-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.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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HubplannerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.hubplanner import (
+ HubPlannerResumeConfig,
+ hubplanner_source,
+ validate_credentials as validate_hubplanner_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.settings import (
+ ENDPOINTS,
+ HUBPLANNER_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HubplannerSource(SimpleSource[HubplannerSourceConfig]):
+class HubplannerSource(ResumableSource[HubplannerSourceConfig, HubPlannerResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HUBPLANNER
@@ -23,8 +47,93 @@ class HubplannerSource(SimpleSource[HubplannerSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.HUBPLANNER,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
- label="Hubplanner",
+ label="Hub Planner",
+ caption="""Enter your Hub Planner API key to sync your resource-scheduling, project-planning and time-tracking data into the PostHog Data warehouse.
+
+Generate a **Read Only** API key in Hub Planner under **Settings → API** (admin access required).""",
iconPath="/static/services/hubplanner.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/hubplanner",
unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ 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.hubplanner.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ # Both a missing/invalid key and an under-permissioned key surface as 403 from Hub Planner
+ # (there's no 401 path). Retrying can never satisfy a credential problem, so stop the sync.
+ return {
+ "403 Client Error: Forbidden for url: https://api.hubplanner.com": "Your Hub Planner API key is invalid or lacks the required permissions. Generate a new Read Only key under Settings → API, then reconnect.",
+ "401 Client Error: Unauthorized for url: https://api.hubplanner.com": "Your Hub Planner API key is invalid or has been revoked. Generate a new key under Settings → API, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: HubplannerSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = HUBPLANNER_ENDPOINTS[endpoint]
+ has_incremental = endpoint_config.incremental_search_field is not None
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) 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: HubplannerSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_hubplanner_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Hub Planner API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HubPlannerResumeConfig]:
+ return ResumableSourceManager[HubPlannerResumeConfig](inputs, HubPlannerResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HubplannerSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HubPlannerResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return hubplanner_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner.py
new file mode 100644
index 000000000000..a7f1e1eae081
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner.py
@@ -0,0 +1,298 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner import hubplanner
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.hubplanner import (
+ PAGE_SIZE,
+ HubPlannerResumeConfig,
+ _build_request_plan,
+ _format_value,
+ _get_headers,
+ get_rows,
+ hubplanner_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.settings import HUBPLANNER_ENDPOINTS
+
+
+class TestFormatValue:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (
+ "datetime_microseconds_truncated_to_millis",
+ datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC),
+ "2026-01-15T10:30:45.123Z",
+ ),
+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04"),
+ ("string_passthrough", "5b1977ade02d407011112222", "5b1977ade02d407011112222"),
+ ]
+ )
+ def test_format_value(self, _name: str, value: object, expected: str) -> None:
+ assert _format_value(value) == expected
+
+ def test_datetime_has_no_plus_zero_offset(self) -> None:
+ # Hub Planner expects a Z suffix, not the +00:00 offset isoformat() produces.
+ assert "+00:00" not in _format_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestHeaders:
+ def test_authorization_header_is_raw_key_without_bearer_prefix(self) -> None:
+ headers = _get_headers("my-secret-key")
+ assert headers["Authorization"] == "my-secret-key"
+ assert "Bearer" not in headers["Authorization"]
+ assert headers["Content-Type"] == "application/json"
+ assert headers["Accept"] == "application/json"
+
+
+class TestBuildRequestPlan:
+ def test_full_refresh_endpoint_uses_unsorted_get(self) -> None:
+ # No `sort` on full-refresh GET: an unsupported sort field would 400 the whole sync.
+ method, path, body, sort_field = _build_request_plan(
+ HUBPLANNER_ENDPOINTS["projects"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert (method, path, body, sort_field) == ("GET", "/project", None, None)
+
+ def test_incremental_endpoint_without_incremental_selected_uses_get(self) -> None:
+ # A user syncing bookings via full refresh should hit the plain GET list, not search.
+ method, path, body, sort_field = _build_request_plan(
+ HUBPLANNER_ENDPOINTS["bookings"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert method == "GET"
+ assert path == "/booking"
+ assert body is None
+
+ def test_incremental_first_sync_posts_search_with_empty_body(self) -> None:
+ # should_use_incremental_field=True but no stored watermark yet: fetch everything, sorted asc.
+ method, path, body, sort_field = _build_request_plan(
+ HUBPLANNER_ENDPOINTS["bookings"], should_use_incremental_field=True, db_incremental_field_last_value=None
+ )
+ assert (method, path, body, sort_field) == ("POST", "/booking/search", {}, "updatedDate")
+
+ def test_incremental_with_watermark_filters_on_updated_date(self) -> None:
+ method, path, body, sort_field = _build_request_plan(
+ HUBPLANNER_ENDPOINTS["time_entries"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert method == "POST"
+ assert path == "/timeentry/search"
+ assert body == {"updatedDate": {"$gte": "2026-03-04T02:58:14.000Z"}}
+ assert sort_field == "updatedDate"
+
+ def test_search_only_endpoint_lists_via_search(self) -> None:
+ # Milestones have no GET-all endpoint, so full refresh still POSTs to /milestone/search.
+ method, path, body, sort_field = _build_request_plan(
+ HUBPLANNER_ENDPOINTS["milestones"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+ assert (method, path, body, sort_field) == ("POST", "/milestone/search", {}, None)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: Optional[HubPlannerResumeConfig] = None) -> None:
+ self._state = state
+ self.saved: list[HubPlannerResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> Optional[HubPlannerResumeConfig]:
+ return self._state
+
+ def save_state(self, data: HubPlannerResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestGetRows:
+ @staticmethod
+ def _run(manager: _FakeResumableManager, pages: list[list[dict]], **kwargs: Any) -> tuple[list[list[dict]], list]:
+ calls: list[dict[str, Any]] = []
+
+ def fake_fetch(session: Any, method: str, url: str, headers: dict, body: Any, logger: Any) -> list[dict]:
+ calls.append({"method": method, "url": url, "body": body})
+ return pages[len(calls) - 1]
+
+ with (
+ patch.object(hubplanner, "_fetch_page", fake_fetch),
+ patch.object(hubplanner, "make_tracked_session", return_value=MagicMock()),
+ ):
+ batches = list(
+ get_rows(
+ api_key="k",
+ endpoint=kwargs.pop("endpoint", "projects"),
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ )
+ )
+ return batches, calls
+
+ def test_single_short_page_terminates_without_saving_state(self) -> None:
+ manager = _FakeResumableManager()
+ batches, calls = self._run(manager, pages=[[{"_id": "1"}, {"_id": "2"}]])
+
+ assert batches == [[{"_id": "1"}, {"_id": "2"}]]
+ assert len(calls) == 1
+ # A short first page is the last page, so there's no next page to checkpoint.
+ assert manager.saved == []
+
+ def test_paginates_until_short_page_and_saves_state_after_each_full_page(self) -> None:
+ manager = _FakeResumableManager()
+ full_page = [{"_id": str(i)} for i in range(PAGE_SIZE)]
+ short_page = [{"_id": "last"}]
+ batches, calls = self._run(manager, pages=[full_page, short_page])
+
+ assert batches == [full_page, short_page]
+ assert [c["url"].split("page=")[1].split("&")[0] for c in calls] == ["0", "1"]
+ # State saved once after the first (full) page points at page 1; the short page ends the loop.
+ assert manager.saved == [HubPlannerResumeConfig(page=1)]
+
+ def test_resumes_from_saved_page(self) -> None:
+ manager = _FakeResumableManager(state=HubPlannerResumeConfig(page=3))
+ _batches, calls = self._run(manager, pages=[[{"_id": "x"}]])
+
+ assert calls[0]["url"].split("page=")[1].split("&")[0] == "3"
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ manager = _FakeResumableManager()
+ batches, calls = self._run(manager, pages=[[]])
+ assert batches == []
+ assert len(calls) == 1
+
+ def test_incremental_sync_posts_search_body(self) -> None:
+ manager = _FakeResumableManager()
+ _batches, calls = self._run(
+ manager,
+ pages=[[{"_id": "1"}]],
+ endpoint="bookings",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert calls[0]["method"] == "POST"
+ assert "/booking/search" in calls[0]["url"]
+ assert calls[0]["body"] == {"updatedDate": {"$gte": "2026-03-04T00:00:00.000Z"}}
+
+
+class TestFetchPage:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_status_raises_retryable_error(self, _name: str, status_code: int) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ session = MagicMock()
+ session.request.return_value = response
+
+ with patch.object(hubplanner._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ with pytest.raises(hubplanner.HubPlannerRetryableError):
+ hubplanner._fetch_page(session, "GET", "https://api.hubplanner.com/v1/project", {}, None, MagicMock())
+
+ assert session.request.call_count == 5
+
+ def test_bare_list_response_returned_as_is(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = [{"_id": "1"}, {"_id": "2"}]
+ session = MagicMock()
+ session.request.return_value = response
+
+ result = hubplanner._fetch_page(session, "GET", "https://api.hubplanner.com/v1/project", {}, None, MagicMock())
+ assert result == [{"_id": "1"}, {"_id": "2"}]
+
+ def test_non_list_response_returns_empty(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = {"message": "unexpected"}
+ session = MagicMock()
+ session.request.return_value = response
+
+ result = hubplanner._fetch_page(session, "GET", "https://api.hubplanner.com/v1/project", {}, None, MagicMock())
+ assert result == []
+
+ def test_auth_error_does_not_log_response_body(self) -> None:
+ # Hub Planner echoes the API key back in auth-error bodies; logging it would leak the secret.
+ response = requests.Response()
+ response.status_code = 403
+ response._content = b'{"error":"OAUTH_ERROR_TOKEN_NOT_VALID","authHeaders":"my-secret-key"}'
+ session = MagicMock()
+ session.request.return_value = response
+ logger = MagicMock()
+
+ with pytest.raises(requests.HTTPError):
+ hubplanner._fetch_page(session, "GET", "https://api.hubplanner.com/v1/project", {}, None, logger)
+
+ logged = " ".join(str(call) for call in logger.error.call_args_list)
+ assert "my-secret-key" not in logged
+ assert "OAUTH_ERROR_TOKEN_NOT_VALID" not in logged
+
+
+class TestSourceResponse:
+ def test_partitioned_endpoint_sets_datetime_partitioning(self) -> None:
+ response = hubplanner_source(
+ api_key="k", endpoint="bookings", logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.name == "bookings"
+ assert response.primary_keys == ["_id"]
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdDate"]
+ assert response.sort_mode == "asc"
+
+ def test_endpoint_without_partition_key_has_no_partitioning(self) -> None:
+ # Vacations carry no creation timestamp, so they aren't partitioned.
+ response = hubplanner_source(
+ api_key="k", endpoint="vacations", logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("forbidden", 403, False), ("unauthorized", 401, False)])
+ def test_status_maps_to_validity(self, _name: str, status_code: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status_code
+ session = MagicMock()
+ session.get.return_value = response
+
+ with patch.object(hubplanner, "make_tracked_session", return_value=session):
+ assert validate_credentials("some-key") is expected
+
+ def test_network_error_is_invalid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(hubplanner, "make_tracked_session", return_value=session):
+ assert validate_credentials("some-key") is False
+
+
+class TestApiKeyRedaction:
+ # Hub Planner echoes the API key back in auth-error bodies, so the tracked transport must be
+ # given the key as a redact value on every path — otherwise it can leak into captured samples.
+ def test_validate_credentials_redacts_api_key(self) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=200)
+ with patch.object(hubplanner, "make_tracked_session", return_value=session) as factory:
+ validate_credentials("my-secret-key")
+ assert factory.call_args.kwargs["redact_values"] == ("my-secret-key",)
+
+ def test_get_rows_redacts_api_key(self) -> None:
+ with (
+ patch.object(hubplanner, "_fetch_page", return_value=[]),
+ patch.object(hubplanner, "make_tracked_session", return_value=MagicMock()) as factory,
+ ):
+ list(
+ get_rows(
+ api_key="my-secret-key",
+ endpoint="projects",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ )
+ assert factory.call_args.kwargs["redact_values"] == ("my-secret-key",)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner_source.py
new file mode 100644
index 000000000000..15d2f9183fc4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hubplanner/tests/test_hubplanner_source.py
@@ -0,0 +1,139 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HubplannerSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.hubplanner import (
+ HubPlannerResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.hubplanner.source import HubplannerSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHubplannerSource:
+ def setup_method(self) -> None:
+ self.source = HubplannerSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.HUBPLANNER
+
+ def test_source_config_shape(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Hub Planner"
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/hubplanner"
+
+ def test_source_config_has_single_secret_api_key_field(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.name == "api_key"
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.required is True
+ assert api_key.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas iterates a static catalog with no I/O, so the public docs table list can render.
+ assert self.source.lists_tables_without_credentials is True
+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("bookings", True),
+ ("time_entries", True),
+ ("projects", False),
+ ("resources", False),
+ ("milestones", False),
+ ("vacations", False),
+ ]
+ )
+ def test_incremental_support_only_where_server_side_filter_exists(self, endpoint: str, expected: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is expected
+ assert schema.supports_append is expected
+ if expected:
+ assert [f["field"] for f in schema.incremental_fields] == ["updatedDate"]
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_names_filter(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["bookings", "projects"])
+ assert {s.name for s in schemas} == {"bookings", "projects"}
+
+ @parameterized.expand([("forbidden", "403 Client Error"), ("unauthorized", "401 Client Error")])
+ def test_auth_errors_are_non_retryable(self, _name: str, prefix: str) -> None:
+ keys = self.source.get_non_retryable_errors()
+ assert any(key.startswith(prefix) for key in keys)
+
+ def test_validate_credentials_success(self) -> None:
+ config = HubplannerSourceConfig(api_key="good")
+ with patch.object(source_module, "validate_hubplanner_credentials", return_value=True):
+ assert self.source.validate_credentials(config, self.team_id) == (True, None)
+
+ def test_validate_credentials_failure(self) -> None:
+ config = HubplannerSourceConfig(api_key="bad")
+ with patch.object(source_module, "validate_hubplanner_credentials", return_value=False):
+ valid, error = self.source.validate_credentials(config, self.team_id)
+ assert valid is False
+ assert error is not None
+
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is HubPlannerResumeConfig
+
+ def test_source_for_pipeline_plumbs_inputs(self) -> None:
+ config = HubplannerSourceConfig(api_key="k")
+ manager = MagicMock()
+ inputs = MagicMock()
+ inputs.schema_name = "bookings"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+
+ with patch.object(source_module, "hubplanner_source") as mock_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ _args, kwargs = mock_source.call_args
+ assert kwargs["api_key"] == "k"
+ assert kwargs["endpoint"] == "bookings"
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ config = HubplannerSourceConfig(api_key="k")
+ inputs = MagicMock()
+ inputs.schema_name = "projects"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01"
+
+ with patch.object(source_module, "hubplanner_source") as mock_source:
+ self.source.source_for_pipeline(config, MagicMock(), inputs)
+
+ _args, kwargs = mock_source.call_args
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:
+ descriptions: dict[str, Any] = self.source.get_canonical_descriptions()
+ assert set(descriptions).issubset(set(ENDPOINTS))
+ # The high-value core tables should be documented.
+ assert {"projects", "resources", "bookings", "time_entries"}.issubset(set(descriptions))