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 alguna import source (#69627)

Tom Owersfc94bad687cd
diff --git a/frontend/public/services/alguna.svg b/frontend/public/services/alguna.svg
new file mode 100644
index 000000000000..fd0b0821b619
--- /dev/null
+++ b/frontend/public/services/alguna.svg
@@ -0,0 +1,4 @@
+<svg width="24" height="28" viewBox="0 0 24 28" fill="none" xmlns="http://www.w3.org/2000/svg">
+<path d="M11.2145 6.81871V26.9213C3.7962 26.9213 0.0810728 17.9522 5.32664 12.7066L11.2145 6.81871Z" fill="black"/>
+<path d="M14.0863 3.94691L15.4882 2.54502C18.5034 -0.470196 23.659 1.66531 23.659 5.92947V26.9213C18.3722 26.9213 14.0863 22.6355 14.0863 17.3486V3.94691Z" fill="black"/>
+</svg>
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 693294af1e01..64e9bb9a9dba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -50,6 +50,7 @@ the row lists both.
| aircall | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
| algolia | HTTP | requests | ✅ |
+| alguna | HTTP | requests | ✅ |
| alpha_vantage | HTTP | requests | ✅ |
| amazon_ads | HTTP | requests | ✅ |
| amplitude | HTTP | requests | ✅ |
@@ -448,7 +449,6 @@ doesn't conflict with concurrent PRs.
- airops
- aiven
- akeneo
-- alguna
- alpaca_broker_api
- amazon_ads
- amazon_cloudwatch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
new file mode 100644
index 000000000000..c0e0f838883d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/alguna.py
@@ -0,0 +1,144 @@
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ALGUNA_ENDPOINTS
+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
+
+ALGUNA_BASE_URL = "https://api.alguna.io"
+# Alguna's API is date-versioned; every request must send this header or calls fail.
+ALGUNA_API_VERSION = "2026-04-01"
+PAGE_LIMIT = 100
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class AlgunaRetryableError(Exception):
+ pass
+
+
+class AlgunaResumeConfig:
+ # Byte-for-byte deterministic restart point: list endpoints paginate with required
+ # limit/offset params, so the row offset of the next unfetched page is the full resume state.
+ offset: int = 0
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Alguna-Version": ALGUNA_API_VERSION,
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ return f"{ALGUNA_BASE_URL}{path}?{urlencode(params)}"
+
+
+def validate_credentials(api_key: str) -> bool:
+ url = _build_url("/customers", {"limit": 1, "offset": 0, "sort": "created_at:asc"})
+ try:
+ session = make_tracked_session(redact_values=(api_key,))
+ response = session.get(url, headers=_get_headers(api_key), timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ AlgunaRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AlgunaRetryableError(f"Alguna API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Alguna API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = ALGUNA_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ session = make_tracked_session(redact_values=(api_key,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None else 0
+ if offset:
+ logger.debug(f"Alguna: resuming {endpoint} from offset={offset}")
+
+ while True:
+ params: dict[str, Any] = {"limit": PAGE_LIMIT, "offset": offset}
+ if config.sort is not None:
+ params["sort"] = config.sort
+
+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)
+ # Direct access: a 200 body without "data" means the response shape changed — fail the
+ # sync loudly instead of silently reporting 0 rows.
+ items = data["data"]
+ if not items:
+ break
+
+ yield items
+
+ offset += len(items)
+ # A short page means we've reached the end; don't save state for a finished sync.
+ if len(items) < PAGE_LIMIT:
+ break
+
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ resumable_source_manager.save_state(AlgunaResumeConfig(offset=offset))
+
+
+def alguna_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+) -> SourceResponse:
+ config = ALGUNA_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=[config.partition_key],
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py
new file mode 100644
index 000000000000..659e9a08236b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/canonical_descriptions.py
@@ -0,0 +1,158 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Alguna Public API OpenAPI spec (version 2026-04-01):
+# https://alguna.com/docs/api-reference/v2/overview
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "billable_metrics": {
+ "description": "A billable metric defining how ingested usage events are aggregated into a billable value (e.g. count, sum of a field).",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/billing-events-and-metrics/list-billable-metrics",
+ "columns": {
+ "aggregation": "How events are aggregated into a metric value.",
+ "created_at": "Timestamp when the metric was created.",
+ "description": "Description of the metric.",
+ "event_name": "Event name that triggers this metric.",
+ "filter_groups": "Filter groups applied to events before aggregation.",
+ "id": "Unique identifier for the metric.",
+ "name": "Name of the metric.",
+ "tag_ids": "Tag identifiers associated with this metric.",
+ "updated_at": "Timestamp when the metric was last updated.",
+ },
+ },
+ "customers": {
+ "description": "A customer account you bill in Alguna, including currency and tax configuration.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/customers/list-customers",
+ "columns": {
+ "aliases": "Alternative identifiers for the customer.",
+ "billing_address": "Customer billing address.",
+ "contacts": "Customer contacts.",
+ "created_at": "Timestamp when the customer was created.",
+ "currency": "ISO 4217 currency code.",
+ "id": "Unique identifier for the customer.",
+ "name": "Customer name.",
+ "tax_country": "ISO 3166-1 alpha-2 country code used for tax determination.",
+ "tax_id": "Customer tax identification number.",
+ "tax_rate": "Tax rate applied to the customer, expressed as a decimal fraction (0.20 = 20%).",
+ "tax_reason": "Reason determining how tax is applied to the customer.",
+ "tax_status": "Customer tax status.",
+ "tax_type": "Type of tax applied to the customer.",
+ "updated_at": "Timestamp when the customer was last updated.",
+ },
+ },
+ "invoices": {
+ "description": "An invoice issued to a customer for a billing period, with its status lifecycle and total.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/invoices/list-invoices",
+ "columns": {
+ "billing_period": "Formatted billing period string.",
+ "billing_period_end": "End of the billing period.",
+ "billing_period_start": "Start of the billing period.",
+ "created_at": "Timestamp when the invoice was created.",
+ "currency": "ISO 4217 currency code.",
+ "customer_id": "Customer this invoice belongs to.",
+ "description": "Invoice description or memo.",
+ "id": "Unique identifier for the invoice.",
+ "status": "Current status of the invoice.",
+ "total": "Total amount including tax.",
+ "updated_at": "Timestamp when the invoice was last updated.",
+ },
+ },
+ "payments": {
+ "description": "A payment made against an invoice, with amounts received and refunded and payment-processor references.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/payments/list-payments",
+ "columns": {
+ "amount": "Payment amount.",
+ "amount_received": "Amount received.",
+ "amount_refunded": "Amount refunded.",
+ "created_at": "Timestamp when the payment was created.",
+ "currency": "ISO 4217 currency code.",
+ "customer_id": "Customer ID.",
+ "external_id": "Payment processor external ID.",
+ "external_url": "URL to view the payment in the processor's dashboard.",
+ "failed_at": "Timestamp when the payment failed.",
+ "id": "Unique identifier for the payment.",
+ "invoice_id": "Associated invoice ID.",
+ "paid_at": "Timestamp when the payment was completed.",
+ "status": "Payment status.",
+ "updated_at": "Timestamp when the payment was last updated.",
+ },
+ },
+ "plans": {
+ "description": "A reusable pricing plan template that subscriptions can be created from.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/plans/list-plans",
+ "columns": {
+ "created_at": "Timestamp when the plan was created.",
+ "currency": "The currency in which the plan is billed.",
+ "description": "A brief description of the plan.",
+ "id": "Unique identifier for the plan.",
+ "name": "The name of the plan.",
+ "updated_at": "Timestamp when the plan was last updated.",
+ },
+ },
+ "products": {
+ "description": "A product (fixed-price or usage-based) that can be priced on plans and subscriptions.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/products/list-products",
+ "columns": {
+ "billing_frequency": "How often the product is billed.",
+ "created_at": "Timestamp when the product was created.",
+ "description": "A brief description of the product.",
+ "fee_type": "Whether the product is fixed-price or usage-based.",
+ "id": "Unique identifier for the product.",
+ "metric_ids": "Identifiers for associated metrics. Applicable for metered products.",
+ "name": "The name of the product.",
+ "payment_terms": "When the product is billed relative to the billing period.",
+ "revenue_allocation_method": "How revenue is allocated across time periods within a billing cycle.",
+ "sku": "Stock keeping unit code used in external ERP or revenue recognition systems.",
+ "tag_ids": "Identifiers for tags associated with this product.",
+ "unit_label_plural": "Custom plural term for multiple units of the product (e.g. 'API calls'). Falls back to 'units' when omitted.",
+ "unit_label_singular": "Custom singular term for one unit of the product (e.g. 'API call'). Falls back to 'unit' when omitted.",
+ "updated_at": "Timestamp when the product was last updated.",
+ },
+ },
+ "refunds": {
+ "description": "A refund issued against a payment, with amount, status, and payment-processor references.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/refunds/list-refunds",
+ "columns": {
+ "amount": "Refund amount as a decimal string.",
+ "created_at": "Timestamp when the refund was created.",
+ "currency": "Currency code.",
+ "customer_id": "The customer that received the refund.",
+ "external_id": "External reference ID from the payment processor.",
+ "external_url": "Link to view the refund in the payment processor's dashboard.",
+ "failure_reason": "Reason for failure if status is failed.",
+ "id": "Unique identifier for the refund.",
+ "payment_id": "The original payment that was refunded.",
+ "processor_id": "Payment processor's internal refund ID.",
+ "reason": "Reason for the refund.",
+ "status": "Refund status.",
+ "updated_at": "Timestamp when the refund was last updated.",
+ },
+ },
+ "subscriptions": {
+ "description": "A customer's subscription contract, including billing, renewal, and discount configuration.",
+ "docs_url": "https://alguna.com/docs/api-reference/v2/2026-04-01/subscriptions/list-subscriptions",
+ "columns": {
+ "activated_at": "When the subscription was activated.",
+ "billing": "Billing configuration.",
+ "contract": "Contract configuration.",
+ "created_at": "When the subscription was created.",
+ "currency": "ISO 4217 currency code.",
+ "current_version_id": "Current active version ID.",
+ "customer_id": "Customer ID.",
+ "discount": "Subscription-level discount.",
+ "id": "Unique identifier.",
+ "maximum_spend": "Maximum spend threshold.",
+ "metadata": "Key-value metadata.",
+ "minimum_spend": "Minimum spend threshold.",
+ "name": "Subscription name.",
+ "pending_changes": "Pending version changes.",
+ "plan_id": "Plan ID.",
+ "price_escalation": "Price escalation configuration.",
+ "renewal": "Renewal configuration.",
+ "status": "Subscription status.",
+ "trial_period_days": "Trial period in days.",
+ "updated_at": "When the subscription was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
new file mode 100644
index 000000000000..8c2641622212
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/settings.py
@@ -0,0 +1,36 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Every stream is full refresh. Alguna's list endpoints expose no created_at/updated_at server-side
+# filters, and while /invoices supports issue/paid/due/invoicing date-range filters, the invoice
+# *list* payload (InvoiceListItemResponse) doesn't include those date fields — so the pipeline
+# can't track a watermark from synced rows. Billing data is low-cardinality, so full refresh is fine.
+
+
+@dataclass
+class AlgunaEndpointConfig:
+ name: str
+ path: str
+ # Alguna requires `sort` (format "field:order") on most list endpoints; None for the endpoints
+ # that don't accept it (payments, products). All entities carry created_at, and the API docs use
+ # it in sort examples, so it's the stable pagination order for the endpoints that sort.
+ sort: str | None = "created_at:asc"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ partition_key: str = "created_at"
+
+
+ALGUNA_ENDPOINTS: dict[str, AlgunaEndpointConfig] = {
+ "billable_metrics": AlgunaEndpointConfig(name="billable_metrics", path="/metrics"),
+ "customers": AlgunaEndpointConfig(name="customers", path="/customers"),
+ "invoices": AlgunaEndpointConfig(name="invoices", path="/invoices"),
+ "payments": AlgunaEndpointConfig(name="payments", path="/payments", sort=None),
+ "plans": AlgunaEndpointConfig(name="plans", path="/plans"),
+ "products": AlgunaEndpointConfig(name="products", path="/products", sort=None),
+ "refunds": AlgunaEndpointConfig(name="refunds", path="/refunds"),
+ "subscriptions": AlgunaEndpointConfig(name="subscriptions", path="/subscriptions"),
+}
+
+ENDPOINTS = tuple(ALGUNA_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in ALGUNA_ENDPOINTS}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
index 920b73c0d491..48bf8d4cf05b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna import (
+ ALGUNA_BASE_URL,
+ AlgunaResumeConfig,
+ alguna_source,
+ validate_credentials as validate_alguna_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import (
+ 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.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
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AlgunaSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AlgunaSource(SimpleSource[AlgunaSourceConfig]):
+class AlgunaSource(ResumableSource[AlgunaSourceConfig, AlgunaResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ALGUNA
@@ -24,8 +48,85 @@ class AlgunaSource(SimpleSource[AlgunaSourceConfig]):
name=SchemaExternalDataSourceType.ALGUNA,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Alguna",
- iconPath="/static/services/alguna.png",
- keywords=["billing", "invoices", "subscriptions", "usage-based"],
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Alguna API key to automatically pull your Alguna billing data into the PostHog Data warehouse.
+
+You can create an API key in your Alguna dashboard under Settings > Credentials.
+""",
+ iconPath="/static/services/alguna.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/alguna",
+ keywords=["billing", "invoices", "subscriptions", "usage-based", "cpq"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
unreleasedSource=True,
)
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ f"401 Client Error: Unauthorized for url: {ALGUNA_BASE_URL}": "Your Alguna API key is invalid or has been revoked. Create a new API key in your Alguna dashboard under Settings > Credentials, then reconnect.",
+ f"403 Client Error: Forbidden for url: {ALGUNA_BASE_URL}": "Your Alguna API key does not have permission to read this data. Check the key in your Alguna dashboard under Settings > Credentials, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AlgunaSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: AlgunaSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_alguna_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Alguna API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AlgunaResumeConfig]:
+ return ResumableSourceManager[AlgunaResumeConfig](inputs, AlgunaResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AlgunaSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AlgunaResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return alguna_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
new file mode 100644
index 000000000000..a4eb32b502e0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna.py
@@ -0,0 +1,180 @@
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna import (
+ ALGUNA_API_VERSION,
+ AlgunaResumeConfig,
+ alguna_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ALGUNA_ENDPOINTS, ENDPOINTS
+
+SESSION_PATCH_TARGET = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna.make_tracked_session"
+)
+
+
+def _make_manager(resume_state: AlgunaResumeConfig | 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 _response(items: list[dict[str, Any]], status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.status_code = status_code
+ resp.ok = status_code < 400
+ resp.json.return_value = {"data": items, "pagination": {"per_page": 100, "total_pages": 1}}
+ return resp
+
+
+def _query(call: mock._Call) -> dict[str, list[str]]:
+ return parse_qs(urlparse(call.args[0]).query)
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_validate_credentials_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+
+ with mock.patch(SESSION_PATCH_TARGET) as mock_session:
+ mock_session.return_value.get.return_value = response
+ assert validate_credentials("key") is expected
+
+ def test_validate_credentials_swallows_exceptions(self):
+ with mock.patch(SESSION_PATCH_TARGET) as mock_session:
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("key") is False
+
+
+class TestGetRows:
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_paginates_with_limit_offset(self, mock_session):
+ full_page = [{"id": f"cust_{i}"} for i in range(100)]
+ last_page = [{"id": "cust_last"}]
+ mock_session.return_value.get.side_effect = [_response(full_page), _response(last_page)]
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+
+ assert [item["id"] for batch in batches for item in batch] == [*(f"cust_{i}" for i in range(100)), "cust_last"]
+
+ calls = mock_session.return_value.get.call_args_list
+ assert _query(calls[0])["offset"] == ["0"]
+ assert _query(calls[0])["limit"] == ["100"]
+ assert _query(calls[0])["sort"] == ["created_at:asc"]
+ assert _query(calls[1])["offset"] == ["100"]
+
+ # State is saved only after a full page has been yielded, so a crash re-yields
+ # the last page instead of skipping it.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].offset == 100
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_requests_send_auth_and_version_headers(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "cust_1"}])
+
+ list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
+
+ headers = mock_session.return_value.get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer key"
+ # Alguna rejects any request without the date-based version header.
+ assert headers["Alguna-Version"] == ALGUNA_API_VERSION
+
+ @parameterized.expand([("payments",), ("products",)])
+ def test_no_sort_param_for_endpoints_without_sort(self, endpoint: str) -> None:
+ with mock.patch(SESSION_PATCH_TARGET) as mock_session:
+ mock_session.return_value.get.return_value = _response([{"id": "x"}])
+
+ list(get_rows("key", endpoint, mock.MagicMock(), _make_manager()))
+
+ assert "sort" not in _query(mock_session.return_value.get.call_args)
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_resumes_from_saved_offset(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "cust_201"}])
+
+ manager = _make_manager(AlgunaResumeConfig(offset=200))
+ list(get_rows("key", "customers", mock.MagicMock(), manager))
+
+ assert _query(mock_session.return_value.get.call_args_list[0])["offset"] == ["200"]
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_empty_first_page_stops_without_yield(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_short_page_terminates_without_saving_state(self, mock_session):
+ mock_session.return_value.get.return_value = _response([{"id": "cust_1"}, {"id": "cust_2"}])
+
+ manager = _make_manager()
+ batches = list(get_rows("key", "customers", mock.MagicMock(), manager))
+
+ assert len(batches) == 1
+ assert mock_session.return_value.get.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_missing_data_key_raises(self, mock_session):
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.json.return_value = {"unexpected": "envelope"}
+ mock_session.return_value.get.return_value = resp
+
+ # A 200 body without "data" means the response shape changed — the sync must fail
+ # loudly instead of silently reporting 0 rows.
+ with pytest.raises(KeyError):
+ list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
+
+ @mock.patch(SESSION_PATCH_TARGET)
+ def test_auth_error_raises_without_retry(self, mock_session):
+ resp = mock.MagicMock()
+ resp.status_code = 401
+ resp.ok = False
+ resp.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=resp)
+ mock_session.return_value.get.return_value = resp
+
+ with pytest.raises(requests.HTTPError):
+ list(get_rows("key", "customers", mock.MagicMock(), _make_manager()))
+
+ # Credential failures must not burn retry attempts before surfacing.
+ assert mock_session.return_value.get.call_count == 1
+
+
+class TestAlgunaSourceResponse:
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_response_metadata_per_endpoint(self, endpoint: str) -> None:
+ config = ALGUNA_ENDPOINTS[endpoint]
+ response = alguna_source("key", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+
+ @parameterized.expand([(name, config) for name, config in ALGUNA_ENDPOINTS.items()])
+ def test_partition_keys_are_stable_creation_fields(self, _name: str, config) -> None:
+ assert config.partition_key == "created_at"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna_source.py
new file mode 100644
index 000000000000..cc8b1184ed9d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/alguna/tests/test_alguna_source.py
@@ -0,0 +1,127 @@
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.alguna import AlgunaResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.alguna.source import AlgunaSource
+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 AlgunaSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestAlgunaSource:
+ def setup_method(self):
+ self.source = AlgunaSource()
+ self.team_id = 123
+ self.config = AlgunaSourceConfig(api_key="alg-key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.ALGUNA
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Alguna"
+ assert config.label == "Alguna"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # Deliberately gated while the endpoint behavior is unverified against a live account.
+ assert config.unreleasedSource is True
+ assert config.iconPath == "/static/services/alguna.svg"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_key"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert key_field.secret is True
+ assert key_field.required is True
+
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://api.alguna.io/customers?limit=100&offset=0",
+ ),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.alguna.io/invoices?limit=100&offset=0"),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, _name, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("other_vendor", "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers"),
+ ("server_error", "500 Server Error for url: https://api.alguna.io/customers"),
+ ]
+ )
+ def test_non_retryable_errors_does_not_match_unrelated(self, _name, other_vendor_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_vendor_error for key in non_retryable_errors)
+
+ def test_get_schemas_are_full_refresh_only(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No list payload carries the API's filterable date fields, so no stream can track an
+ # incremental watermark — advertising incremental here would corrupt syncs.
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "invoices"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @parameterized.expand(
+ [
+ ("valid", True, True, None),
+ ("invalid", False, False, "Invalid Alguna API key"),
+ ]
+ )
+ def test_validate_credentials(self, _name, mock_return, expected_valid, expected_message):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.alguna.source.validate_alguna_credentials"
+ ) as mock_validate:
+ 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)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AlgunaResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.alguna.source.alguna_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_alguna_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "invoices"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_alguna_source.assert_called_once()
+ kwargs = mock_alguna_source.call_args.kwargs
+ assert kwargs["api_key"] == "alg-key"
+ assert kwargs["endpoint"] == "invoices"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_canonical_descriptions_cover_declared_endpoints(self):
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index c6ce0185347e..3a3a0478b6ef 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
@@ -224,7 +224,7 @@ class AlgoliaSourceConfig(config.Config):
@config.config
class AlgunaSourceConfig(config.Config):
- pass
+ api_key: str
@config.config