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 kong_konnect import source (#71146)

Tom Owers9473fe25873e
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 b4019a894f54..a1bb0bbf0cc1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -254,6 +254,7 @@ the row lists both.
| kernel | HTTP | requests | ✅ |
| klaviyo | HTTP | requests | ✅ |
| koyeb | HTTP | requests | ✅ |
+| kong_konnect | HTTP | requests | ✅ |
| lago | HTTP | requests | ✅ |
| lambda_labs | HTTP | requests | ✅ |
| langfuse | HTTP | requests | ✅ |
@@ -714,7 +715,6 @@ doesn't conflict with concurrent PRs.
- klarna
- klaus
- knock
-- kong_konnect
- koyeb
- kubecost
- kyve
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 4b78ecf3a92f..ac8d7edd30b2 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
@@ -2276,7 +2276,9 @@ class KnockSourceConfig(config.Config):
@config.config
class KongKonnectSourceConfig(config.Config):
- pass
+ api_token: str
+ lookback_days: int | None = config.value(converter=config.str_to_optional_int, default_factory=lambda: None)
+ region: Literal["us", "eu", "au", "me", "in", "sg"] = config.value(default="us")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/canonical_descriptions.py
new file mode 100644
index 000000000000..dbe0f1731520
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/canonical_descriptions.py
@@ -0,0 +1,54 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "api_requests": {
+ "description": "Detailed records for individual requests proxied through Kong Gateway, from Konnect "
+ "Advanced Analytics (near real-time). One row per request.",
+ "docs_url": "https://developer.konghq.com/api/konnect/analytics-requests/",
+ "columns": {
+ "request_start": "Timestamp of when the gateway began processing the request. Used as the incremental cursor and partition key.",
+ "request_id": "Unique identifier for the request.",
+ "trace_id": "Distributed tracing identifier for the request, when tracing is enabled.",
+ "api": "Identifier of the API associated with the request.",
+ "api_package": "Identifier of the API package associated with the request.",
+ "api_product": "Identifier of the API product associated with the request.",
+ "api_product_version": "Identifier of the API product version associated with the request.",
+ "application": "Identifier of the developer application associated with the request.",
+ "auth_type": "Authentication method used for the request (e.g. key-auth or openid-connect).",
+ "client_ip": "IP address of the client that made the request.",
+ "consumer": "Consumer that made the request, in the form control_plane_id:consumer_id.",
+ "control_plane": "Identifier of the control plane that handled the request.",
+ "control_plane_group": "Identifier of the control plane group that handled the request.",
+ "country_code": "Country code derived from the client IP.",
+ "data_plane_node": "Identifier of the data plane node that proxied the request.",
+ "data_plane_node_version": "Version of the data plane node that proxied the request.",
+ "gateway_service": "Identifier of the gateway service that handled the request (scoped by control plane).",
+ "header_host": "Value of the Host header on the request.",
+ "header_user_agent": "Value of the User-Agent header on the request.",
+ "http_method": "HTTP method of the request (GET, POST, etc.).",
+ "latencies_kong_gateway_ms": "Time in milliseconds spent by Kong Gateway processing the request.",
+ "latencies_kong_internal_ms": "Time in milliseconds spent in Kong internal processing.",
+ "latencies_response_ms": "Total response latency in milliseconds.",
+ "latencies_upstream_ms": "Time in milliseconds spent waiting for the upstream service.",
+ "portal": "Identifier of the developer portal associated with the request.",
+ "principal": "Authenticated principal associated with the request.",
+ "realm": "Authentication realm associated with the request.",
+ "request_body_size": "Size of the request body in bytes.",
+ "request_uri": "URI path of the request.",
+ "response_body_size": "Size of the response body in bytes.",
+ "response_header_content_length": "Value of the response Content-Length header.",
+ "response_header_content_type": "Value of the response Content-Type header.",
+ "response_http_status": "HTTP status code returned to the client.",
+ "response_source": "Which component produced the response (e.g. upstream or the gateway itself).",
+ "route": "Identifier of the route that matched the request (scoped by control plane).",
+ "service_port": "Port of the gateway service the request was routed to.",
+ "service_protocol": "Protocol of the gateway service the request was routed to.",
+ "upstream_status": "HTTP status code returned by the upstream service.",
+ "upstream_uri": "URI the request was proxied to on the upstream service.",
+ "a2a_info": "Agent-to-agent call details for AI routes (nullable), including per-call method, task, latency, and error.",
+ "mcp_info": "Model Context Protocol call details for AI routes (nullable), including session id and per-tool call method, latency, and error.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/kong_konnect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/kong_konnect.py
new file mode 100644
index 000000000000..7a7b4bc9bfb6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/kong_konnect.py
@@ -0,0 +1,233 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+
+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.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.settings import (
+ DEFAULT_INITIAL_LOOKBACK_DAYS,
+ KONG_KONNECT_ENDPOINTS,
+ MAX_PAGE_SIZE,
+ REGION_BASE_URLS,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class KongKonnectRetryableError(Exception):
+ pass
+
+
+class KongKonnectResumeConfig:
+ # Bounds of the absolute time window this run is paging through. Pinned in resume state so a resumed
+ # attempt re-issues the identical window and its offset stays meaningful — recomputing `end` as
+ # "now" on resume would shift the window and make the saved offset skip or duplicate rows.
+ start: str | None = None
+ end: str | None = None
+ offset: int = 0
+
+
+def _format_datetime(value: Any) -> str:
+ """Format a datetime/date as a UTC ISO 8601 timestamp for Konnect's absolute time_range bounds."""
+ if isinstance(value, datetime):
+ dt = value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ # Already a string cursor — trust it as-is.
+ return str(value)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _clamp_future_value_to_now(value: Any) -> Any:
+ """Cap a future incremental cursor at now.
+
+ The watermark tracks the max `request_start` seen. A future-dated record would push the window
+ start past now, producing an empty (or rejected) window on every later sync. Requesting rows newer
+ than now is a no-op anyway, so clamping keeps the query valid and lets the sync self-heal.
+ """
+ now = datetime.now(UTC)
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return now if aware > now else value
+ if isinstance(value, date):
+ return now.date() if value > now.date() else value
+ return value
+
+
+def _get_base_url(region: str) -> str:
+ return REGION_BASE_URLS.get(region, REGION_BASE_URLS["us"])
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ # Personal Access Tokens and System Account tokens are both bearer tokens sent identically.
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ "Accept": "application/json",
+ }
+
+
+def _resolve_window(
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ lookback_days: int,
+) -> tuple[str, str]:
+ """Compute the [start, end] absolute window for this run.
+
+ Incremental runs start at the watermark; first sync / full refresh walks back `lookback_days`.
+ `end` is pinned to now so pagination through the window is stable.
+ """
+ now = datetime.now(UTC)
+ if should_use_incremental_field and db_incremental_field_last_value:
+ start_value = _clamp_future_value_to_now(db_incremental_field_last_value)
+ start = _format_datetime(start_value)
+ else:
+ start = _format_datetime(now - timedelta(days=lookback_days))
+ return start, _format_datetime(now)
+
+
+def _build_body(start: str, end: str, offset: int, size: int) -> dict[str, Any]:
+ return {
+ "filters": [],
+ "time_range": {
+ "type": "absolute",
+ "start": start,
+ "end": end,
+ "tz": "Etc/UTC",
+ },
+ # Ascending by time so SourceResponse.sort_mode="asc" lets the pipeline advance the watermark
+ # after each batch and resume mid-sync safely.
+ "order": "ascending",
+ "size": size,
+ "offset": offset,
+ }
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ KongKonnectRetryableError,
+ 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],
+ body: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict:
+ response = session.post(url, headers=headers, json=body, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise KongKonnectRetryableError(f"Kong Konnect API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Kong Konnect API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_token: str, region: str) -> bool:
+ """Cheap probe that the bearer token is genuine: request a single record over a small window."""
+ url = f"{_get_base_url(region)}/api-requests"
+ body = _build_body(
+ _format_datetime(datetime.now(UTC) - timedelta(hours=1)),
+ _format_datetime(datetime.now(UTC)),
+ offset=0,
+ size=1,
+ )
+ try:
+ response = make_tracked_session().post(url, headers=_get_headers(api_token), json=body, timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_token: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ lookback_days: int = DEFAULT_INITIAL_LOOKBACK_DAYS,
+) -> Iterator[list[dict[str, Any]]]:
+ url = f"{_get_base_url(region)}{KONG_KONNECT_ENDPOINTS[endpoint].path}"
+ headers = _get_headers(api_token)
+ session = make_tracked_session()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.start and resume.end:
+ start, end, offset = resume.start, resume.end, resume.offset
+ logger.debug(f"Kong Konnect: resuming api_requests window start={start} end={end} offset={offset}")
+ else:
+ start, end = _resolve_window(should_use_incremental_field, db_incremental_field_last_value, lookback_days)
+ offset = 0
+
+ while True:
+ body = _build_body(start, end, offset, MAX_PAGE_SIZE)
+ data = _fetch_page(session, url, headers, body, logger)
+ results = data.get("results", [])
+
+ if not results:
+ break
+
+ yield results
+
+ offset += len(results)
+ # Save AFTER yielding so a crash re-yields the last page (merge dedupes on request_id) rather
+ # than skipping it. Only persist when another page is likely, i.e. this page was full.
+ if len(results) < MAX_PAGE_SIZE:
+ break
+ resumable_source_manager.save_state(KongKonnectResumeConfig(start=start, end=end, offset=offset))
+
+
+def kong_konnect_source(
+ api_token: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ lookback_days: int = DEFAULT_INITIAL_LOOKBACK_DAYS,
+) -> SourceResponse:
+ endpoint_config = KONG_KONNECT_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ lookback_days=lookback_days,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/settings.py
new file mode 100644
index 000000000000..158b58a0b4cc
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/settings.py
@@ -0,0 +1,63 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Konnect serves the analytics API from region-specific hosts; the region must match the org's geo
+# or the token authenticates against the wrong control plane and returns no data.
+REGION_BASE_URLS: dict[str, str] = {
+ "us": "https://us.api.konghq.com/v2",
+ "eu": "https://eu.api.konghq.com/v2",
+ "au": "https://au.api.konghq.com/v2",
+ "me": "https://me.api.konghq.com/v2",
+ "in": "https://in.api.konghq.com/v2",
+ "sg": "https://sg.api.konghq.com/v2",
+}
+
+DEFAULT_REGION = "us"
+
+# `size` is hard-capped at 1000 per page by the API.
+MAX_PAGE_SIZE = 1000
+
+# Absolute time-window queries must fall within the org's data retention period (plan-gated). On the
+# first sync / full refresh there is no watermark to start from, so we walk back this many days. Users
+# on longer-retention plans can raise it; a value beyond retention is clamped by the API to what exists.
+DEFAULT_INITIAL_LOOKBACK_DAYS = 30
+
+
+@dataclass
+class KongKonnectEndpointConfig:
+ name: str
+ path: str
+ incremental_fields: list[IncrementalField]
+ # Stable per-record timestamp used both as the incremental cursor and the partition key. Kong
+ # request logs are append-only, so this never changes once written.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["request_id"])
+ should_sync_default: bool = True
+
+
+KONG_KONNECT_ENDPOINTS: dict[str, KongKonnectEndpointConfig] = {
+ # Detailed per-request records for every request proxied through the gateway. This is the primary
+ # (and only currently documented) analytics stream: POST /v2/api-requests with a time-window query
+ # body. Incremental sync advances an absolute `request_start` watermark and pages ascending.
+ "api_requests": KongKonnectEndpointConfig(
+ name="api_requests",
+ path="/api-requests",
+ partition_key="request_start",
+ incremental_fields=[
+ {
+ "label": "request_start",
+ "type": IncrementalFieldType.DateTime,
+ "field": "request_start",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(KONG_KONNECT_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in KONG_KONNECT_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/source.py
index a8321bb1b6d5..bbf8349d89b5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/source.py
@@ -1,30 +1,189 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KongKonnectSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.kong_konnect import (
+ DEFAULT_INITIAL_LOOKBACK_DAYS,
+ KongKonnectResumeConfig,
+ kong_konnect_source,
+ validate_credentials as validate_kong_konnect_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.settings import (
+ DEFAULT_REGION,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ REGION_BASE_URLS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class KongKonnectSource(SimpleSource[KongKonnectSourceConfig]):
+class KongKonnectSource(ResumableSource[KongKonnectSourceConfig, KongKonnectResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.KONGKONNECT
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `region` picks the host the stored access token is sent to. Retargeting it must re-require
+ # the secret so a preserved token can't be aimed at a different regional endpoint without re-entry.
+ return ["region"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.KONG_KONNECT,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Kong Inc. (Kong Konnect)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter a Kong Konnect access token to pull your gateway's Advanced Analytics API request logs into the PostHog Data warehouse.
+
+Create a **Personal Access Token** under **Konnect → Personal access tokens**, or a **System Account access token** for a service identity. Either is sent as a bearer token.
+
+Pick the **region** that matches your Konnect organization's geo — the analytics API is region-specific.
+
+How far back the initial sync can reach depends on your Konnect plan's Advanced Analytics data retention.""",
+ docsUrl="https://posthog.com/docs/cdp/sources/kong-konnect",
iconPath="/static/services/kong_konnect.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="kpat_...",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue=DEFAULT_REGION,
+ options=[
+ SourceFieldSelectConfigOption(label="US (us.api.konghq.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (eu.api.konghq.com)", value="eu"),
+ SourceFieldSelectConfigOption(label="Australia (au.api.konghq.com)", value="au"),
+ SourceFieldSelectConfigOption(label="Middle East (me.api.konghq.com)", value="me"),
+ SourceFieldSelectConfigOption(label="India (in.api.konghq.com)", value="in"),
+ SourceFieldSelectConfigOption(label="Singapore (sg.api.konghq.com)", value="sg"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="lookback_days",
+ label="Initial sync window (days)",
+ type=SourceFieldInputConfigType.NUMBER,
+ required=False,
+ placeholder=str(DEFAULT_INITIAL_LOOKBACK_DAYS),
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
)
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Your Kong Konnect access token is invalid or has expired. Create a new token in Konnect and reconnect.",
+ "403 Client Error: Forbidden": "Your Kong Konnect access token is missing the permissions needed to read Advanced Analytics. Grant analytics access to the token or account and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: KongKonnectSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = INCREMENTAL_FIELDS.get(endpoint) is not None
+ return SourceSchema(
+ name=endpoint,
+ # Request logs are append-only time-series; incremental sync advances an absolute
+ # `request_start` window each run.
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description="Detailed records for every request proxied through the gateway (Advanced Analytics). "
+ "Historical depth on initial sync is limited by your Konnect plan's data retention.",
+ )
+
+ 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: KongKonnectSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ # `region` is typed as a Literal with a default, but job_inputs come from user-supplied JSON,
+ # so guard against values outside the known set at runtime.
+ region = config.region
+ if region not in REGION_BASE_URLS:
+ return False, f"Unknown region '{region}'. Choose one of: {', '.join(REGION_BASE_URLS)}."
+
+ if validate_kong_konnect_credentials(config.api_token, region):
+ return True, None
+
+ return False, "Invalid Kong Konnect access token, or the token cannot read Advanced Analytics in this region."
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[KongKonnectResumeConfig]:
+ return ResumableSourceManager[KongKonnectResumeConfig](inputs, KongKonnectResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: KongKonnectSourceConfig,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return kong_konnect_source(
+ api_token=config.api_token,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ lookback_days=_coerce_lookback_days(config.lookback_days),
+ )
+
+
+def _coerce_lookback_days(value: int | None) -> int:
+ """The config converter parses form strings to int; fall back to the default when unset or non-positive."""
+ if value is None or value <= 0:
+ return DEFAULT_INITIAL_LOOKBACK_DAYS
+ return value
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py
new file mode 100644
index 000000000000..706159285e5d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect.py
@@ -0,0 +1,193 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from freezegun import freeze_time
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect import kong_konnect
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.kong_konnect import (
+ MAX_PAGE_SIZE,
+ KongKonnectResumeConfig,
+ _build_body,
+ _clamp_future_value_to_now,
+ _format_datetime,
+ _resolve_window,
+ get_rows,
+ kong_konnect_source,
+ validate_credentials,
+)
+
+
+class TestFormatDatetime:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format_datetime(self, _name: str, value: object, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+
+class TestBuildBody:
+ def test_body_is_absolute_ascending_window(self) -> None:
+ body = _build_body("2026-01-01T00:00:00Z", "2026-01-02T00:00:00Z", offset=200, size=1000)
+ assert body["time_range"] == {
+ "type": "absolute",
+ "start": "2026-01-01T00:00:00Z",
+ "end": "2026-01-02T00:00:00Z",
+ "tz": "Etc/UTC",
+ }
+ # Ascending order is load-bearing: the pipeline advances the watermark trusting asc order.
+ assert body["order"] == "ascending"
+ assert body["size"] == 1000
+ assert body["offset"] == 200
+ assert body["filters"] == []
+
+
+class TestResolveWindow:
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_incremental_starts_at_watermark(self) -> None:
+ start, end = _resolve_window(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 10, 8, 0, 0, tzinfo=UTC),
+ lookback_days=30,
+ )
+ assert start == "2026-06-10T08:00:00Z"
+ assert end == "2026-06-15T12:00:00Z"
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_full_refresh_walks_back_lookback_days(self) -> None:
+ start, end = _resolve_window(
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ lookback_days=7,
+ )
+ assert start == "2026-06-08T12:00:00Z"
+ assert end == "2026-06-15T12:00:00Z"
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_future_watermark_clamped_to_now(self) -> None:
+ # A future-dated cursor would otherwise produce start > end, wedging every later sync.
+ start, _ = _resolve_window(
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2027, 1, 1, tzinfo=UTC),
+ lookback_days=30,
+ )
+ assert start == "2026-06-15T12:00:00Z"
+
+
+class TestClampFutureValue:
+ @parameterized.expand(
+ [
+ ("past_datetime_untouched", datetime(2026, 1, 1, tzinfo=UTC), False),
+ ("future_datetime_clamped", datetime(2027, 1, 1, tzinfo=UTC), True),
+ ]
+ )
+ @freeze_time("2026-06-15T12:00:00Z")
+ def test_clamp(self, _name: str, value: datetime, should_clamp: bool) -> None:
+ result = _clamp_future_value_to_now(value)
+ if should_clamp:
+ assert result == datetime(2026, 6, 15, 12, 0, 0, tzinfo=UTC)
+ else:
+ assert result == value
+
+
+def _manager(resume: KongKonnectResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _page(count: int) -> dict[str, Any]:
+ return {"results": [{"request_id": f"r{i}"} for i in range(count)], "meta": {}}
+
+
+class TestGetRowsPagination:
+ @patch.object(kong_konnect, "make_tracked_session")
+ @patch.object(kong_konnect, "_fetch_page")
+ def test_stops_on_short_page_and_advances_offset(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:
+ # Two full pages then a short page terminates pagination.
+ mock_fetch.side_effect = [_page(MAX_PAGE_SIZE), _page(MAX_PAGE_SIZE), _page(3)]
+ manager = _manager()
+
+ batches = list(get_rows("tok", "us", "api_requests", MagicMock(), manager, lookback_days=30))
+
+ assert [len(b) for b in batches] == [MAX_PAGE_SIZE, MAX_PAGE_SIZE, 3]
+ assert mock_fetch.call_count == 3
+ # Offsets requested must walk forward by page size.
+ offsets = [call.args[3]["offset"] for call in mock_fetch.call_args_list]
+ assert offsets == [0, MAX_PAGE_SIZE, 2 * MAX_PAGE_SIZE]
+
+ @patch.object(kong_konnect, "make_tracked_session")
+ @patch.object(kong_konnect, "_fetch_page")
+ def test_empty_first_page_yields_nothing(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:
+ mock_fetch.side_effect = [_page(0)]
+ batches = list(get_rows("tok", "us", "api_requests", MagicMock(), _manager(), lookback_days=30))
+ assert batches == []
+
+ @patch.object(kong_konnect, "make_tracked_session")
+ @patch.object(kong_konnect, "_fetch_page")
+ def test_saves_state_after_full_page_only(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:
+ mock_fetch.side_effect = [_page(MAX_PAGE_SIZE), _page(2)]
+ manager = _manager()
+
+ list(get_rows("tok", "us", "api_requests", MagicMock(), manager, lookback_days=30))
+
+ # One save after the first (full) page; the final short page must NOT persist state.
+ assert manager.save_state.call_count == 1
+ saved = manager.save_state.call_args.args[0]
+ assert saved.offset == MAX_PAGE_SIZE
+
+ @freeze_time("2026-06-15T12:00:00Z")
+ @patch.object(kong_konnect, "make_tracked_session")
+ @patch.object(kong_konnect, "_fetch_page")
+ def test_resume_reuses_saved_window_not_recomputed(self, mock_fetch: MagicMock, _mock_session: MagicMock) -> None:
+ # A crash saved a mid-window checkpoint; resume must re-issue that exact window + offset,
+ # never recompute `end` as "now" (which would shift the window and skip/duplicate rows).
+ mock_fetch.side_effect = [_page(1)]
+ resume = KongKonnectResumeConfig(start="2026-01-01T00:00:00Z", end="2026-01-05T00:00:00Z", offset=5000)
+
+ list(get_rows("tok", "us", "api_requests", MagicMock(), _manager(resume), lookback_days=30))
+
+ body = mock_fetch.call_args_list[0].args[3]
+ assert body["time_range"]["start"] == "2026-01-01T00:00:00Z"
+ assert body["time_range"]["end"] == "2026-01-05T00:00:00Z"
+ assert body["offset"] == 5000
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ @patch.object(kong_konnect, "make_tracked_session")
+ def test_status_mapping(self, _name: str, status: int, expected: bool, mock_session: MagicMock) -> None:
+ response = MagicMock()
+ response.status_code = status
+ mock_session.return_value.post.return_value = response
+ assert validate_credentials("tok", "us") is expected
+
+ @patch.object(kong_konnect, "make_tracked_session")
+ def test_network_error_is_false(self, mock_session: MagicMock) -> None:
+ mock_session.return_value.post.side_effect = requests.ConnectionError()
+ assert validate_credentials("tok", "us") is False
+
+
+class TestKongKonnectSourceResponse:
+ def test_source_response_shape(self) -> None:
+ response = kong_konnect_source("tok", "eu", "api_requests", MagicMock(), _manager())
+ assert response.name == "api_requests"
+ assert response.primary_keys == ["request_id"]
+ # asc must match the ascending request order for the watermark to advance correctly.
+ assert response.sort_mode == "asc"
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == ["request_start"]
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect_source.py
new file mode 100644
index 000000000000..e0758e41843d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/test_kong_konnect_source.py
@@ -0,0 +1,144 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import KongKonnectSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.kong_konnect import (
+ DEFAULT_INITIAL_LOOKBACK_DAYS,
+ KongKonnectResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.source import (
+ KongKonnectSource,
+ _coerce_lookback_days,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(**overrides: Any) -> KongKonnectSourceConfig:
+ data = {"api_token": "kpat_test", "region": "us"}
+ data.update(overrides)
+ return KongKonnectSourceConfig.from_dict(data)
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert KongKonnectSource().source_type == ExternalDataSourceType.KONGKONNECT
+
+ def test_connection_host_fields_includes_region(self) -> None:
+ # `region` selects the host the stored access token is sent to, so editing it must re-require the secret.
+ assert KongKonnectSource().connection_host_fields == ["region"]
+
+ def test_ships_visible_as_alpha(self) -> None:
+ config = KongKonnectSource().get_source_config
+ # A finished source must be visible (no unreleasedSource) and flagged alpha.
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_fields_and_requiredness(self) -> None:
+ fields = {f.name: f for f in KongKonnectSource().get_source_config.fields}
+ assert set(fields) == {"api_token", "region", "lookback_days"}
+
+ api_token = fields["api_token"]
+ assert isinstance(api_token, SourceFieldInputConfig)
+ assert api_token.required is True
+
+ region = fields["region"]
+ assert isinstance(region, SourceFieldSelectConfig)
+ assert region.required is True
+
+ lookback_days = fields["lookback_days"]
+ assert isinstance(lookback_days, SourceFieldInputConfig)
+ assert lookback_days.required is False
+
+
+class TestGetSchemas:
+ def test_api_requests_supports_incremental(self) -> None:
+ schemas = KongKonnectSource().get_schemas(_config(), team_id=1)
+ assert [s.name for s in schemas] == ["api_requests"]
+ schema = schemas[0]
+ assert schema.supports_incremental is True
+ assert [f["field"] for f in schema.incremental_fields] == ["request_start"]
+
+ def test_names_filter(self) -> None:
+ assert KongKonnectSource().get_schemas(_config(), team_id=1, names=["nonexistent"]) == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static catalog → public docs render the table list.
+ assert KongKonnectSource.lists_tables_without_credentials is True
+ tables = KongKonnectSource().get_documented_tables()
+ assert [t["name"] for t in tables] == ["api_requests"]
+
+
+class TestValidateCredentials:
+ @patch.object(source_module, "validate_kong_konnect_credentials", return_value=True)
+ def test_valid(self, _mock: MagicMock) -> None:
+ ok, err = KongKonnectSource().validate_credentials(_config(), team_id=1)
+ assert ok is True
+ assert err is None
+
+ @patch.object(source_module, "validate_kong_konnect_credentials", return_value=False)
+ def test_invalid(self, _mock: MagicMock) -> None:
+ ok, err = KongKonnectSource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert err is not None
+
+ def test_unknown_region_rejected_without_network(self) -> None:
+ with patch.object(source_module, "validate_kong_konnect_credentials") as mock:
+ ok, err = KongKonnectSource().validate_credentials(_config(region="mars"), team_id=1)
+ assert ok is False
+ assert err is not None
+ mock.assert_not_called()
+
+
+class TestCoerceLookbackDays:
+ @parameterized.expand(
+ [
+ ("none", None, DEFAULT_INITIAL_LOOKBACK_DAYS),
+ ("positive", 90, 90),
+ ("zero", 0, DEFAULT_INITIAL_LOOKBACK_DAYS),
+ ("negative", -3, DEFAULT_INITIAL_LOOKBACK_DAYS),
+ ]
+ )
+ def test_coerce(self, _name: str, value: int | None, expected: int) -> None:
+ assert _coerce_lookback_days(value) == expected
+
+
+class TestSourceForPipeline:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = KongKonnectSource().get_resumable_source_manager(MagicMock())
+ assert manager._data_class is KongKonnectResumeConfig
+
+ @patch.object(source_module, "kong_konnect_source")
+ def test_plumbs_region_and_lookback(self, mock_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "api_requests"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ KongKonnectSource().source_for_pipeline(_config(region="eu", lookback_days="5"), MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["region"] == "eu"
+ assert kwargs["lookback_days"] == 5
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @patch.object(source_module, "kong_konnect_source")
+ def test_incremental_value_gated_off_when_not_incremental(self, mock_source: MagicMock) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "api_requests"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ KongKonnectSource().source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] is None
+
+
+if __name__ == "__main__":
+ pytest.main([__file__])