Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement amplemarket import source (#107251)

Tom Owers2a38aaa7a79c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 062007c15e49..e7843e5751d3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -69,6 +69,7 @@ the row lists both.
| alguna | HTTP | requests + `rest_source.RESTClient` | ✅ |
| alpha_vantage | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
+| amplemarket | HTTP | requests + `rest_source.RESTClient` | ✅ |
| amplitude | HTTP | requests | ✅ |
| anthropic | HTTP | requests | ✅ |
| apify_dataset | HTTP | requests | ✅ |
@@ -850,7 +851,6 @@ doesn't conflict with concurrent PRs.
- amazon_selling_partner
- amazon_sns
- amazon_sqs
-- amplemarket
- anodot_cost
- anomalo
- anvil
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/amplemarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/amplemarket.py
new file mode 100644
index 000000000000..f9525228791d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/amplemarket.py
@@ -0,0 +1,158 @@
+from collections.abc import Iterable
+from typing import Any, Optional, cast
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.settings import (
+ AMPLEMARKET_ENDPOINTS,
+ BASE_URL,
+ AmplemarketEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ JSONResponsePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
+
+# Amplemarket responses carry HAL-style links; the next page is a relative URL the paginator
+# resolves against the response URL.
+NEXT_URL_PATH = "_links.next.href"
+
+
+@frozen
+class AmplemarketResumeConfig:
+ next_url: str
+
+
+def _client_config(api_key: str) -> ClientConfig:
+ return {
+ "base_url": BASE_URL,
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_key},
+ }
+
+
+def validate_credentials(api_key: str) -> bool:
+ # /account-info is the cheapest authenticated probe: one object, no pagination, no credit
+ # consumption.
+ ok, _status = validate_via_probe(
+ lambda: make_tracked_session(redact_values=(api_key,)),
+ f"{BASE_URL}/account-info",
+ headers={"Accept": "application/json", "Authorization": f"Bearer {api_key}"},
+ )
+ return ok
+
+
+def _source_response(config: AmplemarketEndpointConfig, items: Iterable[Any]) -> SourceResponse:
+ return SourceResponse(
+ name=config.name,
+ items=lambda: items,
+ primary_keys=[config.primary_key],
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def _fanout_source(api_key: str, endpoint: str, team_id: int, job_id: str) -> SourceResponse:
+ """Fan a per-user endpoint (tasks) out over the users list.
+
+ The parent users list is small and re-fetched each sync, so the fan-out is not resumable;
+ each user's task pages follow their own `_links.next.href` chain, which carries the
+ `user_id` filter forward.
+ """
+ config = AMPLEMARKET_ENDPOINTS[endpoint]
+ assert config.fanout is not None
+ parent_config = AMPLEMARKET_ENDPOINTS[config.fanout.parent_name]
+
+ dependent_resource = cast(
+ Iterable[Any],
+ build_dependent_resource(
+ endpoint_configs=AMPLEMARKET_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=config.fanout,
+ client_config=_client_config(api_key),
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ should_use_incremental_field=False,
+ # Requests follow the server's default page size (see settings.py).
+ page_size_param=None,
+ parent_endpoint_extra={
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_URL_PATH),
+ "data_selector": parent_config.data_key,
+ },
+ child_endpoint_extra={
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_URL_PATH),
+ "data_selector": config.data_key,
+ },
+ ),
+ )
+
+ return _source_response(config, dependent_resource)
+
+
+def amplemarket_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[AmplemarketResumeConfig],
+) -> SourceResponse:
+ config = AMPLEMARKET_ENDPOINTS[endpoint]
+
+ if config.fanout is not None:
+ return _fanout_source(api_key, endpoint, team_id, job_id)
+
+ rest_config: RESTAPIConfig = {
+ "client": {
+ **_client_config(api_key),
+ "paginator": JSONResponsePaginator(next_url_path=NEXT_URL_PATH),
+ },
+ "resources": [
+ {
+ "name": endpoint,
+ "endpoint": {
+ "path": config.path,
+ "data_selector": config.data_key,
+ },
+ }
+ ],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume = resumable_source_manager.load_state()
+ if resume is not None:
+ initial_paginator_state = {"next_url": resume.next_url}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Persist only while a next page remains; state is staged before the page it covers is
+ # yielded, so a crash re-yields that page and the merge dedupes on the primary key.
+ if state and state.get("next_url"):
+ resumable_source_manager.save_state(AmplemarketResumeConfig(next_url=str(state["next_url"])))
+
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ return _source_response(config, resource)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/canonical_descriptions.py
new file mode 100644
index 000000000000..af45a9bf5fdf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/canonical_descriptions.py
@@ -0,0 +1,147 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "accounts": {
+ "description": "A Prospect Hub account: a company your team is targeting or engaging.",
+ "docs_url": "https://docs.amplemarket.com/api-reference/accounts/get-accounts",
+ "columns": {
+ "id": "Unique identifier for the account.",
+ "name": "The name of the account.",
+ "website": "The account's website domain.",
+ "linkedin_url": "The account's LinkedIn company page URL.",
+ "owner_email": "The email of the user who owns the account.",
+ "last_contacted_at": "When the account was last contacted, in ISO 8601 format.",
+ "last_engaged_at": "When the account last engaged with outreach, in ISO 8601 format.",
+ },
+ },
+ "calls": {
+ "description": "A phone call made or received through Amplemarket's dialer, or logged externally.",
+ "docs_url": "https://docs.amplemarket.com/guides/calls",
+ "columns": {
+ "id": "Unique identifier for the call.",
+ "from": "The phone number that initiated the call.",
+ "to": "The phone number that received the call.",
+ "direction": "The direction of the call: incoming or outgoing.",
+ "duration": "The duration of the call in seconds.",
+ "answered": "Whether the call was answered.",
+ "human": "Whether a human answered the call or it was detected as a machine or voicemail.",
+ "transcription": "Deprecated in favour of transcript. The plain-text transcription submitted when the call was logged, if any.",
+ "transcript": "The call transcript as a chronological list of transcript entries. Empty when no transcript is available.",
+ "notes": "Custom notes associated with the call.",
+ "recording_url": "URL to the call recording, if available.",
+ "disposition_id": "The ID of the call disposition categorizing the outcome.",
+ "disposition_name": "The name of the call disposition, as shown in the dashboard.",
+ "task_id": "The ID of the task associated with this call.",
+ "user_id": "The ID of the user who made the call.",
+ "user_email": "The email of the user who made the call.",
+ "external": "Whether the call was made externally, outside of Amplemarket.",
+ "contact": "The contact associated with this call.",
+ "start_date": "The start date and time of the call in ISO 8601 format.",
+ },
+ },
+ "call_dispositions": {
+ "description": "A call disposition: a category for a call's outcome and the follow-up action it triggers.",
+ "docs_url": "https://docs.amplemarket.com/api-reference/calls/get-call-dispositions",
+ "columns": {
+ "id": "Unique identifier for the disposition.",
+ "name": "The name of the disposition, as shown in the dashboard.",
+ "slug": "A stable machine-readable identifier for the disposition.",
+ "action": "What the disposition does: 'complete' marks the task and lead as completed, 'next_stage' takes no automatic action.",
+ },
+ },
+ "excluded_domains": {
+ "description": "A domain on the account's exclusion list, so its leads are not contacted.",
+ "docs_url": "https://docs.amplemarket.com/guides/exclusion-lists",
+ "columns": {
+ "domain": "The excluded domain.",
+ "source": "Where the exclusion came from.",
+ "date_added": "When the domain was added to the exclusion list.",
+ "excluded_reason": "The primary reason the domain was excluded.",
+ "excluded_reasons": "All reasons the domain was excluded.",
+ },
+ },
+ "excluded_emails": {
+ "description": "An email address on the account's exclusion list, so the lead is not contacted.",
+ "docs_url": "https://docs.amplemarket.com/guides/exclusion-lists",
+ "columns": {
+ "email": "The excluded email address.",
+ "source": "Where the exclusion came from.",
+ "date_added": "When the email was added to the exclusion list.",
+ "excluded_reason": "The primary reason the email was excluded.",
+ "excluded_reasons": "All reasons the email was excluded.",
+ },
+ },
+ "lead_lists": {
+ "description": "A lead list: an uploaded set of leads that undergoes enrichment and processing.",
+ "docs_url": "https://docs.amplemarket.com/guides/lead-lists",
+ "columns": {
+ "id": "Unique identifier for the lead list.",
+ "name": "The name of the lead list.",
+ "status": "The processing status of the lead list: queued, processing, completed, or canceled.",
+ "shared": "Whether the lead list is shared across the account.",
+ "visible": "Whether the lead list is visible in the dashboard.",
+ "owner": "The email of the owner of the lead list.",
+ "type": "The type of input the lead list was created from, such as linkedin or email.",
+ },
+ },
+ "mailboxes": {
+ "description": "A mailbox connected to Amplemarket and used to send sequence emails.",
+ "docs_url": "https://docs.amplemarket.com/api-reference/mailboxes/get-mailboxes",
+ "columns": {
+ "id": "Unique identifier for the mailbox.",
+ "email": "The mailbox email address.",
+ "email_provider": "The email provider: google, outlook, other, or other_mixed.",
+ "daily_email_limit": "The maximum number of emails the mailbox sends per day.",
+ "status": "The mailbox status: active, inactive, or needs_reconnection.",
+ "user": "The user the mailbox belongs to.",
+ "created_at": "When the mailbox was connected, in ISO 8601 format.",
+ "updated_at": "When the mailbox was last updated, in ISO 8601 format.",
+ },
+ },
+ "sequences": {
+ "description": "A sequence: a multi-stage outreach flow that engages leads over email, LinkedIn, and phone.",
+ "docs_url": "https://docs.amplemarket.com/guides/sequences",
+ "columns": {
+ "id": "Unique identifier for the sequence.",
+ "name": "The name of the sequence.",
+ "status": "The status of the sequence, such as active, draft, archived, or paused.",
+ "created_at": "When the sequence was created, in ISO 8601 format.",
+ "updated_at": "When the sequence was last updated, in ISO 8601 format.",
+ "created_by_user_id": "The ID of the user who created the sequence.",
+ "created_by_user_email": "The email of the user who created the sequence.",
+ "dynamic_fields_used": "Lead data fields referenced by the sequence's active stages.",
+ },
+ },
+ "tasks": {
+ "description": "A task assigned to a user, such as a phone call or a manual email, usually created by a sequence stage.",
+ "docs_url": "https://docs.amplemarket.com/guides/tasks",
+ "columns": {
+ "id": "Unique identifier for the task.",
+ "automatic": "Whether the task was automatically created, for example by a sequence.",
+ "type": "The type of the task, such as phone_call or email.",
+ "status": "The status of the task, such as scheduled, completed, or skipped.",
+ "due_on": "The due date and time in ISO 8601 format.",
+ "finished_on": "The completion date and time in ISO 8601 format. Null when not finished.",
+ "notes": "Custom notes associated with the task.",
+ "sequence_key": "The ID of the sequence that created the task. Null when not from a sequence.",
+ "sequence_name": "The name of the sequence that created the task. Null when not from a sequence.",
+ "user_id": "The ID of the user assigned to the task.",
+ "user_email": "The email of the user assigned to the task.",
+ "contact": "The contact associated with the task.",
+ },
+ },
+ "users": {
+ "description": "A user on the Amplemarket account.",
+ "docs_url": "https://docs.amplemarket.com/api-reference/users/get-users",
+ "columns": {
+ "id": "Unique identifier for the user.",
+ "name": "The full name of the user.",
+ "email": "The email of the user.",
+ "status": "The status of the user account.",
+ "role": "The role of the user, such as sales_rep.",
+ "mailboxes": "The mailboxes connected by the user.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/settings.py
new file mode 100644
index 000000000000..a81f619af057
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/settings.py
@@ -0,0 +1,127 @@
+from dataclasses import field
+from typing import Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField
+
+BASE_URL = "https://api.amplemarket.com"
+
+
+@frozen
+class AmplemarketEndpointConfig:
+ name: str
+ path: str
+ # The key the row objects are nested under in the response body (e.g. {"sequences": [...]}).
+ data_key: str
+ primary_key: str = "id"
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ sort_mode: SortMode = "asc"
+ fanout: Optional[DependentEndpointConfig] = None
+ # The remaining fields exist to satisfy the shared FanoutEndpointLike protocol; Amplemarket
+ # page sizes come from the server defaults (see the module comment below), and no endpoint
+ # is incremental yet.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ page_size: int = 100
+
+
+# /tasks requires a user_id filter, so tasks fan out over the users list. Task ids are UUIDs,
+# unique across users, so the child keeps its own id as the primary key.
+_TASKS_FANOUT = DependentEndpointConfig(
+ parent_name="users",
+ resolve_param="user_id",
+ resolve_field="id",
+ include_from_parent=[],
+)
+
+
+# Pagination is cursor-based via `_links.next.href` (HAL-style relative URLs). Requests omit
+# `page[size]` and follow the server defaults: the documented maximum varies per endpoint and
+# is undocumented for most, so sending a larger size risks a 400 on some endpoints.
+#
+# Every endpoint is full refresh. `/calls` documents `start_date_from`/`start_date_to` filters
+# (and returns newest first), but the filter is unverified against the live API and the
+# newest-first order would need descending-watermark handling, so incremental sync is left off
+# until the filter is proven to work.
+#
+# Deliberately not synced, because they are actions or per-query lookups rather than record
+# collections: people/company search and enrichment, email validation, contacts (requires a
+# name/account_id/ids filter), job openings (a prospecting search surface), and the
+# credit-consuming endpoints.
+AMPLEMARKET_ENDPOINTS: dict[str, AmplemarketEndpointConfig] = {
+ "accounts": AmplemarketEndpointConfig(
+ name="accounts",
+ path="/accounts",
+ data_key="accounts",
+ ),
+ "calls": AmplemarketEndpointConfig(
+ name="calls",
+ path="/calls",
+ data_key="calls",
+ partition_key="start_date",
+ # /calls documents that it lists calls newest first.
+ sort_mode="desc",
+ ),
+ "call_dispositions": AmplemarketEndpointConfig(
+ name="call_dispositions",
+ path="/calls/dispositions",
+ data_key="dispositions",
+ ),
+ "excluded_domains": AmplemarketEndpointConfig(
+ name="excluded_domains",
+ path="/excluded-domains",
+ data_key="excluded_domains",
+ primary_key="domain",
+ partition_key="date_added",
+ ),
+ "excluded_emails": AmplemarketEndpointConfig(
+ name="excluded_emails",
+ path="/excluded-emails",
+ data_key="excluded_emails",
+ primary_key="email",
+ partition_key="date_added",
+ ),
+ "lead_lists": AmplemarketEndpointConfig(
+ name="lead_lists",
+ path="/lead-lists",
+ data_key="lead_lists",
+ ),
+ "mailboxes": AmplemarketEndpointConfig(
+ name="mailboxes",
+ path="/mailboxes",
+ data_key="mailboxes",
+ partition_key="created_at",
+ ),
+ "sequences": AmplemarketEndpointConfig(
+ name="sequences",
+ path="/sequences",
+ data_key="sequences",
+ partition_key="created_at",
+ ),
+ # `{user_id}` is bound per parent user row by the fan-out; tasks carry no stable
+ # creation-time field (due_on can be rescheduled), so no partitioning.
+ "tasks": AmplemarketEndpointConfig(
+ name="tasks",
+ path="/tasks?user_id={user_id}",
+ data_key="tasks",
+ fanout=_TASKS_FANOUT,
+ ),
+ "users": AmplemarketEndpointConfig(
+ name="users",
+ path="/users",
+ data_key="users",
+ ),
+}
+
+ENDPOINTS = tuple(AMPLEMARKET_ENDPOINTS.keys())
+
+# No endpoint has a verified server-side timestamp filter, so nothing advertises incremental
+# sync (see the catalog comment above).
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/source.py
index ca5242e3db39..4d32dc4beb69 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/source.py
@@ -1,8 +1,34 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.amplemarket import (
+ AmplemarketResumeConfig,
+ amplemarket_source,
+ validate_credentials as validate_amplemarket_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.settings import (
+ BASE_URL,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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.errors import auth_non_retryable_errors
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amplemarket import (
AmplemarketSourceConfig,
)
@@ -10,18 +36,88 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AmplemarketSource(SimpleSource[AmplemarketSourceConfig]):
+class AmplemarketSource(ResumableSource[AmplemarketSourceConfig, AmplemarketResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
+ api_docs_url = "https://docs.amplemarket.com/api-reference/introduction"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AMPLEMARKET
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return auth_non_retryable_errors(BASE_URL, service="Amplemarket")
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.AMPLEMARKET,
category=DataWarehouseSourceCategory.SALES,
label="Amplemarket",
+ caption="""Enter your Amplemarket API key to pull your Amplemarket data into the PostHog Data warehouse.
+
+You can generate an API key from your Amplemarket dashboard. See the [Amplemarket quickstart guide](https://docs.amplemarket.com/guides/quickstart) for details.""",
iconPath="/static/services/amplemarket.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/amplemarket",
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AmplemarketSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: AmplemarketSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if validate_amplemarket_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Amplemarket API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AmplemarketResumeConfig]:
+ return ResumableSourceManager[AmplemarketResumeConfig](inputs, AmplemarketResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AmplemarketSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AmplemarketResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return amplemarket_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
new file mode 100644
index 000000000000..7e225949f9bc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket.py
@@ -0,0 +1,215 @@
+import json
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.amplemarket import (
+ AmplemarketResumeConfig,
+ amplemarket_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.settings import (
+ AMPLEMARKET_ENDPOINTS,
+ BASE_URL,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import BearerTokenAuth
+
+# RESTClient builds its session via make_tracked_session in the rest_client module.
+CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+# validate_credentials builds its own tracked session in the amplemarket module.
+AMPLEMARKET_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.amplemarket.make_tracked_session"
+)
+
+
+def _response(data_key: str, items: list[dict[str, Any]], next_href: str | None, url: str) -> Response:
+ body: dict[str, Any] = {data_key: items}
+ if next_href is not None:
+ body["_links"] = {"next": {"href": next_href}}
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(body).encode()
+ # The paginator resolves relative next hrefs against the response URL.
+ resp.url = url
+ return resp
+
+
+def _make_manager(resume_state: AmplemarketResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str, Any]]:
+ """Wire a mock session and return a list capturing each request AT PREPARE TIME.
+
+ ``request.params``/``request.url`` are mutated in place across pages, so inspecting them
+ after the run shows only the final state — snapshot a copy when each request is prepared.
+ """
+ session.headers = {}
+ snapshots: list[dict[str, Any]] = []
+
+ def _prepare(request: Any) -> mock.MagicMock:
+ snapshots.append({"url": request.url, "params": dict(request.params or {}), "auth": request.auth})
+ return mock.MagicMock()
+
+ session.prepare_request.side_effect = _prepare
+ session.send.side_effect = responses
+ return snapshots
+
+
+def _source(endpoint: str, manager: mock.MagicMock):
+ return amplemarket_source("api-key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+
+
+def _rows(source_response) -> list[dict[str, Any]]:
+ return [row for page in source_response.items() for row in page]
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch(AMPLEMARKET_SESSION_PATCH)
+ def test_status_mapping(self, mock_session, status_code, expected):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
+
+ assert validate_credentials("api-key") is expected
+
+ @mock.patch(AMPLEMARKET_SESSION_PATCH)
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("api-key") is False
+
+ @mock.patch(AMPLEMARKET_SESSION_PATCH)
+ def test_probes_account_info_with_bearer_token(self, mock_session):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ validate_credentials("api-key")
+
+ call = mock_session.return_value.get.call_args
+ assert call.args[0] == "https://api.amplemarket.com/account-info"
+ assert call.kwargs["headers"]["Authorization"] == "Bearer api-key"
+
+
+class TestPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follows_relative_next_link(self, MockSession):
+ # Amplemarket returns HAL-style relative next hrefs with bracketed cursor params; the
+ # paginator must resolve them against the base URL and drop the original params.
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ _response(
+ "sequences",
+ [{"id": "a"}, {"id": "b"}],
+ "/sequences?page[after]=b&page[size]=20",
+ f"{BASE_URL}/sequences",
+ ),
+ _response("sequences", [{"id": "c"}], None, f"{BASE_URL}/sequences?page[after]=b&page[size]=20"),
+ ],
+ )
+
+ manager = _make_manager()
+ rows = _rows(_source("sequences", manager))
+
+ assert [row["id"] for row in rows] == ["a", "b", "c"]
+ assert requests_seen[0]["url"] == f"{BASE_URL}/sequences"
+ assert requests_seen[0]["params"] == {}
+ assert requests_seen[1]["url"] == f"{BASE_URL}/sequences?page[after]=b&page[size]=20"
+ assert requests_seen[1]["params"] == {}
+ # State is saved only while a next page exists, with the resolved absolute URL.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0] == AmplemarketResumeConfig(
+ next_url=f"{BASE_URL}/sequences?page[after]=b&page[size]=20"
+ )
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_requests_carry_bearer_auth(self, MockSession):
+ session = MockSession.return_value
+ requests_seen = _wire(session, [_response("users", [{"id": "u1"}], None, f"{BASE_URL}/users")])
+
+ _rows(_source("users", _make_manager()))
+
+ auth = requests_seen[0]["auth"]
+ assert isinstance(auth, BearerTokenAuth)
+ assert auth.token == "api-key"
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resumes_from_saved_state(self, MockSession):
+ session = MockSession.return_value
+ resume_url = f"{BASE_URL}/sequences?page[after]=x&page[size]=20"
+ requests_seen = _wire(session, [_response("sequences", [{"id": "y"}], None, resume_url)])
+
+ manager = _make_manager(AmplemarketResumeConfig(next_url=resume_url))
+ rows = _rows(_source("sequences", manager))
+
+ assert [row["id"] for row in rows] == ["y"]
+ assert requests_seen[0]["url"] == resume_url
+ assert requests_seen[0]["params"] == {}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_empty_page_stops_without_checkpoint(self, MockSession):
+ session = MockSession.return_value
+ _wire(session, [_response("calls", [], None, f"{BASE_URL}/calls")])
+
+ manager = _make_manager()
+ rows = _rows(_source("calls", manager))
+
+ assert rows == []
+ manager.save_state.assert_not_called()
+
+
+class TestTasksFanout:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tasks_are_fetched_per_user(self, MockSession):
+ # /tasks requires a user_id filter, so the fan-out binds each parent user's id into the
+ # child path and pages each user's tasks through their own next-link chain.
+ session = MockSession.return_value
+ requests_seen = _wire(
+ session,
+ [
+ _response("users", [{"id": "u1"}, {"id": "u2"}], None, f"{BASE_URL}/users"),
+ _response(
+ "tasks",
+ [{"id": "t1", "user_id": "u1"}],
+ "/tasks?user_id=u1&page[after]=t1",
+ f"{BASE_URL}/tasks?user_id=u1",
+ ),
+ _response(
+ "tasks",
+ [{"id": "t2", "user_id": "u1"}],
+ None,
+ f"{BASE_URL}/tasks?user_id=u1&page[after]=t1",
+ ),
+ _response("tasks", [{"id": "t3", "user_id": "u2"}], None, f"{BASE_URL}/tasks?user_id=u2"),
+ ],
+ )
+
+ rows = _rows(_source("tasks", _make_manager()))
+
+ assert [row["id"] for row in rows] == ["t1", "t2", "t3"]
+ task_urls = [req["url"] for req in requests_seen if "/tasks" in (req["url"] or "")]
+ assert task_urls == [
+ f"{BASE_URL}/tasks?user_id=u1",
+ f"{BASE_URL}/tasks?user_id=u1&page[after]=t1",
+ f"{BASE_URL}/tasks?user_id=u2",
+ ]
+
+
+class TestEndpointSettings:
+ @pytest.mark.parametrize("config", AMPLEMARKET_ENDPOINTS.values(), ids=AMPLEMARKET_ENDPOINTS.keys())
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key in {"start_date", "created_at", "date_added"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket_source.py
new file mode 100644
index 000000000000..46b651a11ed2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/amplemarket/tests/test_amplemarket_source.py
@@ -0,0 +1,65 @@
+import pytest
+from unittest import mock
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.source import AmplemarketSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.amplemarket import (
+ AmplemarketSourceConfig,
+)
+
+
+class TestAmplemarketSource:
+ def setup_method(self):
+ self.source = AmplemarketSource()
+ self.team_id = 123
+ self.config = AmplemarketSourceConfig(api_key="api-key")
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.amplemarket.com/sequences",
+ "403 Client Error: Forbidden for url: https://api.amplemarket.com/calls?page[size]=20",
+ ],
+ )
+ def test_non_retryable_errors_match_amplemarket_client_errors(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "429 Client Error: Too Many Requests for url: https://api.amplemarket.com/people/search",
+ "500 Server Error for url: https://api.amplemarket.com/sequences",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_retryable_or_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_ships_every_endpoint_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No endpoint has a verified server-side timestamp filter, so none may advertise
+ # incremental sync (see settings.py).
+ assert not any(schema.supports_incremental for schema in schemas)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid Amplemarket API key"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.amplemarket.source.validate_amplemarket_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_key)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/amplemarket.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/amplemarket.py
index 752b0d5f850b..c5c3a01f2dd2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/amplemarket.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/amplemarket.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class AmplemarketSourceConfig(config.Config):
- pass
+ api_key: str