: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement savvycal import source (#69374)
Tom Owers874ff7c5d7ed
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex b892815bf6a2..8535398727b0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -306,6 +306,7 @@ the row lists both.| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || salesflare | HTTP | requests | ✅ || salesloft | HTTP | requests | ✅ |+| savvycal | HTTP | requests | ✅ || secoda | HTTP | requests | ✅ || segment | HTTP | requests | ✅ || sendgrid | HTTP | requests | ✅ |@@ -680,7 +681,6 @@ doesn't conflict with concurrent PRs.- sap_fieldglass- sap_hana- sap_successfactors-- savvycal- search_ads_360- sendpulse- senseforcediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 6fd4b65e2254..4bab37ec1e6f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -3022,7 +3022,7 @@ class SapSuccessFactorsSourceConfig(config.Config):@config.configclass SavvyCalSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/canonical_descriptions.pynew file mode 100644index 000000000000..7475ef8de556--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/canonical_descriptions.py@@ -0,0 +1,84 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the SavvyCal OpenAPI spec (https://api.savvycal.com/v1/spec).+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "events": {+ "description": "A scheduled event/booking made through SavvyCal.",+ "docs_url": "https://developers.savvycal.com/api/events",+ "columns": {+ "id": "Unique event identifier.",+ "uuid": "UUID identifier for the event.",+ "summary": "Event title/summary.",+ "description": "Event description.",+ "state": "Event state (confirmed, canceled, awaiting_reschedule, awaiting_checkout, checkout_expired, awaiting_approval, declined, or tentative).",+ "start_at": "Event start time.",+ "end_at": "Event end time.",+ "original_start_at": "Original start time (if rescheduled).",+ "original_end_at": "Original end time (if rescheduled).",+ "duration": "Event duration in minutes.",+ "buffer_before": "Buffer time before the event in minutes.",+ "buffer_after": "Buffer time after the event in minutes.",+ "location": "Event location description.",+ "location_settings": "Location settings.",+ "description_settings": "Settings for description generation.",+ "conferencing": "Video conferencing details.",+ "link": "Associated scheduling link (preview).",+ "poll": "Associated poll (if any).",+ "organizer": "The organizer of the event.",+ "scheduler": "The scheduler of the event.",+ "attendees": "All event attendees.",+ "scope": "Associated scope/team.",+ "is_group_session": "Whether this is a group session.",+ "maximum_group_size": "Maximum number of attendees for a group session.",+ "payment": "Payment information (if applicable).",+ "cancel_reason": "Reason for cancellation.",+ "canceled_at": "When the event was canceled.",+ "reschedule_reason": "Reason for rescheduling.",+ "rescheduled_at": "When the event was rescheduled.",+ "additional_info": "Additional event information.",+ "metadata": "Additional event metadata.",+ "url": "Public URL for the event.",+ "created_at": "When the event was created.",+ },+ },+ "links": {+ "description": "A scheduling link for booking appointments.",+ "docs_url": "https://developers.savvycal.com/api/scheduling-links",+ "columns": {+ "id": "Unique link identifier.",+ "name": "Public link name.",+ "private_name": "Private link name (only visible to the owner).",+ "description": "Link description.",+ "slug": "URL slug for the link.",+ "state": "Link state (active or disabled).",+ "default_duration": "Default meeting duration in minutes.",+ "durations": "Available meeting durations in minutes.",+ "increment": "Time slot increment in minutes.",+ "fields": "Custom fields for this link.",+ "scope": "Associated scope/team (if any).",+ },+ },+ "webhooks": {+ "description": "Webhook configuration for receiving event notifications.",+ "docs_url": "https://developers.savvycal.com/api/webhooks",+ "columns": {+ "id": "Unique webhook identifier.",+ "url": "Webhook endpoint URL.",+ "state": "Webhook state.",+ "version": "Webhook payload version.",+ "created_at": "When the webhook was created.",+ },+ },+ "workflows": {+ "description": "An automated workflow for event processing.",+ "docs_url": "https://developers.savvycal.com/api/workflows",+ "columns": {+ "id": "Unique workflow identifier.",+ "name": "Workflow name.",+ "state": "Workflow state.",+ "created_at": "When the workflow was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/savvycal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/savvycal.pynew file mode 100644index 000000000000..ff77de53a9db--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/savvycal.py@@ -0,0 +1,217 @@+import dataclasses+from collections.abc import Iterator+from datetime import date, datetime+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.settings import SAVVYCAL_ENDPOINTS++SAVVYCAL_BASE_URL = "https://api.savvycal.com/v1"+# List endpoints accept a `limit` of up to 100; the largest page minimises round trips.+PAGE_SIZE = 100+REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRY_ATTEMPTS = 5+# Cheap single-object endpoint used to confirm a token is genuine. Personal access tokens carry+# the account's full read access, so one probe validates every list endpoint.+DEFAULT_PROBE_PATH = "/me"+++class SavvyCalRetryableError(Exception):+ pass+++class SavvyCalResumeConfig:+ # Cursor for the next page, taken verbatim from the API's `metadata.after`. `None` means start+ # from the first page. A crashed sync resumes from the page after the last one yielded; merge+ # dedupes the re-pulled page on `id`.+ after: str | None = None+ # The `from` date bound the interrupted run was started with (events incremental only). Reused+ # verbatim on resume so the saved cursor stays paired with the query it was minted under, even+ # if the watermark advanced between attempts.+ from_date: str | None = None+++def _headers(token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {token}", "Accept": "application/json"}+++def _format_from_date(value: Any) -> str:+ """Format an incremental cursor for the events `from` filter (YYYY-MM-DD).++ `from` is an inclusive lower bound on the event *start date*, so truncating a datetime+ watermark to its date re-fetches the watermark day; merge dedupes on `id`.+ """+ if isinstance(value, datetime):+ return value.date().isoformat()+ if isinstance(value, date):+ return value.isoformat()+ return str(value)+++@retry(+ retry=retry_if_exception_type((SavvyCalRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session,+ path: str,+ params: dict[str, Any],+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], Optional[str]]:+ response = session.get(f"{SAVVYCAL_BASE_URL}{path}", params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise SavvyCalRetryableError(f"SavvyCal API error (retryable): status={response.status_code}, path={path}")++ if not response.ok:+ logger.error(f"SavvyCal API error: status={response.status_code}, body={response.text}, path={path}")+ response.raise_for_status()++ data = response.json()+ # List endpoints wrap records in {"entries": [...], "metadata": {"after": ..., "before": ..., "limit": ...}}.+ if not isinstance(data, dict) or not isinstance(data.get("entries"), list):+ raise SavvyCalRetryableError(f"SavvyCal returned an unexpected payload for {path}: {type(data).__name__}")++ metadata = data.get("metadata")+ after = metadata.get("after") if isinstance(metadata, dict) else None+ return data["entries"], after if isinstance(after, str) and after else None+++def _redact(items: list[dict[str, Any]], redact_fields: frozenset[str]) -> list[dict[str, Any]]:+ """Strip secret-bearing fields from a page before it lands in the warehouse."""+ if not redact_fields:+ return items+ return [{k: v for k, v in item.items() if k not in redact_fields} for item in items]+++def _base_params(+ endpoint: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ resumed_from_date: str | None,+) -> dict[str, Any]:+ config = SAVVYCAL_ENDPOINTS[endpoint]+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.params}++ if endpoint == "events":+ from_date = resumed_from_date+ if from_date is None and should_use_incremental_field and db_incremental_field_last_value is not None:+ from_date = _format_from_date(db_incremental_field_last_value)++ if from_date is not None:+ # `from` only applies with period=fixed. The spec marks `until` independently optional,+ # so we leave the window open-ended; unverifiable without live credentials.+ params["period"] = "fixed"+ params["from"] = from_date+ else:+ params["period"] = "all"++ return params+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SavvyCalResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ after = resume.after if resume else None+ params = _base_params(+ endpoint,+ should_use_incremental_field,+ db_incremental_field_last_value,+ resumed_from_date=resume.from_date if resume else None,+ )+ if resume and resume.after is not None:+ logger.debug(f"SavvyCal: resuming {endpoint} from cursor {after}")++ config = SAVVYCAL_ENDPOINTS[endpoint]+ while True:+ page_params = {**params, "after": after} if after is not None else params+ items, after = _fetch_page(session, config.path, page_params, logger)+ if items:+ yield _redact(items, config.redact_fields)++ # A null `metadata.after` cursor means we've reached the end of the collection.+ if not after:+ break++ # Save AFTER yielding so a crash re-fetches from the next cursor (already-yielded pages are+ # persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(SavvyCalResumeConfig(after=after, from_date=params.get("from")))+++def savvycal_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[SavvyCalResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = SAVVYCAL_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ # Events are requested with direction=asc on start time, matching the incremental cursor;+ # other endpoints are full refresh, where the watermark is unused.+ sort_mode="asc",+ )+++def check_access(api_key: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_key), redact_values=(api_key,))+ try:+ response = session.get(f"{SAVVYCAL_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to SavvyCal: {e}"++ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"SavvyCal returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_key: str) -> tuple[bool, str | None]:+ status, message = check_access(api_key)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid SavvyCal personal access token"+ return False, message or "Could not validate SavvyCal personal access token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/settings.pynew file mode 100644index 000000000000..9f9877c4e833--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/settings.py@@ -0,0 +1,60 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class SavvyCalEndpointConfig:+ name: str+ path: str+ # SavvyCal object IDs are prefixed ULIDs (event_..., link_..., wbhk_..., wkflw_...), unique+ # across the account, so `id` is a safe primary key.+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Extra query params sent on every request to this endpoint.+ params: dict[str, str] = field(default_factory=dict)+ # Stable datetime column to partition on (never a mutable field like start_at).+ partition_key: str | None = None+ # Fields stripped from every row before it lands in the warehouse. Used to keep upstream+ # secrets (e.g. webhook signing secrets) out of a table any project member can query.+ redact_fields: frozenset[str] = field(default_factory=frozenset)+++# SavvyCal v1 REST list endpoints (https://api.savvycal.com/v1/spec). Only `events` supports+# incremental sync: the API exposes `from`/`until` bounds on the event *start date* (with+# `period=fixed`) plus a `direction` sort, but no resource has an updated-after / last-modified+# cursor, so every other stream is full refresh only.+SAVVYCAL_ENDPOINTS: dict[str, SavvyCalEndpointConfig] = {+ "events": SavvyCalEndpointConfig(+ name="events",+ path="/events",+ # Defaults are period=upcoming, state=confirmed, attendance=attending — far narrower than+ # what a warehouse import wants, so widen every filter. `period` is set per-sync in the+ # transport ("all" for full refresh, "fixed" + `from` for incremental).+ params={"state": "all", "attendance": "any", "direction": "asc"},+ partition_key="created_at",+ ),+ "links": SavvyCalEndpointConfig(name="links", path="/links"),+ # The webhook object carries a `secret` (its signing secret); redact it so it never reaches the+ # warehouse table.+ "webhooks": SavvyCalEndpointConfig(+ name="webhooks", path="/webhooks", partition_key="created_at", redact_fields=frozenset({"secret"})+ ),+ "workflows": SavvyCalEndpointConfig(name="workflows", path="/workflows", partition_key="created_at"),+}++ENDPOINTS = tuple(SAVVYCAL_ENDPOINTS.keys())++# `from` filters events on their start date server-side, so start_at is the only genuine+# incremental cursor. Caveat (documented in the source docs): updates to events that started+# before the watermark — e.g. a cancellation of a past event — are only picked up by a full+# refresh; a reschedule moves start_at forward and is re-fetched naturally.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "events": [+ {+ "label": "start_at",+ "type": IncrementalFieldType.DateTime,+ "field": "start_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/source.pyindex 298f028abfce..a9dff4f2b714 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import SavvyCalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.savvycal import (+ SavvyCalResumeConfig,+ savvycal_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SAVVYCAL_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SavvyCalSource(SimpleSource[SavvyCalSourceConfig]):+class SavvyCalSource(ResumableSource[SavvyCalSourceConfig, SavvyCalResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SAVVYCAL@@ -24,7 +48,93 @@ class SavvyCalSource(SimpleSource[SavvyCalSourceConfig]):name=SchemaExternalDataSourceType.SAVVY_CAL,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="SavvyCal",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your SavvyCal personal access token to pull your scheduling data into the PostHog Data warehouse.++You can create a token under [Developer Settings](https://savvycal.com/developers) in SavvyCal — click **Create a token** and give it a name. The token carries your account's full read access, covering events, scheduling links, webhooks, and workflows.+""",iconPath="/static/services/savvycal.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/savvycal",+ keywords=["scheduling", "calendar", "booking"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="Personal access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="pt_secret_...",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.savvycal.com": "Your SavvyCal personal access token is invalid or has been revoked. Create a new token under Developer Settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.savvycal.com": "Your SavvyCal personal access token does not have access to this data. Check the token owner's account permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: SavvyCalSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Only events expose a server-side cursor (`from` bound on start date); every other stream+ # has no updated-after filter, so it's full refresh only.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in INCREMENTAL_FIELDS,+ supports_append=endpoint in INCREMENTAL_FIELDS,+ incremental_fields=list(INCREMENTAL_FIELDS.get(endpoint, [])),+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: SavvyCalSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # Personal access tokens carry the account's full read access, so a single probe validates+ # access to every schema.+ return validate_credentials(config.api_key)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SavvyCalResumeConfig]:+ return ResumableSourceManager[SavvyCalResumeConfig](inputs, SavvyCalResumeConfig)++ def source_for_pipeline(+ self,+ config: SavvyCalSourceConfig,+ resumable_source_manager: ResumableSourceManager[SavvyCalResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in SAVVYCAL_ENDPOINTS:+ raise ValueError(f"Unknown SavvyCal schema '{inputs.schema_name}'")++ return savvycal_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal.pynew file mode 100644index 000000000000..30f052f3a8a0--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal.py@@ -0,0 +1,314 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal import savvycal+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.savvycal import (+ SAVVYCAL_BASE_URL,+ SavvyCalResumeConfig,+ SavvyCalRetryableError,+ check_access,+ get_rows,+ savvycal_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.settings import (+ ENDPOINTS,+ SAVVYCAL_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = savvycal._fetch_page.__wrapped__ # type: ignore[attr-defined]+++class _FakeResumableManager:+ def __init__(self, state: SavvyCalResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[SavvyCalResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> SavvyCalResumeConfig | None:+ return self._state++ def save_state(self, data: SavvyCalResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(+ manager: _FakeResumableManager,+ pages: dict[str | None, tuple[list[dict], Optional[str]]],+ endpoint: str = "events",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ ) -> tuple[list[dict], list[dict[str, Any]]]:+ requested_params: list[dict[str, Any]] = []++ def fake_fetch(+ session: Any, path: str, params: dict[str, Any], logger: Any+ ) -> tuple[list[dict], Optional[str]]:+ requested_params.append(params)+ return pages[params.get("after")]++ rows: list[dict] = []+ with (+ patch.object(savvycal, "_fetch_page", fake_fetch),+ patch.object(savvycal, "make_tracked_session", return_value=MagicMock()),+ ):+ for batch in get_rows(+ api_key="pt_secret_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ):+ rows.extend(batch)+ return rows, requested_params++ def test_single_page_yields_and_stops(self) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(manager, {None: ([{"id": "a"}, {"id": "b"}], None)})+ assert rows == [{"id": "a"}, {"id": "b"}]+ # A null after cursor ends the sync without persisting resume state.+ assert manager.saved == []++ def test_follows_after_cursor_until_null(self) -> None:+ manager = _FakeResumableManager()+ pages: dict[str | None, tuple[list[dict], Optional[str]]] = {+ None: ([{"id": "a"}], "cur_2"),+ "cur_2": ([{"id": "b"}], None),+ }+ rows, params = self._collect(manager, pages)+ assert rows == [{"id": "a"}, {"id": "b"}]+ # State is saved once — after the first page, pointing at the next cursor — then we stop.+ assert [s.after for s in manager.saved] == ["cur_2"]+ # The first request must not carry an after param; the second must.+ assert "after" not in params[0]+ assert params[1]["after"] == "cur_2"++ def test_resumes_from_saved_cursor(self) -> None:+ manager = _FakeResumableManager(SavvyCalResumeConfig(after="cur_2"))+ # The first page must never be fetched on resume.+ rows, _ = self._collect(manager, {"cur_2": ([{"id": "b"}], None)})+ assert rows == [{"id": "b"}]++ def test_empty_first_page_yields_nothing(self) -> None:+ manager = _FakeResumableManager()+ rows, _ = self._collect(manager, {None: ([], None)})+ assert rows == []+ assert manager.saved == []++ def test_events_full_refresh_widens_default_filters(self) -> None:+ # SavvyCal defaults to period=upcoming, state=confirmed, attendance=attending — any of+ # those silently drops most of the account's history from a warehouse import.+ _, params = self._collect(_FakeResumableManager(), {None: ([], None)})+ assert params[0]["period"] == "all"+ assert params[0]["state"] == "all"+ assert params[0]["attendance"] == "any"+ assert params[0]["direction"] == "asc"+ assert params[0]["limit"] == 100+ assert "from" not in params[0]++ @parameterized.expand(+ [+ ("datetime", datetime(2026, 3, 5, 14, 30, tzinfo=UTC), "2026-03-05"),+ ("date", date(2026, 3, 5), "2026-03-05"),+ ]+ )+ def test_events_incremental_maps_watermark_to_fixed_window(+ self, _name: str, watermark: Any, expected_from: str+ ) -> None:+ _, params = self._collect(+ _FakeResumableManager(),+ {None: ([], None)},+ should_use_incremental_field=True,+ db_incremental_field_last_value=watermark,+ )+ assert params[0]["period"] == "fixed"+ assert params[0]["from"] == expected_from++ def test_resume_reuses_saved_from_bound_over_new_watermark(self) -> None:+ # The saved cursor was minted under the original `from` bound; recomputing it from an+ # advanced watermark would pair the cursor with a different query.+ manager = _FakeResumableManager(SavvyCalResumeConfig(after="cur_2", from_date="2026-01-01"))+ pages: dict[str | None, tuple[list[dict], Optional[str]]] = {+ "cur_2": ([{"id": "b"}], "cur_3"),+ "cur_3": ([], None),+ }+ _, params = self._collect(+ manager,+ pages,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),+ )+ assert all(p["from"] == "2026-01-01" for p in params)+ # The re-saved state carries the same original bound forward.+ assert manager.saved[0].from_date == "2026-01-01"++ def test_webhooks_secret_is_redacted(self) -> None:+ # The webhook signing secret must never reach the warehouse table.+ manager = _FakeResumableManager()+ rows, _ = self._collect(+ manager,+ {None: ([{"id": "wbhk_1", "url": "https://x", "secret": "whsec_leak"}], None)},+ endpoint="webhooks",+ )+ assert rows == [{"id": "wbhk_1", "url": "https://x"}]++ def test_non_events_endpoint_sends_no_event_filters(self) -> None:+ _, params = self._collect(_FakeResumableManager(), {None: ([], None)}, endpoint="links")+ assert params[0] == {"limit": 100}++ def test_incremental_flag_ignored_for_full_refresh_endpoint(self) -> None:+ _, params = self._collect(+ _FakeResumableManager(),+ {None: ([], None)},+ endpoint="webhooks",+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),+ )+ assert "from" not in params[0]+ assert "period" not in params[0]+++class TestFetchPage:+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"entries": [], "metadata": {"after": None}}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(SavvyCalRetryableError):+ _fetch_page_unwrapped(session, "/events", {"limit": 100}, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("bad_request", 400)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, "/events", {"limit": 100}, MagicMock())++ def test_success_returns_entries_and_after_cursor(self) -> None:+ body = {"entries": [{"id": "a"}], "metadata": {"after": "cur_2", "before": None, "limit": 100}}+ session = self._session_returning(200, body)+ rows, after = _fetch_page_unwrapped(session, "/events", {"limit": 100}, MagicMock())+ assert rows == [{"id": "a"}]+ assert after == "cur_2"+ args, kwargs = session.get.call_args+ assert args[0] == f"{SAVVYCAL_BASE_URL}/events"+ assert kwargs["params"] == {"limit": 100}++ def test_null_after_returns_none(self) -> None:+ body = {"entries": [{"id": "a"}], "metadata": {"after": None, "before": "cur_1", "limit": 100}}+ session = self._session_returning(200, body)+ _, after = _fetch_page_unwrapped(session, "/events", {"limit": 100}, MagicMock())+ assert after is None++ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_entries", {"metadata": {"after": None}})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(SavvyCalRetryableError):+ _fetch_page_unwrapped(session, "/links", {"limit": 100}, MagicMock())+++class TestCheckAccess:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "SavvyCal returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with patch.object(savvycal, "make_tracked_session", return_value=self._session(response)):+ assert check_access("pt_secret_key") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(savvycal, "make_tracked_session", return_value=session):+ status, message = check_access("pt_secret_key")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid SavvyCal personal access token"),+ ("forbidden", 403, False, "Invalid SavvyCal personal access token"),+ ("server_error", 500, False, "SavvyCal returned HTTP 500"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with patch.object(savvycal, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("pt_secret_key") == (expected_valid, expected_message)+++class TestSavvyCalSourceResponse:+ @parameterized.expand([(e,) for e in ENDPOINTS])+ def test_source_response_shape(self, endpoint: str) -> None:+ response = savvycal_source(+ api_key="pt_secret_key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"++ def test_events_partition_on_stable_created_at(self) -> None:+ response = savvycal_source(+ api_key="pt_secret_key", endpoint="events", logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ # start_at moves on reschedule; partitioning must stay on the immutable creation timestamp.+ assert response.partition_mode == "datetime"+ assert response.partition_keys == ["created_at"]++ def test_links_have_no_partitioning(self) -> None:+ # The Link schema exposes no creation timestamp to partition on.+ response = savvycal_source(+ api_key="pt_secret_key", endpoint="links", logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.partition_mode is None+ assert response.partition_keys is None++ def test_every_endpoint_uses_id_primary_key(self) -> None:+ assert all(config.primary_keys == ["id"] for config in SAVVYCAL_ENDPOINTS.values())+ assert set(SAVVYCAL_ENDPOINTS) == set(ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal_source.pynew file mode 100644index 000000000000..1ab6a6c55326--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/savvycal/tests/test_savvycal_source.py@@ -0,0 +1,143 @@+import pytest+from unittest import mock++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 import SavvyCalSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.savvycal import SavvyCalResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.source import SavvyCalSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestSavvyCalSource:+ def setup_method(self) -> None:+ self.source = SavvyCalSource()+ self.team_id = 123+ self.config = SavvyCalSourceConfig(api_key="pt_secret_key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.SAVVYCAL++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "SavvyCal"+ assert config.label == "SavvyCal"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/savvycal"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_key"]++ def test_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret token; the base URL is hardcoded, so there is no non-secret+ # field an editor could retarget to reuse a preserved token against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_events_support_incremental(self) -> None:+ # Only /events exposes a server-side cursor (`from` on start date); advertising incremental+ # on any other stream would silently sync nothing new.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas["events"].supports_incremental is True+ assert [f["field"] for f in schemas["events"].incremental_fields] == ["start_at"]+ for name in set(ENDPOINTS) - {"events"}:+ assert schemas[name].supports_incremental is False+ assert schemas[name].incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["links"])+ assert len(schemas) == 1+ assert schemas[0].name == "links"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.savvycal.com/v1/events",),+ ("403 Client Error: Forbidden for url: https://api.savvycal.com/v1/me",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.savvycal.com/v1/events",),+ ("429 Client Error: Too Many Requests for url: https://api.savvycal.com/v1/links",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ # The source method forwards the token to the shared validator and returns its result verbatim.+ mock_validate.return_value = (False, "Invalid SavvyCal personal access token")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid SavvyCal personal access token")+ mock_validate.assert_called_once_with("pt_secret_key")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is SavvyCalResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.source.savvycal_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-01-01"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_key"] == "pt_secret_key"+ assert kwargs["endpoint"] == "events"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.savvycal.source.savvycal_source")+ def test_source_for_pipeline_drops_watermark_for_full_refresh(self, mock_source: mock.MagicMock) -> None:+ # A stale watermark from a previous incremental config must not leak into a full refresh.+ inputs = mock.MagicMock()+ inputs.schema_name = "events"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-01-01"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown SavvyCal schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)