: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 writesonic import source (#69622)
Tom Owersda3867d4389e
diff --git a/frontend/public/services/writesonic.svg b/frontend/public/services/writesonic.svgnew file mode 100644index 000000000000..41635677a227--- /dev/null+++ b/frontend/public/services/writesonic.svg@@ -0,0 +1,4 @@+<svg width="64" height="64" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">+ <rect width="64" height="64" rx="14" fill="#FF6719"/>+ <path d="M1153.25 473.701C1121.11 460.706 1084.52 468 1060.05 492.311L944.73 607.008L1005.68 667.207L1119.84 553.639V846.995L897.912 626.457C881.785 610.423 860.244 601.567 837.313 601.538H837.226C814.324 601.538 792.812 610.365 776.685 626.312L553.339 847.342V553.32L668.486 667.381L729.375 607.239L612.983 491.848C588.488 467.594 551.92 460.359 519.811 473.412C487.731 486.464 467 516.969 467 551.15V849.513C467 883.693 487.731 914.227 519.811 927.28C530.408 931.592 541.526 933.676 552.499 933.676C574.735 933.676 596.537 925.08 612.954 908.844L837.197 686.946L1060.05 908.41C1084.52 932.721 1121.11 940.014 1153.25 926.991C1185.39 913.967 1206.18 883.433 1206.18 849.194V551.497C1206.18 517.259 1185.42 486.725 1153.25 473.701Z" fill="#F5F4F1" transform="translate(-22.2919 -13.4378) scale(0.064865)"/>+</svg>diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d7a21441c482..2ba09abcfa63 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -392,6 +392,7 @@ the row lists both.| workable | HTTP | requests | ✅ || workos | HTTP | requests + `rest_source.RESTClient` | ✅ || wrike | HTTP | requests | ✅ |+| writesonic | HTTP | requests | ✅ || wufoo | HTTP | requests | ✅ || zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ || zendesk_sell | HTTP | requests | ✅ |@@ -843,7 +844,6 @@ doesn't conflict with concurrent PRs.- workday- workflowmax- workramp-- writesonic- wufoo- xero- xsolladiff --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 b8b0f2e3bf38..ac6f2aef6c62 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@@ -4039,7 +4039,9 @@ class WrikeSourceConfig(config.Config):@config.configclass WritesonicSourceConfig(config.Config):- pass+ api_key: str+ site_url: str+ project_id: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/canonical_descriptions.pynew file mode 100644index 000000000000..0000b6ec64d3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/canonical_descriptions.py@@ -0,0 +1,133 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the official Writesonic GEO Presence API reference+# (https://docs.writesonic.com/reference).++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "performance_summary": {+ "description": "Daily aggregated GEO KPIs per tracked website: visibility score, rank, prompt and mention totals, averaged across prompts and AI platforms.",+ "docs_url": "https://docs.writesonic.com/reference/performance_summary_v2_geo_presence_business_export_performance_summary_get",+ "columns": {+ "date": "UTC day the metrics were measured on.",+ "website_id": "Unique identifier of the tracked website (your own site or a competitor).",+ "website_name": "Display name of the tracked website.",+ "website_url": "URL of the tracked website.",+ "total_prompts": "Number of prompts (queries) evaluated for the day.",+ "total_results": "Number of AI responses collected for the day.",+ "total_mentions": "Number of AI responses that mentioned the website.",+ "visibility_score": "Share of AI responses mentioning the website, as a percentage.",+ "rank": "Average position of the website within AI responses that mention it.",+ },+ },+ "performance_prompts": {+ "description": "Daily aggregated GEO performance per prompt: mentions, average visibility score, and average rank across the AI platforms that answered it.",+ "docs_url": "https://docs.writesonic.com/reference/performance_prompts_v2_geo_presence_business_export_performance_prompts_get",+ "columns": {+ "date": "UTC day the metrics were measured on.",+ "prompt_id": "Unique identifier of the prompt (query).",+ "prompt_text": "The prompt text as asked to the AI platforms.",+ "topic_id": "Unique identifier of the topic the prompt belongs to.",+ "topic_name": "Name of the topic the prompt belongs to.",+ "total_models": "Number of AI platforms that answered the prompt on the day.",+ "total_mentions": "Number of AI responses that mentioned your brand.",+ "avg_visibility_score": "Average visibility score for the prompt across platforms.",+ "avg_rank": "Average position of your brand within responses that mention it.",+ },+ },+ "performance_answers": {+ "description": "Raw, response-level AI answers per prompt-topic-platform for a day, including the answer text and the brands each response mentioned.",+ "docs_url": "https://docs.writesonic.com/reference/performance_answers_v2_geo_presence_business_export_performance_answers_get",+ "columns": {+ "date": "UTC day the response was collected on.",+ "prompt_id": "Unique identifier of the prompt (query).",+ "prompt": "The prompt text as asked to the AI platform.",+ "topic_id": "Unique identifier of the topic the prompt belongs to.",+ "topic_name": "Name of the topic the prompt belongs to.",+ "platform_id": "Unique identifier of the AI platform (e.g. ChatGPT, Perplexity).",+ "platform_name": "Name of the AI platform that produced the response.",+ "response_id": "Unique identifier of the individual AI response.",+ "answer_text": "Full text of the AI response.",+ "rank": "Position of your brand within the response, when mentioned.",+ "visibility_score": "Visibility score of your brand for this response.",+ "brand_mentions": "List of tracked websites mentioned in the response, with per-brand rank, visibility score, and the sentences that mention them.",+ },+ },+ "content_citations": {+ "description": "Citations (source pages) referenced by AI answers on a day, with the tracked websites each citation mentions and the responses that used it.",+ "docs_url": "https://docs.writesonic.com/reference/content_citations_v2_geo_presence_business_export_content_citations_get",+ "columns": {+ "date": "UTC day the export covers (stamped from the request date).",+ "citation_id": "Unique identifier of the citation.",+ "citation_title": "Title of the cited page.",+ "citation_uri": "URL of the cited page.",+ "citation_domain": "Domain of the cited page.",+ "created_at": "When the citation was first recorded.",+ "mentioned_websites_json": "Tracked websites (own and competitors) the citation mentions.",+ "responses_json": "AI responses that referenced the citation, with prompt, platform, and topic context.",+ },+ },+ "content_keywords": {+ "description": "Keywords and themes extracted from AI answers on a day, with the responses and sentiment behind each keyword.",+ "docs_url": "https://docs.writesonic.com/reference/content_keywords_v2_geo_presence_business_export_content_keywords_get",+ "columns": {+ "date": "UTC day the export covers (stamped from the request date).",+ "id": "Unique identifier of the keyword record.",+ "keyword": "The extracted keyword.",+ "theme": "Theme the keyword belongs to.",+ "subtheme": "Subtheme the keyword belongs to.",+ "responses": "AI responses the keyword was extracted from, with platform, query, sentence, and sentiment.",+ "created_at": "When the keyword was first recorded.",+ },+ },+ "topics": {+ "description": "The topics configured for the tracked site. Prompts are grouped under topics.",+ "docs_url": "https://docs.writesonic.com/reference/topics_export_v2_geo_presence_business_export_config_topics_get",+ "columns": {+ "topic_id": "Unique identifier of the topic.",+ "name": "Name of the topic.",+ "created_at": "When the topic was created.",+ "updated_at": "When the topic was last updated.",+ },+ },+ "platforms": {+ "description": "The AI platforms/models (e.g. ChatGPT, Perplexity, Google AI Overviews) enabled for the tracked site.",+ "docs_url": "https://docs.writesonic.com/reference/platforms_export_v2_geo_presence_business_export_config_platforms_get",+ "columns": {+ "platform_id": "Unique identifier of the AI platform.",+ "name": "Name of the AI platform.",+ "provider": "Provider of the AI platform.",+ "category_id": "Unique identifier of the platform category.",+ "category": "Category of the platform (e.g. Search Models).",+ },+ },+ "websites": {+ "description": "All websites associated with the tracked site: your own properties and every tracked competitor.",+ "docs_url": "https://docs.writesonic.com/reference/websites_export_v2_geo_presence_business_export_config_websites_get",+ "columns": {+ "website_id": "Unique identifier of the website.",+ "name": "Display name of the website.",+ "url": "URL of the website.",+ "is_competitor": "Whether the website is a tracked competitor.",+ "is_self_website": "Whether the website is one of your own properties.",+ "logo": "URL of the website's logo/favicon.",+ "created_at": "When the website was added.",+ "updated_at": "When the website was last updated.",+ },+ },+ "prompts": {+ "description": "All prompts (queries) configured for the tracked site, with their topic, country, and status.",+ "docs_url": "https://docs.writesonic.com/reference/prompts_export_v2_geo_presence_business_export_config_prompts_get",+ "columns": {+ "prompt_id": "Unique identifier of the prompt.",+ "prompt": "The prompt text.",+ "topic_id": "Unique identifier of the topic the prompt belongs to.",+ "topic": "Name of the topic the prompt belongs to.",+ "country_code": "Country the prompt is evaluated for.",+ "status": "Status of the prompt (e.g. ACTIVE).",+ "created_at": "When the prompt was created.",+ "updated_at": "When the prompt was last updated.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/posthog_com_doc.md b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/posthog_com_doc.mdnew file mode 100644index 000000000000..f35f69c64735--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/posthog_com_doc.md@@ -0,0 +1,63 @@+---+title: Linking Writesonic as a source+sidebar: Docs+showTitle: true+availability: { free: full, selfServe: full, enterprise: full }+sourceId: Writesonic+beta: true+---++<!--+This is the user-facing posthog.com doc for the Writesonic source. It must be copied to the posthog.com+repo at contents/docs/cdp/sources/writesonic.md (served at /docs/cdp/sources/writesonic). It lives here+only because no posthog.com checkout was available when the source was implemented — it does not belong+in the posthog repo long-term. Once moved, run:+ python manage.py audit_source_docs --docs-dir ../posthog.com/contents/docs/cdp/sources+-->++import SourceSetupIntro from "../\_snippets/source-setup-intro.mdx"+import SyncModes from "../\_snippets/sync-modes.mdx"+import TroubleshootingLink from "../\_snippets/dw-troubleshooting-link.mdx"+import AlphaRelease from "../\_snippets/alpha-release.mdx"++<AlphaRelease />++[Writesonic](https://writesonic.com) tracks your brand's visibility in AI search — how often, how prominently, and in what context AI platforms like ChatGPT, Perplexity, and Google AI Overviews mention your brand (GEO, generative engine optimization). This connector pulls your daily performance metrics, raw AI answers with brand mentions, citations, keywords, and tracked configuration (topics, prompts, platforms, websites) into the PostHog Data warehouse, where you can join AI visibility with your product analytics.++## Prerequisites++You need a Writesonic account on a plan with API access to GEO data, with at least one website tracked. Your API key is revealed in the API dashboard of your Writesonic account.++## Adding a data source++<SourceSetupIntro />++You'll need:++- **API key** — from your Writesonic account's API dashboard. It authenticates every request through the `X-API-Key` header.+- **Site URL** — the URL of the tracked website, exactly as configured in Writesonic (e.g. `https://example.com`).+- **Project ID** (optional) — only needed to disambiguate when the same site is tracked in multiple Writesonic projects.++To sync more than one tracked site, add a separate Writesonic source per site.++## Sync modes++<SyncModes />++The performance and content tables (`performance_summary`, `performance_prompts`, `performance_answers`, `content_citations`, `content_keywords`) are exported one UTC day at a time and sync incrementally by date — the first sync backfills up to the last 365 days, and each later sync picks up from the last synced day. The configuration tables (`topics`, `platforms`, `websites`, `prompts`) are small and sync as full refresh.++## Configuration++<SourceParameters />++## Supported tables++<SourceTables />++## Troubleshooting++- **Invalid or inactive API key** — the key is wrong or was deactivated. Check the key in your Writesonic API dashboard and reconnect.+- **Site not found** — Writesonic couldn't match the configured site URL (and project ID, if set) to a tracked website in your account. Copy the URL exactly as it appears in your Writesonic workspace.+- **Plan does not include API access** — GEO data exports require a Writesonic plan with API access. Upgrade your plan and reconnect.++<TroubleshootingLink />diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/settings.pynew file mode 100644index 000000000000..df255f15eaf7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/settings.py@@ -0,0 +1,124 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://api.writesonic.com"++# Writesonic caps `size` at 100 per page (default 50).+PAGE_SIZE = 100++# The performance/content export endpoints require a `date` param (one UTC day per request), so a+# first sync walks day windows backwards-bounded by this lookback. GEO tracking only produces data+# from the day a site was onboarded, so earlier days simply return empty pages.+DEFAULT_LOOKBACK_DAYS = 365+++@dataclass+class WritesonicEndpointConfig:+ name: str+ path: str+ primary_keys: list[str]+ # Daily endpoints require a `date` query param (UTC day) and are synced one day at a time,+ # which is also the incremental granularity. Non-daily (config) endpoints are full refresh.+ daily: bool = False+ # The content export rows don't carry the requested export date, so we stamp it in — it's+ # both part of the primary key and the incremental/partition field.+ inject_date: bool = False+ # Stable field used for datetime partitioning. Must never change after a row is written.+ partition_key: Optional[str] = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++_DATE_FIELD: IncrementalField = {+ "label": "date",+ "type": IncrementalFieldType.Date,+ "field": "date",+ "field_type": IncrementalFieldType.Date,+}+++WRITESONIC_ENDPOINTS: dict[str, WritesonicEndpointConfig] = {+ # Daily aggregated KPIs (visibility score, rank, mentions) per tracked website.+ "performance_summary": WritesonicEndpointConfig(+ name="performance_summary",+ path="/v2/geo/presence/business/export/performance/summary",+ primary_keys=["date", "website_id"],+ daily=True,+ partition_key="date",+ incremental_fields=[_DATE_FIELD],+ ),+ # Aggregated performance per prompt (across AI platforms) for the given day.+ "performance_prompts": WritesonicEndpointConfig(+ name="performance_prompts",+ path="/v2/geo/presence/business/export/performance/prompts",+ primary_keys=["date", "prompt_id"],+ daily=True,+ partition_key="date",+ incremental_fields=[_DATE_FIELD],+ ),+ # Raw response-level rows with brand mentions per prompt-topic-platform for the given day.+ # `response_id`'s uniqueness scope isn't documented, so the date stays in the key.+ "performance_answers": WritesonicEndpointConfig(+ name="performance_answers",+ path="/v2/geo/presence/business/export/performance/answers",+ primary_keys=["date", "response_id"],+ daily=True,+ partition_key="date",+ incremental_fields=[_DATE_FIELD],+ ),+ # Citations referenced by AI answers on the given day, with the websites they mention.+ "content_citations": WritesonicEndpointConfig(+ name="content_citations",+ path="/v2/geo/presence/business/export/content/citations",+ primary_keys=["date", "citation_id"],+ daily=True,+ inject_date=True,+ partition_key="date",+ incremental_fields=[_DATE_FIELD],+ ),+ # Keywords/themes extracted from AI answers on the given day.+ "content_keywords": WritesonicEndpointConfig(+ name="content_keywords",+ path="/v2/geo/presence/business/export/content/keywords",+ primary_keys=["date", "id"],+ daily=True,+ inject_date=True,+ partition_key="date",+ incremental_fields=[_DATE_FIELD],+ ),+ # Config dimension tables. Small, no server-side updated-since filter -> full refresh.+ "topics": WritesonicEndpointConfig(+ name="topics",+ path="/v2/geo/presence/business/export/config/topics",+ primary_keys=["topic_id"],+ partition_key="created_at",+ ),+ "platforms": WritesonicEndpointConfig(+ name="platforms",+ path="/v2/geo/presence/business/export/config/platforms",+ primary_keys=["platform_id"],+ ),+ "websites": WritesonicEndpointConfig(+ name="websites",+ path="/v2/geo/presence/business/export/config/websites",+ primary_keys=["website_id"],+ partition_key="created_at",+ ),+ "prompts": WritesonicEndpointConfig(+ name="prompts",+ path="/v2/geo/presence/business/export/config/prompts",+ primary_keys=["prompt_id"],+ partition_key="created_at",+ ),+}++ENDPOINTS = tuple(WRITESONIC_ENDPOINTS.keys())++# Only the daily export endpoints have a genuine server-side date filter (the required `date`+# param); the config exports return `created_at`/`updated_at` but expose no updated-since filter.+SUPPORTS_INCREMENTAL: set[str] = {name for name, cfg in WRITESONIC_ENDPOINTS.items() if cfg.daily}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: cfg.incremental_fields for name, cfg in WRITESONIC_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/source.pyindex 76d97a6c581c..457525e1813e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/source.py@@ -1,31 +1,181 @@-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 WritesonicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ SUPPORTS_INCREMENTAL,+ WRITESONIC_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.writesonic import (+ WritesonicResumeConfig,+ validate_credentials as validate_writesonic_credentials,+ writesonic_source,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class WritesonicSource(SimpleSource[WritesonicSourceConfig]):+class WritesonicSource(ResumableSource[WritesonicSourceConfig, WritesonicResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.WRITESONIC+ @property+ def connection_host_fields(self) -> list[str]:+ # `site_url` (and optionally `project_id`) pick which tracked site the stored API key+ # is used against; retargeting either must re-require the key so an editor without it+ # can't aim an existing connection at different data.+ return ["site_url", "project_id"]+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.WRITESONIC,- category=DataWarehouseSourceCategory.MARKETING___EMAIL,+ category=DataWarehouseSourceCategory.ANALYTICS,label="Writesonic",- iconPath="/static/services/writesonic.png",- keywords=["seo", "geo", "ai visibility", "content marketing"],- fields=cast(list[FieldType], []),+ caption="""Connect Writesonic to pull your GEO (generative engine optimization) data — brand visibility, rank, and mentions across AI platforms like ChatGPT and Perplexity — into the PostHog Data warehouse.++You'll need:++- A Writesonic **API key** with GEO API access (revealed in your account's API dashboard; requires a plan with API access)+- The **site URL** of the tracked website, exactly as configured in Writesonic (e.g. `https://example.com`)+- Optionally, a **project ID** to disambiguate when the same site is tracked in multiple projects+""",+ iconPath="/static/services/writesonic.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/writesonic",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["seo", "geo", "ai visibility", "content marketing"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Your Writesonic API key",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="site_url",+ label="Site URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="project_id",+ label="Project ID (optional)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="bb2baeaa-a48c-482b-af00-67df964b5d2b",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: WritesonicSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=endpoint in SUPPORTS_INCREMENTAL,+ supports_append=endpoint in SUPPORTS_INCREMENTAL,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=WRITESONIC_ENDPOINTS[endpoint].primary_keys,+ description="Only syncs the last 365 days on initial sync"+ if endpoint in SUPPORTS_INCREMENTAL+ else None,+ )+ 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: WritesonicSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_writesonic_credentials(+ api_key=config.api_key,+ site_url=config.site_url,+ project_id=config.project_id,+ schema_name=schema_name,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.writesonic.com": (+ "Writesonic rejected the API key. Generate a new key in your Writesonic API dashboard and reconnect."+ ),+ "403 Client Error: Forbidden for url: https://api.writesonic.com": (+ "Your Writesonic plan does not include API access to GEO data. Upgrade to a plan with "+ "API access and reconnect."+ ),+ "404 Client Error: Not Found for url: https://api.writesonic.com": (+ "Writesonic could not find a tracked site for the configured URL. Check the site URL "+ "(and project ID, if set) against your Writesonic workspace."+ ),+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WritesonicResumeConfig]:+ return ResumableSourceManager[WritesonicResumeConfig](inputs, WritesonicResumeConfig)++ def source_for_pipeline(+ self,+ config: WritesonicSourceConfig,+ resumable_source_manager: ResumableSourceManager[WritesonicResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return writesonic_source(+ api_key=config.api_key,+ site_url=config.site_url,+ project_id=config.project_id,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ 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/writesonic/tests/test_writesonic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.pynew file mode 100644index 000000000000..57940fe27e29--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic.py@@ -0,0 +1,363 @@+from datetime import UTC, date, datetime+from typing import Any++import pytest+from freezegun import freeze_time+from unittest import mock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic import writesonic+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.settings import WRITESONIC_ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.writesonic import (+ WritesonicResumeConfig,+ WritesonicRetryableError,+ _check_response,+ _to_date,+ get_rows,+ validate_credentials,+ writesonic_source,+)+++class _FakeManager:+ def __init__(self, state: WritesonicResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[WritesonicResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> WritesonicResumeConfig | None:+ return self._state++ def save_state(self, data: WritesonicResumeConfig) -> None:+ self.saved.append(data)+++class _FakeApi:+ """Canned paginated Writesonic responses plus a record of every request made."""++ def __init__(+ self,+ daily_pages: dict[str, list[list[dict[str, Any]]]] | None = None,+ config_pages: list[list[dict[str, Any]]] | None = None,+ ) -> None:+ self.daily_pages = daily_pages or {}+ self.config_pages = config_pages or []+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def get(self, path: str, *, api_key: str, logger: Any, params: dict[str, Any] | None = None) -> Any:+ params = params or {}+ self.calls.append((path, params))+ pages = self.daily_pages.get(params["date"], []) if "date" in params else self.config_pages+ page = params["page"]+ items = pages[page - 1] if 1 <= page <= len(pages) else []+ data = {+ "items": items,+ "page": page,+ "size": params["size"],+ "total": sum(len(p) for p in pages),+ "count": len(items),+ "total_pages": len(pages),+ }+ return mock.Mock(json=lambda data=data: data)+++def _collect(endpoint: str, manager: _FakeManager, monkeypatch: Any, api: _FakeApi, **kwargs: Any) -> list[dict]:+ monkeypatch.setattr(writesonic, "_get", api.get)+ rows: list[dict] = []+ for batch in get_rows(+ api_key="key",+ site_url="https://example.com",+ project_id=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(batch)+ return rows+++class TestToDate:+ @parameterized.expand(+ [+ ("date_value", date(2026, 7, 1), date(2026, 7, 1)),+ ("aware_datetime", datetime(2026, 7, 1, 12, 30, tzinfo=UTC), date(2026, 7, 1)),+ ("date_string", "2026-07-01", date(2026, 7, 1)),+ ("iso_string", "2026-07-01T12:30:00Z", date(2026, 7, 1)),+ ("epoch_int", 1782950400, date(2026, 7, 2)),+ ("bad_string", "not-a-date", None),+ ("none", None, None),+ ("bool", True, None),+ ]+ )+ def test_to_date(self, _name, value, expected):+ assert _to_date(value) == expected+++class TestConfigEndpoints:+ def test_paginates_until_total_pages(self, monkeypatch):+ api = _FakeApi(config_pages=[[{"topic_id": "t1"}], [{"topic_id": "t2"}]])+ rows = _collect("topics", _FakeManager(), monkeypatch, api)+ assert [r["topic_id"] for r in rows] == ["t1", "t2"]+ assert [p["page"] for (_, p) in api.calls] == [1, 2]++ def test_sends_site_url_and_page_size(self, monkeypatch):+ api = _FakeApi(config_pages=[[{"topic_id": "t1"}]])+ _collect("topics", _FakeManager(), monkeypatch, api)+ _, params = api.calls[0]+ assert params["url"] == "https://example.com"+ assert params["size"] == 100+ assert "project_id" not in params++ def test_sends_project_id_when_configured(self, monkeypatch):+ api = _FakeApi(config_pages=[[{"topic_id": "t1"}]])+ monkeypatch.setattr(writesonic, "_get", api.get)+ list(+ get_rows(+ api_key="key",+ site_url="https://example.com",+ project_id="proj-1",+ endpoint="topics",+ logger=mock.MagicMock(),+ manager=_FakeManager(), # type: ignore[arg-type]+ )+ )+ assert api.calls[0][1]["project_id"] == "proj-1"++ def test_resumes_from_saved_page(self, monkeypatch):+ api = _FakeApi(config_pages=[[{"topic_id": "t1"}], [{"topic_id": "t2"}]])+ rows = _collect("topics", _FakeManager(WritesonicResumeConfig(page=2)), monkeypatch, api)+ # Page 1 was already yielded before the crash; only page 2 is re-fetched.+ assert [r["topic_id"] for r in rows] == ["t2"]+ assert [p["page"] for (_, p) in api.calls] == [2]++ def test_saves_state_after_each_page(self, monkeypatch):+ api = _FakeApi(config_pages=[[{"topic_id": "t1"}], [{"topic_id": "t2"}]])+ manager = _FakeManager()+ _collect("topics", manager, monkeypatch, api)+ assert [(s.date, s.page) for s in manager.saved] == [(None, 2), (None, 3)]++ def test_unknown_endpoint_raises(self, monkeypatch):+ with pytest.raises(ValueError):+ _collect("nonexistent", _FakeManager(), monkeypatch, _FakeApi())+++@freeze_time("2026-07-09T12:00:00Z")+class TestDailyEndpoints:+ def test_walks_days_from_watermark_to_today_inclusive(self, monkeypatch):+ # The watermark day is re-fetched: its previous sync may have run mid-day and captured+ # partial data. Skipping it would permanently freeze that day's rows.+ api = _FakeApi(daily_pages={"2026-07-08": [[{"date": "2026-07-08", "website_id": "w1"}]]})+ rows = _collect(+ "performance_summary",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 8),+ )+ assert [p["date"] for (_, p) in api.calls] == ["2026-07-08", "2026-07-09"]+ assert rows == [{"date": "2026-07-08", "website_id": "w1"}]++ def test_first_sync_starts_at_default_lookback(self, monkeypatch):+ api = _FakeApi()+ _collect(+ "performance_summary",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ )+ assert api.calls[0][1]["date"] == "2025-07-09"+ assert api.calls[-1][1]["date"] == "2026-07-09"++ def test_future_cursor_clamped_to_today(self, monkeypatch):+ api = _FakeApi()+ _collect(+ "performance_summary",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2027, 1, 1),+ )+ assert [p["date"] for (_, p) in api.calls] == ["2026-07-09"]++ def test_paginates_within_a_day(self, monkeypatch):+ api = _FakeApi(+ daily_pages={+ "2026-07-09": [+ [{"date": "2026-07-09", "website_id": "w1"}],+ [{"date": "2026-07-09", "website_id": "w2"}],+ ]+ }+ )+ rows = _collect(+ "performance_summary",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 9),+ )+ assert [r["website_id"] for r in rows] == ["w1", "w2"]+ assert [p["page"] for (_, p) in api.calls] == [1, 2]++ def test_injects_date_into_content_rows(self, monkeypatch):+ # Content export rows don't carry the export date, but it's part of the primary key,+ # the partition key, and the incremental cursor — a missing column breaks all three.+ api = _FakeApi(daily_pages={"2026-07-09": [[{"citation_id": "c1"}]]})+ rows = _collect(+ "content_citations",+ _FakeManager(),+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 9),+ )+ assert rows == [{"citation_id": "c1", "date": "2026-07-09"}]++ def test_resumes_from_saved_day_and_page(self, monkeypatch):+ api = _FakeApi(+ daily_pages={+ "2026-07-07": [[{"date": "2026-07-07", "website_id": "w1"}]],+ "2026-07-08": [+ [{"date": "2026-07-08", "website_id": "w1"}],+ [{"date": "2026-07-08", "website_id": "w2"}],+ ],+ }+ )+ manager = _FakeManager(WritesonicResumeConfig(date="2026-07-08", page=2))+ rows = _collect(+ "performance_summary",+ manager,+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 7),+ )+ # Completed days and pages are skipped; the resume day continues at its saved page.+ assert [(p["date"], p["page"]) for (_, p) in api.calls] == [("2026-07-08", 2), ("2026-07-09", 1)]+ assert [r["website_id"] for r in rows] == ["w2"]++ def test_saves_state_after_each_page_and_day(self, monkeypatch):+ api = _FakeApi(+ daily_pages={+ "2026-07-08": [+ [{"date": "2026-07-08", "website_id": "w1"}],+ [{"date": "2026-07-08", "website_id": "w2"}],+ ]+ }+ )+ manager = _FakeManager()+ _collect(+ "performance_summary",+ manager,+ monkeypatch,+ api,+ should_use_incremental_field=True,+ db_incremental_field_last_value=date(2026, 7, 8),+ )+ saved = [(s.date, s.page) for s in manager.saved]+ # Page-level saves point at the next page of the in-flight day; day-level saves point+ # at the next day with page reset, so a crash never skips unread rows.+ assert ("2026-07-08", 2) in saved+ assert ("2026-07-08", 3) in saved+ assert ("2026-07-09", 1) in saved+ assert saved[-1] == ("2026-07-10", 1)+++class TestCheckResponse:+ def _response(self, status_code: int, headers: dict[str, str] | None = None) -> Any:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.headers = headers or {}+ response.text = "body"+ if not response.ok:+ response.raise_for_status.side_effect = requests.HTTPError(f"{status_code} error", response=response)+ return response++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 502), ("unavailable", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name, status):+ with pytest.raises(WritesonicRetryableError):+ _check_response(self._response(status), "https://api.writesonic.com/x", mock.MagicMock())++ def test_retry_after_header_is_carried(self):+ with pytest.raises(WritesonicRetryableError) as exc_info:+ _check_response(+ self._response(429, headers={"Retry-After": "30"}),+ "https://api.writesonic.com/x",+ mock.MagicMock(),+ )+ assert exc_info.value.retry_after == 30.0++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404), ("unprocessable", 422)])+ def test_terminal_statuses_raise_http_error(self, _name, status):+ with pytest.raises(requests.HTTPError):+ _check_response(self._response(status), "https://api.writesonic.com/x", mock.MagicMock())++ def test_ok_returns_response(self):+ response = self._response(200)+ assert _check_response(response, "https://api.writesonic.com/x", mock.MagicMock()) is response+++class TestValidateCredentials:+ def _mock_session(self, status_code: int) -> Any:+ response = mock.MagicMock()+ response.status_code = status_code+ session = mock.MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("not_found", 404, False),+ ("unprocessable", 422, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name, status, expected_ok):+ with mock.patch.object(writesonic, "make_tracked_session", return_value=self._mock_session(status)):+ ok, message = validate_credentials(api_key="key", site_url="https://example.com")+ assert ok is expected_ok+ if not expected_ok:+ assert message++ def test_unreachable_api_fails_gracefully(self):+ session = mock.MagicMock()+ session.get.side_effect = requests.ConnectionError("boom")+ with mock.patch.object(writesonic, "make_tracked_session", return_value=session):+ ok, message = validate_credentials(api_key="key", site_url="https://example.com")+ assert ok is False+ assert message is not None and "reach" in message+++class TestSourceResponse:+ @parameterized.expand([(endpoint,) for endpoint in WRITESONIC_ENDPOINTS])+ def test_source_response_matches_endpoint_config(self, endpoint):+ config = WRITESONIC_ENDPOINTS[endpoint]+ response = writesonic_source(+ api_key="key",+ site_url="https://example.com",+ project_id=None,+ endpoint=endpoint,+ logger=mock.MagicMock(),+ manager=mock.MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic_source.pynew file mode 100644index 000000000000..5f567d7c3324--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/tests/test_writesonic_source.py@@ -0,0 +1,188 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ 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 WritesonicSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.settings import (+ ENDPOINTS,+ WRITESONIC_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.source import WritesonicSource+from products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.writesonic import (+ WritesonicResumeConfig,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestWritesonicSource:+ def setup_method(self):+ self.source = WritesonicSource()+ self.team_id = 123+ self.config = WritesonicSourceConfig(api_key="key_test", site_url="https://example.com")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.WRITESONIC++ def test_get_source_config(self):+ config = self.source.get_source_config+ assert config.name.value == "Writesonic"+ assert config.category == DataWarehouseSourceCategory.ANALYTICS+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.unreleasedSource is True+ assert config.iconPath == "/static/services/writesonic.svg"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/writesonic"++ def test_api_key_field_is_secret_password(self):+ 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_site_url_required_and_project_id_optional(self):+ fields = {f.name: f for f in self.source.get_source_config.fields if isinstance(f, SourceFieldInputConfig)}+ assert fields["site_url"].required is True+ assert fields["project_id"].required is False++ def test_connection_host_fields_cover_data_targeting_fields(self):+ # Changing which tracked site the stored API key is used against must force re-entry+ # of the key; dropping either field lets an editor retarget the connection silently.+ assert set(self.source.connection_host_fields) == {"site_url", "project_id"}++ def test_lists_tables_without_credentials(self):+ # get_schemas is a static catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("performance_summary", True),+ ("performance_prompts", True),+ ("performance_answers", True),+ ("content_citations", True),+ ("content_keywords", True),+ ("topics", False),+ ("platforms", False),+ ("websites", False),+ ("prompts", False),+ ]+ )+ def test_incremental_capability_per_endpoint(self, name, incremental):+ # Only the daily exports have a genuine server-side date filter (the required `date`+ # param); the config exports must stay full refresh.+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ assert schemas[name].supports_incremental is incremental+ if incremental:+ assert [f["field"] for f in schemas[name].incremental_fields] == ["date"]+ else:+ assert schemas[name].incremental_fields == []++ def test_primary_keys_are_exposed(self):+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ for name, endpoint_config in WRITESONIC_ENDPOINTS.items():+ assert schemas[name].detected_primary_keys == endpoint_config.primary_keys++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["performance_summary"])+ assert len(schemas) == 1+ assert schemas[0].name == "performance_summary"++ def test_validate_credentials_plumbs_config(self):+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.source.validate_writesonic_credentials",+ return_value=(True, None),+ ) as validate:+ ok, message = self.source.validate_credentials(self.config, self.team_id, schema_name="topics")+ assert ok is True+ assert message is None+ kwargs = validate.call_args.kwargs+ assert kwargs["api_key"] == "key_test"+ assert kwargs["site_url"] == "https://example.com"+ assert kwargs["project_id"] is None+ assert kwargs["schema_name"] == "topics"++ @parameterized.expand(+ [+ (+ "401 Client Error: Unauthorized for url: https://api.writesonic.com/v2/geo/presence/business/export/config/topics?url=https%3A%2F%2Fexample.com",+ ),+ (+ "403 Client Error: Forbidden for url: https://api.writesonic.com/v2/geo/presence/business/export/performance/summary",+ ),+ (+ "404 Client Error: Not Found for url: https://api.writesonic.com/v2/geo/presence/business/export/config/websites",+ ),+ ]+ )+ def test_non_retryable_errors_match_auth_and_config_failures(self, observed_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",),+ ("500 Server Error for url: https://api.writesonic.com/v2/geo/presence/business/export/config/topics",),+ ("429 Client Error: Too Many Requests for url: https://api.writesonic.com/v2/geo",),+ ]+ )+ def test_non_retryable_errors_ignore_retryable_and_unrelated(self, unrelated_error):+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is WritesonicResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "performance_summary"+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2026-07-01"+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.source.writesonic_source"+ ) as source_fn:+ self.source.source_for_pipeline(self.config, manager, inputs)+ kwargs = source_fn.call_args.kwargs+ assert kwargs["api_key"] == "key_test"+ assert kwargs["site_url"] == "https://example.com"+ assert kwargs["endpoint"] == "performance_summary"+ assert kwargs["manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-07-01"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self):+ manager = mock.MagicMock()+ inputs = mock.MagicMock()+ inputs.schema_name = "topics"+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2026-07-01"+ with mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.writesonic.source.writesonic_source"+ ) as source_fn:+ self.source.source_for_pipeline(self.config, manager, inputs)+ assert source_fn.call_args.kwargs["db_incremental_field_last_value"] is None++ def test_canonical_descriptions_keyed_by_endpoint_names(self):+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(WRITESONIC_ENDPOINTS)++ def test_documented_tables_render_for_public_docs(self):+ # lists_tables_without_credentials=True must produce a credential-free catalog for posthog.com;+ # a regression in get_schemas' placeholder path would silently empty the docs' Supported tables.+ tables = {t["name"]: t for t in self.source.get_documented_tables()}+ assert set(tables) == set(ENDPOINTS)+ assert "Incremental" in tables["performance_summary"]["sync_methods"]+ assert tables["topics"]["sync_methods"] == ["Full refresh"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/writesonic.py b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/writesonic.pynew file mode 100644index 000000000000..775ac37395c1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/writesonic/writesonic.py@@ -0,0 +1,377 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime, timedelta+from email.utils import parsedate_to_datetime+from typing import Any, Optional+from urllib.parse import urljoin++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from urllib3.util.retry import Retry++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.writesonic.settings import (+ BASE_URL,+ DEFAULT_LOOKBACK_DAYS,+ PAGE_SIZE,+ WRITESONIC_ENDPOINTS,+ WritesonicEndpointConfig,+)++REQUEST_TIMEOUT = 60++# Let tenacity be the only retry layer so every request gets the same bounded budget.+NO_URLLIB_RETRY = Retry(total=0)++# Upper bound on how long we'll honor a server-provided `Retry-After`, so a large (or hostile)+# value can't pin a worker thread indefinitely. Writesonic doesn't document its rate limits.+MAX_RETRY_AFTER_SECONDS = 120+++class WritesonicRetryableError(Exception):+ def __init__(self, message: str, retry_after: Optional[float] = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++def _parse_retry_after(value: Optional[str]) -> Optional[float]:+ """Parse a `Retry-After` header (delta-seconds or HTTP-date) into seconds-from-now.++ Returns None for a missing, malformed, or already-elapsed value so the caller falls back to+ its default backoff."""+ if value is None:+ return None+ value = value.strip()+ if not value:+ return None+ try:+ seconds = float(value)+ return seconds if seconds >= 0 else None+ except ValueError:+ pass+ try:+ retry_dt = parsedate_to_datetime(value)+ except (TypeError, ValueError):+ return None+ if retry_dt.tzinfo is None:+ retry_dt = retry_dt.replace(tzinfo=UTC)+ delta = (retry_dt - datetime.now(UTC)).total_seconds()+ return delta if delta > 0 else None+++_EXPONENTIAL_JITTER = wait_exponential_jitter(initial=2, max=60)+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Prefer the server's `Retry-After` cool-down on a 429/5xx; otherwise back off exponentially."""+ outcome = retry_state.outcome+ exc = outcome.exception() if outcome is not None else None+ if isinstance(exc, WritesonicRetryableError) and exc.retry_after is not None:+ return min(exc.retry_after, MAX_RETRY_AFTER_SECONDS)+ return _EXPONENTIAL_JITTER(retry_state)+++class WritesonicResumeConfig:+ # Daily endpoints resume at (day, page); config endpoints only use `page`.+ date: Optional[str] = None+ page: Optional[int] = None+++def _to_date(value: Any) -> Optional[date]:+ """Coerce a stored incremental cursor (date, datetime, epoch seconds, or ISO string) to a date."""+ if value is None or isinstance(value, bool):+ return None+ if isinstance(value, datetime):+ return (value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)).date()+ if isinstance(value, date):+ return value+ if isinstance(value, (int, float)):+ return datetime.fromtimestamp(value, tz=UTC).date()+ if isinstance(value, str) and value.strip():+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00")).date()+ except ValueError:+ return None+ return None+++def _base_params(site_url: str, project_id: Optional[str]) -> dict[str, Any]:+ params: dict[str, Any] = {"url": site_url}+ if project_id:+ params["project_id"] = project_id+ return params+++def validate_credentials(+ api_key: str,+ site_url: str,+ project_id: Optional[str] = None,+ schema_name: Optional[str] = None,+) -> tuple[bool, str | None]:+ """Cheap probe against the websites config export to confirm the key and site URL work.++ Every GEO export endpoint sits behind the same API key scope, so one probe covers all+ schemas — a per-schema check (`schema_name` set) behaves identically."""+ url = urljoin(BASE_URL, "/v2/geo/presence/business/export/config/websites")+ try:+ response = _make_session(api_key).get(+ url,+ params={**_base_params(site_url, project_id), "size": 1},+ headers={"X-API-Key": api_key, "Accept": "application/json"},+ timeout=30,+ )+ except Exception:+ return False, "Could not reach Writesonic. Please try again."++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Writesonic rejected the API key. Check the key in your Writesonic API dashboard."+ if response.status_code == 403:+ return False, (+ "Your Writesonic plan does not include API access to GEO data. "+ "Upgrade to a plan with API access and try again."+ )+ if response.status_code == 404:+ return False, (+ "Writesonic could not find a tracked site for this URL. "+ "Check the site URL (and project ID, if set) against your Writesonic workspace."+ )+ if response.status_code == 422:+ return (+ False,+ "Writesonic rejected the site URL. Enter the full URL of the tracked site, e.g. https://example.com.",+ )+ return False, f"Writesonic returned an unexpected status ({response.status_code}) while validating credentials."+++def _make_session(api_key: str) -> requests.Session:+ """Tracked session with the credential hardening the fixed-host connectors use.++ `redact_values` masks the API key in logged URLs and captured request samples (the+ `X-API-Key` header name isn't on the transport's denylist), and `allow_redirects=False`+ stops a 30x from replaying the credentialed header off-host."""+ return make_tracked_session(retry=NO_URLLIB_RETRY, redact_values=(api_key,), allow_redirects=False)+++def _check_response(response: requests.Response, url: str, logger: FilteringBoundLogger) -> requests.Response:+ """Classify a Writesonic response: 429/5xx are retryable, other 4xx are terminal."""+ if response.status_code == 429 or response.status_code >= 500:+ headers = getattr(response, "headers", None) or {}+ retry_after = _parse_retry_after(headers.get("Retry-After"))+ raise WritesonicRetryableError(+ f"Writesonic API error (retryable): status={response.status_code}, url={url}",+ retry_after=retry_after,+ )++ if not response.ok:+ logger.error(f"Writesonic API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response+++@retry(+ retry=retry_if_exception_type((WritesonicRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=_retry_wait,+ reraise=True,+)+def _get(+ path: str,+ *,+ api_key: str,+ logger: FilteringBoundLogger,+ params: Optional[dict[str, Any]] = None,+) -> requests.Response:+ url = urljoin(BASE_URL, path)+ response = _make_session(api_key).get(+ url,+ params=params,+ headers={"X-API-Key": api_key, "Accept": "application/json"},+ timeout=REQUEST_TIMEOUT,+ )+ return _check_response(response, url, logger)+++def _iter_pages(+ endpoint_config: WritesonicEndpointConfig,+ *,+ api_key: str,+ params: dict[str, Any],+ start_page: int,+ logger: FilteringBoundLogger,+) -> Iterator[tuple[int, list[dict[str, Any]]]]:+ """Walk page-number pagination for one request shape, yielding (page, items) per page."""+ page = start_page+ while True:+ response = _get(+ endpoint_config.path,+ api_key=api_key,+ logger=logger,+ params={**params, "page": page, "size": PAGE_SIZE},+ )+ data = response.json()+ items = data.get("items") or []+ if not items:+ break++ yield page, items++ total_pages = data.get("total_pages")+ if total_pages is not None and page >= total_pages:+ break+ page += 1+++def _iter_daily(+ endpoint_config: WritesonicEndpointConfig,+ *,+ api_key: str,+ site_url: str,+ project_id: Optional[str],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[WritesonicResumeConfig],+ start_date: date,+ end_date: date,+) -> Iterator[list[dict[str, Any]]]:+ """Sync a daily export endpoint one UTC day at a time.++ The required `date` param is both the incremental granularity and the resume granularity.+ State is saved *after* each page's rows are yielded, so a crash re-fetches the in-flight+ page (merge dedupes on the primary key) rather than skipping it."""+ resume = manager.load_state() if manager.can_resume() else None+ resumed_date = _to_date(resume.date) if resume and resume.date else None+ current = resumed_date or start_date+ start_page = resume.page if resume and resumed_date and resume.page else 1+ if resumed_date:+ logger.debug(f"Writesonic {endpoint_config.name}: resuming from {resumed_date.isoformat()} page {start_page}")++ while current <= end_date:+ day = current.isoformat()+ params = {**_base_params(site_url, project_id), "date": day}+ for page, items in _iter_pages(+ endpoint_config, api_key=api_key, params=params, start_page=start_page, logger=logger+ ):+ if endpoint_config.inject_date:+ # Content export rows don't carry the export date; stamp it in since it's part+ # of the primary key, the partition key, and the incremental cursor.+ items = [{**item, "date": day} for item in items]+ yield items+ manager.save_state(WritesonicResumeConfig(date=day, page=page + 1))++ next_day = current + timedelta(days=1)+ manager.save_state(WritesonicResumeConfig(date=next_day.isoformat(), page=1))+ current = next_day+ start_page = 1+++def _iter_config(+ endpoint_config: WritesonicEndpointConfig,+ *,+ api_key: str,+ site_url: str,+ project_id: Optional[str],+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[WritesonicResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Full refresh of a config export endpoint with page resume."""+ resume = manager.load_state() if manager.can_resume() else None+ start_page = resume.page if resume and resume.page else 1+ if resume and resume.page:+ logger.debug(f"Writesonic {endpoint_config.name}: resuming from page {start_page}")++ params = _base_params(site_url, project_id)+ for page, items in _iter_pages(+ endpoint_config, api_key=api_key, params=params, start_page=start_page, logger=logger+ ):+ yield items+ manager.save_state(WritesonicResumeConfig(page=page + 1))+++def get_rows(+ api_key: str,+ site_url: str,+ project_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[WritesonicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = WRITESONIC_ENDPOINTS.get(endpoint)+ if endpoint_config is None:+ raise ValueError(f"Unknown Writesonic endpoint: {endpoint}")++ if not endpoint_config.daily:+ yield from _iter_config(+ endpoint_config,+ api_key=api_key,+ site_url=site_url,+ project_id=project_id,+ logger=logger,+ manager=manager,+ )+ return++ last_value_date = _to_date(db_incremental_field_last_value) if should_use_incremental_field else None+ end_date = datetime.now(UTC).date()+ # Restart inclusively from the watermark day: its previous sync may have run mid-day and+ # captured partial data. Merge dedupes the re-fetched rows on the primary key.+ start_date = last_value_date or (end_date - timedelta(days=DEFAULT_LOOKBACK_DAYS))+ if start_date > end_date:+ # A future cursor (clock skew or bad data) would make the day loop a no-op and silently+ # skip the sync. Clamp to today so we still sync the latest day.+ logger.warning(+ f"Writesonic {endpoint}: incremental cursor {start_date.isoformat()} is in the future; syncing today"+ )+ start_date = end_date++ yield from _iter_daily(+ endpoint_config,+ api_key=api_key,+ site_url=site_url,+ project_id=project_id,+ logger=logger,+ manager=manager,+ start_date=start_date,+ end_date=end_date,+ )+++def writesonic_source(+ api_key: str,+ site_url: str,+ project_id: Optional[str],+ endpoint: str,+ logger: FilteringBoundLogger,+ manager: ResumableSourceManager[WritesonicResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ endpoint_config = WRITESONIC_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ site_url=site_url,+ project_id=project_id,+ endpoint=endpoint,+ logger=logger,+ manager=manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="month" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ sort_mode="asc",+ )