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 Sleekplan source (#77129)

Tom Owersf5d0ccecfea2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 57dab28f03ff..6ebbfe6cdbee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -587,6 +587,7 @@ the row lists both.
| simplesat | HTTP | requests | ✅ |
| skyvern | HTTP | requests | ✅ |
| slack | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| sleekplan | HTTP | requests + `rest_source.RESTClient` | ✅ |
| smaily | HTTP | requests | ✅ |
| smartengage | HTTP | requests + `rest_source.RESTClient` | ✅ |
| smartreach | HTTP | requests | ✅ |
@@ -1342,7 +1343,6 @@ doesn't conflict with concurrent PRs.
- site24x7
- skyvern
- slash
-- sleekplan
- sleuth
- smaily
- smartlook
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sleekplan.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sleekplan.py
index 91af74710913..f216afc7b6a9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sleekplan.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/sleekplan.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SleekplanSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/canonical_descriptions.py
new file mode 100644
index 000000000000..6bc4c9967370
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/canonical_descriptions.py
@@ -0,0 +1,155 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Users": {
+ "description": "End users of your product who have interacted with the Sleekplan widget, including the people who submitted feedback, voted, commented, or answered a survey.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "user_id": "Unique identifier for the end user in Sleekplan.",
+ "data_id": "Your own identifier for the user, as passed to the widget or the API.",
+ "admin_id": "Identifier of the workspace member this user is linked to, when the user is an admin.",
+ "anonymous": "Whether the user was created without identifying details.",
+ "data_name": "Display name shown on the board.",
+ "data_full_name": "Full name of the user.",
+ "data_mail": "Email address, used to identify the user.",
+ "data_img": "URL of the user's avatar image.",
+ "segments": "Segment IDs the user belongs to.",
+ "data": "Custom metadata attached to the user.",
+ "data_system": "System metadata collected by the widget, such as browser, platform, country, and timezone.",
+ "stats_feedback": "Number of feedback posts the user has submitted.",
+ "stats_votes": "Number of votes the user has cast.",
+ "stats_comments": "Number of comments the user has written.",
+ "stats_satisfaction": "Number of satisfaction (CSAT) responses the user has submitted.",
+ "stats_promoter": "Number of promoter (NPS) responses the user has submitted.",
+ "notify": "Whether the user receives notifications.",
+ "notify_settings": "Per-topic notification preferences, covering mentions, changelog, and subscriptions.",
+ "weight": "Weighting applied to the user's votes.",
+ "created": "When the user was first seen.",
+ "updated": "When the user record last changed.",
+ },
+ },
+ "Posts": {
+ "description": "Feedback posts on your board: feature requests, bug reports, and ideas, with their status, category, votes, and roadmap fields.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "feedback_id": "Unique identifier for the post.",
+ "product_id": "Identifier of the Sleekplan workspace the post belongs to.",
+ "title": "Title of the post.",
+ "description": "Body of the post, as plain text.",
+ "description_html": "Body of the post, rendered as HTML.",
+ "status": "Status ID of the post, for example planned or completed.",
+ "trend": "Trending score used by the default board sort.",
+ "type": "Category ID of the post.",
+ "total_up": "Number of upvotes.",
+ "total_down": "Number of downvotes.",
+ "total_sum": "Net vote total.",
+ "total_comments": "Number of comments on the post.",
+ "total_ratio": "Ratio of upvotes to total votes.",
+ "total_subscriber": "Number of users subscribed to the post.",
+ "scoring": "Prioritization score for the post.",
+ "effort": "Estimated effort, from 0 to 3.",
+ "owner_id": "Workspace member who owns the post.",
+ "merge_id": "Identifier of the post this one was merged into.",
+ "is_active": "Whether the post is visible on the board.",
+ "notify": "Whether notifications are enabled for the post.",
+ "tags": "Tags assigned to the post.",
+ "estimated": "Estimated delivery date for the post.",
+ "vote": "The requesting key owner's own vote on the post.",
+ "subscription": "Whether the requesting key owner is subscribed to the post.",
+ "user": "The end user who submitted the post.",
+ "created": "When the post was submitted.",
+ "updated": "When the post last changed.",
+ },
+ },
+ "Comments": {
+ "description": "Comments left on feedback posts, including private notes between workspace members and threaded replies.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "comment_id": "Unique identifier for the comment.",
+ "feedback_id": "Identifier of the post the comment belongs to.",
+ "product_id": "Identifier of the Sleekplan workspace.",
+ "comment": "Body of the comment, as plain text.",
+ "comment_html": "Body of the comment, rendered as HTML.",
+ "parent": "Identifier of the comment this one replies to.",
+ "status": "Status of the comment.",
+ "type": "Type of the comment.",
+ "modified": "Whether the comment has been edited.",
+ "files": "Files attached to the comment.",
+ "pinned": "Whether the comment is pinned to the top of the post.",
+ "public": "Whether the comment is visible to end users. Private comments are only visible to workspace members.",
+ "is_active": "Whether the comment is visible.",
+ "likes": "Number of likes on the comment.",
+ "child_count": "Number of replies to the comment.",
+ "has_child": "Whether the comment has replies.",
+ "liked": "Whether the requesting key owner liked the comment.",
+ "user": "The user who wrote the comment.",
+ "created": "When the comment was written.",
+ "updated": "When the comment last changed.",
+ },
+ },
+ "Votes": {
+ "description": "Individual votes cast on feedback posts, one row per user per post. Fetched per post, so every row carries the post it belongs to.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "feedback_id": "Identifier of the post that was voted on.",
+ "user_id": "Identifier of the user who cast the vote, lifted out of the nested user record.",
+ "vote": "Direction of the vote: 1 for an upvote, -1 for a downvote.",
+ "user": "The user who cast the vote.",
+ "created": "When the vote was cast.",
+ },
+ },
+ "Updates": {
+ "description": "Changelog entries, including drafts and scheduled entries, with their engagement stats.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "changelog_id": "Unique identifier for the changelog entry.",
+ "product_id": "Identifier of the Sleekplan workspace.",
+ "feedback_id": "Identifier of the feedback post this entry was published from.",
+ "title": "Title of the entry.",
+ "description": "Body of the entry, as plain text.",
+ "description_html": "Body of the entry, rendered as HTML.",
+ "type": "Category ID of the entry.",
+ "segment": "Segment the entry is limited to.",
+ "settings": "Display settings for the entry, such as the call to action link and its text and color.",
+ "files": "Files attached to the entry.",
+ "scheduled": "Whether the entry is scheduled for a future date.",
+ "draft": "Whether the entry is still a draft.",
+ "enabled": "Whether the entry is enabled.",
+ "queue": "Position of the entry in the publishing queue.",
+ "announcement": "Whether the entry is shown as an in-app announcement.",
+ "notify": "Whether subscribers are notified about the entry.",
+ "notify_delay": "Whether the notification is delayed.",
+ "reactions": "Whether reactions are enabled on the entry.",
+ "stats": "Engagement stats for the entry, covering announcements, pageviews, emails, and clicks.",
+ "created": "Publication date of the entry.",
+ },
+ },
+ "Satisfaction": {
+ "description": "Customer satisfaction (CSAT) survey responses, rated 1 to 5. A response submitted within 30 days of a previous one replaces it rather than creating a new record.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "satisfaction_id": "Unique identifier for the response.",
+ "vote": "Satisfaction rating, from 1 to 5.",
+ "data_record": "Group key the response was recorded against.",
+ "comment": "Free-text comment left with the rating.",
+ "meta": "Metadata captured with the response, such as the referring URL.",
+ "user": "The user who submitted the response.",
+ "updated": "When the response was last submitted or replaced.",
+ },
+ },
+ "Promoter": {
+ "description": "Net promoter score (NPS) survey responses, rated 1 to 10. A response submitted within 14 days of a previous one replaces it rather than creating a new record.",
+ "docs_url": "https://sleekplan.com/docs/api",
+ "columns": {
+ "promoter_id": "Unique identifier for the response.",
+ "vote": "Net promoter rating, from 1 to 10.",
+ "comment": "Free-text comment left with the rating.",
+ "meta": "Metadata captured with the response, such as the referring URL.",
+ "user": "The user who submitted the response.",
+ "created": "When the response was first submitted.",
+ "updated": "When the response was last submitted or replaced.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/settings.py
new file mode 100644
index 000000000000..cb2b82beb395
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/settings.py
@@ -0,0 +1,144 @@
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+from products.warehouse_sources.backend.types import IncrementalField
+
+SLEEKPLAN_BASE_URL = "https://api.sleekplan.com/v1"
+
+# Every list endpoint caps `per_page` at 100.
+MAX_PAGE_SIZE = 100
+
+# The survey endpoints take `date_start`/`date_end`, and the docs don't name the column they filter
+# on. Sleekplan also replaces a satisfaction response within 30 days (a promoter response within 14)
+# rather than appending a new one, so a record can change after its date. Re-reading a trailing
+# window on every incremental run covers both; the merge upsert dedupes what comes back twice.
+SURVEY_LOOKBACK_DAYS = 30
+SURVEY_START_PARAM = "date_start"
+
+# Comments and votes are addressed per post (/post/{postid}/...), so both fan out over /posts.
+# `sort=new` is the closest thing to a stable parent ordering the endpoint offers: its other sort
+# options (trend, top, scoring, priority) are recomputed values that can reshuffle mid-walk.
+_POST_PARENT_PARAMS = {"sort": "new"}
+
+# `sort=old` walks a post's children oldest first, so rows added mid-walk land at the end instead of
+# shifting the pages behind them. Child request params live here rather than on the endpoint config:
+# the fan-out helper builds the child request, so it is the only thing that reads them.
+POST_COMMENTS_FANOUT = DependentEndpointConfig(
+ parent_name="Posts",
+ resolve_param="postid",
+ resolve_field="feedback_id",
+ include_from_parent=["feedback_id"],
+ parent_field_renames={"feedback_id": "feedback_id"},
+ parent_params=_POST_PARENT_PARAMS,
+ child_params={"sort": "old"},
+)
+
+POST_VOTES_FANOUT = DependentEndpointConfig(
+ parent_name="Posts",
+ resolve_param="postid",
+ resolve_field="feedback_id",
+ include_from_parent=["feedback_id"],
+ parent_field_renames={"feedback_id": "feedback_id"},
+ parent_params=_POST_PARENT_PARAMS,
+ child_params={"sort": "old", "filter": "all"},
+)
+
+
+@dataclass(frozen=False)
+class SleekplanEndpointConfig:
+ name: str
+ path: str
+ data_selector: str
+ primary_key: list[str]
+ page_size: int = MAX_PAGE_SIZE
+ params: dict[str, Any] = field(default_factory=dict)
+ partition_key: str | None = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: str | None = None
+ # "asc" only where the endpoint takes a sort param we can pin to an ascending, immutable
+ # column. Everything else stays "desc" so the incremental watermark is only written once the
+ # run finishes, rather than being checkpointed against an order we cannot guarantee.
+ sort_mode: Literal["asc", "desc"] = "desc"
+ fanout: DependentEndpointConfig | None = None
+
+
+SLEEKPLAN_ENDPOINTS: dict[str, SleekplanEndpointConfig] = {
+ # Sorted ascending by creation date so rows added while we page don't shift earlier pages.
+ "Users": SleekplanEndpointConfig(
+ name="Users",
+ path="/users",
+ data_selector="data.items.*",
+ primary_key=["user_id"],
+ params={"sort": "created", "sort_dir": "ASC"},
+ partition_key="created",
+ sort_mode="asc",
+ ),
+ "Posts": SleekplanEndpointConfig(
+ name="Posts",
+ path="/posts",
+ data_selector="data.items.*",
+ primary_key=["feedback_id"],
+ params=_POST_PARENT_PARAMS,
+ partition_key="created",
+ ),
+ # `comment_id` looks workspace-wide, but the docs never say so, so the post id stays in the key:
+ # a per-post id would collide across posts and seed duplicate rows.
+ "Comments": SleekplanEndpointConfig(
+ name="Comments",
+ path="/post/{postid}/comments",
+ data_selector="data.comments.*",
+ primary_key=["feedback_id", "comment_id"],
+ partition_key="created",
+ sort_mode="asc",
+ fanout=POST_COMMENTS_FANOUT,
+ ),
+ # A vote carries no id of its own; it is one user's vote on one post, so that pair is the key.
+ "Votes": SleekplanEndpointConfig(
+ name="Votes",
+ path="/post/{postid}/votes",
+ data_selector="data.votes",
+ primary_key=["feedback_id", "user_id"],
+ partition_key="created",
+ sort_mode="asc",
+ fanout=POST_VOTES_FANOUT,
+ ),
+ "Updates": SleekplanEndpointConfig(
+ name="Updates",
+ path="/updates",
+ data_selector="data.items.*",
+ primary_key=["changelog_id"],
+ partition_key="created",
+ ),
+ # `updated` is the only timestamp on a satisfaction response, which also rules it out as a
+ # partition key (partitions would be rewritten every time a response is replaced).
+ "Satisfaction": SleekplanEndpointConfig(
+ name="Satisfaction",
+ path="/satisfaction",
+ data_selector="data",
+ primary_key=["satisfaction_id"],
+ incremental_fields=[incremental_field("updated")],
+ default_incremental_field="updated",
+ ),
+ "Promoter": SleekplanEndpointConfig(
+ name="Promoter",
+ path="/promoter",
+ data_selector="data",
+ primary_key=["promoter_id"],
+ partition_key="created",
+ incremental_fields=[incremental_field("updated")],
+ default_incremental_field="updated",
+ ),
+}
+
+ENDPOINTS = tuple(SLEEKPLAN_ENDPOINTS)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SLEEKPLAN_ENDPOINTS.items()
+}
+
+# The survey endpoints re-read a trailing window each run, so appending would duplicate rows.
+MERGE_ONLY_ENDPOINTS = ("Satisfaction", "Promoter")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/sleekplan.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/sleekplan.py
new file mode 100644
index 000000000000..1c29e6dcd5f6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/sleekplan.py
@@ -0,0 +1,307 @@
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any, Optional, cast
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ PageNumberPaginator,
+)
+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,
+ Endpoint,
+ EndpointResource,
+ IncrementalConfig,
+)
+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
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.settings import (
+ SLEEKPLAN_BASE_URL,
+ SLEEKPLAN_ENDPOINTS,
+ SURVEY_LOOKBACK_DAYS,
+ SURVEY_START_PARAM,
+ SleekplanEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 30
+FIRST_PAGE = 1
+EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
+
+
+@dataclass(frozen=False)
+class SleekplanResumeConfig:
+ # Next page to fetch, for the top-level endpoints.
+ page: Optional[int] = None
+ # Fan-out checkpoint for Comments and Votes:
+ # {"completed": [child_path, ...], "current": child_path | None, "child_state": {"page": N} | None}.
+ fanout_state: Optional[dict] = None
+
+
+class SleekplanPaginator(PageNumberPaginator):
+ """Page-number paginator that stops on the `has_more` flag.
+
+ The list endpoints wrap their rows in `{"data": {"items": ..., "has_more": bool, "page": int}}`,
+ so `has_more: false` ends the walk without paying for the extra empty page. The survey endpoints
+ return a bare array under `data` with no flag, and fall back to the base class's stop-on-empty.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(base_page=FIRST_PAGE, page_param="page")
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if not self._has_next_page:
+ return
+
+ try:
+ body = response.json()
+ except ValueError:
+ return
+
+ if not isinstance(body, dict):
+ return
+ envelope = body.get("data")
+ if isinstance(envelope, dict) and envelope.get("has_more") is False:
+ self._has_next_page = False
+
+
+def _flatten_vote_user(row: dict[str, Any]) -> dict[str, Any]:
+ """Lift the voter's id to the row root so `Votes` has a usable primary key.
+
+ A vote has no id of its own and nests the voter under `user`, which the (post id, user id)
+ primary key cannot address.
+ """
+ user = row.get("user")
+ row["user_id"] = user.get("user_id") if isinstance(user, dict) else None
+ return row
+
+
+# Per-row reshaping the `data_selector` can't express, keyed by endpoint. Only the fan-out
+# endpoints need one today.
+DATA_MAPS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {"Votes": _flatten_vote_user}
+
+
+def _format_survey_date(value: Any) -> str:
+ """Format an incremental cursor value as the `YYYY-MM-DD` date `date_start` takes, less the
+ replacement-window lookback (see SURVEY_LOOKBACK_DAYS)."""
+ normalized = coerce_datetime_to_utc(value)
+ if normalized is None:
+ return str(value)
+ capped = min(normalized, datetime.now(UTC))
+ return max(capped - timedelta(days=SURVEY_LOOKBACK_DAYS), EPOCH).strftime("%Y-%m-%d")
+
+
+def _incremental_window(field_name: str) -> IncrementalConfig:
+ return {
+ "cursor_path": field_name,
+ "start_param": SURVEY_START_PARAM,
+ "initial_value": "1970-01-01",
+ "convert": _format_survey_date,
+ }
+
+
+def _resolve_incremental_field(config: SleekplanEndpointConfig, incremental_field: str | None) -> str:
+ """The user's chosen cursor, as long as the endpoint advertises it."""
+ advertised = {field["field"] for field in config.incremental_fields}
+ if incremental_field in advertised:
+ return cast(str, incremental_field)
+ return config.default_incremental_field or next(iter(advertised))
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": SLEEKPLAN_BASE_URL,
+ # Framework auth rather than a hand-built header, so the key is redacted from logs and
+ # captured samples.
+ "auth": {"type": "bearer", "token": api_key},
+ "headers": {"Accept": "application/json"},
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ # `capture=False`: Sleekplan is a feedback board, so responses carry arbitrary
+ # user-authored content -- post/comment bodies, voter emails, survey free-text -- that
+ # the generic name-based scrubber can't anonymize. Same reasoning as Frill and
+ # Featurebase, the other feedback-board sources. Requests are still metered and logged.
+ "session": make_tracked_session(redact_values=(api_key,), capture=False),
+ }
+
+
+def _endpoint_params(config: SleekplanEndpointConfig) -> dict[str, Any]:
+ return {"per_page": config.page_size, **config.params}
+
+
+def _resource(
+ config: SleekplanEndpointConfig,
+ should_use_incremental_field: bool,
+ incremental_field: str | None,
+) -> EndpointResource:
+ endpoint_config: Endpoint = {
+ "path": config.path,
+ "params": _endpoint_params(config),
+ "data_selector": config.data_selector,
+ "paginator": SleekplanPaginator(),
+ }
+
+ use_merge = should_use_incremental_field and bool(config.incremental_fields)
+ if use_merge:
+ endpoint_config["incremental"] = _incremental_window(_resolve_incremental_field(config, incremental_field))
+
+ return {
+ "name": config.name,
+ "table_name": config.name,
+ "write_disposition": {"disposition": "merge", "strategy": "upsert"} if use_merge else "replace",
+ "endpoint": endpoint_config,
+ "table_format": "delta",
+ }
+
+
+def _make_source_response(config: SleekplanEndpointConfig, items_fn: Callable[[], Iterable[Any]]) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=items_fn,
+ primary_keys=config.primary_key,
+ sort_mode=config.sort_mode,
+ partition_count=1 if config.partition_key else None,
+ partition_size=1 if config.partition_key else None,
+ 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,
+ )
+
+
+def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+ """Probe the cheapest authenticated list call.
+
+ A Sleekplan API key inherits its owner's dashboard permissions, so a 403 means the key is real
+ but its owner cannot read that resource. That is only fatal for the schema being checked -- at
+ source-create time the key itself is still valid.
+ """
+ is_valid, status_code = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,), capture=False),
+ f"{SLEEKPLAN_BASE_URL}/users?per_page=1",
+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ if is_valid:
+ return True, None
+
+ if status_code == 401:
+ return False, "Invalid Sleekplan API key."
+ if status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, f"This Sleekplan API key does not have permission to read {schema_name}."
+ if status_code is None:
+ return False, "Could not reach the Sleekplan API."
+ return False, f"Sleekplan API returned an unexpected status ({status_code})."
+
+
+def sleekplan_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SleekplanResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = SLEEKPLAN_ENDPOINTS[endpoint]
+ client_config = _client_config(api_key)
+
+ if config.fanout is not None:
+ return _fan_out_source(config, client_config, team_id, job_id, resumable_source_manager)
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and resume_config.page is not None:
+ initial_paginator_state = {"page": resume_config.page}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # The hook fires after a page is yielded, so a crash re-fetches the checkpointed page
+ # (merge dedupes it) rather than skipping rows. Redis TTL cleans up on completion.
+ if state and state.get("page") is not None:
+ resumable_source_manager.save_state(SleekplanResumeConfig(page=int(state["page"])))
+
+ rest_config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": {},
+ "resources": [_resource(config, should_use_incremental_field, incremental_field)],
+ }
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ db_incremental_field_last_value,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+ return _make_source_response(config, lambda: resource)
+
+
+def _fan_out_source(
+ config: SleekplanEndpointConfig,
+ client_config: ClientConfig,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[SleekplanResumeConfig],
+) -> SourceResponse:
+ assert config.fanout is not None
+ parent_config = SLEEKPLAN_ENDPOINTS[config.fanout.parent_name]
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and resume_config.fanout_state is not None:
+ initial_paginator_state = resume_config.fanout_state
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ if state is not None:
+ resumable_source_manager.save_state(SleekplanResumeConfig(fanout_state=state))
+
+ resource = cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=SLEEKPLAN_ENDPOINTS,
+ child_endpoint=config.name,
+ fanout=config.fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ page_size_param="per_page",
+ parent_endpoint_extra={
+ "paginator": SleekplanPaginator(),
+ "data_selector": parent_config.data_selector,
+ },
+ child_endpoint_extra={
+ "paginator": SleekplanPaginator(),
+ "data_selector": config.data_selector,
+ },
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ ),
+ )
+ data_map = DATA_MAPS.get(config.name)
+ if data_map is not None:
+ resource = resource.add_map(data_map)
+
+ items = cast(Iterable[Any], resource)
+ return _make_source_response(config, lambda: items)
+
+
+__all__ = ["SleekplanResumeConfig", "sleekplan_source", "validate_credentials"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/source.py
index 62f199ec603b..fca14a14a3ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/source.py
@@ -1,32 +1,132 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sleekplan import (
SleekplanSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ MERGE_ONLY_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.sleekplan import (
+ SleekplanResumeConfig,
+ sleekplan_source,
+ validate_credentials as validate_sleekplan_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SleekplanSource(SimpleSource[SleekplanSourceConfig]):
+class SleekplanSource(ResumableSource[SleekplanSourceConfig, SleekplanResumeConfig]):
+ # `get_schemas` iterates a static endpoint catalog with no I/O -- safe for public docs.
+ lists_tables_without_credentials = True
+ # Sleekplan has only ever published one API (`/v1`) and documents no version selector, so the
+ # framework's unversioned default stands.
+ api_docs_url = "https://sleekplan.com/docs/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SLEEKPLAN
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Sleekplan API key is invalid or has been revoked. Generate a new key under Settings > Developer and reconnect.",
+ "403 Client Error": "Your Sleekplan API key does not have permission to read this data. A key inherits the permissions of the member who created it, so create the key from an account that can see this board.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SleekplanSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=MERGE_ONLY_ENDPOINTS)
+
+ def validate_credentials(
+ self,
+ config: SleekplanSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_sleekplan_credentials(config.api_key, schema_name=schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SleekplanResumeConfig]:
+ return ResumableSourceManager[SleekplanResumeConfig](inputs, SleekplanResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SleekplanSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SleekplanResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return sleekplan_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ 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,
+ incremental_field=inputs.incremental_field,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.SLEEKPLAN,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="Sleekplan",
+ caption="""Enter your Sleekplan API key to sync feedback posts, comments, votes, changelog updates, end users, and survey responses into the PostHog Data warehouse.
+
+Create a key in Sleekplan under **Settings > Developer**. A key inherits the permissions of the member who created it, so create it from an account that can see every board you want to sync.""",
+ docsUrl="https://posthog.com/docs/cdp/sources/sleekplan",
iconPath="/static/services/sleekplan.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["feedback", "roadmap", "changelog", "nps", "csat"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan.py
new file mode 100644
index 000000000000..d475db2f9eb4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan.py
@@ -0,0 +1,397 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+
+from unittest.mock import MagicMock, Mock, patch
+
+from parameterized import parameterized
+from requests import Request
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.settings import (
+ SLEEKPLAN_ENDPOINTS,
+ SURVEY_LOOKBACK_DAYS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.sleekplan import (
+ SleekplanPaginator,
+ SleekplanResumeConfig,
+ _format_survey_date,
+ _incremental_window,
+ _resolve_incremental_field,
+ _resource,
+ sleekplan_source,
+ validate_credentials,
+)
+
+TRANSPORT = "products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.sleekplan"
+
+
+class _FakeResource:
+ def __init__(self, name: str, rows: list[dict]) -> None:
+ self.name = name
+ self._rows = rows
+
+ def add_map(self, mapper: Any) -> "_FakeResource":
+ self._rows = [mapper(dict(row)) for row in self._rows]
+ return self
+
+ def __iter__(self):
+ return iter(self._rows)
+
+
+def _page_response(body: Any) -> Mock:
+ response = Mock()
+ response.json.return_value = body
+ return response
+
+
+def _manager(*, can_resume: bool = False, state: SleekplanResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = state
+ return manager
+
+
+class TestSleekplanPaginator:
+ @parameterized.expand(
+ [
+ ("has_more_true_continues", {"data": {"items": {"1": {}}, "has_more": True}}, [{}], True),
+ ("has_more_false_stops", {"data": {"items": {"1": {}}, "has_more": False}}, [{}], False),
+ ("empty_page_stops", {"data": {"items": {}, "has_more": True}}, [], False),
+ ("bare_array_envelope_continues", {"status": "success", "data": [{"promoter_id": 1}]}, [{}], True),
+ ("missing_envelope_continues", {"status": "success"}, [{}], True),
+ ]
+ )
+ def test_termination(self, _name: str, body: Any, data: list[dict], expected_has_next: bool) -> None:
+ paginator = SleekplanPaginator()
+
+ paginator.update_state(_page_response(body), data)
+
+ assert paginator.has_next_page is expected_has_next
+
+ def test_non_json_body_does_not_stop_pagination(self) -> None:
+ paginator = SleekplanPaginator()
+ response = Mock()
+ response.json.side_effect = ValueError("not json")
+
+ paginator.update_state(response, [{}])
+
+ assert paginator.has_next_page is True
+
+ def test_first_request_starts_at_page_one(self) -> None:
+ request = Request()
+
+ SleekplanPaginator().init_request(request)
+
+ assert request.params == {"page": 1}
+
+ def test_resume_state_round_trips_into_the_request(self) -> None:
+ paginator = SleekplanPaginator()
+ paginator.update_state(_page_response({"data": {"items": {"1": {}}, "has_more": True}}), [{}])
+ state = paginator.get_resume_state()
+
+ resumed = SleekplanPaginator()
+ resumed.set_resume_state(cast(dict, state))
+ request = Request()
+ resumed.init_request(request)
+
+ assert request.params == {"page": 2}
+
+ def test_resume_state_is_none_once_pagination_is_done(self) -> None:
+ paginator = SleekplanPaginator()
+
+ paginator.update_state(_page_response({"data": {"items": {"1": {}}, "has_more": False}}), [{}])
+
+ assert paginator.get_resume_state() is None
+
+
+class TestSurveyDateFormatting:
+ def test_applies_the_replacement_window_lookback(self) -> None:
+ value = datetime(2025, 6, 1, 12, 0, tzinfo=UTC)
+
+ assert _format_survey_date(value) == (value - timedelta(days=SURVEY_LOOKBACK_DAYS)).strftime("%Y-%m-%d")
+
+ def test_caps_a_future_cursor_at_today(self) -> None:
+ formatted = _format_survey_date(datetime(2999, 1, 1, tzinfo=UTC))
+
+ assert formatted <= datetime.now(UTC).strftime("%Y-%m-%d")
+
+ def test_clamps_to_the_epoch(self) -> None:
+ # Subtracting the lookback from an early cursor would otherwise produce a pre-1970 date.
+ assert _format_survey_date(datetime(1970, 1, 5, tzinfo=UTC)) == "1970-01-01"
+
+ @parameterized.expand([("initial_seed", "1970-01-01"), ("unparseable", "not-a-date")])
+ def test_passes_through_a_non_datetime_value(self, _name: str, value: str) -> None:
+ assert _format_survey_date(value) == value
+
+ def test_incremental_window_targets_the_date_start_filter(self) -> None:
+ window = _incremental_window("updated")
+
+ assert window["cursor_path"] == "updated"
+ assert window["start_param"] == "date_start"
+ assert window["convert"] is _format_survey_date
+
+
+class TestResolveIncrementalField:
+ @parameterized.expand(
+ [
+ ("advertised_choice_is_honoured", "updated", "updated"),
+ ("unadvertised_choice_falls_back", "created", "updated"),
+ ("no_choice_falls_back", None, "updated"),
+ ]
+ )
+ def test_resolution(self, _name: str, chosen: str | None, expected: str) -> None:
+ assert _resolve_incremental_field(SLEEKPLAN_ENDPOINTS["Promoter"], chosen) == expected
+
+
+class TestResource:
+ @parameterized.expand(
+ [
+ ("Users", "/users", "data.items.*", {"sort": "created", "sort_dir": "ASC"}),
+ ("Posts", "/posts", "data.items.*", {"sort": "new"}),
+ ("Updates", "/updates", "data.items.*", {}),
+ ("Satisfaction", "/satisfaction", "data", {}),
+ ("Promoter", "/promoter", "data", {}),
+ ]
+ )
+ def test_endpoint_request_shape(self, name: str, path: str, selector: str, extra_params: dict) -> None:
+ resource = _resource(SLEEKPLAN_ENDPOINTS[name], should_use_incremental_field=False, incremental_field=None)
+
+ endpoint = cast(dict[str, Any], resource["endpoint"])
+ assert endpoint["path"] == path
+ assert endpoint["data_selector"] == selector
+ assert endpoint["params"] == {"per_page": 100, **extra_params}
+ assert isinstance(endpoint["paginator"], SleekplanPaginator)
+
+ @parameterized.expand(["Users", "Posts", "Updates"])
+ def test_endpoints_without_a_server_side_filter_never_go_incremental(self, name: str) -> None:
+ resource = _resource(SLEEKPLAN_ENDPOINTS[name], should_use_incremental_field=True, incremental_field="updated")
+
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in cast(dict[str, Any], resource["endpoint"])
+
+ @parameterized.expand(["Satisfaction", "Promoter"])
+ def test_survey_endpoints_window_on_date_start_when_incremental(self, name: str) -> None:
+ resource = _resource(SLEEKPLAN_ENDPOINTS[name], should_use_incremental_field=True, incremental_field=None)
+
+ assert resource["write_disposition"] == {"disposition": "merge", "strategy": "upsert"}
+ assert cast(dict[str, Any], resource["endpoint"])["incremental"]["start_param"] == "date_start"
+
+ @parameterized.expand(["Satisfaction", "Promoter"])
+ def test_survey_endpoints_full_refresh_when_incremental_disabled(self, name: str) -> None:
+ resource = _resource(SLEEKPLAN_ENDPOINTS[name], should_use_incremental_field=False, incremental_field=None)
+
+ assert resource["write_disposition"] == "replace"
+ assert "incremental" not in cast(dict[str, Any], resource["endpoint"])
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, (True, None)),
+ ("unauthorized", 401, None, (False, "Invalid Sleekplan API key.")),
+ # A key inherits its owner's permissions, so a 403 only blocks the schema being checked.
+ ("forbidden_at_source_create", 403, None, (True, None)),
+ (
+ "forbidden_for_a_schema",
+ 403,
+ "Posts",
+ (False, "This Sleekplan API key does not have permission to read Posts."),
+ ),
+ ("server_error", 500, None, (False, "Sleekplan API returned an unexpected status (500).")),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, schema_name: str | None, expected: tuple) -> None:
+ with patch(f"{TRANSPORT}.validate_via_probe", return_value=(status_code == 200, status_code)):
+ assert validate_credentials("key", schema_name=schema_name) == expected
+
+ def test_unreachable_api_is_reported(self) -> None:
+ with patch(f"{TRANSPORT}.validate_via_probe", return_value=(False, None)):
+ assert validate_credentials("key") == (False, "Could not reach the Sleekplan API.")
+
+ def test_probe_sends_the_key_as_a_bearer_token(self) -> None:
+ with patch(f"{TRANSPORT}.validate_via_probe", return_value=(True, 200)) as mock_probe:
+ validate_credentials("secret-key")
+
+ _, kwargs = mock_probe.call_args
+ assert kwargs["headers"]["Authorization"] == "Bearer secret-key"
+
+ def test_probe_session_redacts_the_key_and_disables_sample_capture(self) -> None:
+ # Users/posts/comments carry emails and free-text feedback the generic scrubber can't
+ # anonymize, so the probe -- like every other Sleekplan request -- must not be captured.
+ with (
+ patch(f"{TRANSPORT}.validate_via_probe", return_value=(True, 200)) as mock_probe,
+ patch(f"{TRANSPORT}.make_tracked_session") as mock_make_session,
+ ):
+ validate_credentials("secret-key")
+ mock_probe.call_args.args[0]()
+
+ mock_make_session.assert_called_once_with(redact_values=("secret-key",), capture=False)
+
+
+class TestTopLevelSource:
+ @parameterized.expand(
+ [
+ ("Users", ["user_id"], "created", "asc"),
+ ("Posts", ["feedback_id"], "created", "desc"),
+ ("Updates", ["changelog_id"], "created", "desc"),
+ ("Promoter", ["promoter_id"], "created", "desc"),
+ # `updated` is the only timestamp on a satisfaction response, and partitioning on it
+ # would rewrite partitions whenever a response is replaced.
+ ("Satisfaction", ["satisfaction_id"], None, "desc"),
+ ]
+ )
+ def test_source_response_shape(
+ self, name: str, primary_keys: list[str], partition_key: str | None, sort_mode: str
+ ) -> None:
+ with patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()):
+ response = sleekplan_source(
+ api_key="key", endpoint=name, team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+
+ assert response.name == name
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+ assert response.partition_keys == ([partition_key] if partition_key else None)
+
+ def test_uses_framework_bearer_auth(self) -> None:
+ with patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()) as mock_resource:
+ sleekplan_source(
+ api_key="secret-key", endpoint="Posts", team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+
+ (rest_config, *_), _ = mock_resource.call_args
+ assert rest_config["client"]["auth"] == {"type": "bearer", "token": "secret-key"}
+ assert rest_config["client"]["base_url"] == "https://api.sleekplan.com/v1"
+
+ def test_session_redacts_the_key_and_disables_sample_capture(self) -> None:
+ # Posts/comments/votes/survey responses carry emails and free-text feedback the generic
+ # scrubber can't anonymize, so sample capture must stay off (still metered and logged).
+ with (
+ patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()) as mock_resource,
+ patch(f"{TRANSPORT}.make_tracked_session") as mock_make_session,
+ ):
+ sleekplan_source(
+ api_key="secret-key", endpoint="Posts", team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+
+ (rest_config, *_), _ = mock_resource.call_args
+ mock_make_session.assert_called_once_with(redact_values=("secret-key",), capture=False)
+ assert rest_config["client"]["session"] is mock_make_session.return_value
+
+ def test_seeds_the_paginator_from_saved_state(self) -> None:
+ manager = _manager(can_resume=True, state=SleekplanResumeConfig(page=4))
+
+ with patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()) as mock_resource:
+ sleekplan_source(
+ api_key="key", endpoint="Posts", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert mock_resource.call_args.kwargs["initial_paginator_state"] == {"page": 4}
+
+ def test_ignores_a_fan_out_checkpoint_left_by_another_schema(self) -> None:
+ manager = _manager(can_resume=True, state=SleekplanResumeConfig(fanout_state={"completed": []}))
+
+ with patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()) as mock_resource:
+ sleekplan_source(
+ api_key="key", endpoint="Posts", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert mock_resource.call_args.kwargs["initial_paginator_state"] is None
+
+ @parameterized.expand(
+ [
+ ("saves_next_page", {"page": 5}, SleekplanResumeConfig(page=5)),
+ ("ignores_terminal_state", None, None),
+ ]
+ )
+ def test_resume_hook(self, _name: str, state: dict | None, expected: SleekplanResumeConfig | None) -> None:
+ manager = _manager()
+
+ with patch(f"{TRANSPORT}.rest_api_resource", return_value=Mock()) as mock_resource:
+ sleekplan_source(
+ api_key="key", endpoint="Posts", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ mock_resource.call_args.kwargs["resume_hook"](state)
+
+ if expected is None:
+ manager.save_state.assert_not_called()
+ else:
+ manager.save_state.assert_called_once_with(expected)
+
+
+class TestFanOutSource:
+ def test_comments_carry_their_parent_post_id(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources",
+ return_value=[
+ _FakeResource("Posts", [{"feedback_id": 77}]),
+ _FakeResource("Comments", [{"comment_id": 5, "_Posts_feedback_id": 77}]),
+ ],
+ ):
+ response = sleekplan_source(
+ api_key="key", endpoint="Comments", team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+ rows = list(cast(Any, response.items()))
+
+ assert rows == [{"comment_id": 5, "feedback_id": 77}]
+
+ @parameterized.expand(
+ [
+ ("identified_voter", {"user": {"user_id": 9}}, 9),
+ ("missing_voter", {}, None),
+ ]
+ )
+ def test_votes_lift_the_voter_id_to_the_row_root(self, _name: str, vote_row: dict, expected: int | None) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources",
+ return_value=[
+ _FakeResource("Posts", [{"feedback_id": 77}]),
+ _FakeResource("Votes", [{"vote": 1, "_Posts_feedback_id": 77, **vote_row}]),
+ ],
+ ):
+ response = sleekplan_source(
+ api_key="key", endpoint="Votes", team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+ rows = list(cast(Any, response.items()))
+
+ # The (post, user) pair is the only primary key a vote has.
+ assert rows[0]["feedback_id"] == 77
+ assert rows[0]["user_id"] == expected
+
+ @parameterized.expand(["Comments", "Votes"])
+ def test_fan_out_pages_with_per_page(self, name: str) -> None:
+ with patch(f"{TRANSPORT}.build_dependent_resource", return_value=_FakeResource(name, [])) as mock_build:
+ sleekplan_source(
+ api_key="key", endpoint=name, team_id=1, job_id="job-1", resumable_source_manager=_manager()
+ )
+
+ kwargs = mock_build.call_args.kwargs
+ assert kwargs["page_size_param"] == "per_page"
+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], SleekplanPaginator)
+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], SleekplanPaginator)
+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "data.items.*"
+
+ def test_fan_out_resumes_from_its_own_checkpoint(self) -> None:
+ fanout_state = {"completed": ["/post/1/comments"], "current": "/post/2/comments", "child_state": {"page": 3}}
+ manager = _manager(can_resume=True, state=SleekplanResumeConfig(fanout_state=fanout_state))
+
+ with patch(f"{TRANSPORT}.build_dependent_resource", return_value=_FakeResource("Comments", [])) as mock_build:
+ sleekplan_source(
+ api_key="key", endpoint="Comments", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert mock_build.call_args.kwargs["initial_paginator_state"] == fanout_state
+
+ mock_build.call_args.kwargs["resume_hook"](fanout_state)
+ manager.save_state.assert_called_once_with(SleekplanResumeConfig(fanout_state=fanout_state))
+
+ def test_fan_out_ignores_a_page_checkpoint_left_by_another_schema(self) -> None:
+ manager = _manager(can_resume=True, state=SleekplanResumeConfig(page=9))
+
+ with patch(f"{TRANSPORT}.build_dependent_resource", return_value=_FakeResource("Comments", [])) as mock_build:
+ sleekplan_source(
+ api_key="key", endpoint="Comments", team_id=1, job_id="job-1", resumable_source_manager=manager
+ )
+
+ assert mock_build.call_args.kwargs["initial_paginator_state"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan_source.py
new file mode 100644
index 000000000000..c535e46a045a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/sleekplan/tests/test_sleekplan_source.py
@@ -0,0 +1,172 @@
+from unittest.mock import Mock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.sleekplan import (
+ SleekplanSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.sleekplan import SleekplanResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.source import SleekplanSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.sleekplan.source"
+
+
+class TestSleekplanSourceConfig:
+ def setup_method(self) -> None:
+ self.source = SleekplanSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SLEEKPLAN
+
+ def test_source_config_is_released_and_alpha(self) -> None:
+ config = self.source.get_source_config
+
+ # A finished source ships with no `unreleasedSource` flag, which would hide it entirely.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_has_single_api_key_field(self) -> None:
+ config = self.source.get_source_config
+
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas iterates a static endpoint catalog with no I/O.
+ assert self.source.lists_tables_without_credentials is True
+
+ @parameterized.expand([("401 Client Error",), ("403 Client Error",)])
+ def test_auth_failures_are_non_retryable(self, error: str) -> None:
+ assert error in self.source.get_non_retryable_errors()
+
+
+class TestSleekplanSourceSchemas:
+ def setup_method(self) -> None:
+ self.source = SleekplanSource()
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1)
+
+ assert {schema.name for schema in schemas} == {
+ "Users",
+ "Posts",
+ "Comments",
+ "Votes",
+ "Updates",
+ "Satisfaction",
+ "Promoter",
+ }
+
+ @parameterized.expand(["Users", "Posts", "Comments", "Votes", "Updates"])
+ def test_endpoints_without_a_server_side_filter_are_full_refresh_only(self, name: str) -> None:
+ # Sleekplan only documents `date_start`/`date_end` on the survey endpoints; advertising
+ # incremental anywhere else would page the whole collection and call it a delta.
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=[name])
+
+ assert [schema.supports_incremental for schema in schemas] == [False]
+ assert [schema.supports_append for schema in schemas] == [False]
+ assert schemas[0].incremental_fields == []
+
+ @parameterized.expand(["Satisfaction", "Promoter"])
+ def test_survey_endpoints_are_incremental_merge_only(self, name: str) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=[name])
+
+ assert schemas[0].supports_incremental is True
+ # Each run re-reads a trailing window, so appending would duplicate rows.
+ assert schemas[0].supports_append is False
+ assert [field["field"] for field in schemas[0].incremental_fields] == ["updated"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1, names=["Posts"])
+
+ assert [schema.name for schema in schemas] == ["Posts"]
+
+ def test_every_table_has_canonical_descriptions(self) -> None:
+ schemas = self.source.get_schemas(config=Mock(), team_id=1)
+
+ assert {schema.name for schema in schemas} == set(self.source.get_canonical_descriptions())
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+
+class TestSleekplanSourceCredentialValidation:
+ def setup_method(self) -> None:
+ self.source = SleekplanSource()
+
+ @parameterized.expand([("at_source_create", None), ("for_a_schema", "Posts")])
+ def test_validate_credentials_delegates_to_transport(self, _name: str, schema_name: str | None) -> None:
+ config = SleekplanSourceConfig(api_key="test-key")
+
+ with patch(f"{SOURCE_MODULE}.validate_sleekplan_credentials", return_value=(True, None)) as mock_validate:
+ result = self.source.validate_credentials(config, team_id=1, schema_name=schema_name)
+
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("test-key", schema_name=schema_name)
+
+
+class TestSleekplanSourcePipelinePlumbing:
+ def setup_method(self) -> None:
+ self.source = SleekplanSource()
+
+ def test_get_resumable_source_manager_returns_bound_manager(self) -> None:
+ inputs = Mock()
+ inputs.team_id = 1
+ inputs.job_id = "job-1"
+ inputs.logger = Mock()
+
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SleekplanResumeConfig
+
+ def test_source_for_pipeline_forwards_arguments(self) -> None:
+ config = SleekplanSourceConfig(api_key="test-key")
+ inputs = Mock()
+ inputs.schema_name = "Promoter"
+ inputs.team_id = 42
+ inputs.job_id = "job-42"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2025-01-01T00:00:00Z"
+ inputs.incremental_field = "updated"
+ manager = Mock(spec=ResumableSourceManager)
+
+ with patch(f"{SOURCE_MODULE}.sleekplan_source", return_value=Mock()) as mock_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint="Promoter",
+ team_id=42,
+ job_id="job-42",
+ resumable_source_manager=manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2025-01-01T00:00:00Z",
+ incremental_field="updated",
+ )
+
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self) -> None:
+ config = SleekplanSourceConfig(api_key="test-key")
+ inputs = Mock()
+ inputs.schema_name = "Posts"
+ inputs.team_id = 42
+ inputs.job_id = "job-42"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "should-be-ignored"
+ inputs.incremental_field = None
+ manager = Mock(spec=ResumableSourceManager)
+
+ with patch(f"{SOURCE_MODULE}.sleekplan_source", return_value=Mock()) as mock_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None