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 asana import source (#61589)

Tom Owersece8228e7905
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index ac304014267f..c2b6576d5b48 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -45,6 +45,7 @@ the row lists both.
| Source | Comm method | Primary library | Tracked transport |
| ---------------- | --------------------------- | --------------------------------------------------------------- | --------------------------- |
| aircall | HTTP | requests | ✅ |
+| asana | HTTP | requests | ✅ |
| attio | HTTP | requests + `rest_source.RESTClient` | ✅ |
| bamboohr | HTTP | requests | ✅ |
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
@@ -159,7 +160,6 @@ doesn't conflict with concurrent PRs.
- amplitude
- apple_search_ads
- appsflyer
-- asana
- ashby
- auth0
- azure_blob
diff --git a/posthog/temporal/data_imports/sources/asana/asana.py b/posthog/temporal/data_imports/sources/asana/asana.py
new file mode 100644
index 000000000000..2d1b957715a4
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/asana/asana.py
@@ -0,0 +1,223 @@
+import dataclasses
+from collections.abc import Iterator
+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.asana.settings import ASANA_ENDPOINTS, PRIMARY_KEY, AsanaEndpointConfig
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+ASANA_BASE_URL = "https://app.asana.com/api/1.0"
+# Asana caps list pages at 100 items.
+PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class AsanaRetryableError(Exception):
+ pass
+
+
+class AsanaResumeConfig:
+ # Initial request URLs (one per parent for fan-out endpoints) not yet started.
+ remaining_urls: list[str]
+ # The next page URL to fetch for the in-progress request, or None when finished.
+ current_url: Optional[str]
+
+
+def _get_headers(access_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _with_query(path: str, params: dict[str, Any]) -> str:
+ """Append query params to a relative path that may already carry a `?workspace=` filter."""
+ clean = {key: value for key, value in params.items() if value is not None}
+ if not clean:
+ return f"{ASANA_BASE_URL}{path}"
+ separator = "&" if "?" in path else "?"
+ return f"{ASANA_BASE_URL}{path}{separator}{urlencode(clean)}"
+
+
+def _list_params(config: AsanaEndpointConfig) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_SIZE}
+ if config.opt_fields:
+ params["opt_fields"] = ",".join(config.opt_fields)
+ return params
+
+
+@retry(
+ retry=retry_if_exception_type((AsanaRetryableError, 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
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # Asana rate-limits at 150 req/min (free) / 1500 (paid) and returns 429 with a Retry-After
+ # header; exponential backoff is sufficient and avoids parsing the header here.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AsanaRetryableError(f"Asana API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Asana API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_items(
+ start_url: str, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> Iterator[dict[str, Any]]:
+ """Fully paginate a single list request, yielding individual records (used for discovery)."""
+ url: Optional[str] = start_url
+ while url is not None:
+ data = _fetch_page(url, headers, logger, session)
+ yield from data.get("data") or []
+ next_page = data.get("next_page")
+ url = next_page.get("uri") if isinstance(next_page, dict) else None
+
+
+def _list_workspaces(
+ headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> list[dict[str, Any]]:
+ url = _with_query("/workspaces", {"limit": PAGE_SIZE, "opt_fields": "is_organization"})
+ return list(_iter_items(url, headers, logger, session))
+
+
+def _list_projects(
+ headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> Iterator[dict[str, Any]]:
+ for workspace in _list_workspaces(headers, logger, session):
+ gid = workspace["gid"]
+ yield from _iter_items(
+ _with_query(f"/projects?workspace={gid}", {"limit": PAGE_SIZE}), headers, logger, session
+ )
+
+
+def _build_initial_urls(
+ config: AsanaEndpointConfig, headers: dict[str, str], logger: FilteringBoundLogger, session: requests.Session
+) -> list[str]:
+ """Resolve the set of request URLs for an endpoint, fanning out over parents as needed."""
+ params = _list_params(config)
+
+ if config.fan_out == "none":
+ return [_with_query(config.path_template, params)]
+
+ if config.fan_out in ("workspace", "organization"):
+ urls = []
+ for workspace in _list_workspaces(headers, logger, session):
+ if config.fan_out == "organization" and not workspace.get("is_organization"):
+ # `/organizations/{gid}/teams` is only valid for organization workspaces.
+ continue
+ urls.append(_with_query(config.path_template.format(gid=workspace["gid"]), params))
+ return urls
+
+ if config.fan_out == "project":
+ return [
+ _with_query(config.path_template.format(gid=project["gid"]), params)
+ for project in _list_projects(headers, logger, session)
+ ]
+
+ raise ValueError(f"Unknown fan_out mode: {config.fan_out}")
+
+
+def validate_credentials(access_token: str) -> bool:
+ """Confirm the personal access token is valid. /users/me needs no extra scopes."""
+ try:
+ response = make_tracked_session().get(
+ f"{ASANA_BASE_URL}/users/me",
+ headers=_get_headers(access_token),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AsanaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = ASANA_ENDPOINTS[endpoint]
+ headers = _get_headers(access_token)
+ # One session for the whole run so pagination and fan-out reuse pooled connections.
+ session = make_tracked_session()
+
+ 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
+ logger.debug(f"Asana: resuming {endpoint} from URL: {current}")
+ else:
+ remaining = _build_initial_urls(config, headers, logger, session)
+ current = remaining.pop(0) if remaining else None
+
+ while current is not None:
+ data = _fetch_page(current, headers, logger, session)
+ items = data.get("data") or []
+
+ next_page = data.get("next_page")
+ next_url = next_page.get("uri") if isinstance(next_page, dict) else None
+
+ # Advance: continue the current request's page chain, else move to the next parent URL.
+ if next_url:
+ new_current: Optional[str] = next_url
+ new_remaining = remaining
+ elif remaining:
+ new_current = remaining[0]
+ new_remaining = remaining[1:]
+ else:
+ new_current = None
+ new_remaining = []
+
+ if items:
+ yield items
+
+ # Save AFTER yielding (and only while there's more to fetch) so a crash re-yields the
+ # last batch — merge dedupes on gid — rather than skipping it.
+ if new_current is not None:
+ resumable_source_manager.save_state(
+ AsanaResumeConfig(remaining_urls=new_remaining, current_url=new_current)
+ )
+
+ current = new_current
+ remaining = new_remaining
+
+
+def asana_source(
+ access_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AsanaResumeConfig],
+) -> SourceResponse:
+ config = ASANA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ access_token=access_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=[PRIMARY_KEY],
+ 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/asana/settings.py b/posthog/temporal/data_imports/sources/asana/settings.py
new file mode 100644
index 000000000000..a43516236440
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/asana/settings.py
@@ -0,0 +1,149 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+# How an endpoint's request URLs are derived:
+# "none" -> a single top-level list endpoint (no parent fan-out)
+# "workspace" -> one request per workspace the token can see
+# "organization" -> one request per workspace that is an organization
+# "project" -> one request per project across all visible workspaces
+FanOut = Literal["none", "workspace", "organization", "project"]
+
+
+@dataclass
+class AsanaEndpointConfig:
+ name: str
+ fan_out: FanOut
+ # Relative path appended to the API base. Contains a single ``{gid}`` placeholder for
+ # fan-out endpoints (the parent resource id), and no placeholder for top-level ones.
+ path_template: str
+ # Asana list endpoints return compact records ({gid, name, resource_type}) by default.
+ # ``opt_fields`` opts extra properties into the response — keep the partition key here.
+ opt_fields: list[str] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Must be present in opt_fields.
+ # Never a ``modified_at``-style field — partitions would rewrite on every sync.
+ partition_key: Optional[str] = None
+
+
+# Every Asana resource is identified by its global id ``gid``.
+PRIMARY_KEY = "gid"
+
+ASANA_ENDPOINTS: dict[str, AsanaEndpointConfig] = {
+ "workspaces": AsanaEndpointConfig(
+ name="workspaces",
+ fan_out="none",
+ path_template="/workspaces",
+ opt_fields=["name", "email_domains", "is_organization", "resource_type"],
+ ),
+ "users": AsanaEndpointConfig(
+ name="users",
+ fan_out="none",
+ path_template="/users",
+ opt_fields=["name", "email", "photo", "workspaces", "resource_type"],
+ ),
+ "projects": AsanaEndpointConfig(
+ name="projects",
+ fan_out="workspace",
+ path_template="/projects?workspace={gid}",
+ opt_fields=[
+ "name",
+ "created_at",
+ "modified_at",
+ "archived",
+ "color",
+ "current_status",
+ "default_view",
+ "due_date",
+ "due_on",
+ "start_on",
+ "notes",
+ "public",
+ "owner",
+ "team",
+ "workspace",
+ "completed",
+ "completed_at",
+ "members",
+ "followers",
+ "permalink_url",
+ "resource_type",
+ ],
+ partition_key="created_at",
+ ),
+ "tasks": AsanaEndpointConfig(
+ name="tasks",
+ fan_out="project",
+ path_template="/tasks?project={gid}",
+ opt_fields=[
+ "name",
+ "created_at",
+ "modified_at",
+ "completed",
+ "completed_at",
+ "due_on",
+ "due_at",
+ "start_on",
+ "assignee",
+ "assignee_status",
+ "notes",
+ "parent",
+ "projects",
+ "tags",
+ "workspace",
+ "resource_subtype",
+ "num_hearts",
+ "num_likes",
+ "permalink_url",
+ "custom_fields",
+ ],
+ partition_key="created_at",
+ ),
+ "tags": AsanaEndpointConfig(
+ name="tags",
+ fan_out="workspace",
+ path_template="/tags?workspace={gid}",
+ opt_fields=["name", "created_at", "color", "notes", "workspace", "permalink_url", "resource_type"],
+ partition_key="created_at",
+ ),
+ "sections": AsanaEndpointConfig(
+ name="sections",
+ fan_out="project",
+ path_template="/projects/{gid}/sections",
+ opt_fields=["name", "created_at", "project", "resource_type"],
+ partition_key="created_at",
+ ),
+ "teams": AsanaEndpointConfig(
+ name="teams",
+ fan_out="organization",
+ path_template="/organizations/{gid}/teams",
+ opt_fields=["name", "description", "organization", "permalink_url", "visibility", "resource_type"],
+ ),
+ "custom_fields": AsanaEndpointConfig(
+ name="custom_fields",
+ fan_out="workspace",
+ path_template="/workspaces/{gid}/custom_fields",
+ opt_fields=[
+ "name",
+ "description",
+ "type",
+ "resource_subtype",
+ "enabled",
+ "format",
+ "precision",
+ "is_global_to_workspace",
+ "created_by",
+ "resource_type",
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(ASANA_ENDPOINTS.keys())
+
+# Asana exposes a server-side `modified_since` filter only on /tasks (and the premium-only
+# task search endpoint). The other endpoints have no usable server-side timestamp filter, so
+# the whole source ships full-refresh-only for now — declaring incremental support without a
+# real server filter would make every "incremental" run cost the same as a full refresh.
+# Incremental tasks (via `modified_since`) and the Events API are tracked as follow-ups; they
+# need a live token to smoke-test the filter behaviour before we can rely on it.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/posthog/temporal/data_imports/sources/asana/source.py b/posthog/temporal/data_imports/sources/asana/source.py
index 2cbaa913bd19..700a76508446 100644
--- a/posthog/temporal/data_imports/sources/asana/source.py
+++ b/posthog/temporal/data_imports/sources/asana/source.py
@@ -1,19 +1,31 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
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.asana.asana import (
+ AsanaResumeConfig,
+ asana_source,
+ validate_credentials as validate_asana_credentials,
+)
+from posthog.temporal.data_imports.sources.asana.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
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 AsanaSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AsanaSource(SimpleSource[AsanaSourceConfig]):
+class AsanaSource(ResumableSource[AsanaSourceConfig, AsanaResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ASANA
@@ -23,7 +35,88 @@ class AsanaSource(SimpleSource[AsanaSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.ASANA,
label="Asana",
- iconPath="/static/services/asana.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter an Asana personal access token to pull your Asana data into the PostHog Data warehouse.
+
+You can create a personal access token from the [developer console](https://app.asana.com/0/my-apps).
+
+Grant these read scopes so every table can sync:
+- `workspaces:read`
+- `users:read`
+- `projects:read`
+- `tasks:read`
+- `tags:read`
+- `teams:read`
+- `custom_fields:read`
+""",
+ iconPath="/static/services/asana.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/asana",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="1/12345...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://app.asana.com": "Your Asana token is invalid or expired. Please generate a new personal access token and reconnect.",
+ "403 Client Error: Forbidden for url: https://app.asana.com": "Your Asana token is missing the required read scopes. Please grant the scopes listed in the connection form and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AsanaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ supports_append=INCREMENTAL_FIELDS.get(endpoint, None) is not None,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in list(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: AsanaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_asana_credentials(config.access_token):
+ return True, None
+
+ return False, "Invalid Asana personal access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AsanaResumeConfig]:
+ return ResumableSourceManager[AsanaResumeConfig](inputs, AsanaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AsanaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AsanaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return asana_source(
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/asana/tests/test_asana.py b/posthog/temporal/data_imports/sources/asana/tests/test_asana.py
new file mode 100644
index 000000000000..f60b2f958641
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/asana/tests/test_asana.py
@@ -0,0 +1,203 @@
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.asana.asana import (
+ ASANA_BASE_URL,
+ AsanaResumeConfig,
+ _build_initial_urls,
+ _list_params,
+ _with_query,
+ asana_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.asana.settings import ASANA_ENDPOINTS, ENDPOINTS
+
+
+def _make_manager(resume_state: Optional[AsanaResumeConfig] = 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 _page(items: list[dict[str, Any]], next_uri: Optional[str]) -> dict[str, Any]:
+ return {"data": items, "next_page": {"uri": next_uri, "offset": "tok"} if next_uri else None}
+
+
+def _ok_response(payload: dict[str, Any]) -> mock.MagicMock:
+ resp = mock.MagicMock(status_code=200, ok=True)
+ resp.json.return_value = payload
+ return resp
+
+
+class TestWithQuery:
+ def test_appends_with_question_mark_when_no_existing_query(self):
+ assert _with_query("/workspaces", {"limit": 100}) == f"{ASANA_BASE_URL}/workspaces?limit=100"
+
+ def test_appends_with_ampersand_when_query_present(self):
+ url = _with_query("/projects?workspace=1", {"limit": 100})
+ assert url == f"{ASANA_BASE_URL}/projects?workspace=1&limit=100"
+
+ def test_drops_none_values(self):
+ assert _with_query("/workspaces", {"limit": None}) == f"{ASANA_BASE_URL}/workspaces"
+
+ def test_encodes_comma_separated_opt_fields(self):
+ url = _with_query("/workspaces", {"opt_fields": "name,created_at"})
+ assert "opt_fields=name%2Ccreated_at" in url
+
+
+class TestListParams:
+ def test_includes_limit_and_opt_fields(self):
+ params = _list_params(ASANA_ENDPOINTS["projects"])
+ assert params["limit"] == 100
+ assert params["opt_fields"] == ",".join(ASANA_ENDPOINTS["projects"].opt_fields)
+ assert "created_at" in params["opt_fields"]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (403, False), (500, False)])
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_status_mapping(self, mock_session, status_code, expected):
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials("token") is expected
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token") is False
+
+
+class TestBuildInitialUrls:
+ def test_top_level_endpoint_yields_single_url(self):
+ urls = _build_initial_urls(ASANA_ENDPOINTS["workspaces"], {}, mock.MagicMock(), mock.MagicMock())
+ assert urls == [
+ f"{ASANA_BASE_URL}/workspaces?limit=100&opt_fields=name%2Cemail_domains%2Cis_organization%2Cresource_type"
+ ]
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._list_workspaces")
+ def test_workspace_fan_out_one_url_per_workspace(self, mock_list_workspaces):
+ mock_list_workspaces.return_value = [{"gid": "1"}, {"gid": "2"}]
+ urls = _build_initial_urls(ASANA_ENDPOINTS["projects"], {}, mock.MagicMock(), mock.MagicMock())
+ assert len(urls) == 2
+ assert all(url.startswith(f"{ASANA_BASE_URL}/projects?workspace=") for url in urls)
+ assert "workspace=1" in urls[0]
+ assert "workspace=2" in urls[1]
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._list_workspaces")
+ def test_organization_fan_out_skips_non_org_workspaces(self, mock_list_workspaces):
+ mock_list_workspaces.return_value = [
+ {"gid": "1", "is_organization": True},
+ {"gid": "2", "is_organization": False},
+ ]
+ urls = _build_initial_urls(ASANA_ENDPOINTS["teams"], {}, mock.MagicMock(), mock.MagicMock())
+ assert len(urls) == 1
+ assert urls[0].startswith(f"{ASANA_BASE_URL}/organizations/1/teams")
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._list_projects")
+ def test_project_fan_out_one_url_per_project(self, mock_list_projects):
+ mock_list_projects.return_value = iter([{"gid": "p1"}, {"gid": "p2"}])
+ urls = _build_initial_urls(ASANA_ENDPOINTS["tasks"], {}, mock.MagicMock(), mock.MagicMock())
+ assert [u.split("project=")[1].split("&")[0] for u in urls] == ["p1", "p2"]
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_paginates_via_next_page_uri(self, mock_session):
+ pages = [
+ _ok_response(_page([{"gid": "1"}, {"gid": "2"}], f"{ASANA_BASE_URL}/workspaces?offset=tok2")),
+ _ok_response(_page([{"gid": "3"}], None)),
+ ]
+ mock_session.return_value.get.side_effect = pages
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "workspaces", mock.MagicMock(), manager))
+
+ assert [item["gid"] for batch in batches for item in batch] == ["1", "2", "3"]
+ # Saved once: after the first page (which has a next uri); not after the terminal page.
+ manager.save_state.assert_called_once()
+ saved = manager.save_state.call_args.args[0]
+ assert saved.current_url == f"{ASANA_BASE_URL}/workspaces?offset=tok2"
+ assert saved.remaining_urls == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session):
+ mock_session.return_value.get.return_value = _ok_response(_page([{"gid": "9"}], None))
+
+ resume_url = f"{ASANA_BASE_URL}/workspaces?offset=resume"
+ manager = _make_manager(AsanaResumeConfig(remaining_urls=[], current_url=resume_url))
+
+ list(get_rows("token", "workspaces", mock.MagicMock(), manager))
+
+ assert mock_session.return_value.get.call_args_list[0].args[0] == resume_url
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._build_initial_urls")
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_drains_remaining_parent_urls(self, mock_session, mock_build_urls):
+ # Two parents, each a single page with no next_page — the generator must advance to
+ # the second parent URL once the first finishes.
+ mock_build_urls.return_value = [
+ f"{ASANA_BASE_URL}/tasks?project=p1",
+ f"{ASANA_BASE_URL}/tasks?project=p2",
+ ]
+ mock_session.return_value.get.side_effect = [
+ _ok_response(_page([{"gid": "a"}], None)),
+ _ok_response(_page([{"gid": "b"}], None)),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "tasks", mock.MagicMock(), manager))
+
+ assert [item["gid"] for batch in batches for item in batch] == ["a", "b"]
+ assert mock_session.return_value.get.call_count == 2
+ # 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"{ASANA_BASE_URL}/tasks?project=p2"
+ assert saved.remaining_urls == []
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._build_initial_urls")
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana.make_tracked_session")
+ def test_empty_single_endpoint_yields_nothing_and_saves_nothing(self, mock_session, mock_build_urls):
+ mock_build_urls.return_value = [f"{ASANA_BASE_URL}/workspaces?limit=100"]
+ mock_session.return_value.get.return_value = _ok_response(_page([], None))
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "workspaces", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.asana._build_initial_urls")
+ def test_no_parents_yields_nothing(self, mock_build_urls):
+ mock_build_urls.return_value = []
+ manager = _make_manager()
+ assert list(get_rows("token", "projects", mock.MagicMock(), manager)) == []
+ manager.save_state.assert_not_called()
+
+
+class TestAsanaSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = ASANA_ENDPOINTS[endpoint]
+ response = asana_source("token", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == ["gid"]
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_format == "week"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(ASANA_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key == "created_at"
+ # The partition field must be opted into the response, else partitioning fails.
+ assert config.partition_key in config.opt_fields
diff --git a/posthog/temporal/data_imports/sources/asana/tests/test_asana_source.py b/posthog/temporal/data_imports/sources/asana/tests/test_asana_source.py
new file mode 100644
index 000000000000..951d77a1ab07
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/asana/tests/test_asana_source.py
@@ -0,0 +1,122 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.asana.asana import AsanaResumeConfig
+from posthog.temporal.data_imports.sources.asana.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.asana.source import AsanaSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import AsanaSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestAsanaSource:
+ def setup_method(self):
+ self.source = AsanaSource()
+ self.team_id = 123
+ self.config = AsanaSourceConfig(access_token="1/abc")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ASANA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Asana"
+ assert config.label == "Asana"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/asana.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["access_token"]
+
+ def test_access_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(
+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"
+ )
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://app.asana.com/api/1.0/workspaces?limit=100",
+ "403 Client Error: Forbidden for url: https://app.asana.com/api/1.0/tasks?project=1",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ 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_vendor_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://app.asana.com/api/1.0/users",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_covers_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_full_refresh_only(self):
+ # No endpoint advertises incremental until the tasks `modified_since` filter is verified.
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert all(not schema.supports_incremental for schema in schemas)
+ assert all(not schema.supports_append for schema in schemas)
+ assert all(schema.incremental_fields == [] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["tasks"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "tasks"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Asana personal access token"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.asana.source.validate_asana_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ 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.access_token)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AsanaResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.asana.source.asana_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_asana_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "tasks"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_asana_source.assert_called_once()
+ kwargs = mock_asana_source.call_args.kwargs
+ assert kwargs["access_token"] == "1/abc"
+ assert kwargs["endpoint"] == "tasks"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 2f7371eacbac..0ebd369b0092 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -135,7 +135,7 @@ class AppsFlyerSourceConfig(config.Config):
@config.config
class AsanaSourceConfig(config.Config):
- pass
+ access_token: str
@config.config