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 algolia import source (#65619)

Tom Owersebf27df35b7e
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 542d8dc84bf8..5d98a0a8215b 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -47,6 +47,7 @@ the row lists both.
| adroll | HTTP | requests | ✅ |
| aircall | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
+| algolia | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
| apollo | HTTP | requests | ✅ |
@@ -275,7 +276,6 @@ doesn't conflict with concurrent PRs.
- ahrefs
- airbyte
- akeneo
-- algolia
- alpaca_broker_api
- alpha_vantage
- amazon_ads
diff --git a/posthog/temporal/data_imports/sources/algolia/algolia.py b/posthog/temporal/data_imports/sources/algolia/algolia.py
new file mode 100644
index 000000000000..40654e68371a
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/algolia/algolia.py
@@ -0,0 +1,289 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import quote
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.algolia.settings import (
+ ALGOLIA_ENDPOINTS,
+ AlgoliaEndpointConfig,
+ PaginationStyle,
+)
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+# Algolia's REST API is served per-application. The main host handles both reads and the
+# admin/list operations we use; the `-dsn` replica is only a latency optimisation for search,
+# which doesn't matter for a batch import.
+ALGOLIA_HOST_TEMPLATE = "https://{application_id}.algolia.net"
+
+# Both 401 and 403 carry this exact message when the application ID / API key pair is wrong.
+# A genuine key that merely lacks the ACL for an endpoint returns a different 403 message
+# ("Method not allowed with this API key"), which lets us tell "bad credentials" apart from
+# "valid credentials, missing scope".
+INVALID_CREDENTIALS_MESSAGE = "Invalid Application-ID or API key"
+
+# Algolia application IDs are short alphanumeric tokens. We interpolate the ID into the request
+# host, so anything outside this set could break out of the `*.algolia.net` domain and point the
+# request (carrying the API key) at an attacker-controlled host — reject it.
+_APPLICATION_ID_RE = re.compile(r"^[A-Za-z0-9]+$")
+
+
+class InvalidApplicationIdError(ValueError):
+ pass
+
+
+class AlgoliaResumeConfig:
+ # Browse cursor token to continue an index scan from. None on the first page.
+ cursor: str | None = None
+ # 0-based page number for the page-paginated endpoints (synonyms, rules, indices).
+ page: int | None = None
+
+
+class AlgoliaRetryableError(Exception):
+ pass
+
+
+def _base_url(application_id: str) -> str:
+ if not _APPLICATION_ID_RE.match(application_id):
+ raise InvalidApplicationIdError("Algolia Application ID must be alphanumeric (letters and digits only)")
+ return ALGOLIA_HOST_TEMPLATE.format(application_id=application_id)
+
+
+def _get_headers(application_id: str, api_key: str) -> dict[str, str]:
+ return {
+ "X-Algolia-Application-Id": application_id,
+ "X-Algolia-API-Key": api_key,
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ }
+
+
+def _endpoint_url(application_id: str, config: AlgoliaEndpointConfig, index_name: str | None) -> str:
+ path = config.path
+ if config.requires_index:
+ if not index_name:
+ raise ValueError(f"Algolia endpoint '{config.name}' requires an index name")
+ path = path.format(index=quote(index_name, safe=""))
+ return f"{_base_url(application_id)}{path}"
+
+
+@retry(
+ retry=retry_if_exception_type((AlgoliaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ method: str,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ params: dict[str, Any] | None = None,
+ body: dict[str, Any] | None = None,
+) -> dict:
+ response = session.request(method, url, headers=headers, params=params, json=body, timeout=60)
+
+ # Algolia rate-limits the API and surfaces transient errors as 429 / 5xx; retry those.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AlgoliaRetryableError(f"Algolia API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Algolia API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _iter_cursor(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ config: AlgoliaEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[AlgoliaResumeConfig],
+ resume: AlgoliaResumeConfig | None,
+) -> Iterator[Any]:
+ """Page the browse endpoint via its opaque cursor; a missing cursor signals end of index."""
+ cursor = resume.cursor if resume else None
+ while True:
+ body: dict[str, Any] = {"hitsPerPage": config.page_size}
+ if cursor:
+ body["cursor"] = cursor
+ data = _fetch(session, "POST", url, headers, logger, body=body)
+
+ next_cursor = data.get("cursor")
+ for item in data.get(config.data_selector, []):
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save after yielding so a crash re-yields the last batch (merge dedupes on
+ # the primary key) rather than skipping it.
+ if next_cursor:
+ manager.save_state(AlgoliaResumeConfig(cursor=next_cursor))
+
+ if not next_cursor:
+ break
+ cursor = next_cursor
+ manager.save_state(AlgoliaResumeConfig(cursor=cursor))
+
+
+def _iter_pages(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ config: AlgoliaEndpointConfig,
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ manager: ResumableSourceManager[AlgoliaResumeConfig],
+ resume: AlgoliaResumeConfig | None,
+) -> Iterator[Any]:
+ """Page the search (synonyms/rules) and list (indices) endpoints via 0-based page numbers."""
+ page = resume.page if resume and resume.page is not None else 0
+ while True:
+ if config.method == "POST":
+ data = _fetch(session, "POST", url, headers, logger, body={"page": page, "hitsPerPage": config.page_size})
+ else:
+ data = _fetch(session, "GET", url, headers, logger, params={"page": page, "hitsPerPage": config.page_size})
+
+ items = data.get(config.data_selector, [])
+ next_page = page + 1
+ for item in items:
+ batcher.batch(item)
+ if batcher.should_yield():
+ yield batcher.get_table()
+ manager.save_state(AlgoliaResumeConfig(page=next_page))
+
+ if not items:
+ break
+ # `indices` reports the page count directly; the search endpoints don't, so fall back to
+ # a short final page (fewer rows than requested) to detect the end.
+ nb_pages = data.get("nbPages")
+ if nb_pages is not None:
+ if next_page >= nb_pages:
+ break
+ elif len(items) < config.page_size:
+ break
+
+ page = next_page
+ manager.save_state(AlgoliaResumeConfig(page=page))
+
+
+def get_rows(
+ endpoint: str,
+ application_id: str,
+ api_key: str,
+ index_name: str | None,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AlgoliaResumeConfig],
+) -> Iterator[Any]:
+ config = ALGOLIA_ENDPOINTS[endpoint]
+ headers = _get_headers(application_id, api_key)
+ url = _endpoint_url(application_id, config, index_name)
+ batcher = Batcher(logger=logger, chunk_size=5000, chunk_size_bytes=100 * 1024 * 1024)
+ session = make_tracked_session(redact_values=(api_key,))
+
+ resume = manager.load_state() if manager.can_resume() else None
+
+ if config.pagination == PaginationStyle.CURSOR:
+ yield from _iter_cursor(session, url, headers, config, logger, batcher, manager, resume)
+ else:
+ yield from _iter_pages(session, url, headers, config, logger, batcher, manager, resume)
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def validate_credentials(
+ application_id: str,
+ api_key: str,
+ index_name: str | None = None,
+ schema_name: str | None = None,
+) -> tuple[bool, str | None]:
+ """Confirm the application ID / API key pair is genuine.
+
+ Probes the endpoint matching ``schema_name`` (or the configured index browse, falling back to
+ listing indices) with a minimal request. A bad credential pair returns a 403 carrying
+ ``INVALID_CREDENTIALS_MESSAGE``; a genuine key that simply lacks the ACL for the probed
+ endpoint returns a different 403. At source-create (``schema_name is None``) we accept the
+ latter — users may only grant scopes for the endpoints they intend to sync — but reject it for
+ a specific schema check.
+ """
+ config = ALGOLIA_ENDPOINTS.get(schema_name) if schema_name else None
+ if config is None:
+ config = ALGOLIA_ENDPOINTS["records"] if index_name else ALGOLIA_ENDPOINTS["indices"]
+
+ # An index-scoped probe with no index name configured falls back to listing indices.
+ if config.requires_index and not index_name:
+ config = ALGOLIA_ENDPOINTS["indices"]
+
+ headers = _get_headers(application_id, api_key)
+ try:
+ url = _endpoint_url(application_id, config, index_name)
+ except InvalidApplicationIdError as exc:
+ return False, str(exc)
+
+ session = make_tracked_session(redact_values=(api_key,))
+ try:
+ if config.method == "POST":
+ response = session.post(url, headers=headers, json={"hitsPerPage": 0}, timeout=10)
+ else:
+ response = session.get(url, headers=headers, timeout=10)
+ except requests.RequestException as exc:
+ return False, f"Could not reach Algolia: {exc}"
+
+ if response.ok:
+ return True, None
+
+ if response.status_code in (401, 403):
+ message = ""
+ try:
+ message = response.json().get("message", "")
+ except ValueError:
+ pass
+
+ if INVALID_CREDENTIALS_MESSAGE in message:
+ return False, "Invalid Algolia Application ID or API key"
+
+ # Genuine credentials, but the key lacks the ACL for the probed endpoint.
+ if schema_name is None:
+ return True, None
+ return False, f"Your Algolia API key is missing the ACL required to sync '{schema_name}'"
+
+ return False, f"Algolia API returned status {response.status_code}"
+
+
+def algolia_source(
+ endpoint: str,
+ application_id: str,
+ api_key: str,
+ index_name: str | None,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AlgoliaResumeConfig],
+) -> SourceResponse:
+ config = ALGOLIA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ endpoint=endpoint,
+ application_id=application_id,
+ api_key=api_key,
+ index_name=index_name,
+ logger=logger,
+ manager=manager,
+ ),
+ primary_keys=config.primary_keys,
+ # Full-refresh endpoints with no stable datetime field to partition on.
+ partition_count=1,
+ partition_size=1,
+ )
diff --git a/posthog/temporal/data_imports/sources/algolia/canonical_descriptions.py b/posthog/temporal/data_imports/sources/algolia/canonical_descriptions.py
new file mode 100644
index 000000000000..b02ca65320cd
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/algolia/canonical_descriptions.py
@@ -0,0 +1,46 @@
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
+
+# Sourced from the Algolia REST API reference (https://www.algolia.com/doc/rest-api/search/).
+# `records` holds the user's own index objects, so its columns are index-specific and left to the
+# LLM; only the universal `objectID` is documented here.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "records": {
+ "description": "Every object stored in the Algolia index, retrieved via the browse endpoint.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/search/#tag/Records/operation/browse",
+ "columns": {
+ "objectID": "Unique identifier of the record within the index.",
+ },
+ },
+ "synonyms": {
+ "description": "Synonyms configured on the index, defining terms Algolia treats as equivalent at query time.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/search/#tag/Synonyms",
+ "columns": {
+ "objectID": "Unique identifier of the synonym.",
+ "type": "Synonym type (e.g. synonym, oneWaySynonym, altCorrection1, placeholder).",
+ "synonyms": "List of words considered equivalent.",
+ },
+ },
+ "rules": {
+ "description": "Query rules on the index that change ranking or results when a query matches their conditions.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/search/#tag/Rules",
+ "columns": {
+ "objectID": "Unique identifier of the rule.",
+ "conditions": "Conditions that trigger the rule.",
+ "consequence": "Effect applied to the query when the rule's conditions match.",
+ "enabled": "Whether the rule is currently active.",
+ },
+ },
+ "indices": {
+ "description": "All indices on the Algolia application with their size and timing metadata.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/search/#tag/Indices/operation/listIndices",
+ "columns": {
+ "name": "Index name.",
+ "entries": "Number of records in the index.",
+ "dataSize": "Size of the index data in bytes.",
+ "fileSize": "Total size of the index including metadata, in bytes.",
+ "createdAt": "Date the index was created (ISO 8601).",
+ "updatedAt": "Date the index was last updated (ISO 8601).",
+ "primary": "Name of the primary index, set on replica indices.",
+ },
+ },
+}
diff --git a/posthog/temporal/data_imports/sources/algolia/settings.py b/posthog/temporal/data_imports/sources/algolia/settings.py
new file mode 100644
index 000000000000..ab751be45fab
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/algolia/settings.py
@@ -0,0 +1,80 @@
+from dataclasses import dataclass, field
+from enum import Enum
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+class PaginationStyle(Enum):
+ # Browse endpoint returns an opaque `cursor` token; absence of the token signals end of index.
+ CURSOR = "cursor"
+ # Search endpoints (synonyms/rules) and `GET /1/indexes` use 0-based `page` numbers.
+ PAGE = "page"
+
+
+@dataclass
+class AlgoliaEndpointConfig:
+ name: str
+ # Path on the Algolia REST API. `{index}` is substituted with the configured index name.
+ path: str
+ method: str
+ pagination: PaginationStyle
+ # Key in the JSON response that holds the list of rows (`hits`, `items`).
+ data_selector: str
+ primary_keys: list[str] = field(default_factory=lambda: ["objectID"])
+ # Whether the endpoint targets a specific index (so it needs the `index_name` field).
+ requires_index: bool = True
+ should_sync_default: bool = True
+ # Rows requested per page (`hitsPerPage`). Algolia caps browse/search at 1000.
+ page_size: int = 1000
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+
+
+# All Algolia endpoints below are full-refresh: the index browse endpoint and the
+# synonyms/rules search endpoints expose no server-side "updated since" filter, so an
+# incremental sync would still page the whole resource. The cursor (browse) and page
+# (search/list) tokens make every endpoint resumable, so a heartbeat timeout picks back
+# up where it left off rather than restarting.
+ALGOLIA_ENDPOINTS: dict[str, AlgoliaEndpointConfig] = {
+ "records": AlgoliaEndpointConfig(
+ name="records",
+ path="/1/indexes/{index}/browse",
+ method="POST",
+ pagination=PaginationStyle.CURSOR,
+ data_selector="hits",
+ primary_keys=["objectID"],
+ ),
+ "synonyms": AlgoliaEndpointConfig(
+ name="synonyms",
+ path="/1/indexes/{index}/synonyms/search",
+ method="POST",
+ pagination=PaginationStyle.PAGE,
+ data_selector="hits",
+ primary_keys=["objectID"],
+ should_sync_default=False,
+ ),
+ "rules": AlgoliaEndpointConfig(
+ name="rules",
+ path="/1/indexes/{index}/rules/search",
+ method="POST",
+ pagination=PaginationStyle.PAGE,
+ data_selector="hits",
+ primary_keys=["objectID"],
+ should_sync_default=False,
+ ),
+ "indices": AlgoliaEndpointConfig(
+ name="indices",
+ path="/1/indexes",
+ method="GET",
+ pagination=PaginationStyle.PAGE,
+ data_selector="items",
+ primary_keys=["name"],
+ requires_index=False,
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(ALGOLIA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in ALGOLIA_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/algolia/source.py b/posthog/temporal/data_imports/sources/algolia/source.py
index e5f8fb7bbdd9..ea65e6060c13 100644
--- a/posthog/temporal/data_imports/sources/algolia/source.py
+++ b/posthog/temporal/data_imports/sources/algolia/source.py
@@ -1,20 +1,40 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.algolia.algolia import (
+ AlgoliaResumeConfig,
+ algolia_source,
+ validate_credentials as validate_algolia_credentials,
+)
+from posthog.temporal.data_imports.sources.algolia.settings import ALGOLIA_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import AlgoliaSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
+_ENDPOINT_DESCRIPTIONS: dict[str, str] = {
+ "records": "All objects in the index, paged via the browse cursor. Full refresh only.",
+ "synonyms": "Synonyms configured on the index. Full refresh only.",
+ "rules": "Query rules configured on the index. Full refresh only.",
+ "indices": "Every index on the application. Full refresh only.",
+}
+
@SourceRegistry.register
-class AlgoliaSource(SimpleSource[AlgoliaSourceConfig]):
+class AlgoliaSource(ResumableSource[AlgoliaSourceConfig, AlgoliaResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ALGOLIA
@@ -25,7 +45,121 @@ class AlgoliaSource(SimpleSource[AlgoliaSourceConfig]):
name=SchemaExternalDataSourceType.ALGOLIA,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Algolia",
- iconPath="/static/services/algolia.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Enter your Algolia Application ID and an API key to pull your Algolia data into the PostHog Data warehouse.
+
+You can find your Application ID and create API keys in your [Algolia dashboard](https://dashboard.algolia.com/account/api-keys/all).
+
+The API key needs the ACLs for the data you want to sync:
+- `browse` — index records
+- `settings` — synonyms and query rules
+- `listIndexes` — the list of indices
+""",
+ iconPath="/static/services/algolia.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/algolia",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="application_id",
+ label="Application ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="YourApplicationID",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="index_name",
+ label="Index name",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your_index",
+ secret=False,
+ ),
+ ],
+ ),
)
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored API key is sent to the host derived from `application_id`, so retargeting it
+ # must re-require the secret.
+ return ["application_id"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Algolia returns 403 (not 401) for both a wrong Application-ID/API-key pair and a key
+ # missing the ACL for an endpoint. Either way retrying can't fix it, so stop the sync.
+ "403 Client Error: Forbidden for url:": "Your Algolia Application ID or API key is invalid, or the key is missing the ACL needed to sync this data. Check your credentials and key permissions in the Algolia dashboard, then reconnect.",
+ "401 Client Error: Unauthorized for url:": "Your Algolia Application ID or API key is invalid. Create a new key in the Algolia dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AlgoliaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ return SourceSchema(
+ name=endpoint,
+ # No Algolia endpoint exposes a server-side "updated since" filter, so every table
+ # is full refresh; the cursor/page tokens still make each one resumable.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=ALGOLIA_ENDPOINTS[endpoint].should_sync_default,
+ description=_ENDPOINT_DESCRIPTIONS.get(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: AlgoliaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_algolia_credentials(
+ application_id=config.application_id,
+ api_key=config.api_key,
+ index_name=config.index_name,
+ schema_name=schema_name,
+ )
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AlgoliaResumeConfig]:
+ return ResumableSourceManager[AlgoliaResumeConfig](inputs, AlgoliaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AlgoliaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AlgoliaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return algolia_source(
+ endpoint=inputs.schema_name,
+ application_id=config.application_id,
+ api_key=config.api_key,
+ index_name=config.index_name,
+ logger=inputs.logger,
+ manager=resumable_source_manager,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from posthog.temporal.data_imports.sources.algolia.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS, # noqa: PLC0415
+ )
+
+ return CANONICAL_DESCRIPTIONS
diff --git a/posthog/temporal/data_imports/sources/algolia/tests/test_algolia.py b/posthog/temporal/data_imports/sources/algolia/tests/test_algolia.py
new file mode 100644
index 000000000000..424e10e894d9
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/algolia/tests/test_algolia.py
@@ -0,0 +1,293 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import pyarrow as pa
+import requests
+
+from posthog.temporal.data_imports.sources.algolia.algolia import (
+ AlgoliaResumeConfig,
+ InvalidApplicationIdError,
+ _base_url,
+ _endpoint_url,
+ algolia_source,
+ get_rows,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.algolia.settings import ALGOLIA_ENDPOINTS
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+def _response(body: dict[str, Any], status_code: int = 200) -> MagicMock:
+ resp = MagicMock()
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 300
+ resp.json.return_value = body
+ resp.text = str(body)
+ return resp
+
+
+def _rows(tables: list[Any]) -> list[dict[str, Any]]:
+ out: list[dict[str, Any]] = []
+ for table in tables:
+ assert isinstance(table, pa.Table)
+ out.extend(table.to_pylist())
+ return out
+
+
+class TestBaseUrl:
+ def test_builds_per_application_host(self) -> None:
+ assert _base_url("MYAPPID") == "https://MYAPPID.algolia.net"
+
+ @pytest.mark.parametrize("bad", ["evil.com/", "app id", "app.algolia.net", "a/b", "app#x", ""])
+ def test_rejects_non_alphanumeric_application_id(self, bad: str) -> None:
+ # The application_id is interpolated into the request host, so anything that could
+ # break out of *.algolia.net must be rejected before a request is made.
+ with pytest.raises(InvalidApplicationIdError):
+ _base_url(bad)
+
+
+class TestEndpointUrl:
+ def test_formats_index_into_path(self) -> None:
+ url = _endpoint_url("APP", ALGOLIA_ENDPOINTS["records"], "my_index")
+ assert url == "https://APP.algolia.net/1/indexes/my_index/browse"
+
+ def test_quotes_index_name(self) -> None:
+ url = _endpoint_url("APP", ALGOLIA_ENDPOINTS["records"], "my index/slash")
+ assert url == "https://APP.algolia.net/1/indexes/my%20index%2Fslash/browse"
+
+ def test_index_scoped_endpoint_requires_index(self) -> None:
+ with pytest.raises(ValueError):
+ _endpoint_url("APP", ALGOLIA_ENDPOINTS["records"], None)
+
+ def test_app_level_endpoint_ignores_index(self) -> None:
+ assert _endpoint_url("APP", ALGOLIA_ENDPOINTS["indices"], None) == "https://APP.algolia.net/1/indexes"
+
+
+class _Driver:
+ """Drives get_rows against a fake tracked session, capturing every request."""
+
+ def __init__(self, responses: list[MagicMock]) -> None:
+ self.responses = iter(responses)
+ self.calls: list[dict[str, Any]] = []
+
+ def _request(self, method: str, url: str, **kwargs: Any) -> MagicMock:
+ self.calls.append({"method": method, "url": url, "json": kwargs.get("json"), "params": kwargs.get("params")})
+ return next(self.responses)
+
+ def run(self, endpoint: str, manager: MagicMock) -> list[dict[str, Any]]:
+ with patch(
+ "posthog.temporal.data_imports.sources.algolia.algolia.make_tracked_session"
+ ) as mock_session_factory:
+ session = mock_session_factory.return_value
+ session.request.side_effect = self._request
+ tables = list(
+ get_rows(
+ endpoint=endpoint,
+ application_id="APP",
+ api_key="key",
+ index_name="idx",
+ logger=MagicMock(),
+ manager=manager,
+ )
+ )
+ return _rows(tables)
+
+
+def _fresh_manager() -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+ return manager
+
+
+class TestCursorPagination:
+ def test_pages_until_cursor_absent(self) -> None:
+ manager = _fresh_manager()
+ driver = _Driver(
+ [
+ _response({"hits": [{"objectID": "1"}], "cursor": "c1"}),
+ _response({"hits": [{"objectID": "2"}]}),
+ ]
+ )
+
+ rows = driver.run("records", manager)
+
+ assert [r["objectID"] for r in rows] == ["1", "2"]
+ # First browse request carries no cursor; the second carries the cursor returned first.
+ assert driver.calls[0]["json"] == {"hitsPerPage": 1000}
+ assert driver.calls[1]["json"] == {"hitsPerPage": 1000, "cursor": "c1"}
+
+ def test_saves_cursor_after_non_terminal_page(self) -> None:
+ manager = _fresh_manager()
+ driver = _Driver(
+ [
+ _response({"hits": [{"objectID": "1"}], "cursor": "c1"}),
+ _response({"hits": [{"objectID": "2"}]}),
+ ]
+ )
+
+ driver.run("records", manager)
+
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [AlgoliaResumeConfig(cursor="c1")]
+
+ def test_single_terminal_page_saves_nothing(self) -> None:
+ manager = _fresh_manager()
+ driver = _Driver([_response({"hits": [{"objectID": "only"}]})])
+
+ rows = driver.run("records", manager)
+
+ assert [r["objectID"] for r in rows] == ["only"]
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_cursor(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AlgoliaResumeConfig(cursor="resumed")
+ driver = _Driver([_response({"hits": [{"objectID": "x"}]})])
+
+ driver.run("records", manager)
+
+ assert driver.calls[0]["json"] == {"hitsPerPage": 1000, "cursor": "resumed"}
+
+
+class TestPagePagination:
+ def test_search_endpoint_stops_on_short_page(self) -> None:
+ manager = _fresh_manager()
+ # Fewer rows than the requested page size signals the last page for search endpoints.
+ driver = _Driver([_response({"hits": [{"objectID": "s1"}], "nbHits": 1})])
+
+ rows = driver.run("synonyms", manager)
+
+ assert [r["objectID"] for r in rows] == ["s1"]
+ assert len(driver.calls) == 1
+ manager.save_state.assert_not_called()
+
+ def test_search_endpoint_walks_multiple_pages(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ manager = _fresh_manager()
+ monkeypatch.setattr(ALGOLIA_ENDPOINTS["synonyms"], "page_size", 2)
+ driver = _Driver(
+ [
+ _response({"hits": [{"objectID": "a"}, {"objectID": "b"}], "nbHits": 3}),
+ _response({"hits": [{"objectID": "c"}], "nbHits": 3}),
+ ]
+ )
+
+ rows = driver.run("synonyms", manager)
+
+ assert [r["objectID"] for r in rows] == ["a", "b", "c"]
+ assert [c["json"]["page"] for c in driver.calls] == [0, 1]
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [AlgoliaResumeConfig(page=1)]
+
+ def test_indices_uses_nb_pages_to_terminate(self) -> None:
+ manager = _fresh_manager()
+ driver = _Driver(
+ [
+ _response({"items": [{"name": "i1"}], "nbPages": 2}),
+ _response({"items": [{"name": "i2"}], "nbPages": 2}),
+ ]
+ )
+
+ rows = driver.run("indices", manager)
+
+ assert [r["name"] for r in rows] == ["i1", "i2"]
+ # GET endpoints page via query params, and must request the configured page size so the
+ # listing doesn't fall back to Algolia's small server-side default.
+ assert [c["params"]["page"] for c in driver.calls] == [0, 1]
+ assert all(c["params"]["hitsPerPage"] == ALGOLIA_ENDPOINTS["indices"].page_size for c in driver.calls)
+
+ def test_resume_seeds_page(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = AlgoliaResumeConfig(page=3)
+ driver = _Driver([_response({"items": [{"name": "i"}], "nbPages": 4})])
+
+ driver.run("indices", manager)
+
+ assert driver.calls[0]["params"]["page"] == 3
+
+
+class TestAlgoliaSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ALGOLIA_ENDPOINTS.keys()))
+ def test_primary_keys_match_settings(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ response = algolia_source(
+ endpoint=endpoint,
+ application_id="APP",
+ api_key="key",
+ index_name="idx",
+ logger=MagicMock(),
+ manager=manager,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == ALGOLIA_ENDPOINTS[endpoint].primary_keys
+
+ def test_items_is_lazy(self) -> None:
+ # Building the SourceResponse must not issue any request; only iterating items should.
+ manager = MagicMock(spec=ResumableSourceManager)
+ with patch("posthog.temporal.data_imports.sources.algolia.algolia.make_tracked_session") as factory:
+ algolia_source(
+ endpoint="records",
+ application_id="APP",
+ api_key="key",
+ index_name="idx",
+ logger=MagicMock(),
+ manager=manager,
+ )
+ factory.assert_not_called()
+
+
+class TestValidateCredentials:
+ def _run(self, response: MagicMock, **kwargs: Any) -> tuple[bool, str | None]:
+ with patch("posthog.temporal.data_imports.sources.algolia.algolia.make_tracked_session") as factory:
+ session = factory.return_value
+ session.get.return_value = response
+ session.post.return_value = response
+ return validate_credentials(application_id="APP", api_key="key", **kwargs)
+
+ def test_ok(self) -> None:
+ valid, error = self._run(_response({}, status_code=200), index_name="idx")
+ assert valid is True
+ assert error is None
+
+ def test_invalid_credentials(self) -> None:
+ resp = _response({"message": "Invalid Application-ID or API key", "status": 403}, status_code=403)
+ valid, error = self._run(resp, index_name="idx")
+ assert valid is False
+ assert error is not None and "Invalid Algolia Application ID or API key" in error
+
+ def test_missing_acl_accepted_at_source_create(self) -> None:
+ # A genuine key lacking the ACL for the probe returns a different 403; at source
+ # create (no schema_name) we accept it.
+ resp = _response({"message": "Method not allowed with this API key", "status": 403}, status_code=403)
+ valid, error = self._run(resp, index_name="idx")
+ assert valid is True
+ assert error is None
+
+ def test_missing_acl_rejected_for_specific_schema(self) -> None:
+ resp = _response({"message": "Method not allowed with this API key", "status": 403}, status_code=403)
+ valid, error = self._run(resp, index_name="idx", schema_name="synonyms")
+ assert valid is False
+ assert error is not None
+
+ def test_invalid_application_id_rejected_before_request(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.algolia.algolia.make_tracked_session") as factory:
+ valid, error = validate_credentials(application_id="evil.com/", api_key="key", index_name="idx")
+ assert valid is False
+ assert error is not None
+ factory.return_value.get.assert_not_called()
+ factory.return_value.post.assert_not_called()
+
+ def test_network_error_returns_message(self) -> None:
+ with patch("posthog.temporal.data_imports.sources.algolia.algolia.make_tracked_session") as factory:
+ factory.return_value.get.side_effect = requests.ConnectionError("boom")
+ valid, error = validate_credentials(application_id="APP", api_key="key")
+ assert valid is False
+ assert error is not None and "boom" in error
+
+ def test_unexpected_status_returns_message(self) -> None:
+ valid, error = self._run(_response({}, status_code=500), index_name="idx")
+ assert valid is False
+ assert error is not None and "500" in error
diff --git a/posthog/temporal/data_imports/sources/algolia/tests/test_algolia_source.py b/posthog/temporal/data_imports/sources/algolia/tests/test_algolia_source.py
new file mode 100644
index 000000000000..5cac0aa10dac
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/algolia/tests/test_algolia_source.py
@@ -0,0 +1,157 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.algolia.algolia import AlgoliaResumeConfig
+from posthog.temporal.data_imports.sources.algolia.settings import ALGOLIA_ENDPOINTS, ENDPOINTS
+from posthog.temporal.data_imports.sources.algolia.source import AlgoliaSource
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.generated_configs import AlgoliaSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "records",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestAlgoliaSource:
+ def setup_method(self) -> None:
+ self.source = AlgoliaSource()
+ self.team_id = 123
+ self.config = AlgoliaSourceConfig(application_id="APPID", api_key="test-key", index_name="my_index")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ALGOLIA
+
+ def test_application_id_is_a_connection_host_field(self) -> None:
+ # The stored API key is sent to the host derived from application_id, so changing
+ # it must force the key to be re-entered.
+ assert self.source.connection_host_fields == ["application_id"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Algolia"
+ assert config.label == "Algolia"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/algolia.png"
+
+ fields = [f for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert [f.name for f in fields] == ["application_id", "api_key", "index_name"]
+
+ by_name = {f.name: f for f in fields}
+ assert by_name["application_id"].type == SourceFieldInputConfigType.TEXT
+ assert by_name["application_id"].secret is False
+ assert by_name["api_key"].type == SourceFieldInputConfigType.PASSWORD
+ assert by_name["api_key"].secret is True
+ assert all(f.required for f in fields)
+
+ @pytest.mark.parametrize("expected_key", ["403 Client Error", "401 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ keys = self.source.get_non_retryable_errors()
+ assert any(expected_key in k for k in keys)
+
+ def test_get_schemas_all_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # No Algolia endpoint exposes a server-side updated-since filter, so every schema is
+ # full refresh only.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_should_sync_defaults_match_settings(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ for name, endpoint in ALGOLIA_ENDPOINTS.items():
+ assert schemas[name].should_sync_default == endpoint.should_sync_default
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["records"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "records"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ ((False, "Invalid Algolia Application ID or API key"), False, "Invalid Algolia Application ID or API key"),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.algolia.source.validate_algolia_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ 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(
+ application_id="APPID",
+ api_key="test-key",
+ index_name="my_index",
+ schema_name=None,
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.algolia.source.validate_algolia_credentials")
+ def test_validate_credentials_passes_schema_name(self, mock_validate: mock.MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+
+ self.source.validate_credentials(self.config, self.team_id, schema_name="synonyms")
+
+ assert mock_validate.call_args.kwargs["schema_name"] == "synonyms"
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AlgoliaResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.algolia.source.algolia_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="synonyms", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ endpoint="synonyms",
+ application_id="APPID",
+ api_key="test-key",
+ index_name="my_index",
+ logger=inputs.logger,
+ manager=manager,
+ )
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ described = self.source.get_canonical_descriptions()
+ assert set(described.keys()) == set(ENDPOINTS)
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 7e741e3c3aa5..57219ecaa929 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -200,7 +200,9 @@ class AkeneoSourceConfig(config.Config):
@config.config
class AlgoliaSourceConfig(config.Config):
- pass
+ application_id: str
+ api_key: str
+ index_name: str
@config.config