: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the kafka import source (#108391)
Tom Owers0bd76c25bad0
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.pyindex 19457179d606..2581e58797aa 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/helpers.py@@ -425,11 +425,11 @@ def ssh_tunnel_connection_changed(existing: Any, incoming: Any) -> bool:# Nested containers that keep their secrets one level down, not at the top level: the-# SourceFieldSelectConfig ones (Stripe `auth_method`, Snowflake `auth_type`, ServiceNow-# `auth_method`) key their selected branch as `selection`; the SourceFieldSwitchGroupConfig+# SourceFieldSelectConfig ones (Stripe `auth_method`, Snowflake `auth_type`, Kafka+# `authentication`) key their selected branch as `selection`; the SourceFieldSwitchGroupConfig# one (Billomat's `registered_app`) keys it as `enabled` instead, but the same carried-over-# secret check below applies either way.-_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type", "registered_app")+_NESTED_AUTH_CONTAINERS = ("auth_method", "auth_type", "authentication", "registered_app")# Secrets the edit form can never re-supply (parsed into the individual fields on create, then# stripped from API reads and hidden in the edit form), so gating credential re-entry on them woulddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex ed70ec79e29a..88f3bc8f1d4d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -29,6 +29,7 @@ vendor's API, see [COVERAGE_GAPS.md](COVERAGE_GAPS.md), refreshed by the| **gRPC** | The vendor SDK uses gRPC over HTTP/2 (binary, not REST). Routed through the [tracked gRPC transport](common/grpc/) via client interceptors (see `common/grpc/`). || **DB protocol** | Native database wire protocol via a driver (e.g. PostgreSQL, MySQL, Snowflake). Not HTTP. || **SSH (SFTP)** | SFTP over an SSH transport via `paramiko`. Not HTTP, so neither the HTTP nor the gRPC tracked transport applies. |+| **Kafka protocol** | Kafka wire protocol via `confluent-kafka` (librdkafka). Not HTTP, so neither the HTTP nor the gRPC tracked transport applies. || **Webhook (S3-buffered)** | Vendor pushes events to a webhook endpoint; payloads are buffered to S3 by the `WebhookSourceManager` and consumed by the pipeline. |When a source uses more than one transport (e.g. BigQuery REST + Storage gRPC, or Stripe pull-API + webhooks),@@ -410,6 +411,7 @@ the row lists both.| justcall | HTTP | requests | ✅ || justsift | HTTP | requests | ✅ || k6_cloud | HTTP | requests | ✅ |+| kafka | Kafka protocol | confluent-kafka (librdkafka) | ➖ || kalshi | HTTP | requests (rest_source.RESTClient) | ✅ || kandji | HTTP | requests (rest_source.RESTClient) | ✅ || kapa_ai | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1157,7 +1159,6 @@ doesn't conflict with concurrent PRs.- jobtread- judgeme_reviews- justsift-- kafka- kajabi- kameleoon- kaufland_marketplacediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex 249c029104f7..3db4e9f3024e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -113,6 +113,8 @@ class SourceResponse:incremental watermark). Gated by the pipeline together with a non-None resumable-source manager,so a resumable-source class whose current table isn't actually resumable (e.g. a SQL full loadwith no orderable primary key) sets this False and is treated as non-resumable for shutdown."""+ destination_reset_required: bool = False+ """Whether source metadata discovered during setup requires rebuilding the destination table."""lanes: Optional[list[OutputLane]] = None"""Tables this response's items feed, when it feeds more than the one `name` alone describes.None means the single lane built from `name` and `cdc_write_mode`."""diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kafka.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kafka.pyindex 1e3d8501fd45..4acb69315c8d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kafka.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/kafka.py@@ -1,9 +1,22 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class KafkaAuthenticationConfig(config.Config):+ selection: Literal["sasl_plain", "sasl_scram_sha_256", "sasl_scram_sha_512", "none"] = "sasl_plain"+ username: str | None = None+ password: str | None = None++@config.configclass KafkaSourceConfig(config.Config):- pass+ bootstrap_servers: str+ authentication: KafkaAuthenticationConfig+ encryption: Literal["tls", "none"] = config.value(default="tls")+ ca_certificate: str | None = None+ value_format: Literal["json", "text"] = config.value(default="json")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/kafka.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/kafka.pynew file mode 100644index 000000000000..dd239dcc62e5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/kafka.py@@ -0,0 +1,512 @@+import time+import base64+import hashlib+import logging+import datetime+from collections.abc import Callable, Iterator, Mapping+from typing import Any, ClassVar, Literal++import orjson+from confluent_kafka import (+ TIMESTAMP_NOT_AVAILABLE,+ Consumer,+ KafkaError,+ KafkaException,+ Message,+ TopicCollection,+ TopicPartition,+)+from confluent_kafka.admin import AdminClient+from structlog.types import FilteringBoundLogger++from posthog.cloud_utils import is_cloud+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConvention+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ DATABASE_HOST_NOT_ALLOWED_ERROR,+ HostNotAllowedError,+ is_team_allowlisted_for_internal_hosts,+ resolve_safe_host,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kafka import KafkaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.settings import (+ CLIENT_ID,+ CONSUME_BATCH_SIZE,+ CONSUME_TIMEOUT_SECONDS,+ HEADERS_COLUMN,+ IDLE_TIMEOUT_SECONDS,+ INTERNAL_TOPIC_PREFIX,+ KEY_COLUMN,+ KEY_ENCODING_COLUMN,+ METADATA_TIMEOUT_SECONDS,+ OFFSET_COLUMN,+ PARTITION_COLUMN,+ PRIMARY_KEYS,+ RAW_VALUE_COLUMN,+ RAW_VALUE_ENCODING_COLUMN,+ TIMESTAMP_COLUMN,+ TIMESTAMP_MS_COLUMN,+ TOMBSTONE_COLUMN,+ TOPIC_COLUMN,+ VALUE_COLUMN,+ VALUE_ENCODING_COLUMN,+ WATERMARK_TIMEOUT_SECONDS,+)++AUTHENTICATION_FAILED_MESSAGE = (+ "Kafka rejected the username or password. Check the credentials and the SASL mechanism, then try again."+)+MISSING_SASL_CREDENTIALS_MESSAGE = "Enter a username and password, or choose no authentication."+TLS_FAILED_MESSAGE = (+ "PostHog could not open a TLS connection to your Kafka brokers. Check that the brokers accept TLS "+ "on these ports, and add your CA certificate if a public certificate authority did not sign theirs."+)+UNREACHABLE_MESSAGE = (+ "PostHog could not connect to your Kafka brokers. Check the bootstrap servers, and that the brokers "+ "accept connections from the internet."+)+NO_TOPICS_MESSAGE = (+ "PostHog connected to Kafka but found no topics. Check that this user has permission to describe "+ "and read the topics you want to import."+)+TOPIC_NOT_FOUND_MESSAGE = "The Kafka topic for this table no longer exists, or this user can no longer read it."+KAFKA_CLOUD_UNAVAILABLE_MESSAGE = (+ "Kafka sources are not available on PostHog Cloud because the Kafka client cannot pin broker DNS addresses."+)++_SASL_MECHANISMS: dict[str, str] = {+ "sasl_plain": "PLAIN",+ "sasl_scram_sha_256": "SCRAM-SHA-256",+ "sasl_scram_sha_512": "SCRAM-SHA-512",+}++# The client's type stubs leave out librdkafka's error code constants.+_PARTITION_EOF: int = KafkaError._PARTITION_EOF # type: ignore[attr-defined]+# librdkafka reports these through `error_cb` while `list_topics` only reports a timeout, so the+# callback's errors are what name the cause.+_AUTHENTICATION_ERROR_CODES: set[int] = {+ KafkaError._AUTHENTICATION, # type: ignore[attr-defined]+ KafkaError.SASL_AUTHENTICATION_FAILED, # type: ignore[attr-defined]+}+_TLS_ERROR_CODES: set[int] = {KafkaError._SSL} # type: ignore[attr-defined]+++class KafkaSourceError(Exception):+ """A failure with a message that is safe and useful to show the user."""+++@frozen+class KafkaCursor:+ """The next offset to read in each partition of one topic, keyed by partition number.++ Partition numbers are strings because the cursor is stored as JSON, whose object keys are strings.+ """++ cursor_kind: ClassVar[str] = "kafka_offsets"++ offsets: dict[str, int]+ topic_id: str | None = None+++@frozen+class KafkaCluster:+ topics: list[str]+++class _ErrorCollector:+ def __init__(self) -> None:+ self.errors: list[KafkaError] = []++ def __call__(self, error: KafkaError) -> None:+ self.errors.append(error)++ def user_error(self) -> KafkaSourceError:+ codes = {error.code() for error in self.errors}+ if codes & _AUTHENTICATION_ERROR_CODES:+ return KafkaSourceError(AUTHENTICATION_FAILED_MESSAGE)+ if codes & _TLS_ERROR_CODES:+ return KafkaSourceError(TLS_FAILED_MESSAGE)+ return KafkaSourceError(UNREACHABLE_MESSAGE)+++def parse_bootstrap_hosts(bootstrap_servers: str) -> list[str]:+ hosts = []+ for server in bootstrap_servers.split(","):+ address = server.strip().split("://")[-1]+ if not address:+ continue+ if address.startswith("["):+ hosts.append(address[1 : address.index("]")])+ else:+ hosts.append(address.rsplit(":", 1)[0] if address.count(":") == 1 else address)+ return hosts+++def build_client_config(config: KafkaSourceConfig, error_cb: Callable[[KafkaError], None]) -> dict[str, Any]:+ authentication = config.authentication+ uses_sasl = authentication.selection != "none"+ uses_tls = config.encryption == "tls"+ client_config: dict[str, Any] = {+ "bootstrap.servers": config.bootstrap_servers,+ "security.protocol": f"{'SASL_' if uses_sasl else ''}{'SSL' if uses_tls else 'PLAINTEXT'}",+ "client.id": CLIENT_ID,+ "error_cb": error_cb,+ "logger": logging.getLogger(__name__),+ }+ if uses_sasl:+ if not authentication.username or not authentication.password:+ raise KafkaSourceError(MISSING_SASL_CREDENTIALS_MESSAGE)+ client_config["sasl.mechanism"] = _SASL_MECHANISMS[authentication.selection]+ client_config["sasl.username"] = authentication.username+ client_config["sasl.password"] = authentication.password+ if uses_tls and config.ca_certificate:+ client_config["ssl.ca.pem"] = config.ca_certificate+ return client_config+++def _check_hosts(hosts: list[str], team_id: int) -> None:+ for host in hosts:+ resolution = resolve_safe_host(host, team_id)+ if resolution.connect_host is None:+ raise HostNotAllowedError(f"{DATABASE_HOST_NOT_ALLOWED_ERROR}: {resolution.error}")+++def fetch_cluster(config: KafkaSourceConfig, team_id: int) -> KafkaCluster:+ """List the importable topics, after checking every broker the client talks to is a public host.++ The bootstrap servers only hand out the cluster's metadata. The client then connects to each+ broker the metadata advertises, so those addresses are checked as well as the configured ones.+ """+ if is_cloud() and not is_team_allowlisted_for_internal_hosts(team_id):+ # librdkafka resolves broker names itself and exposes no resolver hook. A separate preflight+ # lookup would leave a DNS-rebinding gap, so untrusted Cloud teams cannot use this raw socket.+ raise HostNotAllowedError(KAFKA_CLOUD_UNAVAILABLE_MESSAGE)++ _check_hosts(parse_bootstrap_hosts(config.bootstrap_servers), team_id)++ errors = _ErrorCollector()+ admin = AdminClient(build_client_config(config, errors))+ try:+ metadata = admin.list_topics(timeout=METADATA_TIMEOUT_SECONDS)+ except KafkaException as e:+ raise errors.user_error() from e++ # The client's metadata types leave `host` unannotated, and it is always set on a returned broker.+ _check_hosts([str(broker.host) for broker in metadata.brokers.values()], team_id)+ topics = sorted(+ name+ for name, topic in metadata.topics.items()+ if not name.startswith(INTERNAL_TOPIC_PREFIX) and topic.error is None+ )+ return KafkaCluster(topics=topics)+++def resolve_start_offsets(+ stored: Mapping[str, int] | None,+ watermarks: Mapping[int, tuple[int, int]],+ logger: FilteringBoundLogger,+) -> dict[int, int]:+ """The offset each partition starts from, given the cursor and each partition's (low, high) watermarks.++ A partition the cursor does not know, such as one added to the topic since the last run, starts at+ its first retained message. Starting it at the end would skip what was written before this run.+ """+ starts: dict[int, int] = {}+ for partition, (low, high) in watermarks.items():+ stored_offset = stored.get(str(partition)) if stored is not None else None+ if stored_offset is None:+ starts[partition] = low+ elif stored_offset < low:+ logger.warning(+ "Kafka retention deleted messages this table never read",+ partition=partition,+ stored_offset=stored_offset,+ low_watermark=low,+ )+ starts[partition] = low+ elif stored_offset > high:+ # The log is shorter than the cursor, so the topic was deleted and created again.+ logger.warning(+ "Kafka partition is behind the stored cursor, reading it again from the start",+ partition=partition,+ stored_offset=stored_offset,+ high_watermark=high,+ )+ starts[partition] = low+ else:+ starts[partition] = stored_offset+ return starts+++_RESERVED_PAYLOAD_COLUMNS = frozenset(+ {+ TOPIC_COLUMN,+ PARTITION_COLUMN,+ OFFSET_COLUMN,+ TIMESTAMP_COLUMN,+ TIMESTAMP_MS_COLUMN,+ KEY_COLUMN,+ KEY_ENCODING_COLUMN,+ HEADERS_COLUMN,+ TOMBSTONE_COLUMN,+ RAW_VALUE_COLUMN,+ RAW_VALUE_ENCODING_COLUMN,+ VALUE_COLUMN,+ VALUE_ENCODING_COLUMN,+ "_ph_debug",+ "_ph_partition_key",+ "_dlt_id",+ "_dlt_load_id",+ }+)+++@frozen+class _DecodedValue:+ value: str | None+ encoding: str | None+++def _decode_losslessly(data: bytes | str | None) -> _DecodedValue:+ if data is None:+ return _DecodedValue(value=None, encoding=None)+ if isinstance(data, str):+ return _DecodedValue(value=data, encoding="utf-8")+ try:+ return _DecodedValue(value=data.decode("utf-8"), encoding="utf-8")+ except UnicodeDecodeError:+ return _DecodedValue(value=base64.b64encode(data).decode("ascii"), encoding="base64")+++def _payload_column_name(name: str) -> str:+ try:+ normalized = NamingConvention.normalize_identifier(name)+ except ValueError:+ normalized = "column"+ if name == normalized and normalized not in _RESERVED_PAYLOAD_COLUMNS and not normalized.startswith("_kafka_"):+ return normalized+ digest = hashlib.sha256(name.encode("utf-8")).hexdigest()[:8]+ return f"_kafka_payload_{normalized}_{digest}"+++def _timestamp(timestamp_type: int, timestamp_ms: int) -> datetime.datetime | None:+ if timestamp_type == TIMESTAMP_NOT_AVAILABLE:+ return None+ try:+ return datetime.datetime.fromtimestamp(timestamp_ms / 1000, tz=datetime.UTC)+ except (ValueError, OverflowError, OSError):+ return None+++def message_to_row(message: Message, value_format: Literal["json", "text"]) -> dict[str, Any]:+ row: dict[str, Any] = {}+ value = message.value()+ if value is not None:+ if value_format == "text":+ decoded_value = _decode_losslessly(value)+ row[VALUE_COLUMN], row[VALUE_ENCODING_COLUMN] = decoded_value.value, decoded_value.encoding+ else:+ try:+ decoded = orjson.loads(value)+ except orjson.JSONDecodeError:+ decoded_value = _decode_losslessly(value)+ row[RAW_VALUE_COLUMN], row[RAW_VALUE_ENCODING_COLUMN] = decoded_value.value, decoded_value.encoding+ else:+ if isinstance(decoded, dict):+ row.update({_payload_column_name(key): item for key, item in decoded.items()})+ else:+ # Stored as JSON text, so a topic that mixes numbers and strings keeps one column type.+ row[VALUE_COLUMN] = orjson.dumps(decoded).decode()++ timestamp_type, timestamp_ms = message.timestamp()+ decoded_key = _decode_losslessly(message.key())+ headers = message.headers()+ encoded_headers = []+ for name, data in headers.items() if isinstance(headers, dict) else headers or []:+ decoded_header = _decode_losslessly(data)+ encoded_headers.append(+ [name, {"data": decoded_header.value, "encoding": decoded_header.encoding}]+ if decoded_header.encoding == "base64"+ else [name, decoded_header.value]+ )++ row.update(+ {+ TOPIC_COLUMN: message.topic(),+ PARTITION_COLUMN: message.partition(),+ OFFSET_COLUMN: message.offset(),+ TIMESTAMP_COLUMN: _timestamp(timestamp_type, timestamp_ms),+ TIMESTAMP_MS_COLUMN: None if timestamp_type == TIMESTAMP_NOT_AVAILABLE else timestamp_ms,+ KEY_COLUMN: decoded_key.value,+ KEY_ENCODING_COLUMN: decoded_key.encoding,+ HEADERS_COLUMN: orjson.dumps(encoded_headers).decode() if headers else None,+ TOMBSTONE_COLUMN: value is None,+ }+ )+ return row+++def read_partitions(+ consumer: Consumer,+ topic: str,+ starts: Mapping[int, int],+ ends: Mapping[int, int],+ value_format: Literal["json", "text"],+ on_progress: Callable[[dict[int, int]], None],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Yield the messages of each partition from its start offset up to, not including, its end offset.++ `on_progress` receives the next offset to read in every partition after each batch, so it never+ names an offset past a row that has not been yielded.+ """+ next_offsets = dict(starts)+ remaining = {partition for partition in starts if starts[partition] < ends[partition]}+ if not remaining:+ on_progress(next_offsets)+ return++ consumer.assign([TopicPartition(topic, partition, starts[partition]) for partition in remaining])+ last_delivery = time.monotonic()+ while remaining:+ rows: list[dict[str, Any]] = []+ for message in consumer.consume(num_messages=CONSUME_BATCH_SIZE, timeout=CONSUME_TIMEOUT_SECONDS):+ partition = message.partition()+ offset = message.offset()+ error = message.error()+ if error is not None and error.code() != _PARTITION_EOF:+ raise KafkaException(error)+ if partition is None or offset is None or partition not in remaining:+ continue+ if error is not None:+ next_offsets[partition] = max(next_offsets[partition], min(offset, ends[partition]))+ remaining.discard(partition)+ continue+ if offset >= ends[partition]:+ # Written after this run captured its end offsets. The next run reads it.+ remaining.discard(partition)+ continue+ rows.append(message_to_row(message, value_format))+ next_offsets[partition] = offset + 1+ if next_offsets[partition] >= ends[partition]:+ remaining.discard(partition)++ # A read_committed consumer skips transaction markers and aborted messages without delivering+ # them, so a partition can pass its end offset with no message at the end to say so.+ if remaining:+ for position in consumer.position([TopicPartition(topic, partition) for partition in remaining]):+ if position.offset >= 0:+ next_offsets[position.partition] = max(+ next_offsets[position.partition], min(position.offset, ends[position.partition])+ )+ if next_offsets[position.partition] >= ends[position.partition]:+ remaining.discard(position.partition)++ if rows:+ last_delivery = time.monotonic()+ yield rows+ elif remaining and time.monotonic() - last_delivery > IDLE_TIMEOUT_SECONDS:+ logger.warning(+ "Kafka partitions stopped short of their end offsets, the next sync continues them",+ partitions=sorted(remaining),+ )+ remaining.clear()+ on_progress(next_offsets)+++def kafka_source(+ config: KafkaSourceConfig,+ topic: str,+ team_id: int,+ cursor: SourceCursorManager[KafkaCursor],+ resume: bool,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ """Read the topic from the stored cursor, or from the start when `resume` is false."""+ cluster = fetch_cluster(config, team_id)+ if topic not in cluster.topics:+ raise KafkaSourceError(TOPIC_NOT_FOUND_MESSAGE)++ errors = _ErrorCollector()+ client_config = build_client_config(config, errors)+ consumer = Consumer(+ {+ **client_config,+ # Required by the client, though the source assigns partitions itself and never joins or+ # commits to the group, so a customer's own consumer groups are never touched.+ "group.id": f"{CLIENT_ID}-{team_id}",+ "enable.auto.commit": False,+ "enable.auto.offset.store": False,+ "enable.partition.eof": True,+ "isolation.level": "read_committed",+ }+ )+ try:+ topic_metadata = consumer.list_topics(topic, timeout=METADATA_TIMEOUT_SECONDS).topics[topic]+ if topic_metadata.error is not None:+ raise KafkaSourceError(TOPIC_NOT_FOUND_MESSAGE)+ try:+ topic_description = (+ AdminClient(client_config)+ .describe_topics(TopicCollection([topic]), request_timeout=METADATA_TIMEOUT_SECONDS)[topic]+ .result(timeout=METADATA_TIMEOUT_SECONDS)+ )+ except KafkaException as e:+ raise KafkaSourceError(TOPIC_NOT_FOUND_MESSAGE) from e+ topic_id = str(topic_description.topic_id)+ watermarks = {+ partition: consumer.get_watermark_offsets(+ TopicPartition(topic, partition), timeout=WATERMARK_TIMEOUT_SECONDS, cached=False+ )+ for partition in topic_metadata.partitions+ }+ except Exception as e:+ consumer.close()+ if isinstance(e, KafkaException):+ raise errors.user_error() from e+ raise++ try:+ stored = cursor.load()+ topic_recreated = False+ if resume and stored is not None and stored.topic_id and stored.topic_id != topic_id:+ topic_recreated = True+ logger.warning(+ "Kafka topic identity changed, rebuilding the destination from the new topic",+ old_topic_id=stored.topic_id,+ new_topic_id=topic_id,+ )+ stored_offsets = stored.offsets if resume and stored is not None and not topic_recreated else None+ starts = resolve_start_offsets(stored_offsets, watermarks, logger)+ ends = {partition: high for partition, (_, high) in watermarks.items()}+ except Exception:+ consumer.close()+ raise++ def on_progress(next_offsets: dict[int, int]) -> None:+ cursor.stage(+ KafkaCursor(+ offsets={str(partition): offset for partition, offset in next_offsets.items()}, topic_id=topic_id+ )+ )++ def items() -> Iterator[list[dict[str, Any]]]:+ try:+ yield from read_partitions(consumer, topic, starts, ends, config.value_format, on_progress, logger)+ finally:+ consumer.close()++ return SourceResponse(+ name=topic,+ items=items,+ primary_keys=PRIMARY_KEYS,+ partition_mode="datetime",+ partition_keys=[TIMESTAMP_COLUMN],+ # Messages arrive ordered by offset within a partition, not by timestamp across partitions.+ sort_mode="desc",+ rows_to_sync=sum(ends[partition] - starts[partition] for partition in starts),+ destination_reset_required=topic_recreated,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/settings.pynew file mode 100644index 000000000000..be6bf32da595--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/settings.py@@ -0,0 +1,45 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++TOPIC_COLUMN = "_kafka_topic"+PARTITION_COLUMN = "_kafka_partition"+OFFSET_COLUMN = "_kafka_offset"+TIMESTAMP_COLUMN = "_kafka_timestamp"+TIMESTAMP_MS_COLUMN = "_kafka_timestamp_ms"+KEY_COLUMN = "_kafka_key"+KEY_ENCODING_COLUMN = "_kafka_key_encoding"+HEADERS_COLUMN = "_kafka_headers"+TOMBSTONE_COLUMN = "_kafka_tombstone"+# Holds a JSON-format message whose value does not parse, so one bad message does not fail the sync.+RAW_VALUE_COLUMN = "_kafka_raw_value"+RAW_VALUE_ENCODING_COLUMN = "_kafka_raw_value_encoding"+# Holds a value that is not a JSON object, and every value of a text-format topic.+VALUE_COLUMN = "value"+VALUE_ENCODING_COLUMN = "_kafka_value_encoding"++# A partition and an offset name one message of one topic, and each topic is its own table.+PRIMARY_KEYS = [PARTITION_COLUMN, OFFSET_COLUMN]++# The offset cursor decides where a run starts. The timestamp is offered as the incremental field+# because incremental syncs need one, and its maximum shows how far the table has caught up.+INCREMENTAL_FIELDS: list[IncrementalField] = [+ {+ "label": TIMESTAMP_COLUMN,+ "type": IncrementalFieldType.DateTime,+ "field": TIMESTAMP_COLUMN,+ "field_type": IncrementalFieldType.DateTime,+ }+]++# Kafka and Confluent Platform name their internal topics with a leading underscore+# (`__consumer_offsets`, `__transaction_state`, `_schemas`, `_confluent-*`).+INTERNAL_TOPIC_PREFIX = "_"++CLIENT_ID = "posthog-data-warehouse"+METADATA_TIMEOUT_SECONDS = 15+WATERMARK_TIMEOUT_SECONDS = 15+CONSUME_BATCH_SIZE = 1000+CONSUME_TIMEOUT_SECONDS = 1.0+# A partition that stops delivering before its end offset is waiting on an open transaction, which+# hides the messages after it from a read_committed consumer. The run stops waiting after this long+# and the next run continues from the partition's position.+IDLE_TIMEOUT_SECONDS = 60.0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/source.pyindex 49bf11905692..4095d2a74bb4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/source.py@@ -1,25 +1,221 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ 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.sources.common.cursor import CursorSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ HostNotAllowedError,+ TemporaryHostResolutionError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kafka import KafkaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.kafka import (+ AUTHENTICATION_FAILED_MESSAGE,+ MISSING_SASL_CREDENTIALS_MESSAGE,+ NO_TOPICS_MESSAGE,+ TLS_FAILED_MESSAGE,+ TOPIC_NOT_FOUND_MESSAGE,+ KafkaCursor,+ KafkaSourceError,+ fetch_cluster,+ kafka_source,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.settings import (+ INCREMENTAL_FIELDS,+ PRIMARY_KEYS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _credential_fields() -> list[FieldType]:+ return [+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="API key or SASL username",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=False,+ placeholder="API secret or SASL password",+ secret=True,+ ),+ ]++@SourceRegistry.register-class KafkaSource(SimpleSource[KafkaSourceConfig]):+class KafkaSource(SimpleSource[KafkaSourceConfig], CursorSource[KafkaCursor]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KAFKA+ @property+ def connection_host_fields(self) -> list[str]:+ # The SASL password is sent to the brokers named here, so changing them must re-require it.+ return ["bootstrap_servers"]++ def cursor_class(self) -> type[KafkaCursor]:+ return KafkaCursor+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.KAFKA,category=DataWarehouseSourceCategory.DATABASES,+ keywords=["streaming", "topics", "msk", "event streaming"],label="Kafka",+ caption=(+ "Import the messages of your Kafka topics. Each topic becomes a table, and each sync "+ "reads the messages written since the last one. Message values must be JSON or plain "+ "text. PostHog connects to every broker your cluster advertises, so each one must be "+ "reachable from the internet."+ ),+ releaseStatus=ReleaseStatus.ALPHA,iconPath="/static/services/kafka.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="bootstrap_servers",+ label="Bootstrap servers",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="broker-1.example.com:9092,broker-2.example.com:9092",+ caption="A comma-separated list of `host:port` pairs.",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="authentication",+ label="Authentication",+ required=True,+ defaultValue="sasl_plain",+ options=[+ SourceFieldSelectConfigOption(+ label="SASL/PLAIN (Confluent Cloud API key)",+ value="sasl_plain",+ fields=_credential_fields(),+ ),+ SourceFieldSelectConfigOption(+ label="SASL/SCRAM-SHA-256",+ value="sasl_scram_sha_256",+ fields=_credential_fields(),+ ),+ SourceFieldSelectConfigOption(+ label="SASL/SCRAM-SHA-512",+ value="sasl_scram_sha_512",+ fields=_credential_fields(),+ ),+ SourceFieldSelectConfigOption(label="None", value="none"),+ ],+ ),+ SourceFieldSelectConfig(+ name="encryption",+ label="Encryption",+ required=True,+ defaultValue="tls",+ options=[+ SourceFieldSelectConfigOption(label="TLS", value="tls"),+ SourceFieldSelectConfigOption(label="None", value="none"),+ ],+ ),+ SourceFieldInputConfig(+ name="ca_certificate",+ label="CA certificate",+ type=SourceFieldInputConfigType.TEXTAREA,+ required=False,+ placeholder="-----BEGIN CERTIFICATE-----",+ caption="Only needed when a public certificate authority did not sign your brokers' certificates.",+ secret=False,+ ),+ SourceFieldSelectConfig(+ name="value_format",+ label="Message format",+ required=True,+ defaultValue="json",+ caption=(+ "With JSON, the fields of each message become columns. With text, each message "+ "is stored whole in a `value` column."+ ),+ options=[+ SourceFieldSelectConfigOption(label="JSON", value="json"),+ SourceFieldSelectConfigOption(label="Text", value="text"),+ ],+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return dict.fromkeys(+ (+ AUTHENTICATION_FAILED_MESSAGE,+ MISSING_SASL_CREDENTIALS_MESSAGE,+ TLS_FAILED_MESSAGE,+ TOPIC_NOT_FOUND_MESSAGE,+ )+ )++ def validate_credentials(+ self,+ config: KafkaSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ try:+ cluster = fetch_cluster(config, team_id)+ except (KafkaSourceError, HostNotAllowedError, TemporaryHostResolutionError) as e:+ return False, str(e)++ if not cluster.topics:+ return False, NO_TOPICS_MESSAGE+ if schema_name is not None and schema_name not in cluster.topics:+ return False, TOPIC_NOT_FOUND_MESSAGE+ return True, None++ def get_schemas(+ self,+ config: KafkaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ cluster = fetch_cluster(config, team_id)+ return [+ SourceSchema(+ name=topic,+ supports_incremental=True,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS,+ detected_primary_keys=PRIMARY_KEYS,+ )+ for topic in cluster.topics+ if names is None or topic in names+ ]++ def source_for_pipeline(self, config: KafkaSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return kafka_source(+ config=config,+ topic=inputs.schema_name,+ team_id=inputs.team_id,+ cursor=self.get_cursor_manager(inputs),+ resume=inputs.should_use_incremental_field,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka.pynew file mode 100644index 000000000000..8009b89f27d1--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka.py@@ -0,0 +1,447 @@+import re+import datetime+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest.mock import MagicMock, patch++from confluent_kafka import (+ TIMESTAMP_CREATE_TIME,+ TIMESTAMP_NOT_AVAILABLE,+ Consumer,+ KafkaError,+ KafkaException,+ Message,+ TopicPartition,+)+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ HostNotAllowedError,+ HostResolution,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kafka import KafkaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.kafka import (+ AUTHENTICATION_FAILED_MESSAGE,+ KAFKA_CLOUD_UNAVAILABLE_MESSAGE,+ MISSING_SASL_CREDENTIALS_MESSAGE,+ UNREACHABLE_MESSAGE,+ KafkaCluster,+ KafkaCursor,+ KafkaSourceError,+ build_client_config,+ fetch_cluster,+ kafka_source,+ message_to_row,+ parse_bootstrap_hosts,+ read_partitions,+ resolve_start_offsets,+)++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.kafka.kafka"+_EOF = KafkaError._PARTITION_EOF # type: ignore[attr-defined]+++class _FakeMessage:+ def __init__(+ self,+ partition: int,+ offset: int,+ value: bytes | None = b"{}",+ key: bytes | None = None,+ headers: list[tuple[str, bytes | None]] | None = None,+ timestamp: tuple[int, int] = (TIMESTAMP_CREATE_TIME, 1_700_000_000_000),+ error: KafkaError | None = None,+ ) -> None:+ self._partition = partition+ self._offset = offset+ self._value = value+ self._key = key+ self._headers = headers+ self._timestamp = timestamp+ self._error = error++ def topic(self) -> str:+ return "orders"++ def partition(self) -> int:+ return self._partition++ def offset(self) -> int:+ return self._offset++ def value(self) -> bytes | None:+ return self._value++ def key(self) -> bytes | None:+ return self._key++ def headers(self) -> list[tuple[str, bytes | None]] | None:+ return self._headers++ def timestamp(self) -> tuple[int, int]:+ return self._timestamp++ def error(self) -> KafkaError | None:+ return self._error+++class _FakeConsumer:+ def __init__(+ self, batches: list[list[_FakeMessage]], positions: dict[int, int] | None = None, may_idle: bool = False+ ) -> None:+ self._batches = list(batches)+ self._positions = positions or {}+ self._may_idle = may_idle+ self.assigned: list[tuple[int, int]] | None = None++ def assign(self, partitions: list[TopicPartition]) -> None:+ self.assigned = [(tp.partition, tp.offset) for tp in partitions]++ def consume(self, num_messages: int, timeout: float) -> list[_FakeMessage]:+ if self._batches:+ return self._batches.pop(0)+ # A read that should have finished must not wait for more messages.+ assert self._may_idle, "read past the last message"+ return []++ def position(self, partitions: list[TopicPartition]) -> list[TopicPartition]:+ return [TopicPartition(tp.topic, tp.partition, self._positions.get(tp.partition, -1001)) for tp in partitions]+++def _read(+ consumer: _FakeConsumer, starts: dict[int, int], ends: dict[int, int]+) -> tuple[list[dict[str, Any]], dict[int, int]]:+ progress: list[dict[int, int]] = []+ rows = [+ row+ for batch in read_partitions(+ cast(Consumer, consumer),+ "orders",+ starts,+ ends,+ "json",+ lambda offsets: progress.append(dict(offsets)),+ MagicMock(),+ )+ for row in batch+ ]+ return rows, progress[-1]+++def _config(**overrides: Any) -> KafkaSourceConfig:+ return KafkaSourceConfig.from_dict(+ {+ "bootstrap_servers": "broker.example.com:9092",+ "authentication": {"selection": "sasl_plain", "username": "key", "password": "secret"},+ **overrides,+ }+ )+++class TestResolveStartOffsets:+ @parameterized.expand(+ [+ ("no_cursor_starts_at_the_first_retained_message", None, (10, 50), 10),+ ("cursor_inside_the_log", {"0": 30}, (10, 50), 30),+ ("cursor_at_the_end_reads_nothing", {"0": 50}, (10, 50), 50),+ ("retention_deleted_past_the_cursor", {"0": 5}, (10, 50), 10),+ ("topic_recreated_behind_the_cursor", {"0": 900}, (0, 40), 0),+ ("partition_added_since_the_last_run", {"1": 30}, (10, 50), 10),+ ]+ )+ def test_start_offset(+ self, _name: str, stored: dict[str, int] | None, watermarks: tuple[int, int], expected: int+ ) -> None:+ assert resolve_start_offsets(stored, {0: watermarks}, MagicMock()) == {0: expected}+++class TestMessageToRow:+ @parameterized.expand(+ [+ ("json_object_becomes_columns", "json", b'{"id": 1, "name": "a"}', {"id": 1, "name": "a"}),+ ("json_non_object_is_kept_as_json_text", "json", b"[1, 2]", {"value": "[1,2]"}),+ ("json_string_is_kept_as_json_text", "json", b'"hi"', {"value": '"hi"'}),+ ("invalid_json_is_kept_raw", "json", b"not json {", {"_kafka_raw_value": "not json {"}),+ ("text_is_kept_whole", "text", b'{"id": 1}', {"value": '{"id": 1}'}),+ ("tombstone_has_no_payload", "json", None, {}),+ ]+ )+ def test_payload(self, _name: str, value_format: Any, value: bytes | None, expected_payload: dict) -> None:+ row = message_to_row(cast(Message, _FakeMessage(0, 7, value=value)), value_format)+ envelope = {key: row.pop(key) for key in list(row) if key.startswith("_kafka_") and key != "_kafka_raw_value"}+ assert row == expected_payload+ assert envelope["_kafka_tombstone"] is (value is None)++ def test_reserved_and_invalid_payload_fields_are_namespaced(self) -> None:+ message = _FakeMessage(+ 2,+ 7,+ value=b'{"_kafka_offset": 99, "_ph_debug": "payload", "not valid!": true, "ok": 1}',+ )+ row = message_to_row(cast(Message, message), "json")+ assert (row["_kafka_partition"], row["_kafka_offset"]) == (2, 7)+ assert row["ok"] == 1+ assert "_ph_debug" not in row+ assert any(key.startswith("_kafka_payload_not_validx_") for key in row)+ assert len([key for key in row if key.startswith("_kafka_payload_")]) == 3++ def test_envelope(self) -> None:+ message = _FakeMessage(1, 3, key=b"user-1", headers=[("trace", b"abc"), ("empty", None)])+ row = message_to_row(cast(Message, message), "json")+ assert row["_kafka_key"] == "user-1"+ assert row["_kafka_headers"] == '[["trace","abc"],["empty",null]]'+ assert row["_kafka_timestamp"] == datetime.datetime(2023, 11, 14, 22, 13, 20, tzinfo=datetime.UTC)++ def test_message_without_a_timestamp(self) -> None:+ message = _FakeMessage(0, 0, timestamp=(TIMESTAMP_NOT_AVAILABLE, -1))+ row = message_to_row(cast(Message, message), "json")+ assert row["_kafka_timestamp"] is None+ assert row["_kafka_timestamp_ms"] is None++ def test_out_of_range_timestamp_keeps_raw_milliseconds(self) -> None:+ timestamp_ms = 2**63 - 1+ message = _FakeMessage(0, 0, timestamp=(TIMESTAMP_CREATE_TIME, timestamp_ms))+ row = message_to_row(cast(Message, message), "json")+ assert row["_kafka_timestamp"] is None+ assert row["_kafka_timestamp_ms"] == timestamp_ms++ def test_binary_key_headers_and_raw_value_are_base64_encoded(self) -> None:+ message = _FakeMessage(0, 0, value=b"\xff", key=b"\xfe", headers=[("binary", b"\xfd")])+ row = message_to_row(cast(Message, message), "json")+ assert row["_kafka_raw_value"] == "/w=="+ assert row["_kafka_raw_value_encoding"] == "base64"+ assert row["_kafka_key"] == "/g=="+ assert row["_kafka_key_encoding"] == "base64"+ assert row["_kafka_headers"] == '[["binary",{"data":"/Q==","encoding":"base64"}]]'+++class TestReadPartitions:+ def test_stops_at_the_end_offsets_captured_at_the_start(self) -> None:+ consumer = _FakeConsumer(+ [+ [_FakeMessage(0, 3), _FakeMessage(1, 0), _FakeMessage(0, 4)],+ # Written after the run captured its end offsets.+ [_FakeMessage(0, 5), _FakeMessage(1, 1)],+ ]+ )+ rows, cursor = _read(consumer, starts={0: 3, 1: 0}, ends={0: 5, 1: 1})+ assert consumer.assigned == [(0, 3), (1, 0)]+ assert [(row["_kafka_partition"], row["_kafka_offset"]) for row in rows] == [(0, 3), (1, 0), (0, 4)]+ assert cursor == {0: 5, 1: 1}++ def test_a_partition_that_ends_in_transaction_markers_finishes_at_its_position(self) -> None:+ # The markers at offsets 1 and 2 are never delivered, so only the position shows the end.+ consumer = _FakeConsumer([[_FakeMessage(0, 0)]], positions={0: 3})+ rows, cursor = _read(consumer, starts={0: 0}, ends={0: 3})+ assert len(rows) == 1+ assert cursor == {0: 3}++ def test_end_of_partition_finishes_it(self) -> None:+ eof = _FakeMessage(0, 2, error=KafkaError(_EOF))+ rows, cursor = _read(_FakeConsumer([[_FakeMessage(0, 0), eof]]), starts={0: 0}, ends={0: 2})+ assert len(rows) == 1+ assert cursor == {0: 2}++ def test_a_stalled_partition_stops_at_its_position(self) -> None:+ # An open transaction holds back what a read_committed consumer can see.+ consumer = _FakeConsumer([[_FakeMessage(0, 0)]], positions={0: 1}, may_idle=True)+ with patch(f"{_MODULE}.IDLE_TIMEOUT_SECONDS", -1):+ rows, cursor = _read(consumer, starts={0: 0}, ends={0: 10})+ assert len(rows) == 1+ assert cursor == {0: 1}++ def test_nothing_to_read_reports_the_start_offsets_without_assigning(self) -> None:+ consumer = _FakeConsumer([])+ rows, cursor = _read(consumer, starts={0: 7}, ends={0: 7})+ assert (rows, cursor, consumer.assigned) == ([], {0: 7}, None)++ def test_a_message_error_fails_the_read(self) -> None:+ broken = _FakeMessage(0, 0, error=KafkaError(KafkaError.TOPIC_AUTHORIZATION_FAILED)) # type: ignore[attr-defined]+ with pytest.raises(KafkaException):+ _read(_FakeConsumer([[broken]]), starts={0: 0}, ends={0: 5})+++class TestKafkaSourceSetup:+ @staticmethod+ def _topic_metadata(error: KafkaError | None = None) -> MagicMock:+ return MagicMock(error=error, partitions={0: MagicMock()})++ @staticmethod+ def _topic_description(topic_id: str = "topic-id") -> MagicMock:+ future = MagicMock()+ future.result.return_value = MagicMock(topic_id=topic_id)+ return MagicMock(describe_topics=MagicMock(return_value={"orders": future}))++ def test_consumer_reads_only_committed_records(self) -> None:+ consumer = MagicMock()+ consumer.list_topics.return_value = MagicMock(topics={"orders": self._topic_metadata()})+ consumer.get_watermark_offsets.return_value = (0, 0)+ cursor = MagicMock()+ cursor.load.return_value = None+ with (+ patch(f"{_MODULE}.fetch_cluster", return_value=KafkaCluster(topics=["orders"])),+ patch(f"{_MODULE}.Consumer", return_value=consumer) as consumer_class,+ patch(f"{_MODULE}.AdminClient", return_value=self._topic_description()),+ ):+ response = kafka_source(_config(), "orders", 1, cursor, True, MagicMock())++ assert consumer_class.call_args.args[0]["isolation.level"] == "read_committed"+ assert list(cast(Iterable[Any], response.items())) == []+ consumer.close.assert_called_once()++ def test_topic_metadata_error_closes_the_consumer(self) -> None:+ consumer = MagicMock()+ consumer.list_topics.return_value = MagicMock(+ topics={"orders": self._topic_metadata(KafkaError(KafkaError.UNKNOWN_TOPIC_OR_PART))} # type: ignore[attr-defined]+ )+ with (+ patch(f"{_MODULE}.fetch_cluster", return_value=KafkaCluster(topics=["orders"])),+ patch(f"{_MODULE}.Consumer", return_value=consumer),+ patch(f"{_MODULE}.AdminClient") as admin,+ pytest.raises(KafkaSourceError, match=re.escape("topic for this table no longer exists")),+ ):+ kafka_source(_config(), "orders", 1, MagicMock(), True, MagicMock())++ consumer.close.assert_called_once()+ admin.assert_not_called()++ def test_changed_topic_identity_rebuilds_from_the_low_watermark(self) -> None:+ consumer = MagicMock()+ consumer.list_topics.return_value = MagicMock(topics={"orders": self._topic_metadata()})+ consumer.get_watermark_offsets.return_value = (3, 5)+ cursor = MagicMock()+ cursor.load.return_value = KafkaCursor(offsets={"0": 100}, topic_id="old-topic-id")+ with (+ patch(f"{_MODULE}.fetch_cluster", return_value=KafkaCluster(topics=["orders"])),+ patch(f"{_MODULE}.Consumer", return_value=consumer),+ patch(f"{_MODULE}.AdminClient", return_value=self._topic_description("new-topic-id")),+ ):+ response = kafka_source(_config(), "orders", 1, cursor, True, MagicMock())++ assert response.destination_reset_required is True+ assert response.rows_to_sync == 2+++class TestClientConfig:+ @parameterized.expand(+ [+ ("sasl_plain", "tls", "SASL_SSL", "PLAIN"),+ ("sasl_scram_sha_512", "tls", "SASL_SSL", "SCRAM-SHA-512"),+ ("sasl_scram_sha_256", "none", "SASL_PLAINTEXT", "SCRAM-SHA-256"),+ ("none", "tls", "SSL", None),+ ("none", "none", "PLAINTEXT", None),+ ]+ )+ def test_security_protocol(self, selection: str, encryption: str, protocol: str, mechanism: str | None) -> None:+ config = _config(+ authentication={"selection": selection, "username": "key", "password": "secret"}, encryption=encryption+ )+ client_config = build_client_config(config, MagicMock())+ assert client_config["security.protocol"] == protocol+ assert client_config.get("sasl.mechanism") == mechanism++ def test_ca_certificate_is_passed_as_pem(self) -> None:+ client_config = build_client_config(_config(ca_certificate="-----BEGIN CERTIFICATE-----"), MagicMock())+ assert client_config["ssl.ca.pem"] == "-----BEGIN CERTIFICATE-----"++ def test_sasl_without_credentials_is_rejected(self) -> None:+ with pytest.raises(KafkaSourceError, match=re.escape(MISSING_SASL_CREDENTIALS_MESSAGE)):+ build_client_config(_config(authentication={"selection": "sasl_plain"}), MagicMock())+++ [+ ("host_and_port_list", "a.example.com:9092, b.example.com:9093", ["a.example.com", "b.example.com"]),+ ("listener_scheme", "SASL_SSL://a.example.com:9092", ["a.example.com"]),+ ("ipv6", "[2001:db8::1]:9092", ["2001:db8::1"]),+ ("no_port", "a.example.com", ["a.example.com"]),+ ("trailing_comma", "a.example.com:9092,", ["a.example.com"]),+ ]+)+def test_parse_bootstrap_hosts(_name: str, servers: str, expected: list[str]) -> None:+ assert parse_bootstrap_hosts(servers) == expected+++class TestFetchCluster:+ @staticmethod+ def _metadata(topics: dict[str, Any], broker_hosts: list[str]) -> MagicMock:+ return MagicMock(+ topics={name: MagicMock(error=error) for name, error in topics.items()},+ brokers={index: MagicMock(host=host) for index, host in enumerate(broker_hosts)},+ )++ @staticmethod+ def _resolve(private_hosts: set[str]) -> Any:+ def resolve(host: str, team_id: int) -> HostResolution:+ if host in private_hosts:+ return HostResolution(connect_host=None, error="This host points to an internal or private IP address")+ return HostResolution(connect_host=host, error=None)++ return resolve++ def test_lists_readable_topics_without_internal_ones(self) -> None:+ metadata = self._metadata(+ {"orders": None, "__consumer_offsets": None, "_schemas": None, "broken": KafkaError(3), "clicks": None},+ ["broker.example.com"],+ )+ with (+ patch(f"{_MODULE}.AdminClient") as admin,+ patch(f"{_MODULE}.resolve_safe_host", side_effect=self._resolve(set())),+ ):+ admin.return_value.list_topics.return_value = metadata+ assert fetch_cluster(_config(), team_id=1).topics == ["clicks", "orders"]++ def test_a_private_advertised_broker_is_rejected(self) -> None:+ # The bootstrap host is public, but the metadata it returns points the client at a private address.+ metadata = self._metadata({"orders": None}, ["10.0.0.5"])+ with (+ patch(f"{_MODULE}.AdminClient") as admin,+ patch(f"{_MODULE}.resolve_safe_host", side_effect=self._resolve({"10.0.0.5"})),+ ):+ admin.return_value.list_topics.return_value = metadata+ with pytest.raises(HostNotAllowedError):+ fetch_cluster(_config(), team_id=1)++ def test_cloud_teams_are_rejected_before_connecting(self) -> None:+ with (+ patch(f"{_MODULE}.is_cloud", return_value=True),+ patch(f"{_MODULE}.is_team_allowlisted_for_internal_hosts", return_value=False),+ patch(f"{_MODULE}.AdminClient") as admin,+ ):+ with pytest.raises(HostNotAllowedError, match=re.escape(KAFKA_CLOUD_UNAVAILABLE_MESSAGE)):+ fetch_cluster(_config(), team_id=1)+ admin.assert_not_called()++ def test_a_private_bootstrap_host_is_rejected_before_connecting(self) -> None:+ with (+ patch(f"{_MODULE}.AdminClient") as admin,+ patch(f"{_MODULE}.resolve_safe_host", side_effect=self._resolve({"broker.example.com"})),+ ):+ with pytest.raises(HostNotAllowedError):+ fetch_cluster(_config(), team_id=1)+ admin.assert_not_called()++ @parameterized.expand(+ [+ ("authentication_failure", KafkaError._AUTHENTICATION, AUTHENTICATION_FAILED_MESSAGE), # type: ignore[attr-defined]+ ("unreachable_brokers", KafkaError._TRANSPORT, UNREACHABLE_MESSAGE), # type: ignore[attr-defined]+ ]+ )+ def test_a_failed_metadata_request_is_named_by_the_client_errors(+ self, _name: str, reported_code: int, expected_message: str+ ) -> None:+ def admin_client(client_config: dict[str, Any]) -> MagicMock:+ def list_topics(timeout: float) -> None:+ client_config["error_cb"](KafkaError(reported_code))+ raise KafkaException(KafkaError(KafkaError._TIMED_OUT)) # type: ignore[attr-defined]++ return MagicMock(list_topics=list_topics)++ with (+ patch(f"{_MODULE}.AdminClient", side_effect=admin_client),+ patch(f"{_MODULE}.resolve_safe_host", side_effect=self._resolve(set())),+ ):+ with pytest.raises(KafkaSourceError, match=re.escape(expected_message)):+ fetch_cluster(_config(), team_id=1)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka_source.pynew file mode 100644index 000000000000..cbb5f8ace1c3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/kafka/tests/test_kafka_source.py@@ -0,0 +1,57 @@+from unittest.mock import patch++from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ HostNotAllowedError,+ TemporaryHostResolutionError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.kafka import KafkaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.kafka import (+ NO_TOPICS_MESSAGE,+ TOPIC_NOT_FOUND_MESSAGE,+ UNREACHABLE_MESSAGE,+ KafkaCluster,+ KafkaSourceError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.kafka.source import KafkaSource++_FETCH_CLUSTER = "products.warehouse_sources.backend.temporal.data_imports.sources.kafka.source.fetch_cluster"++_CONFIG = KafkaSourceConfig.from_dict(+ {"bootstrap_servers": "broker.example.com:9092", "authentication": {"selection": "none"}}+)+++def test_kafka_requires_incremental_merge() -> None:+ with patch(_FETCH_CLUSTER, return_value=KafkaCluster(topics=["orders"])):+ schema = KafkaSource().get_schemas(_CONFIG, team_id=1)[0]+ assert schema.supports_incremental is True+ assert schema.supports_append is False+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("topics_visible", KafkaCluster(topics=["orders"]), None, (True, None)),+ ("no_topics_visible", KafkaCluster(topics=[]), None, (False, NO_TOPICS_MESSAGE)),+ ("schema_topic_exists", KafkaCluster(topics=["orders"]), "orders", (True, None)),+ ("schema_topic_gone", KafkaCluster(topics=["orders"]), "clicks", (False, TOPIC_NOT_FOUND_MESSAGE)),+ ]+ )+ def test_cluster_contents(+ self, _name: str, cluster: KafkaCluster, schema_name: str | None, expected: tuple[bool, str | None]+ ) -> None:+ with patch(_FETCH_CLUSTER, return_value=cluster):+ assert KafkaSource().validate_credentials(_CONFIG, team_id=1, schema_name=schema_name) == expected++ @parameterized.expand(+ [+ ("unreachable", KafkaSourceError(UNREACHABLE_MESSAGE)),+ ("private_host", HostNotAllowedError("Database host not allowed: private")),+ ("resolver_outage", TemporaryHostResolutionError("broker.example.com")),+ ]+ )+ def test_a_connection_failure_is_reported_not_raised(self, _name: str, error: Exception) -> None:+ with patch(_FETCH_CLUSTER, side_effect=error):+ assert KafkaSource().validate_credentials(_CONFIG, team_id=1) == (False, str(error))diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex 4a0da2dd1b3e..57553f49c067 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -938,6 +938,7 @@ async def _run(source_cursor_manager: SourceCursorManager[Any] | None = None,) -> PipelineResult:try:+ reset_pipeline = reset_pipeline or source_response.destination_reset_requiredmodels = await _get_models(job_inputs.run_id)use_v3 = models.job.pipeline_version == ExternalDataJob.PipelineVersion.V3diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 7e13b9866d7d..c9743feeac5b 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -6576,6 +6576,63 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["password"] == "new_password"mock_validate_credentials.assert_called_once()+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.kafka.source.KafkaSource.validate_credentials",+ return_value=(True, None),+ )+ def test_kafka_host_change_requires_nested_password(self, mock_validate_credentials):+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Kafka",+ created_by=self.user,+ prefix="test_kafka_nested_secret",+ job_inputs={+ "source_type": "Kafka",+ "bootstrap_servers": "broker.example.com:9092",+ "authentication": {+ "selection": "sasl_plain",+ "username": "api-key",+ "password": "stored-secret",+ },+ "encryption": "tls",+ "value_format": "json",+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"bootstrap_servers": "attacker.example.com:9092"}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["bootstrap_servers"] == "broker.example.com:9092"+ mock_validate_credentials.assert_not_called()++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={+ "job_inputs": {+ "bootstrap_servers": "new-broker.example.com:9092",+ "authentication": {+ "selection": "sasl_plain",+ "username": "api-key",+ "password": "new-secret",+ },+ }+ },+ )++ assert response.status_code == 200, response.json()+ source.refresh_from_db()+ assert source.job_inputs["bootstrap_servers"] == "new-broker.example.com:9092"+ assert source.job_inputs["authentication"]["password"] == "new-secret"+ mock_validate_credentials.assert_called_once()+@patch("products.warehouse_sources.backend.temporal.data_imports.sources.billomat.source.BillomatSource.validate_credentials",return_value=(True, None),@@ -6812,6 +6869,37 @@ class TestExternalDataSource(APIBaseTest):assert source.job_inputs["api_key"] == "new_key"mock_validate_credentials.assert_called_once()+ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.kafka.source.KafkaSource.validate_credentials",+ return_value=(True, None),+ )+ def test_update_kafka_bootstrap_servers_without_nested_password_is_rejected(self, mock_validate_credentials):+ source = ExternalDataSource.objects.create(+ team_id=self.team.pk,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ destination_id=str(uuid.uuid4()),+ source_type="Kafka",+ created_by=self.user,+ prefix="kafka_src",+ job_inputs={+ "bootstrap_servers": "broker.example.com:9092",+ "authentication": {"selection": "sasl_plain", "username": "key", "password": "secret"},+ },+ )++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/",+ data={"job_inputs": {"bootstrap_servers": "attacker.example.com:9092"}},+ )++ assert response.status_code == 400+ assert "re-entering your credentials" in str(response.json())+ source.refresh_from_db()+ assert source.job_inputs["bootstrap_servers"] == "broker.example.com:9092"+ assert source.job_inputs["authentication"]["password"] == "secret"+ mock_validate_credentials.assert_not_called()+def _servicenow_source(self) -> ExternalDataSource:# ServiceNow's connection target is `instance_url` (not a top-level `host`) and its# secret lives nested inside the `auth_method` container.