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): add guru analytics, folder, tag and group tables (#110788)

Tom Owersa618784e6d6e
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 7a38f56bc273..33647d9a276f 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -643,7 +643,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/gumroad.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gumroad/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/guru/guru.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/guru/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gusto/gusto.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/gusto/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/harvest/harvest.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index e73fb2526449..d494fb16f6ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3880,10 +3880,10 @@ Today (4): `cards`, `collections`, `groups`, `members`
Diffed against: <https://developer.getguru.com/reference/authentication>
-- [ ] `team analytics (GET /v1/teams/{id}/analytics)` — the vendor's headline usage stream - card views, searches, copies per user; the main reason to warehouse Guru data (high)
-- [ ] `group members (GET /v1/groups/{id}/members)` — membership table joining the groups and members we already sync (high)
-- [ ] `tag categories and tags (GET /v1/teams/{id}/tagcategories, /tagcategories/tags)` — lookup resolving the tag IDs carried on synced cards (high)
-- [ ] `folders (GET /v1/folders, GET /v1/folders/{id}/items)` — the board/folder hierarchy that organizes cards - lookup plus card-to-folder membership (high)
+- [x] `team analytics (GET /v1/teams/{id}/analytics)` — the vendor's headline usage stream - card views, searches, copies per user; the main reason to warehouse Guru data (high)
+- [x] `group members (GET /v1/groups/{id}/members)` — membership table joining the groups and members we already sync (high)
+- [x] `tag categories and tags (GET /v1/teams/{id}/tagcategories, /tagcategories/tags)` — lookup resolving the tag IDs carried on synced cards (high)
+- [x] `folders (GET /v1/folders, GET /v1/folders/{id}/items)` — the board/folder hierarchy that organizes cards - lookup plus card-to-folder membership (high)
- [ ] `card comments (GET /v1/cards/{id}/comments)` — engagement and feedback events attached to synced cards (medium)
- [ ] `card verifiers (GET /v1/cards/verifiers, /v1/cards/{id}/verifiers)` — verification ownership per card - drives knowledge-freshness reporting (medium)
- [ ] `team stats (GET /v1/teams/{id}/stats)` — rolled-up workspace counters for trend dashboards (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/canonical_descriptions.py
index da3cbd7dd1f0..cb14660112a6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/canonical_descriptions.py
@@ -68,4 +68,77 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"groups": "Groups the member belongs to.",
},
},
+ "group_members": {
+ "description": "Membership of a user in a Guru group, one row per group and member.",
+ "docs_url": "https://developer.getguru.com/reference/getv1groupsgetgroupmembers",
+ "columns": {
+ "group_id": "ID of the group the member belongs to.",
+ "email": "Email address of the member.",
+ "id": "ID of the group member.",
+ "user": "The underlying user object for the member.",
+ "dateCreated": "Time at which the member was added to the group.",
+ "managedByScim": "Whether the membership is managed by SCIM provisioning.",
+ },
+ },
+ "folders": {
+ "description": "A folder that organizes cards inside a collection.",
+ "docs_url": "https://developer.getguru.com/reference/getv1foldersgetfolders",
+ "columns": {
+ "id": "Unique identifier for the folder.",
+ "title": "Title of the folder.",
+ "description": "Optional short description of the folder.",
+ "slug": "URL slug of the folder.",
+ "collection": "The collection the folder belongs to.",
+ "home": "Whether this folder is the top level folder for its collection.",
+ "lastModified": "Time at which the folder was last modified.",
+ "lastModifiedBy": "The user who last modified the folder.",
+ "numberOfFacts": "Number of cards in the folder.",
+ "groupsSharedWith": "Groups the folder is shared with.",
+ },
+ },
+ "folder_items": {
+ "description": "A card or subfolder that sits directly inside a folder, one row per folder and item.",
+ "docs_url": "https://developer.getguru.com/reference/getv1foldersgetfolderitems",
+ "columns": {
+ "folder_id": "ID of the folder that contains the item.",
+ "id": "ID of the card or subfolder.",
+ "itemId": "ID of the item placement within the folder.",
+ "type": "Kind of item: card or folder.",
+ },
+ },
+ "tag_categories": {
+ "description": "A tag category that groups related tags for the team.",
+ "docs_url": "https://developer.getguru.com/reference/getv1teamstagcategoriesgettagcategories",
+ "columns": {
+ "id": "Unique identifier for the tag category.",
+ "name": "Name of the tag category.",
+ "defaultCategory": "Whether this is the default tag category.",
+ "createdBy": "The user who created the tag category.",
+ "dateCreated": "Time at which the tag category was created.",
+ "tags": "Tags in the category.",
+ },
+ },
+ "tags": {
+ "description": "A tag that labels cards, one row per tag, taken from its tag category.",
+ "docs_url": "https://developer.getguru.com/reference/getv1teamstagcategoriesgettagcategories",
+ "columns": {
+ "id": "Unique identifier for the tag. Cards reference tags by this ID.",
+ "value": "Name of the tag.",
+ "categoryId": "ID of the tag category the tag belongs to.",
+ "categoryName": "Name of the tag category the tag belongs to.",
+ "numberOfCards": "Number of cards that have the tag.",
+ },
+ },
+ "analytics_events": {
+ "description": "A usage event from the Guru analytics export, such as a card view, copy, or search.",
+ "docs_url": "https://developer.getguru.com/docs/list-analytics-data",
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "type": "Type of the event (e.g. card-viewed, search).",
+ "eventType": "Type of the event.",
+ "eventDate": "Time at which the event occurred.",
+ "user": "Email address of the user who performed the event.",
+ "properties": "Event-specific properties. The most common is cardId, the card the event applies to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/guru.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/guru.py
index 2f89e0d61e9c..1e22761b511e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/guru.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/guru.py
@@ -1,6 +1,9 @@
+import json
+import hashlib
import dataclasses
from datetime import UTC, date, datetime
-from typing import Any, Optional
+from typing import Any, Optional, cast
+from urllib.parse import quote
from requests.auth import HTTPBasicAuth
@@ -11,9 +14,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+ build_dependent_resource,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
HeaderLinkPaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
@@ -46,6 +55,14 @@ def _format_last_modified(value: Any) -> str:
return str(value)
+def _format_from_date(value: Any) -> str:
+ # The analytics `fromDate` param accepts at most millisecond precision.
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)
+ return dt.astimezone(UTC).isoformat(timespec="milliseconds")
+ return _format_last_modified(value)
+
+
def _build_params(
config: GuruEndpointConfig,
should_use_incremental_field: bool,
@@ -57,6 +74,11 @@ def _build_params(
if not config.incremental_fields:
return params
+ if config.date_filter_param:
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ params[config.date_filter_param] = _format_from_date(db_incremental_field_last_value)
+ return params
+
if should_use_incremental_field and db_incremental_field_last_value is not None:
cursor_field = incremental_field or config.incremental_fields[0]["field"]
params["q"] = f"{cursor_field} >= {_format_last_modified(db_incremental_field_last_value)}"
@@ -82,6 +104,49 @@ def _normalize_member(item: dict[str, Any]) -> dict[str, Any]:
return item
+def _ensure_event_id(event: dict[str, Any]) -> dict[str, Any]:
+ # The OpenAPI schema documents an event `id`, but the analytics guide's sample omits it.
+ # Fall back to a content hash so the merge key is never null and overlapping `fromDate`
+ # windows still dedupe.
+ if event.get("id"):
+ return event
+ digest = hashlib.sha256(json.dumps(event, sort_keys=True, default=str).encode()).hexdigest()
+ return {**event, "id": digest}
+
+
+def _flatten_tag_category(category: dict[str, Any]) -> list[dict[str, Any]]:
+ # Tags nested in a category omit their category reference, so carry it onto each row.
+ return [
+ {"categoryId": category["id"], "categoryName": category.get("name"), **tag}
+ for tag in category.get("tags") or []
+ ]
+
+
+def _client_config(username: str, api_token: str) -> ClientConfig:
+ return {
+ "base_url": GURU_BASE_URL,
+ "auth": {"type": "http_basic", "username": username, "password": api_token},
+ # Guru paginates via `Link: <url>; rel="next-page"` with an opaque continuation token.
+ "paginator": HeaderLinkPaginator(links_next_key="next-page"),
+ # The next-page/resume URLs are server-controlled; pin them to the Guru API host and
+ # refuse redirects so a tampered link can't move the credentialed request off-host and
+ # leak the Basic auth credentials (SSRF). Empty list => same host as base_url only.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ }
+
+
+def _get_team_id(username: str, api_token: str) -> str:
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+ response = session.get(f"{GURU_BASE_URL}/whoami", auth=HTTPBasicAuth(username, api_token), timeout=30)
+ response.raise_for_status()
+ return response.json()["team"]["id"]
+
+
+def _primary_keys(config: GuruEndpointConfig) -> list[str]:
+ return config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]
+
+
def validate_credentials(username: str, api_token: str) -> bool:
"""Confirm the user token is valid. /whoami is a cheap authenticated probe."""
ok, _status = validate_via_probe(
@@ -93,6 +158,42 @@ def validate_credentials(username: str, api_token: str) -> bool:
return ok
+def _fanout_source(
+ username: str,
+ api_token: str,
+ config: GuruEndpointConfig,
+ fanout: DependentEndpointConfig,
+ team_id: int,
+ job_id: str,
+) -> SourceResponse:
+ resource = build_dependent_resource(
+ endpoint_configs=GURU_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=fanout,
+ client_config=_client_config(username, api_token),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ # Guru child endpoints have no server-side time filter, so fan-out is always full refresh.
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={"data_selector_required": True},
+ child_endpoint_extra={"data_selector_required": True},
+ page_size_param=None,
+ )
+ child = cast(Resource, resource)
+ if config.name == "group_members":
+ child = child.add_map(_normalize_member)
+
+ return SourceResponse(
+ name=config.name,
+ items=lambda: child,
+ primary_keys=_primary_keys(config),
+ partition_count=1,
+ partition_size=1,
+ sort_mode="asc",
+ )
+
+
def guru_source(
username: str,
api_token: str,
@@ -106,10 +207,17 @@ def guru_source(
) -> SourceResponse:
config = GURU_ENDPOINTS[endpoint]
+ if config.fanout is not None:
+ return _fanout_source(username, api_token, config, config.fanout, team_id, job_id)
+
+ path = config.path
+ if "{team_id}" in path:
+ path = path.replace("{team_id}", quote(_get_team_id(username, api_token), safe=""))
+
params = _build_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)
endpoint_config: Endpoint = {
- "path": config.path,
+ "path": path,
"params": params,
# Guru returns a bare JSON array; a non-list 200 body means the response shape
# changed — fail loud instead of wrapping the stray object as a single row.
@@ -121,19 +229,13 @@ def guru_source(
}
if endpoint == "members":
resource_config["data_map"] = _normalize_member
+ elif endpoint == "tags":
+ resource_config["data_map"] = _flatten_tag_category
+ elif endpoint == "analytics_events":
+ resource_config["data_map"] = _ensure_event_id
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": GURU_BASE_URL,
- "auth": {"type": "http_basic", "username": username, "password": api_token},
- # Guru paginates via `Link: <url>; rel="next-page"` with an opaque continuation token.
- "paginator": HeaderLinkPaginator(links_next_key="next-page"),
- # The next-page/resume URLs are server-controlled; pin them to the Guru API host and
- # refuse redirects so a tampered link can't move the credentialed request off-host and
- # leak the Basic auth credentials (SSRF). Empty list => same host as base_url only.
- "allowed_hosts": [],
- "allow_redirects": False,
- },
+ "client": _client_config(username, api_token),
"resources": [resource_config],
}
@@ -163,12 +265,14 @@ def guru_source(
return SourceResponse(
name=endpoint,
items=lambda: resource,
- primary_keys=[config.primary_key],
+ primary_keys=_primary_keys(config),
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,
partition_format="month" if config.partition_key else None,
partition_keys=[config.partition_key] if config.partition_key else None,
- sort_mode="asc",
+ # Guru documents no order for the analytics export, so "desc" defers the watermark
+ # commit to the end of the run instead of checkpointing it after each batch.
+ sort_mode="desc" if config.date_filter_param else "asc",
column_hints=resource.column_hints,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/settings.py
index 300cee7e95e0..7f51827ba785 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/settings.py
@@ -1,26 +1,43 @@
from dataclasses import dataclass, field
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class GuruEndpointConfig:
name: str
path: str
- primary_key: str = "id"
+ primary_key: str | list[str] = "id"
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Stable creation-time field used for datetime partitioning. Never an
# updated_at-style field, which would rewrite partitions on every sync.
partition_key: Optional[str] = None
# Static query params sent on the first request of a page chain.
extra_params: dict[str, str] = field(default_factory=dict)
+ # Query param that takes the incremental cursor as an inclusive lower bound. When unset,
+ # incremental endpoints filter with a Guru Query Language `q` expression instead.
+ date_filter_param: Optional[str] = None
+ fanout: Optional[DependentEndpointConfig] = None
+
+ @property
+ def default_incremental_field(self) -> Optional[str]:
+ return self.incremental_fields[0]["field"] if self.incremental_fields else None
+
+ @property
+ def page_size(self) -> int:
+ # Guru fixes the page size per endpoint and takes no page-size param.
+ return 0
# Guru responses are bare JSON arrays paginated via a `Link: <url>; rel="next-page"`
-# header with an opaque continuation token. Only the card search surface supports a
-# server-side date filter (Guru Query Language `lastModified >= <ISO8601>`); the
-# dimension tables (collections, groups, members) are full refresh per run.
+# header with an opaque continuation token. Only the card search surface (Guru Query
+# Language `lastModified >= <ISO8601>`) and the analytics event export (`fromDate`) support
+# a server-side date filter; the dimension tables are full refresh per run. A `{team_id}`
+# path placeholder is filled from the authenticated user's team.
GURU_ENDPOINTS: dict[str, GuruEndpointConfig] = {
"cards": GuruEndpointConfig(
name="cards",
@@ -51,6 +68,60 @@ GURU_ENDPOINTS: dict[str, GuruEndpointConfig] = {
# top-level `email` so it can serve as the primary key.
primary_key="email",
),
+ "group_members": GuruEndpointConfig(
+ name="group_members",
+ path="/groups/{groupId}/members",
+ # Members carry no top-level id; email (copied from user.email) plus the parent group
+ # is unique across the table.
+ primary_key=["group_id", "email"],
+ fanout=DependentEndpointConfig(
+ parent_name="groups",
+ resolve_param="groupId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "group_id"},
+ ),
+ ),
+ "folders": GuruEndpointConfig(
+ name="folders",
+ path="/folders",
+ ),
+ "folder_items": GuruEndpointConfig(
+ name="folder_items",
+ path="/folders/{folderId}/items",
+ # A card can sit in several folders, so the item id is only unique per folder.
+ primary_key=["folder_id", "id"],
+ fanout=DependentEndpointConfig(
+ parent_name="folders",
+ resolve_param="folderId",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "folder_id"},
+ ),
+ ),
+ "tag_categories": GuruEndpointConfig(
+ name="tag_categories",
+ path="/teams/{team_id}/tagcategories",
+ ),
+ "tags": GuruEndpointConfig(
+ name="tags",
+ # Guru has no tag list endpoint; tags are flattened out of each tag category.
+ path="/teams/{team_id}/tagcategories",
+ ),
+ "analytics_events": GuruEndpointConfig(
+ name="analytics_events",
+ path="/teams/{team_id}/analytics",
+ partition_key="eventDate",
+ date_filter_param="fromDate",
+ incremental_fields=[
+ {
+ "label": "eventDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "eventDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
}
ENDPOINTS = tuple(GURU_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru.py
index f70a29e893fe..691163ba0d1b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru.py
@@ -5,17 +5,18 @@ from typing import Any
import pytest
from unittest import mock
-from requests import Response
+from requests import HTTPError, Response
from products.warehouse_sources.backend.temporal.data_imports.sources.guru.guru import (
GuruResumeConfig,
_build_params,
+ _ensure_event_id,
_format_last_modified,
_normalize_member,
guru_source,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.guru.settings import ENDPOINTS, GURU_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.guru.settings import GURU_ENDPOINTS
# RESTClient builds its session via make_tracked_session in the rest_client module.
CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
@@ -33,6 +34,10 @@ def _response(items: Any, next_link: str | None = None) -> Response:
return resp
+def _whoami_response(team_id: str) -> Response:
+ return _response({"team": {"id": team_id}, "tokenType": "API"})
+
+
def _redirect(location: str) -> Response:
resp = Response()
resp.status_code = 302
@@ -139,7 +144,34 @@ class TestBuildParams:
assert params["sortField"] == "dateCreated"
assert params["sortOrder"] == "asc"
- @pytest.mark.parametrize("endpoint", ["collections", "groups", "members"])
+ @pytest.mark.parametrize(
+ "last_value, expected_from_date",
+ [
+ (datetime(2024, 1, 2, 3, 4, 5, 678901, tzinfo=UTC), "2024-01-02T03:04:05.678+00:00"),
+ (datetime(2024, 1, 2, 3, 4, 5), "2024-01-02T03:04:05.000+00:00"),
+ ],
+ )
+ def test_incremental_analytics_uses_from_date_not_gql(self, last_value, expected_from_date):
+ params = _build_params(
+ GURU_ENDPOINTS["analytics_events"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=last_value,
+ incremental_field="eventDate",
+ )
+
+ assert params == {"fromDate": expected_from_date}
+
+ def test_full_refresh_analytics_sends_no_from_date(self):
+ params = _build_params(
+ GURU_ENDPOINTS["analytics_events"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+
+ assert params == {}
+
+ @pytest.mark.parametrize("endpoint", ["collections", "groups", "members", "folders", "tag_categories", "tags"])
def test_non_incremental_endpoints_have_no_search_params(self, endpoint):
params = _build_params(
GURU_ENDPOINTS[endpoint],
@@ -177,6 +209,26 @@ class TestNormalizeMember:
_normalize_member({"user": {"firstName": "Jane"}})
+class TestEnsureEventId:
+ def test_keeps_vendor_id(self):
+ event = {"id": "e1", "type": "card-viewed"}
+ assert _ensure_event_id(event) == event
+
+ def test_documented_event_without_id_gets_stable_content_key(self):
+ event = {
+ "type": "card-viewed",
+ "user": "[email protected]",
+ "eventDate": "2016-01-20T03:10:11.351+0000",
+ "properties": {"cardId": "c1"},
+ }
+ other = {**event, "eventDate": "2016-01-20T03:10:12.000+0000"}
+
+ first = _ensure_event_id(event)["id"]
+
+ assert first and first == _ensure_event_id(dict(event))["id"]
+ assert first != _ensure_event_id(other)["id"]
+
+
class TestValidateCredentials:
@pytest.mark.parametrize(
"status_code, expected",
@@ -315,15 +367,106 @@ class TestGetRows:
_rows(_source("cards", _make_manager()))
+class TestTeamScopedEndpoints:
+ @mock.patch(GURU_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tags_are_flattened_from_categories_under_resolved_team(self, MockSession, mock_whoami_session):
+ mock_whoami_session.return_value.get.return_value = _whoami_response("team-1")
+ session = MockSession.return_value
+ _, urls = _wire(
+ session,
+ [
+ _response(
+ [
+ {"id": "cat-1", "name": "Fruits", "tags": [{"id": "t1", "value": "Apple"}]},
+ {"id": "cat-2", "name": "Empty", "tags": []},
+ ]
+ )
+ ],
+ )
+
+ rows = _rows(_source("tags", _make_manager()))
+
+ assert urls[0].endswith("/teams/team-1/tagcategories")
+ assert rows == [{"categoryId": "cat-1", "categoryName": "Fruits", "id": "t1", "value": "Apple"}]
+
+ @mock.patch(GURU_SESSION_PATCH)
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_analytics_incremental_request_filters_by_from_date(self, MockSession, mock_whoami_session):
+ mock_whoami_session.return_value.get.return_value = _whoami_response("team-1")
+ session = MockSession.return_value
+ params, urls = _wire(session, [_response([{"id": "e1", "eventDate": "2024-01-02T00:00:00.000+0000"}])])
+
+ response = _source(
+ "analytics_events",
+ _make_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="eventDate",
+ )
+ rows = _rows(response)
+
+ assert urls[0].endswith("/teams/team-1/analytics")
+ assert params[0] == {"fromDate": "2024-01-01T00:00:00.000+00:00"}
+ assert [row["id"] for row in rows] == ["e1"]
+ # Guru documents no order for the export, so the watermark must not checkpoint mid-run.
+ assert response.sort_mode == "desc"
+
+ @mock.patch(GURU_SESSION_PATCH)
+ def test_whoami_auth_failure_surfaces_as_http_error(self, mock_whoami_session):
+ failed = Response()
+ failed.status_code = 401
+ failed.url = "https://api.getguru.com/api/v1/whoami"
+ failed.reason = "Unauthorized"
+ mock_whoami_session.return_value.get.return_value = failed
+
+ with pytest.raises(HTTPError, match="401 Client Error: Unauthorized for url: https://api.getguru.com"):
+ _source("analytics_events", _make_manager())
+
+
+class TestFanoutEndpoints:
+ @pytest.mark.parametrize(
+ "endpoint, parent_id, child_path, child_rows, expected",
+ [
+ (
+ "group_members",
+ "g1",
+ "/groups/g1/members",
+ [{"id": "m1", "user": {"email": "[email protected]"}}],
+ [{"id": "m1", "user": {"email": "[email protected]"}, "group_id": "g1", "email": "[email protected]"}],
+ ),
+ (
+ "folder_items",
+ "f1",
+ "/folders/f1/items",
+ [{"id": "c1", "type": "card"}],
+ [{"id": "c1", "type": "card", "folder_id": "f1"}],
+ ),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_child_rows_carry_parent_id(self, MockSession, endpoint, parent_id, child_path, child_rows, expected):
+ session = MockSession.return_value
+ _, urls = _wire(session, [_response([{"id": parent_id}]), _response(child_rows)])
+
+ response = _source(endpoint, _make_manager())
+ rows = _rows(response)
+
+ assert urls[1].endswith(child_path)
+ assert rows == expected
+ assert all(row[key] is not None for row in rows for key in response.primary_keys)
+
+
class TestGuruSourceResponse:
- @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
- def test_response_metadata_per_endpoint(self, endpoint):
+ @pytest.mark.parametrize("endpoint", [name for name, config in GURU_ENDPOINTS.items() if config.fanout is None])
+ @mock.patch(GURU_SESSION_PATCH)
+ def test_response_metadata_per_endpoint(self, mock_whoami_session, endpoint):
+ mock_whoami_session.return_value.get.return_value = _whoami_response("team-1")
config = GURU_ENDPOINTS[endpoint]
response = _source(endpoint, _make_manager())
assert response.name == endpoint
assert response.primary_keys == [config.primary_key]
- assert response.sort_mode == "asc"
if config.partition_key:
assert response.partition_mode == "datetime"
assert response.partition_keys == [config.partition_key]
@@ -334,4 +477,4 @@ class TestGuruSourceResponse:
@pytest.mark.parametrize("config", list(GURU_ENDPOINTS.values()))
def test_partition_keys_are_stable_creation_fields(self, config):
if config.partition_key:
- assert config.partition_key == "dateCreated"
+ assert config.partition_key in ("dateCreated", "eventDate")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru_source.py
index e584ccbfd7a1..66255c615c26 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/guru/tests/test_guru_source.py
@@ -39,8 +39,8 @@ class TestGuruSource:
assert {schema.name for schema in schemas} == set(ENDPOINTS)
incremental = {schema.name for schema in schemas if schema.supports_incremental}
- # Only the card search surface supports a server-side date filter.
- assert incremental == {"cards"}
+ # Only card search and the analytics export support a server-side date filter.
+ assert incremental == {"cards", "analytics_events"}
@pytest.mark.parametrize(
"mock_return, expected_valid, expected_message",