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 everhour import source (#66757)

Tom Owers1a26b252061f
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 66f636b44dd3..16948091588f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -109,6 +109,7 @@ the row lists both.
| elasticsearch | HTTP | requests | ✅ |
| emailoctopus | HTTP | requests | ✅ |
| eventbrite | HTTP | requests | ✅ |
+| everhour | HTTP | requests | ✅ |
| fillout | HTTP | requests + `rest_source.RESTClient` | ✅ |
| front | HTTP | requests | ✅ |
| fullstory | HTTP | requests | ✅ |
@@ -381,7 +382,6 @@ doesn't conflict with concurrent PRs.
- encharge
- eventee
- eventzilla
-- everhour
- exchange_rates_api
- expensify
- ezofficeinventory
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py
new file mode 100644
index 000000000000..5452be8e5056
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/canonical_descriptions.py
@@ -0,0 +1,84 @@
+"""Canonical, documentation-sourced descriptions for Everhour endpoints and columns.
+
+Sourced from the official Everhour API reference (https://everhour.docs.apiary.io/). Keyed by the
+endpoint names in `settings.py` `EVERHOUR_ENDPOINTS`, which match the `ExternalDataSchema.name` of a
+synced Everhour table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://everhour.docs.apiary.io/"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "clients": {
+ "description": "A client (customer) in the Everhour account that projects can be associated with.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the client.",
+ "name": "Name of the client.",
+ "projects": "Project ids associated with this client.",
+ "businessDetails": "Free-form billing/business details stored for the client.",
+ "createdAt": "When the client was created.",
+ },
+ },
+ "projects": {
+ "description": "A project tracked in Everhour, including its budget settings and total tracked time.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the project. Integration projects are prefixed (e.g. 'as:' for Asana, 'tr:' for Trello).",
+ "name": "Name of the project.",
+ "type": "Project type (e.g. 'board') or the integration platform it originates from.",
+ "workspaceId": "Identifier of the workspace the project belongs to.",
+ "status": "Project status (e.g. 'open', 'archived').",
+ "billing": "Billing configuration for the project (type and rate).",
+ "budget": "Budget configuration for the project.",
+ "client": "Identifier of the client the project belongs to, if any.",
+ "createdAt": "When the project was created.",
+ },
+ },
+ "users": {
+ "description": "A member of the Everhour team.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "Display name of the user.",
+ "email": "Email address of the user.",
+ "role": "Role of the user within the team (e.g. 'admin', 'member').",
+ "status": "Account status of the user (e.g. 'active', 'invited', 'removed').",
+ "rate": "Configured billing/cost rate for the user.",
+ "capacity": "Weekly work capacity configured for the user, in seconds.",
+ },
+ },
+ "tasks": {
+ "description": "A task within a project. Fanned out over every project, with the parent project id injected as `project_id`.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the task. Integration tasks are prefixed (e.g. 'as:' for Asana, 'jira:' for Jira).",
+ "project_id": "Identifier of the parent project this task row was fetched under (injected by the connector).",
+ "name": "Name of the task.",
+ "type": "Task type (e.g. 'task').",
+ "status": "Task status (e.g. 'open', 'completed').",
+ "projects": "Project ids the task belongs to.",
+ "time": "Tracked time totals for the task, in seconds.",
+ "estimate": "Time estimate configured for the task.",
+ "labels": "Labels/tags applied to the task.",
+ "createdAt": "When the task was created.",
+ },
+ },
+ "time_records": {
+ "description": "Individual time entries logged against tasks. Supports incremental sync via the server-side from/to date window.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "id": "Unique identifier for the time record.",
+ "date": "Calendar date the time was logged for (YYYY-MM-DD).",
+ "time": "Duration logged, in seconds.",
+ "user": "The user who logged the time (nested object with id, name, avatar).",
+ "task": "The task the time was logged against (nested object with id, name and its projects).",
+ "comment": "Optional free-text comment on the time record.",
+ "isLocked": "Whether the time record is locked from further edits.",
+ "createdAt": "When the time record was created.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md
new file mode 100644
index 000000000000..36be3f4463cc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.com-doc.md
@@ -0,0 +1,75 @@
+<!--
+This is the user-facing posthog.com documentation for the Everhour source.
+
+There is no posthog.com checkout in this environment, so it cannot be placed at its final
+location here. Copy this file (without this comment block) to:
+
+ posthog.com/contents/docs/cdp/sources/everhour.md
+
+Then run, from the posthog repo:
+
+ python manage.py audit_source_docs --docs-dir ../posthog.com/contents/docs/cdp/sources
+-->
+
+---
+
+title: Linking Everhour as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Everhour
+beta: true
+
+---
+
+import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"
+import SyncModes from "../\_snippets/sync-modes.mdx"
+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"
+import AlphaRelease from "../\_snippets/alpha-release.mdx"
+
+<AlphaRelease />
+
+[Everhour](https://everhour.com) is a time-tracking, budgeting, and resource-planning tool for teams. This source syncs your Everhour clients, projects, tasks, team members, and time records into the PostHog data warehouse so you can join time-tracking data with your product and revenue data.
+
+## Prerequisites
+
+Using the Everhour API requires a **paid Everhour plan**. You'll need your personal API key, which you can find in your [Everhour profile settings](https://app.everhour.com/#/account/profile) under the API section.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+You'll need your Everhour **API key**:
+
+1. Sign in to [Everhour](https://app.everhour.com).
+2. Open your [profile settings](https://app.everhour.com/#/account/profile).
+3. Copy the key from the **API** section.
+
+Paste the key into the API key field when connecting the source in PostHog. The key is sent only over the `X-Api-Key` header to `https://api.everhour.com`.
+
+## Sync modes
+
+<SyncModes />
+
+Most Everhour reference tables (clients, projects, users, tasks) have no server-side change timestamp, so they sync as **full refresh**. **Time records** support incremental sync: PostHog uses Everhour's server-side `from`/`to` date window to pull only entries on or after the last synced date.
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+A few notes:
+
+- **Time values are in seconds.** The `time` field on time records and tasks is a duration in seconds (e.g. `3600` is one hour).
+- **Tasks are fanned out per project.** Each task row carries the parent `project_id` it was fetched under, and the primary key is `(project_id, id)` because a task can belong to more than one project.
+- **Integration IDs are prefixed.** Projects and tasks imported from integrations use a prefixed id (e.g. `as:` for Asana, `jira:` for Jira, `tr:` for Trello).
+
+## Troubleshooting
+
+- **Invalid API key** — if the connection fails to validate, regenerate your key in your Everhour profile settings and reconnect. The key requires a paid Everhour plan.
+- **Rate limits** — Everhour rate-limits at roughly 20 requests per 10 seconds per API key. PostHog automatically honors the `Retry-After` header and backs off, so large initial syncs of time records may take a while to complete.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py
new file mode 100644
index 000000000000..ef2d206701ca
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/everhour.py
@@ -0,0 +1,309 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+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.everhour.settings import (
+ EVERHOUR_ENDPOINTS,
+ EverhourEndpointConfig,
+)
+
+EVERHOUR_BASE_URL = "https://api.everhour.com"
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Defensive cap so a buggy/ignored offset param can't loop forever. 50k pages * 50 rows is far more
+# than any real account holds; reaching it is logged as a warning.
+MAX_PAGES_PER_URL = 50_000
+# First sync lower bound for the /time-records date window. Everhour launched in 2015, so this
+# captures effectively all history while still giving the API a concrete `from` (it otherwise
+# defaults to returning only today's records).
+EARLIEST_FROM_DATE = "2015-01-01"
+
+# Matches the parent project id in a fan-out tasks URL: /projects/{project_id}/tasks
+_PROJECT_ID_RE = re.compile(r"/projects/([^/?]+)/tasks")
+
+
+class EverhourRetryableError(Exception):
+ pass
+
+
+class EverhourResumeConfig:
+ # Base request URLs (with limit + from/to baked in, but no offset) not yet started. For fan-out
+ # endpoints there's one per project; for top-level endpoints just the single list URL.
+ remaining_urls: list[str]
+ # The base URL currently being paginated, or None when finished.
+ current_url: Optional[str]
+ # Offset into ``current_url`` for the next page to fetch.
+ current_offset: int = 0
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "X-Api-Key": api_key,
+ "Accept": "application/json",
+ }
+
+
+def _make_session(api_key: str) -> requests.Session:
+ """Tracked session for Everhour requests.
+
+ `redact_values=(api_key,)` masks the credential everywhere it could surface in logged URLs
+ or captured samples. `allow_redirects=False` keeps the static `X-Api-Key` header pinned to the
+ validated `https://api.everhour.com` origin so a 30x can't replay it cross-origin.
+ """
+ return make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+
+
+def _with_query(path_or_url: str, params: dict[str, Any]) -> str:
+ """Append query params to a path/URL that may already carry a query string."""
+ clean = {key: value for key, value in params.items() if value is not None}
+ base = path_or_url if path_or_url.startswith("http") else f"{EVERHOUR_BASE_URL}{path_or_url}"
+ if not clean:
+ return base
+ separator = "&" if "?" in base else "?"
+ return f"{base}{separator}{urlencode(clean)}"
+
+
+def _format_date(value: Any) -> str:
+ """Format an incremental cursor value as the YYYY-MM-DD Everhour expects."""
+ if isinstance(value, datetime):
+ return value.astimezone(UTC).date().isoformat() if value.tzinfo else value.date().isoformat()
+ if isinstance(value, date):
+ return value.isoformat()
+ # Already a string cursor (e.g. "2026-03-04") — pass through.
+ return str(value)
+
+
+def _time_records_window(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, str]:
+ """Build the from/to date window for /time-records.
+
+ On the first sync (or full refresh) we span all history; on an incremental sync we floor `from`
+ to the watermark's day. Re-querying the whole watermark day each sync is intentional — the boundary
+ rows are re-pulled and deduped by primary key on merge, so no edits on that day are missed.
+ """
+ if should_use_incremental_field and db_incremental_field_last_value:
+ from_date = _format_date(db_incremental_field_last_value)
+ else:
+ from_date = EARLIEST_FROM_DATE
+ return {"from": from_date, "to": datetime.now(UTC).date().isoformat()}
+
+
+@retry(
+ retry=retry_if_exception_type((EverhourRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ url: str, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> list[dict[str, Any]]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Everhour rate-limits at ~20 req / 10s per key and returns 429 with a Retry-After header;
+ # exponential backoff is sufficient and avoids parsing the header here. 5xx is also transient.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise EverhourRetryableError(f"Everhour API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Everhour API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Everhour list endpoints return a bare JSON array; anything else (an error envelope with a
+ # 200, or a future API change) would otherwise be swallowed as an empty page and stop pagination.
+ if not isinstance(data, list):
+ logger.warning(f"Everhour: expected list response, got {type(data).__name__} for url={url}")
+ return []
+ return data
+
+
+def _build_base_url(config: EverhourEndpointConfig, window: dict[str, str] | None) -> str:
+ params: dict[str, Any] = {"limit": config.page_size}
+ if window:
+ params.update(window)
+ return _with_query(config.path_template, params)
+
+
+def _iter_all_items(
+ base_url: str, page_size: int, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> Iterator[dict[str, Any]]:
+ """Fully paginate one base URL via limit/offset, yielding individual records (used for discovery)."""
+ offset = 0
+ for _ in range(MAX_PAGES_PER_URL):
+ items = _fetch_page(_with_query(base_url, {"offset": offset}), headers, logger, session)
+ yield from items
+ if len(items) < page_size:
+ return
+ offset += page_size
+ logger.warning(f"Everhour: hit max page cap while paginating {base_url}")
+
+
+def _build_initial_urls(
+ config: EverhourEndpointConfig,
+ window: dict[str, str] | None,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ session: requests.Session,
+) -> list[str]:
+ """Resolve the set of base request URLs for an endpoint, fanning out over projects as needed."""
+ if config.fan_out == "none":
+ return [_build_base_url(config, window)]
+
+ if config.fan_out == "project":
+ projects_config = EVERHOUR_ENDPOINTS["projects"]
+ projects_url = _build_base_url(projects_config, None)
+ return [
+ _with_query(config.path_template.format(project_id=project["id"]), {"limit": config.page_size})
+ for project in _iter_all_items(projects_url, projects_config.page_size, headers, logger, session)
+ ]
+
+ raise ValueError(f"Unknown fan_out mode: {config.fan_out}")
+
+
+def _parent_project_id(url: str) -> Optional[str]:
+ match = _PROJECT_ID_RE.search(url)
+ return match.group(1) if match else None
+
+
+def validate_credentials(api_key: str) -> bool:
+ """Confirm the API key is valid. /users/me needs only a genuine key, no extra permissions."""
+ try:
+ response = _make_session(api_key).get(
+ f"{EVERHOUR_BASE_URL}/users/me",
+ headers=_get_headers(api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EverhourResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = EVERHOUR_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session for the whole run so pagination and fan-out reuse pooled connections.
+ session = _make_session(api_key)
+
+ window = (
+ _time_records_window(should_use_incremental_field, db_incremental_field_last_value)
+ if config.supports_date_window
+ else None
+ )
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ remaining = list(resume_config.remaining_urls)
+ current = resume_config.current_url
+ offset = resume_config.current_offset
+ logger.debug(f"Everhour: resuming {endpoint} from url={current}, offset={offset}")
+ else:
+ remaining = _build_initial_urls(config, window, headers, logger, session)
+ current = remaining.pop(0) if remaining else None
+ offset = 0
+
+ # The same id only repeats within a base URL when the API ignores `offset`; tracking ids per
+ # URL lets us stop instead of looping forever on the first page.
+ seen_ids: set[Any] = set()
+ pages_on_current = 0
+
+ while current is not None:
+ items = _fetch_page(_with_query(current, {"offset": offset}), headers, logger, session)
+ pages_on_current += 1
+
+ new_items = [item for item in items if item["id"] not in seen_ids]
+ seen_ids.update(item["id"] for item in new_items)
+
+ if config.include_parent_id_as:
+ parent_id = _parent_project_id(current)
+ for item in new_items:
+ item[config.include_parent_id_as] = parent_id
+
+ # A full page of genuinely new rows means there may be more; a short page (or one that
+ # surfaced no new ids, i.e. offset was ignored) ends this URL.
+ would_continue = len(items) >= config.page_size and len(new_items) > 0
+ if would_continue and pages_on_current >= MAX_PAGES_PER_URL:
+ logger.warning(f"Everhour: hit max page cap while paginating {current}")
+ has_more = would_continue and pages_on_current < MAX_PAGES_PER_URL
+
+ if has_more:
+ new_remaining = remaining
+ new_current: Optional[str] = current
+ new_offset = offset + config.page_size
+ elif remaining:
+ new_remaining = remaining[1:]
+ new_current = remaining[0]
+ new_offset = 0
+ else:
+ new_remaining = []
+ new_current = None
+ new_offset = 0
+
+ if new_current != current:
+ seen_ids = set()
+ pages_on_current = 0
+
+ if new_items:
+ yield new_items
+
+ # Save AFTER yielding (and only while there's more to fetch) so a crash re-yields the last
+ # batch — merge dedupes on the primary key — rather than skipping it.
+ if new_current is not None:
+ resumable_source_manager.save_state(
+ EverhourResumeConfig(remaining_urls=new_remaining, current_url=new_current, current_offset=new_offset)
+ )
+
+ remaining = new_remaining
+ current = new_current
+ offset = new_offset
+
+
+def everhour_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[EverhourResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = EVERHOUR_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=config.partition_format if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # /time-records is returned in ascending date order; the reference endpoints are full refresh
+ # so ordering is immaterial for them.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py
new file mode 100644
index 000000000000..127ad3d3764d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/settings.py
@@ -0,0 +1,83 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# How an endpoint's request URLs are derived:
+# "none" -> a single top-level list endpoint (no parent fan-out)
+# "project" -> one request per project (fan out over /projects)
+FanOut = Literal["none", "project"]
+
+
+@dataclass
+class EverhourEndpointConfig:
+ name: str
+ fan_out: FanOut
+ # Relative path appended to the API base. Fan-out task paths carry a single ``{project_id}``
+ # placeholder (the parent project id); top-level paths have no placeholder.
+ path_template: str
+ # Everhour caps most list endpoints at a small page size and paginates with limit/offset.
+ # /time-records is capped at 50 per page; the reference endpoints comfortably take 100.
+ page_size: int = 100
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation/work-date field used for datetime partitioning. Never an "updated_at"-style
+ # field — partitions would rewrite on every sync.
+ partition_key: Optional[str] = None
+ partition_format: Literal["month", "week", "day", "hour"] = "month"
+ # When set, the endpoint accepts ``from``/``to`` (YYYY-MM-DD) date-range filters, enabling
+ # server-side date-windowed incremental sync.
+ supports_date_window: bool = False
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # For fan-out endpoints: inject the parent project id into each row under this key, so the
+ # composite primary key stays unique table-wide (a task can belong to multiple projects).
+ include_parent_id_as: Optional[str] = None
+ # Whether the table is selected for sync by default in the UI.
+ should_sync_default: bool = True
+
+
+EVERHOUR_ENDPOINTS: dict[str, EverhourEndpointConfig] = {
+ "clients": EverhourEndpointConfig(
+ name="clients",
+ fan_out="none",
+ path_template="/clients",
+ ),
+ "projects": EverhourEndpointConfig(
+ name="projects",
+ fan_out="none",
+ path_template="/projects",
+ ),
+ "users": EverhourEndpointConfig(
+ name="users",
+ fan_out="none",
+ path_template="/team/users",
+ ),
+ "tasks": EverhourEndpointConfig(
+ name="tasks",
+ fan_out="project",
+ path_template="/projects/{project_id}/tasks",
+ primary_keys=["project_id", "id"],
+ include_parent_id_as="project_id",
+ ),
+ "time_records": EverhourEndpointConfig(
+ name="time_records",
+ fan_out="none",
+ path_template="/time-records",
+ page_size=50, # /time-records caps the page size at 50
+ partition_key="date",
+ supports_date_window=True,
+ incremental_fields=[
+ {
+ "label": "date",
+ "type": IncrementalFieldType.Date,
+ "field": "date",
+ "field_type": IncrementalFieldType.Date,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(EVERHOUR_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in EVERHOUR_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/source.py
index 517ed8989c66..e0a648de5294 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/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.everhour.everhour import (
+ EverhourResumeConfig,
+ everhour_source,
+ validate_credentials as validate_everhour_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.settings import (
+ ENDPOINTS,
+ EVERHOUR_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EverhourSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class EverhourSource(SimpleSource[EverhourSourceConfig]):
+class EverhourSource(ResumableSource[EverhourSourceConfig, EverhourResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.EVERHOUR
@@ -24,7 +48,94 @@ class EverhourSource(SimpleSource[EverhourSourceConfig]):
name=SchemaExternalDataSourceType.EVERHOUR,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Everhour",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Everhour API key to pull your Everhour time-tracking data into the PostHog Data warehouse.
+
+You can find your API key in your [Everhour profile settings](https://app.everhour.com/#/account/profile) under the API section.
+
+Using the API requires a paid Everhour plan.""",
iconPath="/static/services/everhour.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/everhour",
+ 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.everhour.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
+ # Retrying can never satisfy a credential problem, so stop the sync. Match the stable
+ # status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.everhour.com": "Your Everhour API key is invalid or has been revoked. Generate a new key in your Everhour profile settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.everhour.com": "Your Everhour API key does not have permission to access this data. Check the key's permissions in Everhour, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: EverhourSourceConfig,
+ 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 = EVERHOUR_ENDPOINTS[endpoint]
+ has_incremental = INCREMENTAL_FIELDS.get(endpoint) 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: EverhourSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_everhour_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Everhour API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[EverhourResumeConfig]:
+ return ResumableSourceManager[EverhourResumeConfig](inputs, EverhourResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: EverhourSourceConfig,
+ resumable_source_manager: ResumableSourceManager[EverhourResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return everhour_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/everhour/tests/test_everhour.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
new file mode 100644
index 000000000000..1408444feae3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour.py
@@ -0,0 +1,286 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from freezegun import freeze_time
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.everhour import (
+ EARLIEST_FROM_DATE,
+ EVERHOUR_BASE_URL,
+ EverhourResumeConfig,
+ _build_initial_urls,
+ _format_date,
+ _parent_project_id,
+ _time_records_window,
+ _with_query,
+ everhour_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.settings import (
+ ENDPOINTS,
+ EVERHOUR_ENDPOINTS,
+)
+
+EVERHOUR_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.everhour.everhour"
+
+
+def _make_manager(resume_state: Optional[EverhourResumeConfig] = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _items(start: int, count: int) -> list[dict[str, Any]]:
+ return [{"id": i} for i in range(start, start + count)]
+
+
+class TestWithQuery:
+ def test_appends_with_question_mark_when_no_existing_query(self) -> None:
+ assert _with_query("/clients", {"limit": 100}) == f"{EVERHOUR_BASE_URL}/clients?limit=100"
+
+ def test_appends_with_ampersand_when_query_present(self) -> None:
+ url = _with_query("/time-records?limit=50", {"offset": 50})
+ assert url == f"{EVERHOUR_BASE_URL}/time-records?limit=50&offset=50"
+
+ def test_drops_none_values(self) -> None:
+ assert _with_query("/clients", {"limit": None}) == f"{EVERHOUR_BASE_URL}/clients"
+
+ def test_accepts_full_url(self) -> None:
+ url = _with_query(f"{EVERHOUR_BASE_URL}/projects/5/tasks?limit=100", {"offset": 100})
+ assert url == f"{EVERHOUR_BASE_URL}/projects/5/tasks?limit=100&offset=100"
+
+
+class TestFormatDate:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (date(2026, 3, 4), "2026-03-04"),
+ (datetime(2026, 3, 4, 23, 30, tzinfo=UTC), "2026-03-04"),
+ (datetime(2026, 3, 4, 12, 0), "2026-03-04"),
+ ("2026-03-04", "2026-03-04"),
+ ],
+ )
+ def test_format_date(self, value: Any, expected: str) -> None:
+ assert _format_date(value) == expected
+
+
+class TestTimeRecordsWindow:
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_first_sync_spans_all_history(self) -> None:
+ window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
+ assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_full_refresh_spans_all_history(self) -> None:
+ window = _time_records_window(should_use_incremental_field=False, db_incremental_field_last_value=None)
+ assert window == {"from": EARLIEST_FROM_DATE, "to": "2026-06-15"}
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_incremental_floors_from_to_watermark_day(self) -> None:
+ window = _time_records_window(
+ should_use_incremental_field=True, db_incremental_field_last_value=date(2026, 5, 1)
+ )
+ assert window == {"from": "2026-05-01", "to": "2026-06-15"}
+
+
+class TestParentProjectId:
+ def test_extracts_project_id(self) -> None:
+ assert _parent_project_id(f"{EVERHOUR_BASE_URL}/projects/123/tasks?limit=100&offset=0") == "123"
+
+ def test_extracts_prefixed_project_id(self) -> None:
+ assert _parent_project_id(f"{EVERHOUR_BASE_URL}/projects/as:99/tasks?limit=100") == "as:99"
+
+ def test_returns_none_for_non_task_url(self) -> None:
+ assert _parent_project_id(f"{EVERHOUR_BASE_URL}/clients?limit=100") is None
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials("key") is expected
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ def test_uses_users_me_probe(self, mock_session: mock.MagicMock) -> None:
+ response = mock.MagicMock(status_code=200)
+ mock_session.return_value.get.return_value = response
+ validate_credentials("key")
+ assert mock_session.return_value.get.call_args.args[0] == f"{EVERHOUR_BASE_URL}/users/me"
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ def test_swallows_exceptions(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestBuildInitialUrls:
+ def test_top_level_endpoint_yields_single_url(self) -> None:
+ urls = _build_initial_urls(EVERHOUR_ENDPOINTS["clients"], None, {}, mock.MagicMock(), mock.MagicMock())
+ assert urls == [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_time_records_bakes_in_date_window(self) -> None:
+ window = _time_records_window(should_use_incremental_field=True, db_incremental_field_last_value=None)
+ urls = _build_initial_urls(EVERHOUR_ENDPOINTS["time_records"], window, {}, mock.MagicMock(), mock.MagicMock())
+ assert len(urls) == 1
+ assert "limit=50" in urls[0]
+ assert f"from={EARLIEST_FROM_DATE}" in urls[0]
+ assert "to=2026-06-15" in urls[0]
+
+ @mock.patch(f"{EVERHOUR_MODULE}._iter_all_items")
+ def test_project_fan_out_one_url_per_project(self, mock_iter_items: mock.MagicMock) -> None:
+ mock_iter_items.return_value = iter([{"id": "p1"}, {"id": "p2"}])
+ urls = _build_initial_urls(EVERHOUR_ENDPOINTS["tasks"], None, {}, mock.MagicMock(), mock.MagicMock())
+ assert urls == [
+ f"{EVERHOUR_BASE_URL}/projects/p1/tasks?limit=100",
+ f"{EVERHOUR_BASE_URL}/projects/p2/tasks?limit=100",
+ ]
+
+
+class TestGetRows:
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_single_page_short_stop(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ mock_build_urls.return_value = [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
+ mock_fetch.return_value = _items(0, 3) # < page_size, single page
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "clients", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == [0, 1, 2]
+ assert mock_fetch.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_offset_pagination_advances(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ mock_build_urls.return_value = [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
+ # Full first page (100 rows) -> there may be more; short second page -> stop.
+ mock_fetch.side_effect = [_items(0, 100), _items(100, 5)]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "clients", mock.MagicMock(), manager))
+
+ ids = [item["id"] for batch in batches for item in batch]
+ assert ids == list(range(105))
+ # Second fetch must request offset=100.
+ assert "offset=100" in mock_fetch.call_args_list[1].args[0]
+ # State saved once after the first (non-terminal) page, pointing at offset 100.
+ saved = manager.save_state.call_args.args[0]
+ assert saved.current_offset == 100
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_ignored_offset_does_not_loop_forever(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ # The API ignores `offset` and returns the same full page every time. The seen-id guard must
+ # treat a page with no new ids as terminal rather than looping.
+ mock_build_urls.return_value = [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
+ mock_fetch.side_effect = [_items(0, 100), _items(0, 100)]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "clients", mock.MagicMock(), manager))
+
+ ids = [item["id"] for batch in batches for item in batch]
+ assert ids == list(range(100)) # only the first page's rows, no duplicates
+ assert mock_fetch.call_count == 2
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_fan_out_drains_parents_and_injects_project_id(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ mock_build_urls.return_value = [
+ f"{EVERHOUR_BASE_URL}/projects/p1/tasks?limit=100",
+ f"{EVERHOUR_BASE_URL}/projects/p2/tasks?limit=100",
+ ]
+ mock_fetch.side_effect = [[{"id": "a"}], [{"id": "b"}]]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "tasks", mock.MagicMock(), manager))
+
+ rows = [item for batch in batches for item in batch]
+ assert rows == [
+ {"id": "a", "project_id": "p1"},
+ {"id": "b", "project_id": "p2"},
+ ]
+ # After draining the first parent, state advances to the second parent URL.
+ saved = manager.save_state.call_args.args[0]
+ assert saved.current_url == f"{EVERHOUR_BASE_URL}/projects/p2/tasks?limit=100"
+ assert saved.remaining_urls == []
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_resumes_from_saved_state(self, mock_fetch: mock.MagicMock, _mock_session: mock.MagicMock) -> None:
+ mock_fetch.return_value = _items(0, 1)
+ resume_url = f"{EVERHOUR_BASE_URL}/clients?limit=100"
+ manager = _make_manager(EverhourResumeConfig(remaining_urls=[], current_url=resume_url, current_offset=200))
+
+ list(get_rows("key", "clients", mock.MagicMock(), manager))
+
+ # The first fetch must continue from the saved offset, not start over.
+ assert "offset=200" in mock_fetch.call_args_list[0].args[0]
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ @mock.patch(f"{EVERHOUR_MODULE}._fetch_page")
+ def test_empty_endpoint_yields_nothing_and_saves_nothing(
+ self, mock_fetch: mock.MagicMock, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock
+ ) -> None:
+ mock_build_urls.return_value = [f"{EVERHOUR_BASE_URL}/clients?limit=100"]
+ mock_fetch.return_value = []
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "clients", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{EVERHOUR_MODULE}.make_tracked_session")
+ @mock.patch(f"{EVERHOUR_MODULE}._build_initial_urls")
+ def test_no_urls_yields_nothing(self, mock_build_urls: mock.MagicMock, _mock_session: mock.MagicMock) -> None:
+ mock_build_urls.return_value = []
+ manager = _make_manager()
+ assert list(get_rows("key", "clients", mock.MagicMock(), manager)) == []
+ manager.save_state.assert_not_called()
+
+
+class TestEverhourSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = EVERHOUR_ENDPOINTS[endpoint]
+ response = everhour_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_time_records_partitions_on_stable_date_field(self) -> None:
+ config = EVERHOUR_ENDPOINTS["time_records"]
+ assert config.partition_key == "date"
+
+ def test_fan_out_child_key_includes_parent(self) -> None:
+ # A task can belong to multiple projects, so the project id must be part of the key to stay
+ # unique table-wide.
+ assert EVERHOUR_ENDPOINTS["tasks"].primary_keys == ["project_id", "id"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py
new file mode 100644
index 000000000000..d2cb082212d9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/everhour/tests/test_everhour_source.py
@@ -0,0 +1,158 @@
+import pytest
+from unittest import mock
+
+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.everhour.everhour import EverhourResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.everhour.source import EverhourSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import EverhourSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.everhour.source"
+
+
+class TestEverhourSource:
+ def setup_method(self) -> None:
+ self.source = EverhourSource()
+ self.team_id = 123
+ self.config = EverhourSourceConfig(api_key="ev_abc")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.EVERHOUR
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Everhour"
+ assert config.label == "Everhour"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/everhour.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/everhour"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.everhour.com/clients?limit=100",
+ "403 Client Error: Forbidden for url: https://api.everhour.com/time-records?from=2026-01-01",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://api.everhour.com/projects",
+ "HTTPSConnectionPool(host='api.everhour.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_only_time_records_is_incremental(self) -> None:
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["time_records"].supports_incremental is True
+ assert schemas["time_records"].supports_append is True
+ assert [f["field"] for f in schemas["time_records"].incremental_fields] == ["date"]
+
+ for name in ("clients", "projects", "users", "tasks"):
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["time_records"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "time_records"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas does no I/O, so the static catalog can render in public docs.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Everhour API key"),
+ ],
+ )
+ @mock.patch(f"{SOURCE_MODULE}.validate_everhour_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: bool,
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key)
+
+ 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 EverhourResumeConfig
+
+ @mock.patch(f"{SOURCE_MODULE}.everhour_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_everhour_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "time_records"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_everhour_source.assert_called_once()
+ kwargs = mock_everhour_source.call_args.kwargs
+ assert kwargs["api_key"] == "ev_abc"
+ assert kwargs["endpoint"] == "time_records"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"
+
+ @mock.patch(f"{SOURCE_MODULE}.everhour_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(
+ self, mock_everhour_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "clients"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_everhour_source.call_args.kwargs
+ assert kwargs["db_incremental_field_last_value"] is None
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 fc948e0752aa..601db1470793 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
@@ -1069,7 +1069,7 @@ class EventzillaSourceConfig(config.Config):
@config.config
class EverhourSourceConfig(config.Config):
- pass
+ api_key: str
@config.config