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): add MailerLite webhook ingestion (#77486)

Tom Owersbfe48685f737
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 30cc3ee5d780..11182762f0f1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -395,7 +395,7 @@ the row lists both.
| mailchimp | HTTP | requests + `rest_source.RESTClient` | ✅ |
| marketo | HTTP | requests | ✅ |
| mem0 | HTTP | requests | ✅ |
-| mailerlite | HTTP | requests | ✅ |
+| mailerlite | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| mailersend | HTTP | requests | ✅ |
| mailgun | HTTP | requests | ✅ |
| mailjet | HTTP + Webhook | `rest_source.RESTClient` + requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
index 121c78c806d1..7fabe594c144 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/mailerlite.py
@@ -1,8 +1,21 @@
import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime
from typing import Any, Optional
+from urllib.parse import urlsplit
-from requests import Response
+import orjson
+import pyarrow as pa
+from asgiref.sync import async_to_sync
+from requests import Response, Session
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSyncResult,
+)
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,
@@ -14,10 +27,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.settings import (
+ ALL_WEBHOOK_EVENTS,
API_VERSION_HEADERS,
MAILERLITE_ENDPOINTS,
MAILERLITE_V1,
+ WEBHOOK_SCHEMA_NAMES,
)
MAILERLITE_BASE_URL = "https://connect.mailerlite.com/api"
@@ -25,6 +41,8 @@ MAILERLITE_BASE_URL = "https://connect.mailerlite.com/api"
# MailerLite caps list endpoints at 100 rows per page; default is 25.
PAGE_SIZE = 100
+WEBHOOK_NAME = "PostHog Data warehouse"
+
@dataclasses.dataclass
class MailerLiteResumeConfig:
@@ -59,6 +77,7 @@ def mailerlite_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[MailerLiteResumeConfig],
+ webhook_source_manager: Optional[WebhookSourceManager] = None,
db_incremental_field_last_value: Optional[Any] = None,
api_version: str = MAILERLITE_V1,
) -> SourceResponse:
@@ -118,9 +137,18 @@ def mailerlite_source(
initial_paginator_state=initial_paginator_state,
)
+ webhook_enabled = False
+ if webhook_source_manager is not None and endpoint in WEBHOOK_SCHEMA_NAMES:
+ webhook_enabled = async_to_sync(webhook_source_manager.webhook_enabled)(webhook_only=False)
+
+ def items():
+ if webhook_enabled and webhook_source_manager is not None:
+ return webhook_source_manager.get_items(table_transformer=_webhook_table_transformer)
+ return resource
+
return SourceResponse(
name=endpoint,
- items=lambda: resource,
+ items=items,
primary_keys=["id"],
partition_count=1,
partition_size=1,
@@ -139,3 +167,217 @@ def validate_credentials(api_key: str, path: str = "/subscribers") -> bool:
headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
)
return ok
+
+
+# Envelope keys a webhook delivery adds around the subscriber object. `event` (flat payloads) and
+# `type` (nested ones) name the event, `account_id` identifies the MailerLite account, and
+# `subscriber`/`group` only appear on the nested group events — none exist on a polled row.
+_WEBHOOK_ENVELOPE_KEYS = frozenset({"event", "type", "account_id", "subscriber", "group"})
+
+
+def _decode_nested(value: Any) -> Any:
+ """Undo the buffering layer's occasional JSON-string serialization of a nested structure."""
+ if isinstance(value, str | bytes):
+ try:
+ return orjson.loads(value)
+ except orjson.JSONDecodeError:
+ return None
+ return value
+
+
+def _parse_mailerlite_datetime(value: Any) -> Optional[datetime]:
+ """Parse a MailerLite timestamp to an aware UTC datetime.
+
+ Webhook deliveries use ISO-8601 ("2024-05-28T10:30:29.000000Z") while the REST API returns a
+ space-separated local-looking form ("2024-05-28 10:30:29"); both reach this via a merged
+ webhook batch, so accept either and treat a naive value as UTC.
+ """
+ if not isinstance(value, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ return parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed.astimezone(UTC)
+
+
+def _subscriber_row_from_payload(payload: dict[str, Any]) -> Optional[dict[str, Any]]:
+ """Recover the subscriber object from one webhook delivery, in the polled table's shape.
+
+ Flat events (`subscriber.created` and friends) put the subscriber's own fields at the payload
+ root; the group events nest the same object under `subscriber`. Either way the envelope keys
+ are dropped so a webhook row carries exactly the columns a polled row does.
+ """
+ nested = _decode_nested(payload.get("subscriber"))
+ if isinstance(nested, dict):
+ row = {key: value for key, value in nested.items() if key not in _WEBHOOK_ENVELOPE_KEYS}
+ else:
+ row = {key: value for key, value in payload.items() if key not in _WEBHOOK_ENVELOPE_KEYS}
+
+ return row if row.get("id") is not None else None
+
+
+def _webhook_table_transformer(table: pa.Table) -> pa.Table:
+ """Reshape raw webhook deliveries into rows matching the pull-API table shape.
+
+ Delta merge only dedupes across syncs, so a batch carrying e.g. `subscriber.created` then
+ `subscriber.updated` for one subscriber must collapse to the newest row here — otherwise both
+ land and every later merge multi-matches them.
+ """
+ latest_by_id: dict[Any, tuple[Optional[datetime], dict[str, Any]]] = {}
+
+ for payload in table.to_pylist():
+ row = _subscriber_row_from_payload(payload)
+ if row is None:
+ continue
+
+ updated_at = _parse_mailerlite_datetime(row.get("updated_at"))
+ existing = latest_by_id.get(row["id"])
+ # Later rows win ties so batch arrival order breaks equal or missing timestamps.
+ if existing is None or existing[0] is None or (updated_at is not None and updated_at >= existing[0]):
+ latest_by_id[row["id"]] = (updated_at, row)
+
+ return table_from_py_list([row for _, row in latest_by_id.values()])
+
+
+class MailerLiteUntrustedURLError(Exception):
+ pass
+
+
+_API_NETLOC = urlsplit(MAILERLITE_BASE_URL).netloc
+
+
+def _assert_mailerlite_origin(url: str) -> None:
+ """Reject a webhook-management URL that points off the MailerLite API origin.
+
+ `links.next` is response-controlled and this session sends the API key on every request, so a
+ poisoned next link (off-host, downgraded to http, or on a non-default port — netloc carries the
+ port) would otherwise exfiltrate the key. Redirects are refused separately by the session.
+ """
+ split = urlsplit(url)
+ if not (split.scheme == "https" and split.netloc == _API_NETLOC and split.path.startswith("/api/")):
+ raise MailerLiteUntrustedURLError(f"Refusing to follow a MailerLite URL outside {MAILERLITE_BASE_URL}")
+
+
+def _make_webhook_session(api_key: str) -> Session:
+ return make_tracked_session(
+ headers={
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ "Content-Type": "application/json",
+ },
+ redact_values=(api_key,),
+ # Webhook responses carry the signing secret, so keep the bodies out of HTTP sample
+ # capture; no-redirect pins the credentialed request to the origin it validated.
+ capture=False,
+ allow_redirects=False,
+ )
+
+
+def _iterate_webhooks(session: Session) -> Iterator[dict[str, Any]]:
+ next_url: Optional[str] = f"{MAILERLITE_BASE_URL}/webhooks?limit={PAGE_SIZE}"
+ while next_url:
+ _assert_mailerlite_origin(next_url)
+ response = session.get(next_url, timeout=30)
+ response.raise_for_status()
+ body = response.json()
+ yield from (item for item in body.get("data") or [] if isinstance(item, dict))
+ next_url = (body.get("links") or {}).get("next")
+
+
+def _webhooks_matching(session: Session, webhook_url: str) -> list[dict[str, Any]]:
+ return [item for item in _iterate_webhooks(session) if item.get("url") == webhook_url]
+
+
+def create_webhook(api_key: str, webhook_url: str) -> WebhookCreationResult:
+ """Register an account-level webhook pointing at `webhook_url`.
+
+ MailerLite generates the signing secret itself and returns it once, on this response — there
+ is no way to set or re-read it later, so a create that somehow omits it leaves the user to
+ paste one in manually rather than silently ingesting unverified deliveries.
+ """
+ try:
+ session = _make_webhook_session(api_key)
+ payload = {
+ "name": WEBHOOK_NAME,
+ "url": webhook_url,
+ "events": ALL_WEBHOOK_EVENTS,
+ "enabled": True,
+ }
+ response = session.post(f"{MAILERLITE_BASE_URL}/webhooks", json=payload, timeout=30)
+ if response.status_code not in (200, 201):
+ return WebhookCreationResult(
+ success=False,
+ error=(
+ f"Failed to create the MailerLite webhook (HTTP {response.status_code}). "
+ "Please create it manually below."
+ ),
+ )
+
+ secret = ((response.json() or {}).get("data") or {}).get("secret")
+ if not secret:
+ return WebhookCreationResult(success=True, pending_inputs=["signing_secret"])
+
+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})
+ except Exception as e:
+ return WebhookCreationResult(
+ success=False,
+ error=f"Failed to create the MailerLite webhook: {e}. Please create it manually below.",
+ )
+
+
+def sync_webhook_events(api_key: str, webhook_url: str, desired_events: list[str]) -> WebhookSyncResult:
+ """Add any missing `desired_events` to the webhooks pointing at `webhook_url`.
+
+ Events are merged rather than replaced so a manually broadened webhook keeps its extras.
+ """
+ try:
+ session = _make_webhook_session(api_key)
+ for webhook in _webhooks_matching(session, webhook_url):
+ current = webhook.get("events") or []
+ merged = sorted(set(current) | set(desired_events))
+ if merged == sorted(current):
+ continue
+ response = session.put(
+ f"{MAILERLITE_BASE_URL}/webhooks/{webhook.get('id')}",
+ json={"events": merged},
+ timeout=30,
+ )
+ response.raise_for_status()
+ return WebhookSyncResult(success=True)
+ except Exception as e:
+ return WebhookSyncResult(success=False, error=f"Failed to update MailerLite webhook events: {e}")
+
+
+def get_external_webhook_info(api_key: str, webhook_url: str) -> ExternalWebhookInfo:
+ try:
+ session = _make_webhook_session(api_key)
+ matching = _webhooks_matching(session, webhook_url)
+ if not matching:
+ return ExternalWebhookInfo(exists=False)
+
+ webhook = matching[0]
+ return ExternalWebhookInfo(
+ exists=True,
+ url=webhook.get("url"),
+ enabled_events=webhook.get("events"),
+ status="enabled" if webhook.get("enabled") else "disabled",
+ created_at=webhook.get("created_at"),
+ )
+ except Exception as e:
+ return ExternalWebhookInfo(exists=False, error=str(e))
+
+
+def delete_webhook(api_key: str, webhook_url: str) -> WebhookDeletionResult:
+ try:
+ session = _make_webhook_session(api_key)
+ errors: list[str] = []
+ for webhook in _webhooks_matching(session, webhook_url):
+ response = session.delete(f"{MAILERLITE_BASE_URL}/webhooks/{webhook.get('id')}", timeout=30)
+ if response.status_code not in (200, 204):
+ errors.append(f"webhook {webhook.get('id')}: HTTP {response.status_code}")
+ if errors:
+ return WebhookDeletionResult(success=False, error="; ".join(errors))
+ return WebhookDeletionResult(success=True)
+ except Exception as e:
+ return WebhookDeletionResult(success=False, error=str(e))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
index 4fbade471d5f..ce9df70456bf 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/settings.py
@@ -73,6 +73,45 @@ MAILERLITE_ENDPOINTS: dict[str, MailerLiteEndpointConfig] = {
ENDPOINTS = tuple(MAILERLITE_ENDPOINTS.keys())
+# MailerLite names its events `<resource>.<action>`, so the hog template routes on the part
+# before the dot and one entry covers every subscriber event.
+WEBHOOK_RESOURCE_MAP: dict[str, str] = {"subscribers": "subscriber"}
+
+# Only the events whose delivery carries the whole subscriber object are subscribed, so a
+# webhook row is a drop-in replacement for a polled one:
+# - flat events put the subscriber's fields at the payload root next to `event`/`account_id`
+# - the two group events nest the same object under `subscriber`
+# Deliberately left out:
+# - `subscriber.deleted` needs `batchable: true`, which changes the delivery envelope, and a
+# deletion can't be expressed as a merge row anyway
+# - `subscriber.automation_triggered` / `subscriber.automation_completed` report automation
+# progress rather than a change to the subscriber's own fields
+# - every `campaign.*` event (see WEBHOOK_SCHEMA_NAMES)
+SUBSCRIBER_WEBHOOK_EVENTS: tuple[str, ...] = (
+ "subscriber.active",
+ "subscriber.added_to_group",
+ "subscriber.bounced",
+ "subscriber.created",
+ "subscriber.removed_from_group",
+ "subscriber.spam_reported",
+ "subscriber.unsubscribed",
+ "subscriber.updated",
+)
+
+SCHEMA_TO_WEBHOOK_EVENTS: dict[str, tuple[str, ...]] = {"subscribers": SUBSCRIBER_WEBHOOK_EVENTS}
+
+# `subscribers` is the only webhook-eligible table. `campaigns` is deliberately excluded:
+# `campaign.sent` delivers just {id, name, total_recipients, preview_url, date}, a fraction of
+# the polled campaign object (status, type, settings, filter, emails, stats), and once a schema
+# has webhooks enabled the poll is skipped — so wiring it would drop the columns polling
+# collects today. `campaign.open` / `campaign.click` are per-recipient engagement with no event
+# id and no event timestamp in the payload, so they can't form a stable primary key or a
+# partition/ordering column for a webhook-only table.
+WEBHOOK_SCHEMA_NAMES: frozenset[str] = frozenset(SCHEMA_TO_WEBHOOK_EVENTS)
+
+ALL_WEBHOOK_EVENTS: list[str] = sorted({event for events in SCHEMA_TO_WEBHOOK_EVENTS.values() for event in events})
+
+
# The new MailerLite API (connect.mailerlite.com) is date-versioned through the `X-Version`
# header and serves the latest version when it's absent. Framework version labels map to that
# header here: `v1` predates version pinning and sends no header (the exact behaviour existing
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
index 838a2e6b22f7..e9929c15db6e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/source.py
@@ -1,4 +1,4 @@
-from typing import Optional, cast
+from typing import TYPE_CHECKING, Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
@@ -9,7 +9,15 @@ from posthog.schema import (
SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+ WebhookSyncResult,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -20,9 +28,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
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.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailerlite import (
MailerLiteSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite import mailerlite as api_client
from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.mailerlite import (
MailerLiteResumeConfig,
mailerlite_source,
@@ -32,13 +42,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite
DEFAULT_VERSION,
ENDPOINTS,
MAILERLITE_ENDPOINTS,
+ SCHEMA_TO_WEBHOOK_EVENTS,
SUPPORTED_VERSIONS,
+ WEBHOOK_RESOURCE_MAP,
+ WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
@SourceRegistry.register
-class MailerLiteSource(ResumableSource[MailerLiteSourceConfig, MailerLiteResumeConfig]):
+class MailerLiteSource(
+ ResumableSource[MailerLiteSourceConfig, MailerLiteResumeConfig],
+ WebhookSource[MailerLiteSourceConfig],
+):
api_docs_url = "https://developers.mailerlite.com"
supported_versions = SUPPORTED_VERSIONS
@@ -50,6 +69,18 @@ class MailerLiteSource(ResumableSource[MailerLiteSourceConfig, MailerLiteResumeC
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.MAILERLITE
+ @property
+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.webhook_template import (
+ template,
+ )
+
+ return template
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return WEBHOOK_RESOURCE_MAP
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -75,6 +106,37 @@ You can create an API key in your [MailerLite integrations settings](https://das
),
],
),
+ webhookSetupCaption="""PostHog registers a MailerLite webhook for your subscriber events using your API key. MailerLite generates the signing secret and returns it once, at creation, so PostHog stores it then and uses it to verify every delivery.
+
+**Manual setup** (only needed if automatic registration failed):
+
+MailerLite only manages webhooks through its API, so create one with a request like this, using the webhook URL shown below:
+
+```
+curl -X POST https://connect.mailerlite.com/api/webhooks \\
+ -H "Authorization: Bearer YOUR_API_KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '{"name": "PostHog Data warehouse", "url": "YOUR_WEBHOOK_URL", "events": ["subscriber.created", "subscriber.updated", "subscriber.unsubscribed", "subscriber.bounced", "subscriber.spam_reported", "subscriber.active", "subscriber.added_to_group", "subscriber.removed_from_group"]}'
+```
+
+Copy the `secret` from the response into the field below. MailerLite never returns it again, so if you lose it, delete the webhook and create a new one.""",
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ caption=(
+ "The secret MailerLite returned when the webhook was created. PostHog "
+ "uses it to verify the Signature header on every delivery."
+ ),
+ secret=True,
+ ),
+ ],
+ ),
)
def get_non_retryable_errors(self) -> dict[str, str | None]:
@@ -101,7 +163,7 @@ You can create an API key in your [MailerLite integrations settings](https://das
) -> list[SourceSchema]:
# MailerLite exposes no server-side timestamp filter, so every endpoint is full-refresh only
# (no incremental fields → build_endpoint_schemas marks each supports_incremental=False).
- return build_endpoint_schemas(ENDPOINTS, {}, names)
+ return build_endpoint_schemas(ENDPOINTS, {}, names, supports_webhooks=WEBHOOK_SCHEMA_NAMES)
def validate_credentials(
self,
@@ -120,6 +182,40 @@ You can create an API key in your [MailerLite integrations settings](https://das
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MailerLiteResumeConfig]:
return ResumableSourceManager[MailerLiteResumeConfig](inputs, MailerLiteResumeConfig)
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ def create_webhook(
+ self, config: MailerLiteSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookCreationResult:
+ return api_client.create_webhook(config.api_key, webhook_url)
+
+ def get_desired_webhook_events(
+ self, config: MailerLiteSourceConfig, eligible_schema_names: list[str]
+ ) -> list[str] | None:
+ return sorted({event for name in eligible_schema_names for event in SCHEMA_TO_WEBHOOK_EVENTS.get(name, ())})
+
+ def sync_webhook_events(
+ self,
+ config: MailerLiteSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ eligible_schema_names: list[str],
+ api_version: str | None = None,
+ ) -> WebhookSyncResult:
+ desired_events = self.get_desired_webhook_events(config, eligible_schema_names) or []
+ return api_client.sync_webhook_events(config.api_key, webhook_url, desired_events)
+
+ def get_external_webhook_info(
+ self, config: MailerLiteSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> ExternalWebhookInfo | None:
+ return api_client.get_external_webhook_info(config.api_key, webhook_url)
+
+ def delete_webhook(
+ self, config: MailerLiteSourceConfig, webhook_url: str, team_id: int, api_version: str | None = None
+ ) -> WebhookDeletionResult:
+ return api_client.delete_webhook(config.api_key, webhook_url)
+
def source_for_pipeline(
self,
config: MailerLiteSourceConfig,
@@ -132,5 +228,6 @@ You can create an API key in your [MailerLite integrations settings](https://das
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ webhook_source_manager=self.get_webhook_source_manager(inputs),
api_version=self.resolve_api_version(inputs.api_version),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
index fd18e4e5354d..5c648b8e9138 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite.py
@@ -8,20 +8,28 @@ from unittest.mock import MagicMock, patch
from requests import Response
from requests.exceptions import ChunkedEncodingError, HTTPError
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import table_from_py_list
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
RESTClientRetryableError,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.mailerlite import (
MAILERLITE_BASE_URL,
MailerLiteResumeConfig,
+ _webhook_table_transformer,
+ create_webhook,
+ delete_webhook,
+ get_external_webhook_info,
mailerlite_source,
+ sync_webhook_events,
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.settings import (
ENDPOINTS,
MAILERLITE_V1,
MAILERLITE_V2,
+ SUBSCRIBER_WEBHOOK_EVENTS,
)
# RESTClient builds its session via make_tracked_session in the rest_client module.
@@ -289,3 +297,322 @@ class TestMailerLiteSourceResponse:
)
assert response.name == endpoint
assert response.primary_keys == ["id"]
+
+
+WEBHOOK_URL = "https://ph.example/public/webhooks/abc"
+
+
+def _webhook_list(items: list[dict[str, Any]], next_url: str | None = None) -> Response:
+ return _make_response({"data": items, "links": {"next": next_url}, "meta": {}})
+
+
+def _subscriber(subscriber_id: str, updated_at: str, **overrides: Any) -> dict[str, Any]:
+ return {
+ "id": subscriber_id,
+ "email": f"{subscriber_id}@example.com",
+ "status": "active",
+ "created_at": "2024-05-08T08:26:04.000000Z",
+ "updated_at": updated_at,
+ **overrides,
+ }
+
+
+class TestCreateWebhook:
+ @pytest.mark.parametrize(
+ ("status_code", "body", "expected_success", "expected_extra", "expected_pending"),
+ [
+ (201, {"data": {"id": "1", "secret": "s3cr3t"}}, True, {"signing_secret": "s3cr3t"}, []),
+ (200, {"data": {"id": "1", "secret": "s3cr3t"}}, True, {"signing_secret": "s3cr3t"}, []),
+ # MailerLite returns the secret exactly once; if it's absent we must ask the user for
+ # it rather than leaving a webhook whose deliveries can't be verified.
+ (201, {"data": {"id": "1"}}, True, {}, ["signing_secret"]),
+ (422, {"message": "invalid"}, False, {}, []),
+ (403, {"message": "forbidden"}, False, {}, []),
+ ],
+ )
+ def test_secret_handling_by_response(
+ self,
+ status_code: int,
+ body: dict[str, Any],
+ expected_success: bool,
+ expected_extra: dict[str, str],
+ expected_pending: list[str],
+ ) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.post.return_value = _make_response(body, status_code=status_code)
+ result = create_webhook("key", WEBHOOK_URL)
+
+ assert result.success is expected_success
+ assert result.extra_inputs == expected_extra
+ assert result.pending_inputs == expected_pending
+
+ def test_subscribes_only_to_the_subscriber_events(self) -> None:
+ # A webhook created without these events pushes nothing, and one created with campaign
+ # events would feed partial objects into a polled table.
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.post.return_value = _make_response({"data": {"id": "1", "secret": "s"}}, status_code=201)
+ create_webhook("key", WEBHOOK_URL)
+
+ url, kwargs = session.post.call_args.args[0], session.post.call_args.kwargs
+ assert url == f"{MAILERLITE_BASE_URL}/webhooks"
+ assert kwargs["json"]["url"] == WEBHOOK_URL
+ assert kwargs["json"]["enabled"] is True
+ assert kwargs["json"]["events"] == sorted(SUBSCRIBER_WEBHOOK_EVENTS)
+
+ def test_transport_failure_reports_manual_setup(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.post.side_effect = Exception("boom")
+ result = create_webhook("key", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None and "manually" in result.error
+
+
+class TestDeleteWebhook:
+ def test_deletes_only_webhooks_pointing_at_our_url(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list(
+ [{"id": "1", "url": WEBHOOK_URL}, {"id": "2", "url": "https://other.example/hook"}]
+ )
+ session.delete.return_value = _make_response({}, status_code=204)
+ result = delete_webhook("key", WEBHOOK_URL)
+
+ assert result.success is True
+ assert [call.args[0] for call in session.delete.call_args_list] == [f"{MAILERLITE_BASE_URL}/webhooks/1"]
+
+ def test_no_matching_webhook_is_a_no_op_success(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list([{"id": "2", "url": "https://other.example/hook"}])
+ result = delete_webhook("key", WEBHOOK_URL)
+
+ assert result.success is True
+ session.delete.assert_not_called()
+
+ def test_failed_delete_is_reported(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list([{"id": "1", "url": WEBHOOK_URL}])
+ session.delete.return_value = _make_response({}, status_code=500)
+ result = delete_webhook("key", WEBHOOK_URL)
+
+ assert result.success is False
+ assert result.error is not None and "500" in result.error
+
+
+class TestGetExternalWebhookInfo:
+ @pytest.mark.parametrize(
+ ("enabled", "expected_status"),
+ [(True, "enabled"), (False, "disabled")],
+ )
+ def test_reports_the_matching_webhook(self, enabled: bool, expected_status: str) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.return_value = _webhook_list(
+ [
+ {
+ "id": "1",
+ "url": WEBHOOK_URL,
+ "events": ["subscriber.created"],
+ "enabled": enabled,
+ "created_at": "2024-05-08 08:26:04",
+ }
+ ]
+ )
+ info = get_external_webhook_info("key", WEBHOOK_URL)
+
+ assert info.exists is True
+ assert info.url == WEBHOOK_URL
+ assert info.enabled_events == ["subscriber.created"]
+ assert info.status == expected_status
+ assert info.created_at == "2024-05-08 08:26:04"
+
+ def test_missing_webhook_reports_not_exists(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ MockSession.return_value.get.return_value = _webhook_list([])
+ info = get_external_webhook_info("key", WEBHOOK_URL)
+
+ assert info.exists is False
+ assert info.error is None
+
+ @pytest.mark.parametrize(
+ "off_host_url",
+ [
+ "http://169.254.169.254/latest/meta-data/",
+ "https://evil.example.com/api/webhooks",
+ "https://connect.mailerlite.com.evil.com/api/webhooks",
+ "https://connect.mailerlite.com/oauth/token",
+ ],
+ )
+ def test_off_host_next_link_stops_the_credentialed_walk(self, off_host_url: str) -> None:
+ # `links.next` is response-controlled and this session carries the API key, so a poisoned
+ # link must never be fetched.
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list([{"id": "2", "url": "https://other.example"}], off_host_url)
+ info = get_external_webhook_info("key", WEBHOOK_URL)
+
+ assert info.exists is False
+ assert info.error is not None and "Refusing to follow" in info.error
+ assert session.get.call_count == 1
+
+ def test_on_host_next_link_is_followed(self) -> None:
+ next_url = f"{MAILERLITE_BASE_URL}/webhooks?page=2&limit=100"
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.side_effect = [
+ _webhook_list([{"id": "2", "url": "https://other.example"}], next_url),
+ _webhook_list([{"id": "1", "url": WEBHOOK_URL, "events": [], "enabled": True}]),
+ ]
+ info = get_external_webhook_info("key", WEBHOOK_URL)
+
+ assert info.exists is True
+ assert [call.args[0] for call in session.get.call_args_list][1] == next_url
+
+
+class TestSyncWebhookEvents:
+ def test_missing_events_are_merged_in(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list(
+ [{"id": "1", "url": WEBHOOK_URL, "events": ["subscriber.created", "campaign.sent"]}]
+ )
+ session.put.return_value = _make_response({}, status_code=200)
+ result = sync_webhook_events("key", WEBHOOK_URL, ["subscriber.created", "subscriber.bounced"])
+
+ assert result.success is True
+ # Existing events are kept so a manually broadened webhook isn't narrowed behind the user's back.
+ assert session.put.call_args.kwargs["json"] == {
+ "events": ["campaign.sent", "subscriber.bounced", "subscriber.created"]
+ }
+
+ def test_already_covered_events_skip_the_write(self) -> None:
+ with patch(MAILERLITE_SESSION_PATCH) as MockSession:
+ session = MockSession.return_value
+ session.get.return_value = _webhook_list(
+ [{"id": "1", "url": WEBHOOK_URL, "events": ["subscriber.created", "subscriber.bounced"]}]
+ )
+ result = sync_webhook_events("key", WEBHOOK_URL, ["subscriber.created"])
+
+ assert result.success is True
+ session.put.assert_not_called()
+
+
+class TestWebhookTableTransformer:
+ def test_flat_delivery_drops_the_envelope_keys(self) -> None:
+ payload = {**_subscriber("1", "2024-05-28T10:30:29.000000Z"), "event": "subscriber.created", "account_id": 7}
+
+ rows = _webhook_table_transformer(table_from_py_list([payload])).to_pylist()
+
+ assert rows == [_subscriber("1", "2024-05-28T10:30:29.000000Z")]
+
+ def test_nested_group_delivery_unwraps_the_subscriber(self) -> None:
+ # subscriber.added_to_group nests the same object one level down; without unwrapping it the
+ # row has no id and the delivery is silently dropped.
+ payload = {
+ "type": "subscriber.added_to_group",
+ "subscriber": _subscriber("1", "2024-05-28T10:30:29.000000Z"),
+ "group": {"id": "9", "name": "Newsletter"},
+ "account_id": 7,
+ }
+
+ rows = _webhook_table_transformer(table_from_py_list([payload])).to_pylist()
+
+ assert rows == [_subscriber("1", "2024-05-28T10:30:29.000000Z")]
+
+ def test_latest_row_per_id_survives_a_batch(self) -> None:
+ # Delta merge only dedupes across syncs, so a created-then-updated pair in one batch would
+ # otherwise seed two rows for one subscriber and multi-match on every later merge.
+ payloads = [
+ {**_subscriber("1", "2024-05-28T10:30:29.000000Z", status="unconfirmed"), "event": "subscriber.created"},
+ {**_subscriber("1", "2024-05-29T11:00:00.000000Z", status="active"), "event": "subscriber.updated"},
+ {**_subscriber("2", "2024-05-28T10:30:29.000000Z"), "event": "subscriber.created"},
+ ]
+
+ rows = _webhook_table_transformer(table_from_py_list(payloads)).to_pylist()
+
+ assert sorted(rows, key=lambda r: r["id"]) == [
+ _subscriber("1", "2024-05-29T11:00:00.000000Z", status="active"),
+ _subscriber("2", "2024-05-28T10:30:29.000000Z"),
+ ]
+
+ def test_out_of_order_arrival_still_keeps_the_newest(self) -> None:
+ payloads = [
+ {**_subscriber("1", "2024-05-29T11:00:00.000000Z", status="active"), "event": "subscriber.updated"},
+ {**_subscriber("1", "2024-05-28T10:30:29.000000Z", status="unconfirmed"), "event": "subscriber.created"},
+ ]
+
+ rows = _webhook_table_transformer(table_from_py_list(payloads)).to_pylist()
+
+ assert rows == [_subscriber("1", "2024-05-29T11:00:00.000000Z", status="active")]
+
+ def test_delivery_without_an_id_is_dropped(self) -> None:
+ payloads = [
+ {"event": "subscriber.created", "account_id": 7, "email": "[email protected]"},
+ {**_subscriber("1", "2024-05-28T10:30:29.000000Z"), "event": "subscriber.created"},
+ ]
+
+ rows = _webhook_table_transformer(table_from_py_list(payloads)).to_pylist()
+
+ assert [row["id"] for row in rows] == ["1"]
+
+
+class TestWebhookSourceWiring:
+ def _manager(self, enabled: bool) -> MagicMock:
+ manager = MagicMock(spec=WebhookSourceManager)
+
+ async def _webhook_enabled(webhook_only: bool = False) -> bool:
+ return enabled
+
+ manager.webhook_enabled.side_effect = _webhook_enabled
+ manager.get_items.return_value = "webhook-items"
+ return manager
+
+ def test_enabled_webhook_replaces_the_poll_for_that_sync(self) -> None:
+ webhook_manager = self._manager(enabled=True)
+
+ response = mailerlite_source(
+ api_key="key",
+ endpoint="subscribers",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ webhook_source_manager=webhook_manager,
+ )
+
+ assert response.items() == "webhook-items"
+ # Without the dedup transformer a batch can seed duplicate rows for one subscriber.
+ assert webhook_manager.get_items.call_args.kwargs["table_transformer"] is not None
+
+ def test_disabled_webhook_falls_back_to_the_poll(self) -> None:
+ webhook_manager = self._manager(enabled=False)
+
+ response = mailerlite_source(
+ api_key="key",
+ endpoint="subscribers",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ webhook_source_manager=webhook_manager,
+ )
+
+ assert response.items() != "webhook-items"
+ webhook_manager.get_items.assert_not_called()
+
+ @pytest.mark.parametrize("endpoint", ["campaigns", "groups", "fields"])
+ def test_non_webhook_endpoints_never_consult_the_webhook_manager(self, endpoint: str) -> None:
+ # Webhooks are only wired for subscribers; any other table must keep polling in full.
+ webhook_manager = self._manager(enabled=True)
+
+ response = mailerlite_source(
+ api_key="key",
+ endpoint=endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ webhook_source_manager=webhook_manager,
+ )
+
+ assert response.items() != "webhook-items"
+ webhook_manager.webhook_enabled.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
index ac167af10b51..071437636ba2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/tests/test_mailerlite_source.py
@@ -1,10 +1,21 @@
+from typing import Any
+
import pytest
from unittest.mock import MagicMock, patch
from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+from posthog.cdp.validation import compile_hog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSyncResult,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.mailerlite import (
MailerLiteSourceConfig,
)
@@ -15,6 +26,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite
ENDPOINTS,
MAILERLITE_V1,
MAILERLITE_V2,
+ SUBSCRIBER_WEBHOOK_EVENTS,
+ WEBHOOK_SCHEMA_NAMES,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.source import MailerLiteSource
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -106,11 +119,95 @@ class TestMailerLiteSourceClass:
"products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.source.mailerlite_source"
) as mock_source:
MailerLiteSource().source_for_pipeline(_config(), manager, inputs)
- mock_source.assert_called_once_with(
- api_key="test-key",
- endpoint="subscribers",
- team_id=7,
- job_id="job-1",
- resumable_source_manager=manager,
- api_version=expected_version,
- )
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "test-key"
+ assert kwargs["endpoint"] == "subscribers"
+ assert kwargs["team_id"] == 7
+ assert kwargs["job_id"] == "job-1"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["api_version"] == expected_version
+ # Without the webhook manager a sync silently ignores every pushed row.
+ assert isinstance(kwargs["webhook_source_manager"], WebhookSourceManager)
+
+
+class TestMailerLiteWebhooks:
+ def test_only_subscribers_supports_webhooks(self) -> None:
+ # Enabling webhooks on a schema makes the poll skip once the initial sync completes, so a
+ # table whose events carry a partial object (campaigns) must stay poll-only.
+ schemas = {s.name: s for s in MailerLiteSource().get_schemas(_config(), team_id=1)}
+ assert {name for name, s in schemas.items() if s.supports_webhooks} == {"subscribers"}
+ assert all(s.webhook_only is False for s in schemas.values())
+
+ def test_webhook_resource_map_matches_event_name_prefix(self) -> None:
+ # The hog template routes on the part of the event name before the dot, so the map's value
+ # must equal that prefix or every delivery is dropped as unmapped.
+ source = MailerLiteSource()
+ assert source.webhook_resource_map == {"subscribers": "subscriber"}
+ assert set(source.webhook_resource_map) == set(WEBHOOK_SCHEMA_NAMES)
+ assert {event.split(".")[0] for event in SUBSCRIBER_WEBHOOK_EVENTS} == {"subscriber"}
+
+ def test_webhook_template_verifies_the_signature(self) -> None:
+ template = MailerLiteSource().webhook_template
+ assert template is not None
+ assert template.type == "warehouse_source_webhook"
+ # Deliveries are only trustworthy because of this check; losing it would leave a public
+ # ingest endpoint anyone could post to.
+ assert "sha256HmacChainHex" in template.code
+ assert "request.headers['signature']" in template.code
+ assert {i["key"] for i in template.inputs_schema} >= {"signing_secret", "schema_mapping", "source_id"}
+
+ def test_webhook_template_hog_compiles(self) -> None:
+ # The template is only compiled when a delivery arrives, so a syntax error here ships a
+ # webhook endpoint that fails on every push with nothing to catch it earlier.
+ template = MailerLiteSource().webhook_template
+ assert template is not None
+ assert compile_hog(template.code, template.type)[0] == "_H"
+
+ @pytest.mark.parametrize(
+ ("eligible", "expected"),
+ [
+ (["subscribers"], sorted(SUBSCRIBER_WEBHOOK_EVENTS)),
+ (["campaigns", "groups"], []),
+ (["subscribers", "campaigns"], sorted(SUBSCRIBER_WEBHOOK_EVENTS)),
+ ],
+ )
+ def test_desired_webhook_events_cover_only_webhook_schemas(self, eligible: list[str], expected: list[str]) -> None:
+ assert MailerLiteSource().get_desired_webhook_events(_config(), eligible) == expected
+
+ def test_webhook_signing_secret_is_a_secret_webhook_field(self) -> None:
+ config = MailerLiteSource().get_source_config
+ assert config.webhookFields is not None
+ secret_field = config.webhookFields[0]
+ assert isinstance(secret_field, SourceFieldInputConfig)
+ assert secret_field.name == "signing_secret"
+ assert secret_field.secret is True
+ assert secret_field.type == SourceFieldInputConfigType.PASSWORD
+
+ @pytest.mark.parametrize(
+ ("method", "client_function", "expected"),
+ [
+ ("create_webhook", "create_webhook", WebhookCreationResult(success=True)),
+ ("delete_webhook", "delete_webhook", WebhookDeletionResult(success=True)),
+ ("get_external_webhook_info", "get_external_webhook_info", ExternalWebhookInfo(exists=True)),
+ ],
+ )
+ def test_webhook_management_reaches_the_api_client(self, method: str, client_function: str, expected: Any) -> None:
+ # Unwired, these fall through to the base class, which raises or reports "not supported"
+ # and leaves the user with no webhook at all.
+ with patch(
+ f"products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.mailerlite.{client_function}",
+ return_value=expected,
+ ) as mock_client:
+ result = getattr(MailerLiteSource(), method)(_config(), "https://ph.example/webhook", 1)
+
+ assert result == expected
+ assert mock_client.call_args.args == ("test-key", "https://ph.example/webhook")
+
+ def test_sync_webhook_events_sends_the_eligible_events(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.mailerlite.mailerlite.sync_webhook_events",
+ return_value=WebhookSyncResult(success=True),
+ ) as mock_sync:
+ MailerLiteSource().sync_webhook_events(_config(), "https://ph.example/webhook", 1, ["subscribers"])
+
+ assert mock_sync.call_args.args == ("test-key", "https://ph.example/webhook", sorted(SUBSCRIBER_WEBHOOK_EVENTS))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/webhook_template.py
new file mode 100644
index 000000000000..be6914098c80
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mailerlite/webhook_template.py
@@ -0,0 +1,129 @@
+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+# MailerLite signs every delivery with a `Signature` header holding the lowercase hex
+# HMAC-SHA256 of the raw request body, keyed by the `secret` MailerLite generates when the
+# webhook is created (POST /api/webhooks returns it once).
+#
+# Flat subscriber deliveries carry the event name under `event`; the nested ones
+# (`subscriber.added_to_group`, `subscriber.removed_from_group`) use `type` instead. Both are
+# `<resource>.<action>`, so the resource prefix is the schema routing key and every campaign
+# event falls through unmapped.
+template: HogFunctionTemplateDC = HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-mailerlite",
+ name="MailerLite warehouse source webhook",
+ description="Receive MailerLite webhook events for data warehouse ingestion",
+ icon_url="/static/services/mailerlite.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""\
+if (request.method != 'POST') {
+ return {
+ 'httpResponse': {
+ 'status': 405,
+ 'body': 'Method not allowed'
+ }
+ }
+}
+
+if (not inputs.bypass_signature_check) {
+ if (empty(inputs.signing_secret)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Signing secret not configured',
+ }
+ }
+ }
+
+ let signature := request.headers['signature']
+
+ if (empty(signature)) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Missing signature',
+ }
+ }
+ }
+
+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, request.stringBody])
+
+ if (lower(signature) != computedSignature) {
+ return {
+ 'httpResponse': {
+ 'status': 400,
+ 'body': 'Bad signature',
+ }
+ }
+ }
+}
+
+let eventType := request.body.event ?? request.body.type
+
+if (empty(eventType)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': 'No event type found, skipping'
+ }
+ }
+}
+
+let resourceType := splitByString('.', eventType)[1]
+let schemaId := inputs.schema_mapping?.[resourceType]
+
+if (empty(schemaId)) {
+ return {
+ 'httpResponse': {
+ 'status': 200,
+ 'body': f'No schema mapping for resource type: {resourceType}, skipping'
+ }
+ }
+}
+
+produceToWarehouseWebhooks(request.body, schemaId)""",
+ inputs_schema=[
+ {
+ "type": "string",
+ "key": "signing_secret",
+ "label": "Signing secret",
+ "required": False,
+ "secret": True,
+ "hidden": False,
+ "description": (
+ "The webhook's secret from MailerLite. Used to verify the Signature header "
+ "(HMAC-SHA256 of the raw request body) so deliveries provably come from MailerLite."
+ ),
+ },
+ {
+ "type": "boolean",
+ "key": "bypass_signature_check",
+ "label": "Bypass signature check",
+ "description": "If set, the Signature header will not be checked. This is not recommended.",
+ "default": False,
+ "required": False,
+ "secret": False,
+ },
+ {
+ "type": "json",
+ "key": "schema_mapping",
+ "label": "Schema mapping",
+ "description": "Maps MailerLite resource types to ExternalDataSchema IDs",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ {
+ "type": "string",
+ "key": "source_id",
+ "label": "Source ID",
+ "description": "The ExternalDataSource ID this webhook is associated with",
+ "required": True,
+ "secret": False,
+ "hidden": True,
+ },
+ ],
+)