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(warehouse): add kong konnect catalog, api product and consumer tables (#113870)

Tom Owers0ae2b2ebfddc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 7fb0aa46a351..28fa2a4a17ab 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4847,12 +4847,12 @@ Diffed against: <https://raw.githubusercontent.com/Kong/developer.konghq.com/mai
- [x] `/control-planes/{id}/core-entities/services` — lookup resolving the service_id on api_requests to a named gateway service (high)
- [x] `/control-planes/{id}/core-entities/routes` — lookup resolving route_id on api_requests to a path/method (high)
- [x] `/control-planes/{id}/core-entities/consumers` — lookup resolving consumer_id on api_requests to a named API consumer (high)
-- [ ] `/api-products (API Products v2)` — lookup for the api_product / api_product_version dimensions filterable on api_requests (high)
+- [x] `/api-products (API Products v2)` — lookup for the api_product / api_product_version dimensions filterable on api_requests (high)
- [ ] `/metrics (Analytics Metrics v2)` — vendor's aggregated traffic, latency and error-rate metrics without re-aggregating raw request rows (medium)
- [ ] `/control-planes/{id}/core-entities/plugins` — which rate-limit/auth plugins were active on a service or route when traffic was served (medium)
-- [ ] `/control-planes/{id}/core-entities/consumer_groups and /consumer_groups/{id}/consumers` — consumer-group membership junction for segmenting request volume by tier (medium)
-- [ ] `/realms/{realmId}/consumers (Konnect Consumers v1)` — identity-realm consumer registry backing the consumer dimension (medium)
-- [ ] `/catalog-services and /scorecards (Service Catalog v1)` — service inventory plus scorecard scores, the headline governance metric (medium)
+- [x] `/control-planes/{id}/core-entities/consumer_groups and /consumer_groups/{id}/consumers` — consumer-group membership junction for segmenting request volume by tier (medium)
+- [x] `/realms/{realmId}/consumers (Konnect Consumers v1)` — identity-realm consumer registry backing the consumer dimension (medium)
+- [x] `/catalog-services and /scorecards (Service Catalog v1)` — service inventory plus scorecard scores, the headline governance metric (medium)
- [ ] `/control-planes/{id}/core-entities/upstreams and /targets` — upstream/target topology behind each service for latency attribution (low)
- [ ] `/openmeter/meters and /openmeter/subscriptions (Metering & Billing v3)` — metered usage and subscription state for cost-per-request analysis (low)
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
index 375a5d66e140..fe582891a377 100644
--- 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
@@ -120,4 +120,137 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Unix epoch (seconds) when the consumer was last updated.",
},
},
+ "consumer_groups": {
+ "description": "Gateway consumer groups, one row per group per control plane.",
+ "docs_url": "https://developer.konghq.com/api/konnect/control-planes-config/v2/",
+ "columns": {
+ "control_plane_id": "ID of the control plane the consumer group belongs to.",
+ "id": "Unique identifier of the consumer group within its control plane.",
+ "name": "The name of the consumer group.",
+ "tags": "A set of strings associated with the consumer group for grouping and filtering.",
+ "created_at": "Unix epoch (seconds) when the consumer group was created.",
+ "updated_at": "Unix epoch (seconds) when the consumer group was last updated.",
+ },
+ },
+ "consumer_group_members": {
+ "description": "Membership of gateway consumers in consumer groups, one row per consumer per group per control plane. "
+ "Joins to consumers on control_plane_id and id, and to consumer_groups on control_plane_id and consumer_group_id.",
+ "docs_url": "https://developer.konghq.com/api/konnect/control-planes-config/v2/",
+ "columns": {
+ "control_plane_id": "ID of the control plane the consumer group belongs to.",
+ "consumer_group_id": "ID of the consumer group the consumer is a member of.",
+ "id": "Unique identifier of the consumer within its control plane.",
+ "username": "The unique username of the consumer.",
+ "custom_id": "An existing unique ID for the consumer, used to map Kong consumers to users in another system.",
+ "tags": "Optional set of strings associated with the consumer for grouping and filtering.",
+ "created_at": "Unix epoch (seconds) when the consumer was created.",
+ "updated_at": "Unix epoch (seconds) when the consumer was last updated.",
+ },
+ },
+ "api_products": {
+ "description": "API products in the classic Konnect Dev Portal. Joins to api_requests on api_product.",
+ "docs_url": "https://developer.konghq.com/api/konnect/api-products/v2/",
+ "columns": {
+ "id": "The API product ID.",
+ "name": "The name of the API product.",
+ "description": "The description of the API product.",
+ "portals": "The portals the API product is published to.",
+ "portal_ids": "Deprecated list of IDs of the portals the API product is published to. Use portals instead.",
+ "version_count": "The number of product versions attached to the API product.",
+ "labels": "Key/value labels attached to the API product.",
+ "public_labels": "Key/value labels attached to the API product that are visible to portal developers.",
+ "created_at": "Timestamp of when the API product was created.",
+ "updated_at": "Timestamp of when the API product was last updated.",
+ },
+ },
+ "api_product_versions": {
+ "description": "Versions of each API product, one row per version. Joins to api_requests on api_product_version.",
+ "docs_url": "https://developer.konghq.com/api/konnect/api-products/v2/",
+ "columns": {
+ "api_product_id": "ID of the API product the version belongs to.",
+ "id": "The API product version ID.",
+ "name": "The version of the API product.",
+ "gateway_service": "The gateway service linked to the version, with its control plane ID.",
+ "publish_status": "Deprecated. Whether the version is published to at least one portal.",
+ "deprecated": "Deprecated. Whether the version is marked deprecated in at least one portal.",
+ "portals": "The portals the version is configured for.",
+ "auth_strategy_sync_errors": "Errors from the last attempt to sync the version's auth strategies.",
+ "labels": "Key/value labels attached to the version.",
+ "created_at": "Timestamp of when the version was created.",
+ "updated_at": "Timestamp of when the version was last updated.",
+ },
+ },
+ "catalog_services": {
+ "description": "Services in the Konnect Service Catalog.",
+ "docs_url": "https://developer.konghq.com/api/konnect/service-catalog/v1/",
+ "columns": {
+ "id": "The catalog service ID.",
+ "name": "The machine name that uniquely identifies the service in the catalog.",
+ "display_name": "The display name of the service.",
+ "description": "The description of the service.",
+ "custom_fields": "Catalog-defined fields with information about the service, such as its owner.",
+ "labels": "Key/value labels attached to the service.",
+ "created_at": "Timestamp of when the service was created.",
+ "updated_at": "Timestamp of when the service was last updated.",
+ },
+ },
+ "scorecards": {
+ "description": "Service Catalog scorecards, with each scorecard's current overall score.",
+ "docs_url": "https://developer.konghq.com/api/konnect/service-catalog/v1/",
+ "columns": {
+ "id": "The scorecard ID.",
+ "name": "The name of the scorecard.",
+ "description": "The description of the scorecard.",
+ "score": "The current score, with value (in the scorecard's grading system) and raw_value. Null until the scorecard is evaluated.",
+ "entity_selector": "The selector that picks the catalog services the scorecard evaluates.",
+ "scorecard_template": "The name of the template the scorecard was created from, or null.",
+ "created_at": "Timestamp of when the scorecard was created.",
+ "updated_at": "Timestamp of when the scorecard was last updated.",
+ },
+ },
+ "scorecard_services": {
+ "description": "Catalog services targeted by each scorecard, one row per service per scorecard. "
+ "Joins to scorecards on scorecard_id and to catalog_services on id.",
+ "docs_url": "https://developer.konghq.com/api/konnect/service-catalog/v1/",
+ "columns": {
+ "scorecard_id": "ID of the scorecard that targets the service.",
+ "id": "The catalog service ID.",
+ "name": "The machine name that uniquely identifies the service in the catalog.",
+ "display_name": "The display name of the service.",
+ "score": "The service's current score on this scorecard, with value and raw_value. Null until evaluated.",
+ "custom_fields": "Catalog-defined fields with information about the service, such as its owner.",
+ "labels": "Key/value labels attached to the service.",
+ "created_at": "Timestamp of when the service was created.",
+ "updated_at": "Timestamp of when the service was last updated.",
+ },
+ },
+ "realms": {
+ "description": "Konnect identity realms, which hold consumers shared across control planes.",
+ "docs_url": "https://developer.konghq.com/api/konnect/consumers/v1/",
+ "columns": {
+ "id": "The realm ID.",
+ "name": "The name of the realm.",
+ "ttl": "How long data planes cache a consumer from the realm.",
+ "negative_ttl": "How long data planes cache a failed consumer lookup.",
+ "consumer_groups": "Consumer groups that consumers in the realm belong to.",
+ "allowed_control_planes": "IDs of the control planes that can use consumers from the realm.",
+ "created_at": "Timestamp of when the realm was created.",
+ "updated_at": "Timestamp of when the realm was last updated.",
+ },
+ },
+ "realm_consumers": {
+ "description": "Consumers registered in each Konnect identity realm, one row per consumer per realm.",
+ "docs_url": "https://developer.konghq.com/api/konnect/consumers/v1/",
+ "columns": {
+ "realm_id": "ID of the realm the consumer belongs to.",
+ "id": "The consumer ID.",
+ "username": "The username of the consumer.",
+ "custom_id": "An existing unique ID for the consumer, used to map it to a user in another system.",
+ "type": "The type of the consumer.",
+ "tags": "Tags associated with the consumer.",
+ "consumer_groups": "Consumer groups the consumer belongs to.",
+ "created_at": "Timestamp of when the consumer was created.",
+ "updated_at": "Timestamp of when the consumer was last updated.",
+ },
+ },
}
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
index f146bd336ff0..2707d8c78f3d 100644
--- 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
@@ -2,6 +2,7 @@ import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -12,12 +13,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.kong_konnect.settings import (
CONTROL_PLANE_GROUP_CLUSTER_TYPE,
- CONTROL_PLANES_PAGE_SIZE,
CORE_ENTITY_PAGE_SIZE,
DEFAULT_INITIAL_LOOKBACK_DAYS,
KONG_KONNECT_ENDPOINTS,
+ LIST_PAGE_SIZE,
MAX_PAGE_SIZE,
REGION_BASE_URLS,
+ KongKonnectEndpointConfig,
)
REQUEST_TIMEOUT_SECONDS = 60
@@ -65,8 +67,8 @@ def _clamp_future_value_to_now(value: Any) -> Any:
return value
-def _get_base_url(region: str) -> str:
- return REGION_BASE_URLS.get(region, REGION_BASE_URLS["us"])
+def _get_base_url(region: str, api_version: str = "v2") -> str:
+ return f"{REGION_BASE_URLS.get(region, REGION_BASE_URLS['us'])}/{api_version}"
def _get_headers(api_token: str) -> dict[str, str]:
@@ -166,54 +168,158 @@ def _get_json(
return response.json()
-def _iter_control_planes(
- session: requests.Session, base_url: str, logger: FilteringBoundLogger
+def _iter_page_number(
+ session: requests.Session,
+ url: str,
+ sort: str | None,
+ logger: FilteringBoundLogger,
+ allow_not_found: bool = False,
) -> Iterator[list[dict[str, Any]]]:
page_number = 1
while True:
- params = {"page[size]": CONTROL_PLANES_PAGE_SIZE, "page[number]": page_number, "sort": "created_at"}
- data = _get_json(session, f"{base_url}/control-planes", params, logger) or {}
- control_planes = data.get("data") or []
+ params: dict[str, Any] = {"page[size]": LIST_PAGE_SIZE, "page[number]": page_number}
+ if sort:
+ params["sort"] = sort
+ data = _get_json(session, url, params, logger, allow_not_found=allow_not_found)
+ if data is None:
+ return
+ rows = data.get("data") or []
- if control_planes:
- yield control_planes
+ if rows:
+ yield rows
total = ((data.get("meta") or {}).get("page") or {}).get("total")
- if len(control_planes) < CONTROL_PLANES_PAGE_SIZE or (
- total is not None and page_number * CONTROL_PLANES_PAGE_SIZE >= total
- ):
+ if len(rows) < LIST_PAGE_SIZE or (total is not None and page_number * LIST_PAGE_SIZE >= total):
break
page_number += 1
+def _next_page_after(data: dict[str, Any]) -> str | None:
+ # `meta.next` is a URI path such as `/v1/realms?page[after]=...`, so read the cursor out of it.
+ next_uri = (data.get("meta") or {}).get("next")
+ if not next_uri:
+ return None
+ values = parse_qs(urlparse(next_uri).query).get("page[after]")
+ return values[0] if values else None
+
+
+def _iter_cursor(
+ session: requests.Session,
+ url: str,
+ logger: FilteringBoundLogger,
+ allow_not_found: bool = False,
+) -> Iterator[list[dict[str, Any]]]:
+ params: dict[str, Any] = {"page[size]": LIST_PAGE_SIZE}
+ while True:
+ data = _get_json(session, url, params, logger, allow_not_found=allow_not_found)
+ if data is None:
+ return
+ rows = data.get("data") or []
+
+ if rows:
+ yield rows
+
+ page_after = _next_page_after(data)
+ if not page_after:
+ break
+ params = {"page[size]": LIST_PAGE_SIZE, "page[after]": page_after}
+
+
+def _iter_control_planes(
+ session: requests.Session, base_url: str, logger: FilteringBoundLogger
+) -> Iterator[list[dict[str, Any]]]:
+ yield from _iter_page_number(
+ session, f"{base_url}/control-planes", KONG_KONNECT_ENDPOINTS["control_planes"].sort, logger
+ )
+
+
+def _iter_offset(session: requests.Session, url: str, logger: FilteringBoundLogger) -> Iterator[list[dict[str, Any]]]:
+ offset: str | None = None
+ while True:
+ params: dict[str, Any] = {"size": CORE_ENTITY_PAGE_SIZE}
+ if offset:
+ params["offset"] = offset
+ data = _get_json(session, url, params, logger, allow_not_found=True)
+ if data is None:
+ # The parent was deleted between listing it and fanning out over it.
+ logger.debug(f"Kong Konnect: {url} not found, skipping")
+ return
+
+ rows = data.get("data") or []
+ if rows:
+ yield rows
+
+ offset = data.get("offset")
+ if not offset:
+ break
+
+
def _iter_core_entities(
- session: requests.Session, base_url: str, path: str, logger: FilteringBoundLogger
+ session: requests.Session,
+ base_url: str,
+ endpoint_config: KongKonnectEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
+ parent_config = KONG_KONNECT_ENDPOINTS[endpoint_config.parent] if endpoint_config.parent else None
+
for control_planes in _iter_control_planes(session, base_url, logger):
for control_plane in control_planes:
if (control_plane.get("config") or {}).get("cluster_type") == CONTROL_PLANE_GROUP_CLUSTER_TYPE:
continue
control_plane_id = control_plane["id"]
- url = f"{base_url}/control-planes/{control_plane_id}{path}"
- offset: str | None = None
- while True:
- params: dict[str, Any] = {"size": CORE_ENTITY_PAGE_SIZE}
- if offset:
- params["offset"] = offset
- data = _get_json(session, url, params, logger, allow_not_found=True)
- if data is None:
- # The control plane was deleted between listing it and fanning out over it.
- logger.debug(f"Kong Konnect: control plane {control_plane_id} not found, skipping {path}")
- break
-
- rows = data.get("data") or []
- if rows:
+ control_plane_url = f"{base_url}/control-planes/{control_plane_id}"
+
+ if parent_config is None or endpoint_config.parent_id_field is None:
+ for rows in _iter_offset(session, f"{control_plane_url}{endpoint_config.path}", logger):
yield [{**row, "control_plane_id": control_plane_id} for row in rows]
+ resumable_source_manager.safe_point()
+ continue
- offset = data.get("offset")
- if not offset:
- break
+ for parents in _iter_offset(session, f"{control_plane_url}{parent_config.path}", logger):
+ for parent in parents:
+ child_url = f"{control_plane_url}{endpoint_config.path.replace('{id}', parent['id'])}"
+ for rows in _iter_offset(session, child_url, logger):
+ yield [
+ {**row, "control_plane_id": control_plane_id, endpoint_config.parent_id_field: parent["id"]}
+ for row in rows
+ ]
+ resumable_source_manager.safe_point()
+
+
+def _iter_list(
+ session: requests.Session,
+ url: str,
+ endpoint_config: KongKonnectEndpointConfig,
+ logger: FilteringBoundLogger,
+ allow_not_found: bool = False,
+) -> Iterator[list[dict[str, Any]]]:
+ if endpoint_config.kind == "cursor":
+ return _iter_cursor(session, url, logger, allow_not_found=allow_not_found)
+ return _iter_page_number(session, url, endpoint_config.sort, logger, allow_not_found=allow_not_found)
+
+
+def _iter_top_level(
+ session: requests.Session,
+ region: str,
+ endpoint_config: KongKonnectEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ base_url = _get_base_url(region, endpoint_config.api_version)
+
+ if endpoint_config.parent is None or endpoint_config.parent_id_field is None:
+ yield from _iter_list(session, f"{base_url}{endpoint_config.path}", endpoint_config, logger)
+ return
+
+ parent_config = KONG_KONNECT_ENDPOINTS[endpoint_config.parent]
+ for parents in _iter_list(session, f"{base_url}{parent_config.path}", parent_config, logger):
+ for parent in parents:
+ child_url = f"{base_url}{endpoint_config.path.replace('{id}', parent['id'])}"
+ for rows in _iter_list(session, child_url, endpoint_config, logger, allow_not_found=True):
+ yield [{**row, endpoint_config.parent_id_field: parent["id"]} for row in rows]
+ resumable_source_manager.safe_point()
def get_lookup_rows(
@@ -221,15 +327,17 @@ def get_lookup_rows(
region: str,
endpoint: str,
logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[KongKonnectResumeConfig],
) -> Iterator[list[dict[str, Any]]]:
endpoint_config = KONG_KONNECT_ENDPOINTS[endpoint]
- base_url = _get_base_url(region)
session = make_tracked_session(headers=_get_headers(api_token), redact_values=(api_token,))
- if endpoint_config.kind == "control_planes":
- yield from _iter_control_planes(session, base_url, logger)
+ if endpoint_config.kind == "core_entity":
+ yield from _iter_core_entities(
+ session, _get_base_url(region), endpoint_config, logger, resumable_source_manager
+ )
else:
- yield from _iter_core_entities(session, base_url, endpoint_config.path, logger)
+ yield from _iter_top_level(session, region, endpoint_config, logger, resumable_source_manager)
def validate_credentials(api_token: str, region: str) -> bool:
@@ -302,7 +410,13 @@ def kong_konnect_source(
def items() -> Iterator[list[dict[str, Any]]]:
if endpoint_config.kind != "analytics":
- return get_lookup_rows(api_token=api_token, region=region, endpoint=endpoint, logger=logger)
+ return get_lookup_rows(
+ api_token=api_token,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ )
return get_rows(
api_token=api_token,
region=region,
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
index ead0000d4c9b..db78543986a9 100644
--- 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
@@ -3,15 +3,15 @@ from typing import Literal, 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
+# Konnect serves its APIs 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",
+ "us": "https://us.api.konghq.com",
+ "eu": "https://eu.api.konghq.com",
+ "au": "https://au.api.konghq.com",
+ "me": "https://me.api.konghq.com",
+ "in": "https://in.api.konghq.com",
+ "sg": "https://sg.api.konghq.com",
}
DEFAULT_REGION = "us"
@@ -24,7 +24,8 @@ MAX_PAGE_SIZE = 1000
# on longer-retention plans can raise it; a value beyond retention is clamped by the API to what exists.
DEFAULT_INITIAL_LOOKBACK_DAYS = 30
-CONTROL_PLANES_PAGE_SIZE = 100
+# Page-number (`page[size]`/`page[number]`) and cursor (`page[size]`/`page[after]`) list endpoints.
+LIST_PAGE_SIZE = 100
# Core entity list endpoints cap `size` at 1000 and paginate with an opaque `offset` token.
CORE_ENTITY_PAGE_SIZE = 1000
@@ -44,9 +45,16 @@ class KongKonnectEndpointConfig:
partition_key: Optional[str] = None
primary_keys: list[str] = field(default_factory=lambda: ["request_id"])
should_sync_default: bool = True
- # `analytics` is the time-windowed POST query; `control_planes` is the page-number list; `core_entity`
- # fans out over every control plane.
- kind: Literal["analytics", "control_planes", "core_entity"] = "analytics"
+ # `analytics` is the time-windowed POST query; `page_number` is a `page[number]` list; `cursor` is a
+ # `page[after]` list; `core_entity` fans out over every control plane.
+ kind: Literal["analytics", "page_number", "cursor", "core_entity"] = "analytics"
+ # Konnect versions each API separately, so the path prefix is per endpoint.
+ api_version: Literal["v1", "v2"] = "v2"
+ sort: Optional[str] = None
+ # A child endpoint fans out over the rows of `parent` (an endpoint of the same kind). `{id}` in `path`
+ # is the parent row ID, which is copied onto each child row as `parent_id_field`.
+ parent: Optional[str] = None
+ parent_id_field: Optional[str] = None
description: Optional[str] = None
@@ -74,7 +82,8 @@ KONG_KONNECT_ENDPOINTS: dict[str, KongKonnectEndpointConfig] = {
"control_planes": KongKonnectEndpointConfig(
name="control_planes",
path="/control-planes",
- kind="control_planes",
+ kind="page_number",
+ sort="created_at",
partition_key="created_at",
primary_keys=["id"],
incremental_fields=[],
@@ -106,6 +115,104 @@ KONG_KONNECT_ENDPOINTS: dict[str, KongKonnectEndpointConfig] = {
incremental_fields=[],
description="Gateway consumers across all control planes. Resolves the consumer ID on api_requests.",
),
+ "consumer_groups": KongKonnectEndpointConfig(
+ name="consumer_groups",
+ path="/core-entities/consumer_groups",
+ kind="core_entity",
+ primary_keys=["control_plane_id", "id"],
+ incremental_fields=[],
+ description="Gateway consumer groups across all control planes.",
+ ),
+ "consumer_group_members": KongKonnectEndpointConfig(
+ name="consumer_group_members",
+ path="/core-entities/consumer_groups/{id}/consumers",
+ kind="core_entity",
+ parent="consumer_groups",
+ parent_id_field="consumer_group_id",
+ primary_keys=["control_plane_id", "consumer_group_id", "id"],
+ incremental_fields=[],
+ description="Consumers in each gateway consumer group, one row per consumer per group. "
+ "Segments api_requests by consumer group.",
+ ),
+ # API Products v2 backs the classic Dev Portal. It is the API that the api_product and
+ # api_product_version dimensions on api_requests refer to. The list endpoints only sort by name.
+ "api_products": KongKonnectEndpointConfig(
+ name="api_products",
+ path="/api-products",
+ kind="page_number",
+ sort="name",
+ partition_key="created_at",
+ primary_keys=["id"],
+ incremental_fields=[],
+ description="API products in the classic Dev Portal. Resolves the api_product ID on api_requests.",
+ ),
+ "api_product_versions": KongKonnectEndpointConfig(
+ name="api_product_versions",
+ path="/api-products/{id}/product-versions",
+ kind="page_number",
+ sort="name",
+ parent="api_products",
+ parent_id_field="api_product_id",
+ primary_keys=["api_product_id", "id"],
+ incremental_fields=[],
+ description="Versions of each API product. Resolves the api_product_version ID on api_requests.",
+ ),
+ "catalog_services": KongKonnectEndpointConfig(
+ name="catalog_services",
+ path="/catalog-services",
+ kind="page_number",
+ api_version="v1",
+ sort="created_at",
+ partition_key="created_at",
+ primary_keys=["id"],
+ incremental_fields=[],
+ description="Services in the Konnect Service Catalog.",
+ ),
+ "scorecards": KongKonnectEndpointConfig(
+ name="scorecards",
+ path="/scorecards",
+ kind="page_number",
+ api_version="v1",
+ sort="name",
+ partition_key="created_at",
+ primary_keys=["id"],
+ incremental_fields=[],
+ description="Service Catalog scorecards, with each scorecard's current overall score.",
+ ),
+ # A catalog service can be targeted by many scorecards, so rows key on the scorecard ID too.
+ "scorecard_services": KongKonnectEndpointConfig(
+ name="scorecard_services",
+ path="/scorecards/{id}/catalog-services",
+ kind="page_number",
+ api_version="v1",
+ sort="name",
+ parent="scorecards",
+ parent_id_field="scorecard_id",
+ primary_keys=["scorecard_id", "id"],
+ incremental_fields=[],
+ description="Catalog services targeted by each scorecard, with the service's score on that scorecard.",
+ ),
+ "realms": KongKonnectEndpointConfig(
+ name="realms",
+ path="/realms",
+ kind="cursor",
+ api_version="v1",
+ partition_key="created_at",
+ primary_keys=["id"],
+ incremental_fields=[],
+ description="Konnect consumer identity realms.",
+ ),
+ "realm_consumers": KongKonnectEndpointConfig(
+ name="realm_consumers",
+ path="/realms/{id}/consumers",
+ kind="cursor",
+ api_version="v1",
+ parent="realms",
+ parent_id_field="realm_id",
+ primary_keys=["realm_id", "id"],
+ incremental_fields=[],
+ description="Consumers registered in each Konnect identity realm, shared across the control planes the realm allows.",
+ ),
}
ENDPOINTS = tuple(KONG_KONNECT_ENDPOINTS.keys())
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 eb071ee4561b..831ab05e1fe0 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
@@ -63,7 +63,7 @@ class KongKonnectSource(ResumableSource[KongKonnectSourceConfig, KongKonnectResu
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, plus the control planes, services, routes, and consumers they reference, into the PostHog Data warehouse.
+ caption="""Enter a Kong Konnect access token to pull your gateway's Advanced Analytics API request logs, plus the control planes, gateway entities, consumer groups, API products, Service Catalog scorecards, and identity realm consumers behind them, 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.
@@ -119,7 +119,7 @@ How far back the initial sync can reach depends on your Konnect plan's Advanced
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 this data. Grant the token or account access to Advanced Analytics and control planes, then reconnect.",
+ "403 Client Error: Forbidden": "Your Kong Konnect access token is missing the permissions needed to read this data. Grant the token or account read access to the Konnect area this table comes from (Advanced Analytics, control planes, API Products, Service Catalog, or Consumers), then reconnect.",
}
def get_schemas(
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
index e09625ece28e..695af9db2fe0 100644
--- 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
@@ -11,7 +11,7 @@ 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 (
- CONTROL_PLANES_PAGE_SIZE,
+ LIST_PAGE_SIZE,
MAX_PAGE_SIZE,
KongKonnectResumeConfig,
_clamp_future_value_to_now,
@@ -160,8 +160,8 @@ BASE = "https://us.api.konghq.com/v2"
class TestLookupRows:
@parameterized.expand(
[
- ("short_page_stops", [[CONTROL_PLANES_PAGE_SIZE, None], [2, None]], 2),
- ("total_reached_stops", [[CONTROL_PLANES_PAGE_SIZE, CONTROL_PLANES_PAGE_SIZE]], 1),
+ ("short_page_stops", [[LIST_PAGE_SIZE, None], [2, None]], 2),
+ ("total_reached_stops", [[LIST_PAGE_SIZE, LIST_PAGE_SIZE]], 1),
("empty_first_page", [[0, 0]], 1),
]
)
@@ -177,7 +177,9 @@ class TestLookupRows:
)
mock_session.return_value.get.side_effect = responses
- rows = [row for batch in get_lookup_rows("tok", "us", "control_planes", MagicMock()) for row in batch]
+ rows = [
+ row for batch in get_lookup_rows("tok", "us", "control_planes", MagicMock(), _manager()) for row in batch
+ ]
assert len(rows) == sum(count or 0 for count, _ in pages)
calls = mock_session.return_value.get.call_args_list
@@ -232,7 +234,101 @@ class TestLookupRows:
]
with pytest.raises(requests.HTTPError):
- list(get_lookup_rows("tok", "us", "consumers", MagicMock()))
+ list(get_lookup_rows("tok", "us", "consumers", MagicMock(), _manager()))
+
+ @patch.object(kong_konnect, "make_tracked_session")
+ def test_consumer_group_members_fan_out_over_groups_per_control_plane(self, mock_session: MagicMock) -> None:
+ def fake_get(url: str, params: dict[str, Any], timeout: int) -> MagicMock:
+ routes: dict[str, dict[str, Any]] = {
+ f"{BASE}/control-planes": {"data": [_control_plane("cp-a")], "meta": {"page": {"total": 1}}},
+ f"{BASE}/control-planes/cp-a/core-entities/consumer_groups": {"data": [{"id": "gold"}, {"id": "free"}]},
+ f"{BASE}/control-planes/cp-a/core-entities/consumer_groups/gold/consumers": {"data": [{"id": "c-1"}]},
+ f"{BASE}/control-planes/cp-a/core-entities/consumer_groups/free/consumers": {"data": [{"id": "c-1"}]},
+ }
+ if url not in routes:
+ raise AssertionError(f"unexpected request to {url}")
+ return _json_response(200, routes[url])
+
+ mock_session.return_value.get.side_effect = fake_get
+ manager = _manager()
+
+ rows = [
+ row
+ for batch in get_lookup_rows("tok", "us", "consumer_group_members", MagicMock(), manager)
+ for row in batch
+ ]
+
+ assert rows == [
+ {"id": "c-1", "control_plane_id": "cp-a", "consumer_group_id": "gold"},
+ {"id": "c-1", "control_plane_id": "cp-a", "consumer_group_id": "free"},
+ ]
+ assert manager.safe_point.call_count == 2
+
+ @parameterized.expand(
+ [
+ (
+ "page_number_child_on_v1",
+ "scorecard_services",
+ "scorecard_id",
+ "https://us.api.konghq.com/v1/scorecards",
+ "https://us.api.konghq.com/v1/scorecards/{id}/catalog-services",
+ ),
+ (
+ "page_number_child_on_v2",
+ "api_product_versions",
+ "api_product_id",
+ "https://us.api.konghq.com/v2/api-products",
+ "https://us.api.konghq.com/v2/api-products/{id}/product-versions",
+ ),
+ ]
+ )
+ @patch.object(kong_konnect, "make_tracked_session")
+ def test_page_number_children_fan_out_over_parents(
+ self, _name: str, endpoint: str, parent_id_field: str, parent_url: str, child_url: str, mock_session: MagicMock
+ ) -> None:
+ def fake_get(url: str, params: dict[str, Any], timeout: int) -> MagicMock:
+ assert params["sort"] == "name"
+ if url == parent_url:
+ return _json_response(200, {"data": [{"id": "p-1"}, {"id": "p-gone"}], "meta": {"page": {"total": 2}}})
+ if url == child_url.format(id="p-1"):
+ return _json_response(200, {"data": [{"id": "x-1"}], "meta": {"page": {"total": 1}}})
+ if url == child_url.format(id="p-gone"):
+ return _json_response(404)
+ raise AssertionError(f"unexpected request to {url}")
+
+ mock_session.return_value.get.side_effect = fake_get
+
+ rows = [row for batch in get_lookup_rows("tok", "us", endpoint, MagicMock(), _manager()) for row in batch]
+
+ assert rows == [{"id": "x-1", parent_id_field: "p-1"}]
+
+ @patch.object(kong_konnect, "make_tracked_session")
+ def test_realm_consumers_follow_page_after_cursor_from_meta_next(self, mock_session: MagicMock) -> None:
+ v1 = "https://us.api.konghq.com/v1"
+
+ def fake_get(url: str, params: dict[str, Any], timeout: int) -> MagicMock:
+ if url == f"{v1}/realms":
+ return _json_response(200, {"data": [{"id": "realm-a"}], "meta": {"next": None}})
+ if url == f"{v1}/realms/realm-a/consumers":
+ if params.get("page[after]") == "abc==":
+ return _json_response(200, {"data": [{"id": "c-2"}], "meta": {"next": None}})
+ assert "page[after]" not in params
+ return _json_response(
+ 200,
+ {
+ "data": [{"id": "c-1"}],
+ "meta": {"next": "/v1/realms/realm-a/consumers?page%5Bafter%5D=abc%3D%3D"},
+ },
+ )
+ raise AssertionError(f"unexpected request to {url}")
+
+ mock_session.return_value.get.side_effect = fake_get
+
+ rows = [
+ row for batch in get_lookup_rows("tok", "us", "realm_consumers", MagicMock(), _manager()) for row in batch
+ ]
+
+ assert rows == [{"id": "c-1", "realm_id": "realm-a"}, {"id": "c-2", "realm_id": "realm-a"}]
if __name__ == "__main__":
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
index 6711d41831d5..9dff239388ef 100644
--- 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
@@ -36,7 +36,7 @@ class TestGetSchemas:
assert schemas["api_requests"].supports_incremental is True
assert [f["field"] for f in schemas["api_requests"].incremental_fields] == ["request_start"]
# The lookup list endpoints have no server-side timestamp filter, so they must stay full refresh.
- for name in ("control_planes", "services", "routes", "consumers"):
+ for name in set(schemas) - {"api_requests"}:
assert schemas[name].supports_incremental is False
assert schemas[name].supports_append is False