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 tempo import source (#69390)

Tom Owers903d2c300d8f
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 8535398727b0..c07ad3a23eb3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -339,6 +339,7 @@ the row lists both.
| tavus | HTTP | requests | ✅ |
| teamtailor | HTTP | requests | ✅ |
| teamwork | HTTP | requests | ✅ |
+| tempo | HTTP | requests | ✅ |
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| testrail | HTTP | requests | ✅ |
| thinkific | HTTP | requests | ✅ |
@@ -717,7 +718,6 @@ doesn't conflict with concurrent PRs.
- systeme
- tawk_to
- teachable
-- tempo
- thinkific_courses
- thrive_learning
- ticketmaster
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 4bab37ec1e6f..0450effc4a65 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
@@ -3386,7 +3386,7 @@ class TeamworkSourceConfig(config.Config):
@config.config
class TempoSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/canonical_descriptions.py
new file mode 100644
index 000000000000..dbfd965f4d10
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/canonical_descriptions.py
@@ -0,0 +1,119 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the official Tempo REST API v4 OpenAPI spec (https://apidocs.tempo.io).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "worklogs": {
+ "description": "Time logged against Jira issues: who worked, on what, when, and for how long.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Worklogs",
+ "columns": {
+ "tempoWorklogId": "The worklog id in the Tempo app.",
+ "issue": "The Jira issue the time was logged against (self link and numeric issue id).",
+ "author": "The Jira user who logged the time (account id and self link).",
+ "timeSpentSeconds": "The total amount of time spent, in seconds.",
+ "billableSeconds": "The amount of billable time, in seconds.",
+ "startDate": "The start date of the worklog.",
+ "startTime": "The start time of the worklog.",
+ "startDateTimeUtc": "The start date and time of the worklog in UTC.",
+ "description": "The description of the worklog.",
+ "createdAt": "The date and time when this worklog was created.",
+ "updatedAt": "The last date and time when this worklog was updated.",
+ "attributes": "The work attribute values recorded on the worklog.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "accounts": {
+ "description": "Tempo accounts used to categorize logged time for billing and reporting.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Accounts",
+ "columns": {
+ "id": "The id of the account.",
+ "key": "The key of the account.",
+ "name": "The name of the account.",
+ "status": "The status of the account (OPEN, CLOSED, or ARCHIVED).",
+ "global": "Whether the account is a global account.",
+ "monthlyBudget": "The estimated budget for the month.",
+ "lead": "The Jira user who leads the account.",
+ "contact": "The contact person for the account.",
+ "customer": "The customer the account belongs to.",
+ "category": "The category of the account.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "customers": {
+ "description": "Customers that Tempo accounts can be linked to.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Customers",
+ "columns": {
+ "id": "The id of the customer.",
+ "key": "The key of the customer.",
+ "name": "The name of the customer.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "teams": {
+ "description": "Tempo teams that group Jira users for planning and reporting.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Teams",
+ "columns": {
+ "id": "The id of the team.",
+ "name": "The team's name.",
+ "summary": "Brief description of the team.",
+ "lead": "The Jira user who leads the team.",
+ "program": "The program the team belongs to.",
+ "administrative": "Whether this is an administrative team.",
+ "public": "Whether this is a public team.",
+ "members": "A link to the team's member list.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "plans": {
+ "description": "Resource allocations: planned time for a user or generic resource against an issue or project.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Plans",
+ "columns": {
+ "id": "The id of the plan.",
+ "assignee": "The user or generic resource the time is planned for.",
+ "planItem": "The issue or project the time is planned against.",
+ "startDate": "The starting date of the plan.",
+ "endDate": "The ending date of the plan.",
+ "startTime": "The start time of the plan.",
+ "plannedSecondsPerDay": "The amount of seconds planned daily when effortPersistenceType is SECONDS_PER_DAY.",
+ "totalPlannedSeconds": "The total amount of seconds planned when effortPersistenceType is TOTAL_SECONDS.",
+ "totalPlannedSecondsInScope": "The total amount of seconds planned within the queried date range.",
+ "effortPersistenceType": "How the planned effort is stored: SECONDS_PER_DAY or TOTAL_SECONDS.",
+ "includeNonWorkingDays": "Whether non-working days are included in the plan.",
+ "rule": "Recurrence rule of the plan.",
+ "recurrenceEndDate": "End date for recurrence of the plan.",
+ "planApproval": "The approval status of the plan.",
+ "planCreatorId": "The Jira user account id of the plan creator.",
+ "syncSource": "JIRA_ISSUE if this is a synced plan, otherwise NONE.",
+ "description": "A description containing details of the plan.",
+ "createdAt": "Date and time the plan was created.",
+ "updatedAt": "Date and time the plan was last updated.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "workload_schemes": {
+ "description": "Workload schemes defining required working hours per weekday for members.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Workload-Schemes",
+ "columns": {
+ "id": "The id of the workload scheme.",
+ "name": "The name of the workload scheme.",
+ "description": "The description of the workload scheme.",
+ "days": "The list of days and their required hours in this workload scheme.",
+ "defaultScheme": "Whether this is the default workload scheme.",
+ "memberCount": "The number of members in this workload scheme.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+ "holiday_schemes": {
+ "description": "Holiday schemes defining the holidays that apply to their members.",
+ "docs_url": "https://apidocs.tempo.io/#tag/Holiday-Schemes",
+ "columns": {
+ "id": "The id of the holiday scheme.",
+ "name": "The name of the holiday scheme.",
+ "description": "The description of the holiday scheme.",
+ "defaultScheme": "Whether this is the default holiday scheme.",
+ "memberCount": "The number of people working under this holiday scheme.",
+ "self": "A permanent link to this resource.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/settings.py
new file mode 100644
index 000000000000..d38fee2f002e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/settings.py
@@ -0,0 +1,64 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class TempoEndpointConfig:
+ name: str
+ path: str
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Most list endpoints take limit/offset and return a `metadata.next` URL; holiday-schemes
+ # returns the whole collection in one response.
+ paginated: bool = True
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Server-side query param that filters rows updated on/after the watermark (e.g. `updatedFrom`).
+ incremental_param: Optional[str] = None
+ # Tempo's `orderBy` sorts by the given field DESCENDING; without it, worklogs default to
+ # START_DATE_TIME ascending (per the official OpenAPI spec).
+ order_by: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ partition_key: Optional[str] = None
+ # The plans endpoint requires `from`/`to` query params; we send a wide fixed window.
+ requires_date_window: bool = False
+
+
+# Tempo REST API v4 list endpoints (https://apidocs.tempo.io). Only worklogs expose a documented
+# server-side incremental filter (`updatedFrom`, matching rows created or updated on/after the
+# given timestamp). `/plans` also documents `updatedFrom`, but its ordering is undocumented and we
+# could not verify the filter against a live account, so it ships full refresh for now.
+TEMPO_ENDPOINTS: dict[str, TempoEndpointConfig] = {
+ "worklogs": TempoEndpointConfig(
+ name="worklogs",
+ path="/worklogs",
+ # Worklog ids are numeric and unique across the whole Tempo instance.
+ primary_keys=["tempoWorklogId"],
+ incremental_fields=[
+ {
+ "label": "updatedAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "updatedAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ incremental_param="updatedFrom",
+ # `orderBy=UPDATED` returns worklogs newest-update-first, so the incremental watermark is
+ # only committed once the sync completes (sort_mode="desc").
+ order_by="UPDATED",
+ sort_mode="desc",
+ partition_key="createdAt",
+ ),
+ "accounts": TempoEndpointConfig(name="accounts", path="/accounts"),
+ "customers": TempoEndpointConfig(name="customers", path="/customers"),
+ "teams": TempoEndpointConfig(name="teams", path="/teams"),
+ "plans": TempoEndpointConfig(name="plans", path="/plans", requires_date_window=True),
+ "workload_schemes": TempoEndpointConfig(name="workload_schemes", path="/workload-schemes"),
+ "holiday_schemes": TempoEndpointConfig(name="holiday_schemes", path="/holiday-schemes", paginated=False),
+}
+
+ENDPOINTS = tuple(TEMPO_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TEMPO_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/source.py
index e8dce9dcb493..05b03447719e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/source.py
@@ -1,19 +1,44 @@
-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 TempoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TEMPO_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.tempo import (
+ TempoResumeConfig,
+ check_access,
+ tempo_source,
+ validate_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TempoSource(SimpleSource[TempoSourceConfig]):
+class TempoSource(ResumableSource[TempoSourceConfig, TempoResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TEMPO
@@ -24,7 +49,112 @@ class TempoSource(SimpleSource[TempoSourceConfig]):
name=SchemaExternalDataSourceType.TEMPO,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Tempo",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Tempo API token to pull your time-tracking and resource-planning data into the PostHog Data warehouse.
+
+You can create an API token under **Settings → API Integration** in [Tempo](https://www.tempo.io) (Tempo for Jira Cloud). Tokens are scoped, so grant view (read) access for the data you want to sync: worklogs, accounts, customers, teams, plans, and schemes.
+""",
iconPath="/static/services/tempo.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/tempo",
+ keywords=["jira", "timesheets", "time tracking"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.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://api.tempo.io": "Your Tempo API token is invalid or has been revoked. Generate a new token under Settings → API Integration in Tempo, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.tempo.io": "Your Tempo API token is missing the view scope for this table. Grant the scope on the token in Tempo, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TempoSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # Only worklogs expose a server-side incremental filter (`updatedFrom`).
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(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: TempoSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # Tempo tokens carry granular scopes: at source-create we only confirm the token is genuine
+ # (a 403 counts as valid); with a schema name we confirm the scope for that endpoint.
+ if schema_name is not None and schema_name not in TEMPO_ENDPOINTS:
+ return False, f"Unknown Tempo schema '{schema_name}'"
+ return validate_credentials(config.api_token, endpoint=schema_name)
+
+ def get_endpoint_permissions(
+ self, config: TempoSourceConfig, team_id: int, endpoints: list[str]
+ ) -> dict[str, str | None]:
+ permissions: dict[str, str | None] = {}
+ for endpoint in endpoints:
+ if endpoint not in TEMPO_ENDPOINTS:
+ permissions[endpoint] = None
+ continue
+ status, _ = check_access(config.api_token, endpoint)
+ if status == 401:
+ permissions[endpoint] = "Invalid Tempo API token"
+ elif status == 403:
+ permissions[endpoint] = f"Your Tempo API token is missing the view scope for '{endpoint}'"
+ else:
+ # Only a real denial marks a missing scope — throttles, 5xx, and network blips
+ # must not block the table from being selected.
+ permissions[endpoint] = None
+ return permissions
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TempoResumeConfig]:
+ return ResumableSourceManager[TempoResumeConfig](inputs, TempoResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TempoSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TempoResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in TEMPO_ENDPOINTS:
+ raise ValueError(f"Unknown Tempo schema '{inputs.schema_name}'")
+
+ return tempo_source(
+ api_token=config.api_token,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py
new file mode 100644
index 000000000000..6c8f8e046cda
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tempo.py
@@ -0,0 +1,274 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlsplit
+
+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.tempo.settings import (
+ TEMPO_ENDPOINTS,
+ TempoEndpointConfig,
+)
+
+# Universal base path; Tempo also offers api.eu.tempo.io / api.us.tempo.io for geographic routing,
+# but the universal host serves every region.
+TEMPO_BASE_URL = "https://api.tempo.io/4"
+# List endpoints default to 50 rows per page; 100 keeps round trips down without risking
+# undocumented per-endpoint caps.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+# The plans endpoint requires a `from`/`to` window, so a full sync sends a wide fixed one. Plans
+# are resource allocations that can extend into the future, hence the years of headroom.
+PLANS_WINDOW_START = "2001-01-01"
+PLANS_WINDOW_YEARS_AHEAD = 5
+# Cheap endpoint used to confirm an API token is genuine at source-create. Tempo tokens carry
+# granular scopes, so a 403 here still proves the token itself is valid.
+DEFAULT_PROBE_ENDPOINT = "worklogs"
+
+
+class TempoRetryableError(Exception):
+ pass
+
+
+class TempoResumeConfig:
+ # Full URL of the next page, taken verbatim from the API's `metadata.next` (it embeds limit,
+ # offset, and any filters). A crashed sync resumes from the page after the last one yielded;
+ # merge dedupes the re-pulled page on the primary key. `None` means start from the first page.
+ next_url: str | None = None
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}
+
+
+def _get_session(api_token: str) -> requests.Session:
+ # allow_redirects=False so a 3xx can't silently move the credentialed request off the
+ # validated host (SSRF). See _NoRedirectSession in common/http/transport.py.
+ return make_tracked_session(headers=_headers(api_token), redact_values=(api_token,), allow_redirects=False)
+
+
+def _ensure_tempo_url(url: str) -> str:
+ """Reject pagination/resume URLs that leave the Tempo API host.
+
+ `metadata.next` is server-controlled and the session carries the Bearer token on every
+ request, so a tampered response or poisoned resume state could otherwise point the
+ credentialed request at an arbitrary host and leak the token. Compare the full origin
+ (scheme + netloc), not a prefix, so look-alike hosts are rejected too."""
+ parts, base = urlsplit(url), urlsplit(TEMPO_BASE_URL)
+ if (parts.scheme, parts.netloc) != (base.scheme, base.netloc):
+ raise ValueError(f"Tempo pagination URL does not stay on the Tempo API host: {parts.netloc!r}")
+ return url
+
+
+def _plans_window() -> tuple[str, str]:
+ end = date.today() + timedelta(days=365 * PLANS_WINDOW_YEARS_AHEAD)
+ return PLANS_WINDOW_START, end.isoformat()
+
+
+def _format_updated_from(value: Any) -> str:
+ # `updatedFrom` accepts "yyyy-MM-dd" or "yyyy-MM-dd'T'HH:mm:ss'Z'" (inclusive); the boundary
+ # row is re-fetched and merge dedupes it on the primary key. The watermark round-trips from
+ # Tempo's own `updatedAt` (always UTC), so a naive datetime is treated as UTC, not local time.
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _probe_params(config: TempoEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["limit"] = 1
+ if config.requires_date_window:
+ today = date.today().isoformat()
+ params["from"] = today
+ params["to"] = today
+ return params
+
+
+def _build_initial_params(
+ config: TempoEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["limit"] = PAGE_SIZE
+ if config.requires_date_window:
+ window_from, window_to = _plans_window()
+ params["from"] = window_from
+ params["to"] = window_to
+ if config.order_by:
+ params["orderBy"] = config.order_by
+
+ if should_use_incremental_field:
+ advertised = {f["field"] for f in config.incremental_fields}
+ if not config.incremental_param or incremental_field not in advertised:
+ raise ValueError(f"Tempo endpoint '{config.name}' does not support incremental field '{incremental_field}'")
+ if db_incremental_field_last_value:
+ params[config.incremental_param] = _format_updated_from(db_incremental_field_last_value)
+
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type((TempoRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ params: Optional[dict[str, Any]],
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # `params` is only set for the first request; `metadata.next` is a full URL with limit, offset,
+ # and filters baked in, so follow-up requests must not re-send query params.
+ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Tempo rate limiting is dynamic (no fixed quota) and surfaces as 429 — back off and retry.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TempoRetryableError(f"Tempo API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Tempo API error: status={response.status_code}, body={response.text}, url={url}")
+ # raise_for_status() would embed the full request URL (query string included) in the
+ # exception, which is surfaced as the schema's latest_error. Rebuild it from
+ # scheme/host/path only; the "<status> Client Error: <reason> for url: https://api.tempo.io"
+ # prefix stays stable for get_non_retryable_errors() matching.
+ safe = urlsplit(response.url)
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {safe.scheme}://{safe.netloc}{safe.path}",
+ response=response,
+ )
+
+ data = response.json()
+ # Every list endpoint wraps rows in {"results": [...], "metadata": {...}}; paginated ones set
+ # `metadata.next` to the next page's URL (absent on the last page and on unpaginated endpoints).
+ if not isinstance(data, dict) or not isinstance(data.get("results"), list):
+ raise TempoRetryableError(f"Tempo returned an unexpected payload for {url}: {type(data).__name__}")
+
+ metadata = data.get("metadata")
+ next_url = metadata.get("next") if isinstance(metadata, dict) else None
+ if not (isinstance(next_url, str) and next_url):
+ return data["results"], None
+ return data["results"], _ensure_tempo_url(next_url)
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TempoResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = TEMPO_ENDPOINTS[endpoint]
+ session = _get_session(api_token)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume and resume.next_url:
+ logger.debug(f"Tempo: resuming {endpoint} from {resume.next_url}")
+ # Resume state is persisted outside the process, so re-validate it before use.
+ url = _ensure_tempo_url(resume.next_url)
+ params: Optional[dict[str, Any]] = None
+ else:
+ url = f"{TEMPO_BASE_URL}{config.path}"
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+
+ while True:
+ items, next_url = _fetch_page(session, url, params, logger)
+ if items:
+ yield items
+
+ # No `metadata.next` means we've reached the last page (or the endpoint is unpaginated).
+ if not next_url:
+ break
+
+ url, params = next_url, None
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(TempoResumeConfig(next_url=next_url))
+
+
+def tempo_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TempoResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = TEMPO_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ sort_mode=config.sort_mode,
+ )
+
+
+def check_access(api_token: str, endpoint: str = DEFAULT_PROBE_ENDPOINT) -> tuple[int, Optional[str]]:
+ """Probe a single endpoint to check the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401`` invalid token, ``403`` valid token
+ missing the endpoint's view scope, ``0`` for a connection problem, other HTTP status otherwise.
+ """
+ config = TEMPO_ENDPOINTS[endpoint]
+ session = _get_session(api_token)
+ try:
+ response = session.get(f"{TEMPO_BASE_URL}{config.path}", params=_probe_params(config), timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to Tempo: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"Tempo returned HTTP {response.status_code}"
+
+ return 200, None
+
+
+def validate_credentials(api_token: str, endpoint: str | None = None) -> tuple[bool, str | None]:
+ status, message = check_access(api_token, endpoint or DEFAULT_PROBE_ENDPOINT)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid Tempo API token"
+ if status == 403:
+ # Tempo tokens carry granular scopes. At source-create (no endpoint) a 403 still proves the
+ # token is genuine — the user may only have granted scopes for the tables they'll sync.
+ if endpoint is None:
+ return True, None
+ return False, f"Your Tempo API token is missing the view scope for '{endpoint}'"
+ return False, message or "Could not validate Tempo API token"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo.py
new file mode 100644
index 000000000000..4b288a60e72f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo.py
@@ -0,0 +1,385 @@
+from datetime import UTC, date, datetime, timedelta, timezone
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo import tempo
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.settings import ENDPOINTS, TEMPO_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.tempo import (
+ PAGE_SIZE,
+ TEMPO_BASE_URL,
+ TempoResumeConfig,
+ TempoRetryableError,
+ _build_initial_params,
+ _format_updated_from,
+ check_access,
+ get_rows,
+ tempo_source,
+ validate_credentials,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = tempo._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TempoResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TempoResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TempoResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TempoResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestBuildInitialParams:
+ def test_worklogs_incremental_with_watermark(self) -> None:
+ params = _build_initial_params(
+ TEMPO_ENDPOINTS["worklogs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC),
+ incremental_field="updatedAt",
+ )
+ assert params == {"limit": PAGE_SIZE, "orderBy": "UPDATED", "updatedFrom": "2026-03-01T12:30:45Z"}
+
+ def test_worklogs_first_incremental_sync_has_no_updated_from(self) -> None:
+ params = _build_initial_params(
+ TEMPO_ENDPOINTS["worklogs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updatedAt",
+ )
+ assert params == {"limit": PAGE_SIZE, "orderBy": "UPDATED"}
+
+ def test_worklogs_full_refresh_keeps_order_by_matching_sort_mode(self) -> None:
+ # sort_mode is declared "desc" statically, so the request must always order by UPDATED.
+ params = _build_initial_params(
+ TEMPO_ENDPOINTS["worklogs"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert params == {"limit": PAGE_SIZE, "orderBy": "UPDATED"}
+
+ @parameterized.expand(
+ [("wrong_field", "worklogs", "createdAt"), ("no_incremental_support", "accounts", "updatedAt")]
+ )
+ def test_rejects_unsupported_incremental_field(self, _name: str, endpoint: str, field: str) -> None:
+ with pytest.raises(ValueError, match="does not support incremental field"):
+ _build_initial_params(
+ TEMPO_ENDPOINTS[endpoint],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 1, tzinfo=UTC),
+ incremental_field=field,
+ )
+
+ def test_plans_sends_required_date_window(self) -> None:
+ params = _build_initial_params(
+ TEMPO_ENDPOINTS["plans"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert params["limit"] == PAGE_SIZE
+ assert params["from"] == "2001-01-01"
+ # Plans can extend into the future, so the window must end well past today.
+ assert date.fromisoformat(params["to"]) > date.today()
+
+ def test_unpaginated_endpoint_sends_no_params(self) -> None:
+ params = _build_initial_params(
+ TEMPO_ENDPOINTS["holiday_schemes"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert params == {}
+
+
+class TestFormatUpdatedFrom:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 1, 12, 30, 45, tzinfo=UTC), "2026-03-01T12:30:45Z"),
+ (
+ "non_utc_datetime",
+ datetime(2026, 3, 1, 14, 30, 45, tzinfo=timezone(timedelta(hours=2))),
+ "2026-03-01T12:30:45Z",
+ ),
+ ("naive_datetime", datetime(2026, 3, 1, 12, 30, 45), "2026-03-01T12:30:45Z"),
+ ("date", date(2026, 3, 1), "2026-03-01"),
+ ("string_passthrough", "2026-03-01T12:30:45Z", "2026-03-01T12:30:45Z"),
+ ]
+ )
+ def test_formats(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_updated_from(value) == expected
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str, tuple[list[dict], str | None]],
+ endpoint: str = "accounts",
+ **source_kwargs: Any,
+ ) -> tuple[list[dict], list[tuple[str, Any]]]:
+ calls: list[tuple[str, Any]] = []
+
+ def fake_fetch(session: Any, url: str, params: Any, logger: Any) -> tuple[list[dict], str | None]:
+ calls.append((url, params))
+ return pages[url]
+
+ monkeypatch.setattr(tempo, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(tempo, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="tempo-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ should_use_incremental_field=source_kwargs.get("should_use_incremental_field", False),
+ db_incremental_field_last_value=source_kwargs.get("db_incremental_field_last_value"),
+ incremental_field=source_kwargs.get("incremental_field"),
+ ):
+ rows.extend(batch)
+ return rows, calls
+
+ def test_single_page_without_next_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first_url = f"{TEMPO_BASE_URL}/accounts"
+ rows, _ = self._collect(manager, monkeypatch, {first_url: ([{"id": 1}, {"id": 2}], None)})
+ assert rows == [{"id": 1}, {"id": 2}]
+ # No next page, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_next_url_without_resending_params(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first_url = f"{TEMPO_BASE_URL}/accounts"
+ next_url = f"{TEMPO_BASE_URL}/accounts?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+ pages = {first_url: ([{"id": 1}], next_url), next_url: ([{"id": 2}], None)}
+ rows, calls = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": 1}, {"id": 2}]
+ # The first request carries built params; the next-page URL already embeds them.
+ assert calls[0] == (first_url, {"limit": PAGE_SIZE})
+ assert calls[1] == (next_url, None)
+ assert [s.next_url for s in manager.saved] == [next_url]
+
+ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:
+ next_url = f"{TEMPO_BASE_URL}/accounts?limit={PAGE_SIZE}&offset={PAGE_SIZE}"
+ manager = _FakeResumableManager(TempoResumeConfig(next_url=next_url))
+ # The initial page must never be fetched on resume.
+ rows, calls = self._collect(manager, monkeypatch, {next_url: ([{"id": 5}], None)})
+ assert rows == [{"id": 5}]
+ assert calls == [(next_url, None)]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ first_url = f"{TEMPO_BASE_URL}/accounts"
+ rows, _ = self._collect(manager, monkeypatch, {first_url: ([], None)})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_off_host_resume_state_is_rejected(self, monkeypatch: Any) -> None:
+ # Resume state is persisted outside the process; a poisoned next_url must not receive the
+ # credentialed request.
+ bad_url = "https://evil.example.com/4/accounts?offset=100"
+ manager = _FakeResumableManager(TempoResumeConfig(next_url=bad_url))
+ with pytest.raises(ValueError, match="does not stay on the Tempo API host"):
+ self._collect(manager, monkeypatch, {bad_url: ([], None)})
+
+
+class TestFetchPage:
+ def _session_returning(
+ self, status_code: int, body: Any = None, url: str = f"{TEMPO_BASE_URL}/worklogs", reason: str = "Error"
+ ) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"results": [], "metadata": {"count": 0}}
+ response.text = ""
+ response.url = url
+ response.reason = reason
+ 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(TempoRetryableError):
+ _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+
+ def test_http_error_message_strips_query_string_and_keeps_stable_prefix(self) -> None:
+ # The message becomes the schema's latest_error, so it must not embed query params and it
+ # must keep the prefix get_non_retryable_errors() matches on.
+ session = self._session_returning(
+ 401, url=f"{TEMPO_BASE_URL}/worklogs?limit=100&updatedFrom=2026-03-01", reason="Unauthorized"
+ )
+ with pytest.raises(
+ requests.HTTPError, match=r"^401 Client Error: Unauthorized for url: https://api\.tempo\.io/4/worklogs$"
+ ):
+ _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+
+ def test_off_host_next_url_is_rejected(self) -> None:
+ # metadata.next is server-controlled and the session carries the Bearer token, so a next
+ # URL pointing off the Tempo API host must fail instead of being followed.
+ body = {"results": [{"id": 1}], "metadata": {"count": 1, "next": "https://evil.example.com/4/worklogs"}}
+ session = self._session_returning(200, body)
+ with pytest.raises(ValueError, match="does not stay on the Tempo API host"):
+ _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+
+ def test_success_returns_results_and_next_url(self) -> None:
+ body = {
+ "results": [{"tempoWorklogId": 1}],
+ "metadata": {"count": 1, "next": "https://api.tempo.io/4/worklogs?offset=100"},
+ }
+ session = self._session_returning(200, body)
+ results, next_url = _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+ assert results == [{"tempoWorklogId": 1}]
+ assert next_url == "https://api.tempo.io/4/worklogs?offset=100"
+
+ @parameterized.expand(
+ [
+ ("last_page_without_next", {"results": [{"id": 1}], "metadata": {"count": 1}}),
+ ("unpaginated_metadata", {"results": [{"id": 1}], "metadata": {"count": 1, "next": ""}}),
+ ]
+ )
+ def test_missing_or_empty_next_terminates(self, _name: str, body: dict) -> None:
+ session = self._session_returning(200, body)
+ _, next_url = _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/holiday-schemes", None, MagicMock())
+ assert next_url is None
+
+ @parameterized.expand(
+ [
+ ("non_dict_body", [{"id": 1}]),
+ ("missing_results_key", {"metadata": {"count": 0}}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(TempoRetryableError):
+ _fetch_page_unwrapped(session, f"{TEMPO_BASE_URL}/worklogs", None, MagicMock())
+
+
+class TestTempoSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = tempo_source(
+ api_token="tempo-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == TEMPO_ENDPOINTS[endpoint].primary_keys
+
+ def test_worklogs_response_is_desc_and_partitioned_on_created_at(self) -> None:
+ response = tempo_source(
+ api_token="tempo-token",
+ endpoint="worklogs",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.primary_keys == ["tempoWorklogId"]
+ # orderBy=UPDATED returns newest-update-first; declaring desc defers the watermark commit
+ # to sync completion, so a mid-sync crash can't skip rows.
+ assert response.sort_mode == "desc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["createdAt"]
+
+ def test_full_refresh_endpoints_are_asc_and_unpartitioned(self) -> None:
+ response = tempo_source(
+ api_token="tempo-token",
+ endpoint="accounts",
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.sort_mode == "asc"
+ assert response.partition_mode is None
+
+
+class TestCheckAccess:
+ @staticmethod
+ def _session(response: Any) -> MagicMock:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand(
+ [
+ ("ok", 200, True, 200, None),
+ ("unauthorized", 401, False, 401, None),
+ ("forbidden", 403, False, 403, None),
+ ("server_error", 500, False, 500, "Tempo returned HTTP 500"),
+ ]
+ )
+ @patch(f"{tempo.__name__}.make_tracked_session")
+ def test_status_mapping(
+ self,
+ _name: str,
+ status: int,
+ ok: bool,
+ expected_status: int,
+ expected_message: str | None,
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ mock_session.return_value = self._session(response)
+ assert check_access("tempo-token") == (expected_status, expected_message)
+
+ @patch(f"{tempo.__name__}.make_tracked_session")
+ def test_connection_error_maps_to_zero(self, mock_session: MagicMock) -> None:
+ mock_session.return_value = self._session(requests.ConnectionError("boom"))
+ status, message = check_access("tempo-token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+ @parameterized.expand(
+ [
+ ("ok_no_endpoint", 200, None, (True, None)),
+ ("unauthorized", 401, None, (False, "Invalid Tempo API token")),
+ # A 403 at source-create still proves the token is genuine — Tempo tokens are scoped.
+ ("forbidden_at_create", 403, None, (True, None)),
+ (
+ "forbidden_for_schema",
+ 403,
+ "teams",
+ (False, "Your Tempo API token is missing the view scope for 'teams'"),
+ ),
+ ("server_error", 500, None, (False, "Tempo returned HTTP 500")),
+ ]
+ )
+ @patch(f"{tempo.__name__}.make_tracked_session")
+ def test_validate_credentials(
+ self,
+ _name: str,
+ status: int,
+ endpoint: str | None,
+ expected: tuple[bool, str | None],
+ mock_session: MagicMock,
+ ) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = status < 400
+ mock_session.return_value = self._session(response)
+ assert validate_credentials("tempo-token", endpoint=endpoint) == expected
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo_source.py
new file mode 100644
index 000000000000..029beae00945
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tempo/tests/test_tempo_source.py
@@ -0,0 +1,168 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TempoSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.source import TempoSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.tempo.tempo import TempoResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestTempoSource:
+ def setup_method(self) -> None:
+ self.source = TempoSource()
+ self.team_id = 123
+ self.config = TempoSourceConfig(api_token="tempo-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.TEMPO
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "Tempo"
+ assert config.label == "Tempo"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/tempo"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_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_token")
+ 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 token; the base URL is hardcoded, so there is no
+ # non-secret field an editor could retarget to reuse a preserved token elsewhere.
+ 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(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_worklogs_supports_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas["worklogs"].supports_incremental is True
+ assert [f["field"] for f in schemas["worklogs"].incremental_fields] == ["updatedAt"]
+ for name, schema in schemas.items():
+ if name != "worklogs":
+ assert schema.supports_incremental is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["worklogs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "worklogs"
+
+ 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 = {t["name"]: t for t in self.source.get_documented_tables()}
+ assert set(tables) == set(ENDPOINTS)
+ assert "Incremental" in tables["worklogs"]["sync_methods"]
+ assert tables["accounts"]["sync_methods"] == ["Full refresh"]
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.tempo.io/4/worklogs?limit=100"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.tempo.io/4/teams?limit=100"),
+ ]
+ )
+ 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://api.tempo.io/4/worklogs"),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.tempo.io/4/teams"),
+ ]
+ )
+ 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([("at_create", None), ("for_schema", "worklogs")])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tempo.source.validate_credentials")
+ def test_validate_credentials_delegates_with_token_and_schema(
+ self, _name: str, schema_name: str | None, mock_validate: mock.MagicMock
+ ) -> None:
+ # The status-to-message mapping lives in tempo.validate_credentials; here we only assert the
+ # source probes with the configured token/schema and returns the delegate's verdict unchanged.
+ mock_validate.return_value = (False, "Invalid Tempo API token")
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ mock_validate.assert_called_once_with("tempo-token", endpoint=schema_name)
+ assert result == (False, "Invalid Tempo API token")
+
+ def test_validate_credentials_rejects_unknown_schema(self) -> None:
+ valid, message = self.source.validate_credentials(self.config, self.team_id, schema_name="nope")
+ assert valid is False
+ assert message is not None and "nope" in message
+
+ @parameterized.expand(
+ [
+ # Only a real denial marks a missing scope — transient failures must not block the table.
+ ("forbidden", 403, "Your Tempo API token is missing the view scope for 'teams'"),
+ ("unauthorized", 401, "Invalid Tempo API token"),
+ ("reachable", 200, None),
+ ("server_error", 500, None),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tempo.source.check_access")
+ def test_get_endpoint_permissions(
+ self, _name: str, status: int, expected_reason: str | None, mock_check: mock.MagicMock
+ ) -> None:
+ mock_check.return_value = (status, None)
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["teams"])
+ assert permissions == {"teams": expected_reason}
+
+ def test_get_endpoint_permissions_unknown_endpoint_is_not_probed(self) -> None:
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.tempo.source.check_access"
+ ) as mock_check:
+ permissions = self.source.get_endpoint_permissions(self.config, self.team_id, ["nope"])
+ assert permissions == {"nope": None}
+ mock_check.assert_not_called()
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TempoResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.tempo.source.tempo_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "worklogs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-03-01T12:30:45Z"
+ inputs.incremental_field = "updatedAt"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "tempo-token"
+ assert kwargs["endpoint"] == "worklogs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-03-01T12:30:45Z"
+ assert kwargs["incremental_field"] == "updatedAt"
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown Tempo schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)