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 teamwork import source (#65654)

Tom Owers1ed15fc796bd
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 18e98ae7a534..d7d4f2a06323 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -184,6 +184,7 @@ the row lists both.
| supabase | DB protocol | psycopg (delegates to PostgresSource) | ➖ |
| surveymonkey | HTTP | requests | ✅ |
| taboola | HTTP | requests | ✅ |
+| teamwork | HTTP | requests | ✅ |
| temporalio | gRPC (vendor SDK) | temporalio (`Client`, Rust core via `temporalio.bridge`) | ⚠️ |
| tiktok_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| trello | HTTP | requests | ✅ |
@@ -649,7 +650,6 @@ doesn't conflict with concurrent PRs.
- systeme
- tavus
- teamtailor
-- teamwork
- tempo
- testrail
- thinkific
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 217478941c5a..f92fe07e2ed2 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -3055,7 +3055,8 @@ class TeamtailorSourceConfig(config.Config):
@config.config
class TeamworkSourceConfig(config.Config):
- pass
+ site: str
+ api_key: str
@config.config
diff --git a/posthog/temporal/data_imports/sources/teamwork/canonical_descriptions.py b/posthog/temporal/data_imports/sources/teamwork/canonical_descriptions.py
new file mode 100644
index 000000000000..52d5fc54c4a6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/teamwork/canonical_descriptions.py
@@ -0,0 +1,116 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the public Teamwork.com Projects V3 API docs (https://apidocs.teamwork.com). Partial
+# coverage is fine — any endpoint/column not listed here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "Projects in the Teamwork account, each grouping tasks, milestones, time, and people.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/v3/projects/get-projects-api-v3-projects-json",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "Name of the project.",
+ "description": "Free-text description of the project.",
+ "status": "Project status (e.g. active, archived, completed).",
+ "companyId": "Identifier of the company that owns the project.",
+ "startDate": "Scheduled start date of the project.",
+ "endDate": "Scheduled end date of the project.",
+ },
+ },
+ "tasks": {
+ "description": "Tasks across all projects the connected user can access.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/endpoints-by-object/tasks/get-projects-api-v3-tasks-json",
+ "columns": {
+ "id": "Unique identifier for the task.",
+ "name": "Name of the task.",
+ "status": "Task status (e.g. new, completed, deleted).",
+ "tasklistId": "Identifier of the task list the task belongs to.",
+ "parentTaskId": "Identifier of the parent task, when this is a subtask.",
+ "priority": "Task priority (e.g. low, medium, high).",
+ "startDate": "Date the task is scheduled to start.",
+ "dueDate": "Date the task is due.",
+ "dateUpdated": "Timestamp the task was last updated.",
+ },
+ },
+ "tasklists": {
+ "description": "Task lists, which group related tasks within a project.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/endpoints-by-object/task-lists/get-projects-api-v3-tasklists-json",
+ "columns": {
+ "id": "Unique identifier for the task list.",
+ "name": "Name of the task list.",
+ "projectId": "Identifier of the project the task list belongs to.",
+ "status": "Task list status (e.g. active, archived).",
+ "dateUpdated": "Timestamp the task list was last updated.",
+ },
+ },
+ "milestones": {
+ "description": "Milestones marking key dates and deliverables within projects.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/endpoints-by-object/milestones/get-projects-api-v3-milestones-json",
+ "columns": {
+ "id": "Unique identifier for the milestone.",
+ "name": "Name of the milestone.",
+ "projectId": "Identifier of the project the milestone belongs to.",
+ "deadline": "Date the milestone is due.",
+ "completed": "Whether the milestone has been completed.",
+ "dateCreated": "Timestamp the milestone was created.",
+ "dateUpdated": "Timestamp the milestone was last updated.",
+ },
+ },
+ "timelogs": {
+ "description": "Logged time entries across all projects and tasks.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/endpoints-by-object/time-tracking/get-projects-api-v3-time-json",
+ "columns": {
+ "id": "Unique identifier for the time entry.",
+ "projectId": "Identifier of the project the time was logged against.",
+ "taskId": "Identifier of the task the time was logged against, when applicable.",
+ "userId": "Identifier of the user who logged the time.",
+ "description": "Description of the work the time entry covers.",
+ "minutes": "Duration of the time entry in minutes.",
+ "billable": "Whether the time entry is billable.",
+ "dateCreated": "Timestamp the time entry was created.",
+ "dateEdited": "Timestamp the time entry was last edited.",
+ },
+ },
+ "people": {
+ "description": "People (users) in the Teamwork account.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/endpoints-by-object/people/get-projects-api-v3-people-json",
+ "columns": {
+ "id": "Unique identifier for the person.",
+ "firstName": "Person's first name.",
+ "lastName": "Person's last name.",
+ "email": "Person's email address.",
+ "companyId": "Identifier of the company the person belongs to.",
+ "isAdmin": "Whether the person is an account administrator.",
+ },
+ },
+ "companies": {
+ "description": "Companies (clients and the owner organization) in the Teamwork account.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/v3/companies/get-projects-api-v3-companies-json",
+ "columns": {
+ "id": "Unique identifier for the company.",
+ "name": "Name of the company.",
+ "email": "Primary email address for the company.",
+ "phone": "Primary phone number for the company.",
+ "countryCode": "Country code of the company's address.",
+ },
+ },
+ "tags": {
+ "description": "Tags used to label projects, tasks, and other entities.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/v3/tags/get-projects-api-v3-tags-json",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "name": "Name of the tag.",
+ "color": "Display color of the tag.",
+ },
+ },
+ "comments": {
+ "description": "Comments left on projects, tasks, milestones, and other entities.",
+ "docs_url": "https://apidocs.teamwork.com/docs/teamwork/v3/comments/get-projects-api-v3-comments-json",
+ "columns": {
+ "id": "Unique identifier for the comment.",
+ "body": "Text content of the comment.",
+ "authorId": "Identifier of the user who wrote the comment.",
+ "objectType": "Type of entity the comment is attached to (e.g. task, milestone).",
+ "objectId": "Identifier of the entity the comment is attached to.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/teamwork/settings.py b/posthog/temporal/data_imports/sources/teamwork/settings.py
new file mode 100644
index 000000000000..eb513f810158
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/teamwork/settings.py
@@ -0,0 +1,122 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class TeamworkEndpointConfig:
+ name: str
+ # V3 list-endpoint path, relative to https://{site}.teamwork.com/projects/api/v3
+ path: str
+ # Top-level key in the response envelope holding the array of records (e.g. {"projects": [...]}).
+ data_key: str
+ # `orderBy` value passed to the API. Rows are always requested with `orderMode=asc`.
+ # For incremental endpoints this MUST be the server's update-time sort so the cursor watermark
+ # advances monotonically; for full-refresh endpoints it's a stable created/added sort that keeps
+ # pagination from skipping/duplicating rows as data changes mid-sync. None = don't send `orderBy`.
+ order_by: Optional[str] = None
+ # Record field the incremental cursor reads (and what `updatedAfter` filters on server-side).
+ # None means the endpoint has no usable server-side update sort, so it's full refresh only.
+ incremental_field: Optional[str] = None
+ # Stable datetime field to partition by (a creation timestamp — never an update timestamp, which
+ # would rewrite partitions every sync). None = no partitioning.
+ partition_key: Optional[str] = None
+ should_sync_default: bool = True
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+def _incremental(field_name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Teamwork.com Projects V3 endpoints. Paths, response keys, and the per-endpoint `orderBy` enum were
+# taken from the public V3 API docs (https://apidocs.teamwork.com). Incremental sync is enabled only
+# where the docs confirm BOTH a server-side `updatedAfter` filter AND an ascending sort by the update
+# field; everything else ships full refresh. The exact record field names (`dateUpdated`, `dateEdited`,
+# `dateCreated`) follow the documented `fields[...]` projections and per-endpoint `orderBy` casing, but
+# could not be curl-verified against a live account — see the PR description.
+TEAMWORK_ENDPOINTS: dict[str, TeamworkEndpointConfig] = {
+ "projects": TeamworkEndpointConfig(
+ name="projects",
+ path="/projects.json",
+ data_key="projects",
+ # `projects` exposes no update-time sort (orderBy: name/datecreated/lastactivity/...), so it
+ # can't drive a safe incremental watermark — full refresh, stable-sorted by creation date.
+ order_by="datecreated",
+ ),
+ "tasks": TeamworkEndpointConfig(
+ name="tasks",
+ path="/tasks.json",
+ data_key="tasks",
+ order_by="updatedat",
+ incremental_field="dateUpdated",
+ ),
+ "tasklists": TeamworkEndpointConfig(
+ name="tasklists",
+ path="/tasklists.json",
+ data_key="tasklists",
+ order_by="updatedat",
+ incremental_field="dateUpdated",
+ ),
+ "milestones": TeamworkEndpointConfig(
+ name="milestones",
+ path="/milestones.json",
+ data_key="milestones",
+ order_by="dateUpdated",
+ incremental_field="dateUpdated",
+ partition_key="dateCreated",
+ ),
+ "timelogs": TeamworkEndpointConfig(
+ name="timelogs",
+ path="/time.json",
+ data_key="timelogs",
+ order_by="dateupdated",
+ # V3 timelogs expose the edit timestamp as `dateEdited` (there is no `dateUpdated` field on
+ # the record), while the sort enum is `dateupdated`. The cursor reads `dateEdited`.
+ incremental_field="dateEdited",
+ partition_key="dateCreated",
+ ),
+ "people": TeamworkEndpointConfig(
+ name="people",
+ path="/people.json",
+ data_key="people",
+ # `people` only sorts by name — no update sort — so full refresh.
+ order_by="name",
+ ),
+ "companies": TeamworkEndpointConfig(
+ name="companies",
+ path="/companies.json",
+ data_key="companies",
+ # No update sort available; full refresh, stable-sorted by when the company was added.
+ order_by="dateadded",
+ ),
+ "tags": TeamworkEndpointConfig(
+ name="tags",
+ path="/tags.json",
+ data_key="tags",
+ order_by="name",
+ ),
+ "comments": TeamworkEndpointConfig(
+ name="comments",
+ path="/comments.json",
+ data_key="comments",
+ # `comments` only sorts by date/project/user/type — no update sort — so full refresh.
+ order_by="date",
+ ),
+}
+
+ENDPOINTS = tuple(TEAMWORK_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: _incremental(config.incremental_field)
+ for name, config in TEAMWORK_ENDPOINTS.items()
+ if config.incremental_field is not None
+}
diff --git a/posthog/temporal/data_imports/sources/teamwork/source.py b/posthog/temporal/data_imports/sources/teamwork/source.py
index 33eba7bfaa30..ac4f93ba965f 100644
--- a/posthog/temporal/data_imports/sources/teamwork/source.py
+++ b/posthog/temporal/data_imports/sources/teamwork/source.py
@@ -1,20 +1,36 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import TeamworkSourceConfig
+from posthog.temporal.data_imports.sources.teamwork.canonical_descriptions import CANONICAL_DESCRIPTIONS
+from posthog.temporal.data_imports.sources.teamwork.settings import ENDPOINTS, INCREMENTAL_FIELDS, TEAMWORK_ENDPOINTS
+from posthog.temporal.data_imports.sources.teamwork.teamwork import (
+ TeamworkResumeConfig,
+ normalize_host,
+ teamwork_source,
+ validate_credentials as validate_teamwork_credentials,
+)
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TeamworkSource(SimpleSource[TeamworkSourceConfig]):
+class TeamworkSource(ResumableSource[TeamworkSourceConfig, TeamworkResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TEAMWORK
@@ -25,7 +41,113 @@ class TeamworkSource(SimpleSource[TeamworkSourceConfig]):
name=SchemaExternalDataSourceType.TEAMWORK,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Teamwork",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Teamwork.com site and API key to pull your Teamwork projects data into the PostHog Data warehouse.
+
+Find your API key under **Profile → Edit my details → API & Mobile** in Teamwork. The key inherits your own permissions, so it can only sync data you can see.""",
iconPath="/static/services/teamwork.png",
- fields=cast(list[FieldType], []),
+ docsUrl="https://posthog.com/docs/cdp/sources/teamwork",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="site",
+ label="Site",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="yoursite.teamwork.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API key is sent to the host derived from `site`; retargeting it must re-require the key.
+ return ["site"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Your Teamwork API key is invalid or has been revoked. Generate a new key in your Teamwork profile settings, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your Teamwork API key does not have permission to access this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: TeamworkSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=(inc := INCREMENTAL_FIELDS.get(endpoint)) is not None,
+ supports_append=inc is not None,
+ incremental_fields=inc or [],
+ should_sync_default=TEAMWORK_ENDPOINTS[endpoint].should_sync_default,
+ )
+ 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: TeamworkSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ host = normalize_host(config.site)
+
+ host_is_safe, host_error = _is_host_safe(host, team_id)
+ if not host_is_safe:
+ return False, host_error or "Teamwork site host is not allowed"
+
+ if validate_teamwork_credentials(host, config.api_key):
+ return True, None
+
+ return False, "Teamwork rejected the credentials. Check the site and API key are correct."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TeamworkResumeConfig]:
+ return ResumableSourceManager[TeamworkResumeConfig](inputs, TeamworkResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TeamworkSourceConfig,
+ resumable_source_manager: ResumableSourceManager[TeamworkResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ host = normalize_host(config.site)
+
+ # Re-check host safety at sync time, not just at source creation: `site` can be edited after
+ # validation, and every request below sends the stored API key to it — block internal/private
+ # hosts to prevent SSRF and credential redirection.
+ host_is_safe, host_error = _is_host_safe(host, inputs.team_id)
+ if not host_is_safe:
+ raise ValueError(host_error or "Teamwork site host is not allowed")
+
+ return teamwork_source(
+ host=host,
+ 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/posthog/temporal/data_imports/sources/teamwork/teamwork.py b/posthog/temporal/data_imports/sources/teamwork/teamwork.py
new file mode 100644
index 000000000000..646885a4f9dd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/teamwork/teamwork.py
@@ -0,0 +1,217 @@
+import base64
+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 posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.teamwork.settings import TEAMWORK_ENDPOINTS, TeamworkEndpointConfig
+
+# Max page size accepted by the majority of V3 endpoints.
+PAGE_SIZE = 500
+# A single V3 request is hard-capped at 50,000 records (= 100 pages of 500). We stop one run at that
+# boundary rather than letting the API error out. Incremental endpoints resume past it on the next
+# scheduled run (the cursor watermark has advanced); full-refresh endpoints can't, so we warn loudly.
+MAX_PAGES = 100
+
+
+class TeamworkRetryableError(Exception):
+ pass
+
+
+class TeamworkResumeConfig:
+ # Next 1-based page number to fetch within the current sync window.
+ page: int = 1
+ # The `updatedAfter` cursor used for this sync's window, so a resumed run rebuilds the same query.
+ updated_after: str | None = None
+
+
+def normalize_host(site: str) -> str:
+ """Turn a user-entered Teamwork site into a bare hostname.
+
+ Accepts a subdomain (``mycompany``), a full host (``mycompany.teamwork.com``), or a pasted URL
+ (``https://mycompany.teamwork.com/``). A value with no dot is treated as a subdomain of
+ ``teamwork.com``. Region/custom hosts (``mycompany.eu.teamwork.com``) are preserved as-is.
+ """
+ host = site.strip()
+ host = host.removeprefix("https://").removeprefix("http://")
+ host = host.split("/", 1)[0].strip().rstrip(".").lower()
+ if "." not in host:
+ host = f"{host}.teamwork.com"
+ return host
+
+
+def base_url(host: str) -> str:
+ return f"https://{host}/projects/api/v3"
+
+
+def _auth_header(api_key: str) -> dict[str, str]:
+ # Teamwork uses HTTP Basic auth with the API key as the username and any value as the password.
+ token = base64.b64encode(f"{api_key}:x".encode()).decode()
+ return {"Authorization": f"Basic {token}", "Accept": "application/json"}
+
+
+def _format_updated_after(value: Any) -> str:
+ """Format a cursor value as the ``yyyy-mm-ddThh:mm:ssZ`` string the V3 ``updatedAfter`` param wants."""
+ 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 datetime(value.year, value.month, value.day, tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _build_params(config: TeamworkEndpointConfig, page: int, updated_after: str | None) -> dict[str, Any]:
+ params: dict[str, Any] = {"page": page, "pageSize": PAGE_SIZE}
+ if config.order_by:
+ params["orderBy"] = config.order_by
+ params["orderMode"] = "asc"
+ if updated_after:
+ params["updatedAfter"] = updated_after
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type((TeamworkRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # The session never follows redirects (see `get_rows`), so a 3xx means the validated host tried to
+ # bounce us elsewhere. Refuse it rather than forwarding the Basic auth header off the host boundary.
+ if 300 <= response.status_code < 400:
+ raise ValueError(
+ f"Teamwork API returned an unexpected redirect (status={response.status_code}, url={url}); "
+ "refusing to forward credentials off the validated host."
+ )
+
+ # 429s resume after ~60s on Teamwork; let the exponential backoff handle it. 5xx are transient.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise TeamworkRetryableError(f"Teamwork API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error("Teamwork API error", status=response.status_code, body=response.text, url=url)
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(host: str, api_key: str) -> bool:
+ # /me.json is the cheapest authenticated probe — it only needs a valid key, no extra scopes.
+ url = f"{base_url(host)}/me.json"
+ try:
+ # `allow_redirects=False`: a redirect would forward the Basic auth header off the validated host.
+ response = make_tracked_session(allow_redirects=False).get(url, headers=_auth_header(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamworkResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = TEAMWORK_ENDPOINTS[endpoint]
+ headers = _auth_header(api_key)
+ # `allow_redirects=False`: a redirect would forward the Basic auth header off the validated host.
+ session = make_tracked_session(allow_redirects=False)
+
+ is_incremental = should_use_incremental_field and config.incremental_field is not None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ page = resume.page
+ updated_after = resume.updated_after
+ else:
+ page = 1
+ updated_after = (
+ _format_updated_after(db_incremental_field_last_value)
+ if is_incremental and db_incremental_field_last_value
+ else None
+ )
+
+ endpoint_url = f"{base_url(host)}{config.path}"
+
+ while True:
+ url = f"{endpoint_url}?{urlencode(_build_params(config, page, updated_after))}"
+ data = _fetch_page(session, url, headers, logger)
+
+ items = data.get(config.data_key, [])
+ has_more = bool(data.get("meta", {}).get("page", {}).get("hasMore", False))
+
+ if items:
+ # Yield the page as-is; the pipeline buffers and batches. Save state AFTER yielding and
+ # pointing at the page we just emitted, so a crash re-yields it (merge dedupes on the
+ # primary key) rather than skipping it.
+ yield items
+ resumable_source_manager.save_state(TeamworkResumeConfig(page=page, updated_after=updated_after))
+
+ if not items or not has_more:
+ break
+
+ if page >= MAX_PAGES:
+ if is_incremental:
+ logger.info(
+ f"Teamwork: reached the {MAX_PAGES * PAGE_SIZE}-record per-sync cap for '{endpoint}'; "
+ "remaining rows will sync on the next run as the incremental cursor advances."
+ )
+ else:
+ logger.warning(
+ f"Teamwork: reached the {MAX_PAGES * PAGE_SIZE}-record per-sync cap for full-refresh "
+ f"endpoint '{endpoint}'; rows beyond this limit were not synced this run."
+ )
+ break
+
+ page += 1
+
+
+def teamwork_source(
+ host: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamworkResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = TEAMWORK_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ 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,
+ # Rows are requested ascending (orderMode=asc), so the pipeline can checkpoint the watermark
+ # after every batch and resume safely mid-sync.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork.py b/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork.py
new file mode 100644
index 000000000000..a82848153c21
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork.py
@@ -0,0 +1,340 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.teamwork import teamwork
+from posthog.temporal.data_imports.sources.teamwork.settings import TEAMWORK_ENDPOINTS
+from posthog.temporal.data_imports.sources.teamwork.teamwork import (
+ PAGE_SIZE,
+ TeamworkResumeConfig,
+ _auth_header,
+ _build_params,
+ _fetch_page,
+ _format_updated_after,
+ base_url,
+ get_rows,
+ normalize_host,
+ validate_credentials,
+)
+
+
+class TestNormalizeHost:
+ @parameterized.expand(
+ [
+ ("bare_subdomain", "mycompany", "mycompany.teamwork.com"),
+ ("full_host", "mycompany.teamwork.com", "mycompany.teamwork.com"),
+ ("https_url", "https://mycompany.teamwork.com/", "mycompany.teamwork.com"),
+ ("http_url_with_path", "http://mycompany.teamwork.com/projects", "mycompany.teamwork.com"),
+ ("regional_host", "mycompany.eu.teamwork.com", "mycompany.eu.teamwork.com"),
+ ("trims_whitespace_and_case", " MyCompany ", "mycompany.teamwork.com"),
+ ("trailing_dot", "mycompany.teamwork.com.", "mycompany.teamwork.com"),
+ ]
+ )
+ def test_normalize_host(self, _name: str, raw: str, expected: str) -> None:
+ assert normalize_host(raw) == expected
+
+ def test_base_url(self) -> None:
+ assert base_url("mycompany.teamwork.com") == "https://mycompany.teamwork.com/projects/api/v3"
+
+
+class TestAuthHeader:
+ def test_basic_auth_uses_api_key_as_username(self) -> None:
+ import base64
+
+ header = _auth_header("my-secret-key")
+ assert header["Accept"] == "application/json"
+ scheme, token = header["Authorization"].split(" ", 1)
+ assert scheme == "Basic"
+ assert base64.b64decode(token).decode() == "my-secret-key:x"
+
+
+class TestFormatUpdatedAfter:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format_updated_after(self, _name: str, value: object, expected: str) -> None:
+ assert _format_updated_after(value) == expected
+
+ def test_no_offset_suffix(self) -> None:
+ assert "+00:00" not in _format_updated_after(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+
+
+class TestBuildParams:
+ def test_incremental_endpoint_passes_updated_after_and_asc_sort(self) -> None:
+ config = TEAMWORK_ENDPOINTS["tasks"]
+ params = _build_params(config, page=1, updated_after="2026-03-04T02:58:14Z")
+ assert params == {
+ "page": 1,
+ "pageSize": PAGE_SIZE,
+ "orderBy": "updatedat",
+ "orderMode": "asc",
+ "updatedAfter": "2026-03-04T02:58:14Z",
+ }
+
+ def test_full_refresh_endpoint_has_stable_sort_no_updated_after(self) -> None:
+ config = TEAMWORK_ENDPOINTS["projects"]
+ params = _build_params(config, page=2, updated_after=None)
+ assert params == {"page": 2, "pageSize": PAGE_SIZE, "orderBy": "datecreated", "orderMode": "asc"}
+
+ def test_always_requests_ascending(self) -> None:
+ # sort_mode="asc" in SourceResponse trusts the request to ascend; every endpoint must say so.
+ for config in TEAMWORK_ENDPOINTS.values():
+ params = _build_params(config, page=1, updated_after=None)
+ assert params.get("orderMode") == "asc"
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ fake_response = MagicMock()
+ fake_response.status_code = status_code
+ fake_session = MagicMock()
+ fake_session.get.return_value = fake_response
+ with patch.object(teamwork, "make_tracked_session", lambda *a, **k: fake_session):
+ assert validate_credentials("mycompany.teamwork.com", "key") is expected
+
+ def test_network_error_is_false(self) -> None:
+ fake_session = MagicMock()
+ fake_session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(teamwork, "make_tracked_session", lambda *a, **k: fake_session):
+ assert validate_credentials("mycompany.teamwork.com", "key") is False
+
+ def test_uses_no_redirect_session(self) -> None:
+ # The Basic auth header must never follow a redirect off the validated host.
+ captured: dict[str, Any] = {}
+
+ def fake_session_factory(*_a: Any, **kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ fake_session = MagicMock()
+ fake_session.get.return_value = MagicMock(status_code=200)
+ return fake_session
+
+ with patch.object(teamwork, "make_tracked_session", fake_session_factory):
+ validate_credentials("mycompany.teamwork.com", "key")
+ assert captured["allow_redirects"] is False
+
+
+class TestFetchPage:
+ @staticmethod
+ def _fetch(status_code: int) -> dict:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ session = MagicMock()
+ session.get.return_value = response
+ return _fetch_page(session, "https://mycompany.teamwork.com/x", {}, MagicMock())
+
+ @parameterized.expand([("moved", 301), ("found", 302), ("temporary", 307), ("permanent", 308)])
+ def test_redirect_is_rejected(self, _name: str, status_code: int) -> None:
+ # A 3xx means the host tried to bounce us elsewhere — refuse rather than forward credentials.
+ with pytest.raises(ValueError, match="redirect"):
+ self._fetch(status_code)
+
+ def test_hits_me_endpoint(self) -> None:
+ captured: dict[str, str] = {}
+
+ def fake_get(url: str, **kwargs: Any) -> MagicMock:
+ captured["url"] = url
+ resp = MagicMock()
+ resp.status_code = 200
+ return resp
+
+ fake_session = MagicMock()
+ fake_session.get.side_effect = fake_get
+ with patch.object(teamwork, "make_tracked_session", lambda *a, **k: fake_session):
+ validate_credentials("mycompany.teamwork.com", "key")
+ assert captured["url"] == "https://mycompany.teamwork.com/projects/api/v3/me.json"
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TeamworkResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TeamworkResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TeamworkResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TeamworkResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _page(data_key: str, items: list[dict], has_more: bool) -> dict:
+ return {data_key: items, "meta": {"page": {"hasMore": has_more}}}
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ responses: list[dict],
+ endpoint: str = "tasks",
+ **kwargs: Any,
+ ) -> tuple[list[dict], list[str]]:
+ fetched_urls: list[str] = []
+ iterator = iter(responses)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ fetched_urls.append(url)
+ return next(iterator)
+
+ monkeypatch.setattr(teamwork, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ host="mycompany.teamwork.com",
+ api_key="key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows, fetched_urls
+
+ def test_single_page(self, monkeypatch: Any) -> None:
+ responses = [_page("tasks", [{"id": 1}, {"id": 2}], has_more=False)]
+ rows, urls = self._collect(_FakeResumableManager(), monkeypatch, responses)
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert len(urls) == 1
+ assert "page=1" in urls[0]
+
+ def test_follows_pagination_until_has_more_false(self, monkeypatch: Any) -> None:
+ responses = [
+ _page("tasks", [{"id": 1}], has_more=True),
+ _page("tasks", [{"id": 2}], has_more=True),
+ _page("tasks", [{"id": 3}], has_more=False),
+ ]
+ rows, urls = self._collect(_FakeResumableManager(), monkeypatch, responses)
+ assert rows == [{"id": 1}, {"id": 2}, {"id": 3}]
+ assert ["page=1" in urls[0], "page=2" in urls[1], "page=3" in urls[2]] == [True, True, True]
+
+ def test_stops_on_empty_page(self, monkeypatch: Any) -> None:
+ # hasMore lies and says there's more, but an empty page must terminate the loop.
+ responses = [_page("tasks", [], has_more=True)]
+ rows, urls = self._collect(_FakeResumableManager(), monkeypatch, responses)
+ assert rows == []
+ assert len(urls) == 1
+
+ def test_saves_state_after_each_yielded_page(self, monkeypatch: Any) -> None:
+ responses = [
+ _page("tasks", [{"id": 1}], has_more=True),
+ _page("tasks", [{"id": 2}], has_more=False),
+ ]
+ manager = _FakeResumableManager()
+ self._collect(manager, monkeypatch, responses)
+ # State points at the page just yielded so a crash re-yields it rather than skipping.
+ assert manager.saved == [
+ TeamworkResumeConfig(page=1, updated_after=None),
+ TeamworkResumeConfig(page=2, updated_after=None),
+ ]
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ responses = [_page("tasks", [{"id": 7}], has_more=False)]
+ manager = _FakeResumableManager(TeamworkResumeConfig(page=3, updated_after="2026-01-01T00:00:00Z"))
+ rows, urls = self._collect(manager, monkeypatch, responses)
+ assert rows == [{"id": 7}]
+ assert "page=3" in urls[0]
+ assert "updatedAfter=2026-01-01T00%3A00%3A00Z" in urls[0]
+
+ def test_incremental_builds_updated_after_from_last_value(self, monkeypatch: Any) -> None:
+ responses = [_page("tasks", [{"id": 1}], has_more=False)]
+ rows, urls = self._collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ responses,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert "updatedAfter=2026-03-04T02%3A58%3A14Z" in urls[0]
+ assert "orderBy=updatedat" in urls[0]
+
+ def test_full_refresh_endpoint_never_sends_updated_after(self, monkeypatch: Any) -> None:
+ responses = [_page("projects", [{"id": 1}], has_more=False)]
+ _, urls = self._collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ responses,
+ endpoint="projects",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert "updatedAfter" not in urls[0]
+
+ def test_reads_endpoint_specific_data_key(self, monkeypatch: Any) -> None:
+ # `time.json` returns rows under "timelogs", not "time".
+ responses = [_page("timelogs", [{"id": 99}], has_more=False)]
+ rows, _ = self._collect(_FakeResumableManager(), monkeypatch, responses, endpoint="timelogs")
+ assert rows == [{"id": 99}]
+
+ def test_stops_at_page_cap(self, monkeypatch: Any) -> None:
+ # Every page claims hasMore=True forever; the MAX_PAGES cap must break the loop.
+ def always_more(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ return _page("tasks", [{"id": 1}], has_more=True)
+
+ monkeypatch.setattr(teamwork, "_fetch_page", always_more)
+ batches = list(
+ get_rows(
+ host="mycompany.teamwork.com",
+ api_key="key",
+ endpoint="tasks",
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+ assert len(batches) == teamwork.MAX_PAGES
+
+
+class TestEndpointCatalog:
+ def test_every_endpoint_has_id_primary_key(self) -> None:
+ for config in TEAMWORK_ENDPOINTS.values():
+ assert config.primary_keys == ["id"]
+
+ def test_partition_keys_are_creation_fields_not_update_fields(self) -> None:
+ # An update-timestamp partition key would rewrite partitions every sync.
+ for config in TEAMWORK_ENDPOINTS.values():
+ if config.partition_key is not None:
+ assert "updated" not in config.partition_key.lower()
+ assert "edited" not in config.partition_key.lower()
+
+ def test_incremental_endpoints_sort_by_an_update_field(self) -> None:
+ # If we filter by updatedAfter we must also sort by the update field, or sort_mode="asc" lies.
+ for config in TEAMWORK_ENDPOINTS.values():
+ if config.incremental_field is not None:
+ assert config.order_by is not None
+ assert "updated" in config.order_by.lower()
+
+ @parameterized.expand(
+ [
+ ("projects", "projects", "/projects.json"),
+ ("tasks", "tasks", "/tasks.json"),
+ ("tasklists", "tasklists", "/tasklists.json"),
+ ("milestones", "milestones", "/milestones.json"),
+ ("timelogs", "timelogs", "/time.json"),
+ ("people", "people", "/people.json"),
+ ("companies", "companies", "/companies.json"),
+ ("tags", "tags", "/tags.json"),
+ ("comments", "comments", "/comments.json"),
+ ]
+ )
+ def test_endpoint_paths_and_keys(self, name: str, data_key: str, path: str) -> None:
+ config = TEAMWORK_ENDPOINTS[name]
+ assert config.data_key == data_key
+ assert config.path == path
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork_source.py b/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork_source.py
new file mode 100644
index 000000000000..2a379ffcbd24
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/teamwork/tests/test_teamwork_source.py
@@ -0,0 +1,200 @@
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import TeamworkSourceConfig
+from posthog.temporal.data_imports.sources.teamwork import source as source_module
+from posthog.temporal.data_imports.sources.teamwork.canonical_descriptions import CANONICAL_DESCRIPTIONS
+from posthog.temporal.data_imports.sources.teamwork.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.teamwork.source import TeamworkSource
+from posthog.temporal.data_imports.sources.teamwork.teamwork import TeamworkResumeConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"tasks", "tasklists", "milestones", "timelogs"}
+FULL_REFRESH_ENDPOINTS = {"projects", "people", "companies", "tags", "comments"}
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert TeamworkSource().source_type == ExternalDataSourceType.TEAMWORK
+
+ def test_config_basics(self) -> None:
+ config = TeamworkSource().get_source_config
+ assert config.label == "Teamwork"
+ assert config.category == DataWarehouseSourceCategory.PRODUCTIVITY
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Stays hidden from users until it's shipped released.
+ assert config.unreleasedSource is True
+
+ def test_fields_are_site_and_api_key(self) -> None:
+ fields = TeamworkSource().get_source_config.fields
+ by_name = {f.name: f for f in fields if isinstance(f, SourceFieldInputConfig)}
+ assert set(by_name) == {"site", "api_key"}
+ assert by_name["site"].type == SourceFieldInputConfigType.TEXT
+ assert by_name["site"].required is True
+ assert by_name["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert by_name["api_key"].secret is True
+
+ def test_api_key_is_the_only_secret_field(self) -> None:
+ fields = TeamworkSource().get_source_config.fields
+ secret_fields = {f.name for f in fields if isinstance(f, SourceFieldInputConfig) and f.secret}
+ assert secret_fields == {"api_key"}
+
+ def test_site_is_a_connection_host_field(self) -> None:
+ # The API key is sent to the host derived from `site`, so retargeting it must re-require the key.
+ assert TeamworkSource().connection_host_fields == ["site"]
+
+
+class TestGetSchemas:
+ def test_returns_every_endpoint(self) -> None:
+ schemas = TeamworkSource().get_schemas(MagicMock(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @parameterized.expand(sorted(INCREMENTAL_ENDPOINTS))
+ def test_incremental_endpoints_support_incremental(self, name: str) -> None:
+ schemas = {s.name: s for s in TeamworkSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert len(schemas[name].incremental_fields) == 1
+
+ @parameterized.expand(sorted(FULL_REFRESH_ENDPOINTS))
+ def test_full_refresh_endpoints_do_not_support_incremental(self, name: str) -> None:
+ schemas = {s.name: s for s in TeamworkSource().get_schemas(MagicMock(), team_id=1)}
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+
+ def test_names_filter(self) -> None:
+ schemas = TeamworkSource().get_schemas(MagicMock(), team_id=1, names=["tasks"])
+ assert [s.name for s in schemas] == ["tasks"]
+
+
+class TestValidateCredentials:
+ def test_success(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(source_module, "validate_teamwork_credentials", lambda host, api_key: True)
+ ok, error = TeamworkSource().validate_credentials(
+ TeamworkSourceConfig(site="mycompany", api_key="key"), team_id=1
+ )
+ assert ok is True
+ assert error is None
+
+ def test_failure(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(source_module, "validate_teamwork_credentials", lambda host, api_key: False)
+ ok, error = TeamworkSource().validate_credentials(
+ TeamworkSourceConfig(site="mycompany", api_key="bad"), team_id=1
+ )
+ assert ok is False
+ assert error is not None
+
+ def test_normalizes_host_before_validating(self, monkeypatch: Any) -> None:
+ captured: dict[str, str] = {}
+
+ def fake_validate(host: str, api_key: str) -> bool:
+ captured["host"] = host
+ return True
+
+ monkeypatch.setattr(source_module, "validate_teamwork_credentials", fake_validate)
+ TeamworkSource().validate_credentials(
+ TeamworkSourceConfig(site="https://mycompany.teamwork.com/", api_key="key"), team_id=1
+ )
+ assert captured["host"] == "mycompany.teamwork.com"
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://x.teamwork.com/projects/api/v3/tasks.json",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://x.teamwork.com/projects/api/v3/tasks.json"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed: str) -> None:
+ errors = TeamworkSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ ("rate_limited", "429 Client Error: Too Many Requests"),
+ ("server_error", "500 Server Error: Internal Server Error"),
+ ("read_timeout", "Read timed out."),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed: str) -> None:
+ errors = TeamworkSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestResumableSourceManager:
+ def test_returns_manager_bound_to_resume_config(self) -> None:
+ manager = TeamworkSource().get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is TeamworkResumeConfig
+
+
+class TestSourceForPipeline:
+ def _response(self, endpoint: str, **input_overrides: Any) -> Any:
+ inputs = SimpleNamespace(
+ schema_name=endpoint,
+ team_id=1,
+ logger=MagicMock(),
+ should_use_incremental_field=input_overrides.get("should_use_incremental_field", False),
+ db_incremental_field_last_value=input_overrides.get("db_incremental_field_last_value", None),
+ )
+ return TeamworkSource().source_for_pipeline(
+ TeamworkSourceConfig(site="mycompany", api_key="key"),
+ MagicMock(),
+ inputs, # type: ignore[arg-type]
+ )
+
+ def test_plumbs_endpoint_and_primary_key(self) -> None:
+ response = self._response("tasks")
+ assert response.name == "tasks"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+
+ def test_partitioned_endpoint_sets_datetime_partitioning(self) -> None:
+ response = self._response("timelogs")
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["dateCreated"]
+
+ def test_unpartitioned_endpoint_has_no_partitioning(self) -> None:
+ response = self._response("tasks")
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_unsafe_host_blocks_sync(self, monkeypatch: Any) -> None:
+ # An internal/private host must be rejected at sync time, not just at source creation —
+ # otherwise an edited `site` could redirect the stored API key (SSRF).
+ monkeypatch.setattr(source_module, "_is_host_safe", lambda host, team_id: (False, "blocked"))
+ with pytest.raises(ValueError):
+ self._response("tasks")
+
+
+class TestCanonicalDescriptions:
+ def test_keys_are_known_endpoints(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))
+
+ def test_every_entry_has_a_table_description(self) -> None:
+ for entry in CANONICAL_DESCRIPTIONS.values():
+ assert entry.get("description")
+
+ def test_source_exposes_canonical_descriptions(self) -> None:
+ assert TeamworkSource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])