You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by gi...@apache.org on 2026/09/10 15:55:33 UTC
(seatunnel) 01/01: [Feature][Connector-V2] Support Kafka source connectivity dry-run (#12167)
This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-12167-8571a19add35a0085d96340eb51902f530130cf2
in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit 38385ea1f0fe4fefa3478e08478452adc437f362
Author: Goutam Adwant <86...@users.noreply.github.com>
AuthorDate: Thu Sep 10 15:40:27 2026 +0000
[Feature][Connector-V2] Support Kafka source connectivity dry-run (#12167)
Signed-off-by: Goutam Adwant <wo...@gmail.com>
---
docs/en/connectors/source/Kafka.md | 21 +
docs/en/engines/zeta/user-command.md | 1 +
docs/zh/connectors/source/Kafka.md | 20 +
docs/zh/engines/zeta/user-command.md | 1 +
.../kafka/source/KafkaSourceDryRunValidator.java | 139 ++++++
.../seatunnel/kafka/source/KafkaSourceFactory.java | 21 +-
.../seatunnel/kafka/KafkaFactoryTest.java | 11 +
.../source/KafkaSourceDryRunValidatorTest.java | 512 +++++++++++++++++++++
.../e2e/connector/kafka/KafkaConnectDryRunIT.java | 209 +++++++++
9 files changed, 934 insertions(+), 1 deletion(-)
diff --git a/docs/en/connectors/source/Kafka.md b/docs/en/connectors/source/Kafka.md
index dd5b05e908..b282bf42f5 100644
--- a/docs/en/connectors/source/Kafka.md
+++ b/docs/en/connectors/source/Kafka.md
@@ -23,6 +23,27 @@ import ChangeLog from '../changelog/connector-kafka.md';
Source connector for Apache Kafka.
+### Connectivity dry-run
+
+Zeta's `--dry-run connect` validates the Kafka source using only topic metadata. It uses the configured
+`bootstrap.servers` and `kafka.config` security settings, checks explicit topics with `describeTopics`,
+and resolves `pattern = true` with the same full-name matching as normal execution. Both
+`tables_configs` and the legacy `table_list` are supported. Output schemas, including native fields,
+Kafka header fields and event-time metadata, are inferred through the normal source configuration path.
+
+Metadata requests share a 30-second time budget; a smaller `kafka.config.default.api.timeout.ms`
+is honored. The request timeout is capped by this budget and client cleanup has a bounded wait.
+As in normal Kafka startup, an explicitly configured API timeout must not be smaller than the
+configured (or Kafka-default) `request.timeout.ms` before these dry-run limits are applied.
+Client setup, including DNS and authentication-provider initialization, can take additional time.
+Normal job execution and its timeouts are unchanged. No consumer or producer is created, no records
+are read or written, no consumer offsets are accessed or committed, and missing topics are not created.
+
+Successful validation proves metadata access, **not** permission to consume records, access a consumer
+group, or deserialize actual messages. A pattern with no currently visible matches is allowed, as it
+is at runtime; validation in that case checks topic listing only, not access to future topics. Kafka
+sinks remain unsupported by connectivity dry-run.
+
## Supported DataSource Info
In order to use the Kafka connector, the following dependencies are required.
diff --git a/docs/en/engines/zeta/user-command.md b/docs/en/engines/zeta/user-command.md
index 6c238e965e..433f5517af 100644
--- a/docs/en/engines/zeta/user-command.md
+++ b/docs/en/engines/zeta/user-command.md
@@ -81,6 +81,7 @@ The `--dry-run connect` option runs the static checks first, then uses connector
| Connector | Source | Sink |
|-----------|--------|------|
| Jdbc | Yes (connectivity + schema inference) | Yes (connectivity + table existence + field compatibility) |
+| Kafka | Yes ([topic metadata + runtime output schema](../../connectors/source/Kafka.md#connectivity-dry-run), not consumer/group permissions) | No |
| FakeSource | Yes (schema inference only, no external system) | - |
Every plugin in the job is reported in a validation summary with one of two statuses:
diff --git a/docs/zh/connectors/source/Kafka.md b/docs/zh/connectors/source/Kafka.md
index 8b8efaffdb..3d064dbe83 100644
--- a/docs/zh/connectors/source/Kafka.md
+++ b/docs/zh/connectors/source/Kafka.md
@@ -23,6 +23,26 @@ import ChangeLog from '../changelog/connector-kafka.md';
用于 Apache Kafka 的源连接器。
+### 连通性 dry-run
+
+Zeta 的 `--dry-run connect` 仅通过主题元数据校验 Kafka source。它使用配置的
+`bootstrap.servers` 和 `kafka.config` 安全设置,通过 `describeTopics` 检查显式主题,
+并对 `pattern = true` 使用与正常运行一致的主题全名匹配规则。支持 `tables_configs`
+及旧版 `table_list`。输出 schema 复用正常 source 配置路径,包括 native 字段、Kafka
+header 字段和事件时间元数据。
+
+元数据请求共享 30 秒的时间预算;如果 `kafka.config.default.api.timeout.ms` 更小,
+则使用该值。请求超时不会超过此预算,客户端清理也使用有界等待。与 Kafka 正常启动一致,
+在应用 dry-run 限制之前,显式配置的 API 超时不得小于配置值或 Kafka 默认值的
+`request.timeout.ms`。客户端初始化(包括 DNS
+和认证提供方初始化)可能需要额外时间。正常作业运行及其超时
+配置保持不变。校验不会创建 consumer 或 producer,不会读写消息、访问或提交消费位点,
+也不会创建缺失的主题。
+
+校验成功仅证明可以访问元数据,**不代表**具备消费消息、访问消费组或反序列化实际消息
+的能力。与运行时一致,允许正则表达式当前没有可见的匹配主题;此时仅校验主题列表访问,
+不验证未来主题的访问权限。Kafka sink 仍不支持连通性 dry-run。
+
## 支持的数据源信息
使用 Kafka 连接器需要以下依赖项。
diff --git a/docs/zh/engines/zeta/user-command.md b/docs/zh/engines/zeta/user-command.md
index 6c4f271f59..cded907c75 100644
--- a/docs/zh/engines/zeta/user-command.md
+++ b/docs/zh/engines/zeta/user-command.md
@@ -97,6 +97,7 @@ bin/seatunnel.sh --config $SEATUNNEL_HOME/config/v2.batch.config.template --dry-
| 连接器 | Source | Sink |
|--------|--------|------|
| Jdbc | 支持(连通性 + schema 推断) | 支持(连通性 + 表存在性 + 字段兼容性) |
+| Kafka | 支持([主题元数据 + 运行时输出 schema](../../connectors/source/Kafka.md#连通性-dry-run),不含消费或消费组权限) | 不支持 |
| FakeSource | 支持(仅 schema 推断,无外部系统) | - |
作业中的每个插件都会在校验汇总中报告以下两种状态之一:
diff --git a/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidator.java b/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidator.java
new file mode 100644
index 0000000000..0872625cce
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidator.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.kafka.source;
+
+import org.apache.seatunnel.common.utils.TemporaryClassLoaderContext;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.AdminClientConfig;
+import org.apache.kafka.clients.admin.DescribeTopicsOptions;
+import org.apache.kafka.clients.admin.ListTopicsOptions;
+import org.apache.kafka.common.KafkaFuture;
+import org.apache.kafka.common.config.ConfigException;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.regex.Pattern;
+
+/** Metadata-only validation, isolated from the Kafka source runtime and its offset handling. */
+final class KafkaSourceDryRunValidator {
+
+ private static final int MAX_TIMEOUT_MS = 30_000;
+
+ private KafkaSourceDryRunValidator() {}
+
+ static void validate(KafkaSourceConfig config) throws Exception {
+ if (Thread.currentThread().isInterrupted()) {
+ throw new InterruptedException("Kafka connect dry-run interrupted");
+ }
+ Set<String> topics = new HashSet<>();
+ List<Pattern> patterns = new ArrayList<>();
+ for (ConsumerMetadata metadata : config.getMapMetadata().values()) {
+ if (metadata.isPattern()) {
+ patterns.add(Pattern.compile(metadata.getTopic()));
+ } else {
+ topics.addAll(Arrays.asList(metadata.getTopic().split(",")));
+ }
+ }
+ if (topics.isEmpty() && patterns.isEmpty()) {
+ throw new IllegalArgumentException("Kafka connect dry-run requires at least one topic");
+ }
+
+ Properties properties = new Properties();
+ properties.putAll(config.getProperties());
+ // Match the runtime enumerator: the connector bootstrap option takes precedence.
+ properties.setProperty(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, config.getBootstrap());
+ try (TemporaryClassLoaderContext ignored =
+ TemporaryClassLoaderContext.of(KafkaSourceDryRunValidator.class.getClassLoader())) {
+ AdminClientConfig adminConfig = new AdminClientConfig(properties);
+ int apiTimeoutMs = adminConfig.getInt(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG);
+ int requestTimeoutMs = adminConfig.getInt(AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG);
+ // Preserve Kafka's original validation before applying dry-run limits: an explicit API
+ // timeout below the request timeout also fails during normal source startup.
+ if (properties.containsKey(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG)
+ && apiTimeoutMs < requestTimeoutMs) {
+ throw new ConfigException(
+ AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG
+ + " must not be smaller than "
+ + AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG);
+ }
+ int timeoutMs = Math.min(MAX_TIMEOUT_MS, Math.max(apiTimeoutMs, requestTimeoutMs));
+ properties.put(AdminClientConfig.DEFAULT_API_TIMEOUT_MS_CONFIG, timeoutMs);
+ properties.put(
+ AdminClientConfig.REQUEST_TIMEOUT_MS_CONFIG,
+ Math.min(timeoutMs, requestTimeoutMs));
+
+ long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeoutMs);
+ AdminClient admin = AdminClient.create(properties);
+ try {
+ if (!patterns.isEmpty()) {
+ Set<String> visibleTopics =
+ await(
+ admin.listTopics(
+ new ListTopicsOptions()
+ .timeoutMs(remainingMillis(deadline)))
+ .names(),
+ deadline);
+ for (String topic : visibleTopics) {
+ if (patterns.stream()
+ .anyMatch(pattern -> pattern.matcher(topic).matches())) {
+ topics.add(topic);
+ }
+ }
+ }
+ // An empty pattern match is valid for a source waiting for future topics.
+ if (!topics.isEmpty()) {
+ await(
+ admin.describeTopics(
+ topics,
+ new DescribeTopicsOptions()
+ .timeoutMs(remainingMillis(deadline)))
+ .allTopicNames(),
+ deadline);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ throw e;
+ } finally {
+ // Kafka 3.4 uses Thread.join(timeout): zero would mean an unbounded close wait.
+ admin.close(Duration.ofMillis(1));
+ }
+ }
+ }
+
+ private static int remainingMillis(long deadline) throws TimeoutException {
+ long remaining = deadline - System.nanoTime();
+ if (remaining <= 0) {
+ throw new TimeoutException("Kafka connect dry-run metadata check timed out");
+ }
+ return (int) Math.max(1, TimeUnit.NANOSECONDS.toMillis(remaining));
+ }
+
+ private static <T> T await(KafkaFuture<T> future, long deadline)
+ throws ExecutionException, InterruptedException, TimeoutException {
+ return future.get(remainingMillis(deadline), TimeUnit.MILLISECONDS);
+ }
+}
diff --git a/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceFactory.java b/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceFactory.java
index 716163446e..8c820597a3 100644
--- a/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceFactory.java
+++ b/seatunnel-connectors-v2/connector-kafka/src/main/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceFactory.java
@@ -24,8 +24,10 @@ import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.api.configuration.util.OptionValidationException;
import org.apache.seatunnel.api.source.SeaTunnelSource;
import org.apache.seatunnel.api.source.SourceSplit;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
import org.apache.seatunnel.api.table.connector.TableSource;
import org.apache.seatunnel.api.table.factory.Factory;
+import org.apache.seatunnel.api.table.factory.SupportSourceDryRunValidation;
import org.apache.seatunnel.api.table.factory.TableSourceFactory;
import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
import org.apache.seatunnel.connectors.seatunnel.kafka.config.KafkaSourceOptions;
@@ -37,9 +39,10 @@ import com.google.auto.service.AutoService;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
@AutoService(Factory.class)
-public class KafkaSourceFactory implements TableSourceFactory {
+public class KafkaSourceFactory implements TableSourceFactory, SupportSourceDryRunValidation {
@Override
public String factoryIdentifier() {
@@ -115,6 +118,22 @@ public class KafkaSourceFactory implements TableSourceFactory {
return KafkaSource.class;
}
+ /** Reuses runtime schema construction without creating a source or contacting Kafka. */
+ @Override
+ public List<CatalogTable> inferSchemaForDryRun(TableSourceFactoryContext context) {
+ return new KafkaSourceConfig(context.getOptions())
+ .getMapMetadata().values().stream()
+ .map(ConsumerMetadata::getCatalogTable)
+ .collect(Collectors.toList());
+ }
+
+ /** Checks topic metadata only; does not consume records or access consumer offsets. */
+ @Override
+ public void validateConnectionForDryRun(
+ TableSourceFactoryContext context, List<CatalogTable> catalogTables) throws Exception {
+ KafkaSourceDryRunValidator.validate(new KafkaSourceConfig(context.getOptions()));
+ }
+
private static class KafkaPartitionDiscoveryValidator implements ConditionExtension<Boolean> {
@Override
public String description() {
diff --git a/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/KafkaFactoryTest.java b/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/KafkaFactoryTest.java
index 6af5fa7937..b738375af4 100644
--- a/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/KafkaFactoryTest.java
+++ b/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/KafkaFactoryTest.java
@@ -21,6 +21,9 @@ import org.apache.seatunnel.api.configuration.ReadonlyConfig;
import org.apache.seatunnel.api.configuration.util.ConfigValidator;
import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.api.configuration.util.OptionValidationException;
+import org.apache.seatunnel.api.table.factory.FactoryUtil;
+import org.apache.seatunnel.api.table.factory.SupportSourceDryRunValidation;
+import org.apache.seatunnel.api.table.factory.TableSourceFactory;
import org.apache.seatunnel.connectors.seatunnel.kafka.sink.KafkaSinkFactory;
import org.apache.seatunnel.connectors.seatunnel.kafka.source.KafkaSourceFactory;
@@ -66,6 +69,14 @@ class KafkaFactoryTest {
return cfg;
}
+ @Test
+ void testSourceSupportsConnectDryRun() {
+ Assertions.assertTrue(
+ FactoryUtil.discoverFactory(
+ getClass().getClassLoader(), TableSourceFactory.class, "Kafka")
+ instanceof SupportSourceDryRunValidation);
+ }
+
@Test
void optionRule() {
Assertions.assertNotNull((new KafkaSourceFactory()).optionRule());
diff --git a/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidatorTest.java b/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidatorTest.java
new file mode 100644
index 0000000000..4150b5c219
--- /dev/null
+++ b/seatunnel-connectors-v2/connector-kafka/src/test/java/org/apache/seatunnel/connectors/seatunnel/kafka/source/KafkaSourceDryRunValidatorTest.java
@@ -0,0 +1,512 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.connectors.seatunnel.kafka.source;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.catalog.CatalogTable;
+import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
+import org.apache.seatunnel.api.table.type.BasicType;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.DescribeTopicsOptions;
+import org.apache.kafka.clients.admin.DescribeTopicsResult;
+import org.apache.kafka.clients.admin.ListTopicsOptions;
+import org.apache.kafka.clients.admin.ListTopicsResult;
+import org.apache.kafka.clients.admin.TopicDescription;
+import org.apache.kafka.common.KafkaFuture;
+import org.apache.kafka.common.config.ConfigException;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.TopicAuthorizationException;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.apache.kafka.common.internals.KafkaFutureImpl;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedStatic;
+
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.regex.PatternSyntaxException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.anySet;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.mockito.Mockito.when;
+
+class KafkaSourceDryRunValidatorTest {
+
+ private final KafkaSourceFactory factory = new KafkaSourceFactory();
+
+ @Test
+ void testLiteralTopicsUseOnlyMetadataAndPreserveClientConfiguration() throws Exception {
+ Map<String, Object> options = options("orders,customers");
+ Map<String, Object> kafkaConfig = new HashMap<>();
+ kafkaConfig.put("bootstrap.servers", "ignored:9092");
+ kafkaConfig.put("security.protocol", "SASL_SSL");
+ kafkaConfig.put("sasl.mechanism", "PLAIN");
+ kafkaConfig.put("sasl.jaas.config", "synthetic-jaas-config");
+ kafkaConfig.put("client.id", "configured-client");
+ kafkaConfig.put("default.api.timeout.ms", "120000");
+ kafkaConfig.put("request.timeout.ms", "60000");
+ options.put("kafka.config", kafkaConfig);
+ AdminClient admin = mock(AdminClient.class);
+ describe(admin, KafkaFuture.completedFuture(Collections.emptyMap()));
+ Properties properties = new Properties();
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader caller = new ClassLoader(original) {};
+ Thread.currentThread().setContextClassLoader(caller);
+ try (MockedStatic<AdminClient> clients = createClient(admin, properties)) {
+ doAnswer(
+ invocation -> {
+ assertSame(
+ KafkaSourceFactory.class.getClassLoader(),
+ Thread.currentThread().getContextClassLoader());
+ return null;
+ })
+ .when(admin)
+ .close(any(Duration.class));
+ validate(options);
+ assertSame(caller, Thread.currentThread().getContextClassLoader());
+ assertEquals("localhost:9092", properties.get("bootstrap.servers"));
+ for (String key :
+ Arrays.asList(
+ "security.protocol",
+ "sasl.mechanism",
+ "sasl.jaas.config",
+ "client.id")) {
+ assertEquals(kafkaConfig.get(key), properties.get(key));
+ }
+ assertEquals(30000, properties.get("default.api.timeout.ms"));
+ assertEquals(30000, properties.get("request.timeout.ms"));
+ assertEquals("120000", kafkaConfig.get("default.api.timeout.ms"));
+ assertEquals("ignored:9092", kafkaConfig.get("bootstrap.servers"));
+ ArgumentCaptor<DescribeTopicsOptions> request =
+ ArgumentCaptor.forClass(DescribeTopicsOptions.class);
+ verify(admin)
+ .describeTopics(
+ eq(new HashSet<>(Arrays.asList("orders", "customers"))),
+ request.capture());
+ assertTrue(request.getValue().timeoutMs() > 0);
+ assertTrue(request.getValue().timeoutMs() <= 30000);
+ verify(admin).close(Duration.ofMillis(1));
+ verifyNoMoreInteractions(admin);
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"tables_configs", "table_list"})
+ void testMixedTableTopicsAndPatternsUseRuntimeMatching(String tableOption) throws Exception {
+ Map<String, Object> options = options("unused");
+ options.remove("topic");
+ Map<String, Object> pattern = new HashMap<>();
+ pattern.put("topic", "orders-[0-9]+");
+ pattern.put("pattern", true);
+ options.put(
+ tableOption,
+ Arrays.asList(Collections.singletonMap("topic", "fixed,orders-1"), pattern));
+ AdminClient admin = mock(AdminClient.class);
+ list(admin, new HashSet<>(Arrays.asList("orders-1", "orders-2", "prefix-orders-3")));
+ describe(admin, KafkaFuture.completedFuture(Collections.emptyMap()));
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ validate(options);
+ ArgumentCaptor<ListTopicsOptions> request =
+ ArgumentCaptor.forClass(ListTopicsOptions.class);
+ verify(admin).listTopics(request.capture());
+ assertFalse(request.getValue().shouldListInternal());
+ verify(admin)
+ .describeTopics(
+ eq(new HashSet<>(Arrays.asList("fixed", "orders-1", "orders-2"))),
+ any(DescribeTopicsOptions.class));
+ verify(admin).close(Duration.ofMillis(1));
+ verifyNoMoreInteractions(admin);
+ }
+ }
+
+ @Test
+ void testPatternWithoutCurrentMatchesStillChecksConnectivity() throws Exception {
+ Map<String, Object> options = options("future-.*");
+ options.put("pattern", true);
+ AdminClient admin = mock(AdminClient.class);
+ list(admin, Collections.singleton("other"));
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ validate(options);
+ verify(admin).listTopics(any(ListTopicsOptions.class));
+ verify(admin).close(Duration.ofMillis(1));
+ verifyNoMoreInteractions(admin);
+ }
+ }
+
+ @Test
+ void testMetadataFailuresPropagateAndCloseClient() {
+ for (RuntimeException failure :
+ Arrays.asList(
+ new AuthenticationException("authentication failed"),
+ new TopicAuthorizationException(Collections.singleton("orders")),
+ new UnknownTopicOrPartitionException("missing topic"))) {
+ AdminClient admin = mock(AdminClient.class);
+ KafkaFutureImpl<Map<String, TopicDescription>> future = new KafkaFutureImpl<>();
+ future.completeExceptionally(failure);
+ describe(admin, future);
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ ExecutionException exception =
+ assertThrows(ExecutionException.class, () -> validate(options("orders")));
+ assertSame(failure, exception.getCause());
+ verify(admin).close(Duration.ofMillis(1));
+ }
+ }
+ }
+
+ @Test
+ void testPatternListingFailureDoesNotDescribeTopics() {
+ AdminClient admin = mock(AdminClient.class);
+ ListTopicsResult result = mock(ListTopicsResult.class);
+ KafkaFutureImpl<Set<String>> future = new KafkaFutureImpl<>();
+ future.completeExceptionally(new AuthenticationException("authentication failed"));
+ when(admin.listTopics(any(ListTopicsOptions.class))).thenReturn(result);
+ when(result.names()).thenReturn(future);
+ Map<String, Object> options = options("orders-.*");
+ options.put("pattern", true);
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ assertThrows(ExecutionException.class, () -> validate(options));
+ verify(admin, never()).describeTopics(anySet(), any(DescribeTopicsOptions.class));
+ verify(admin).close(Duration.ofMillis(1));
+ }
+ }
+
+ @Test
+ void testMetadataWaitHonorsSmallerConfiguredDeadline() throws Exception {
+ AdminClient admin = mock(AdminClient.class);
+ KafkaFuture<Map<String, TopicDescription>> future = mock(KafkaFuture.class);
+ when(future.get(anyLong(), eq(TimeUnit.MILLISECONDS)))
+ .thenThrow(new TimeoutException("metadata wait timed out"));
+ describe(admin, future);
+ Properties properties = new Properties();
+ Map<String, Object> options = options("orders");
+ Map<String, Object> kafkaConfig = new HashMap<>();
+ kafkaConfig.put("default.api.timeout.ms", 5000);
+ kafkaConfig.put("request.timeout.ms", 5000);
+ options.put("kafka.config", kafkaConfig);
+ try (MockedStatic<AdminClient> clients = createClient(admin, properties)) {
+ TimeoutException exception =
+ assertThrows(TimeoutException.class, () -> validate(options));
+ assertEquals("metadata wait timed out", exception.getMessage());
+ ArgumentCaptor<Long> timeout = ArgumentCaptor.forClass(Long.class);
+ verify(future).get(timeout.capture(), eq(TimeUnit.MILLISECONDS));
+ assertTrue(timeout.getValue() > 0);
+ assertTrue(timeout.getValue() <= 5000);
+ assertEquals(5000, properties.get("default.api.timeout.ms"));
+ assertEquals(5000, properties.get("request.timeout.ms"));
+ verify(admin).close(Duration.ofMillis(1));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"default.api.timeout.ms", "request.timeout.ms"})
+ void testTimeoutWhitespaceMatchesKafkaConfigurationParsing(String key) throws Exception {
+ Map<String, Object> options = options("orders");
+ Map<String, Object> kafkaConfig = new HashMap<>();
+ kafkaConfig.put("request.timeout.ms", 5000);
+ kafkaConfig.put(key, " 5000 ");
+ options.put("kafka.config", kafkaConfig);
+ AdminClient admin = mock(AdminClient.class);
+ describe(admin, KafkaFuture.completedFuture(Collections.emptyMap()));
+ Properties properties = new Properties();
+ try (MockedStatic<AdminClient> clients = createClient(admin, properties)) {
+ validate(options);
+ assertEquals(5000, properties.get(key));
+ verify(admin).close(Duration.ofMillis(1));
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"default.api.timeout.ms", "request.timeout.ms"})
+ void testInvalidTimeoutDoesNotCreateClient(String key) {
+ for (String value : Arrays.asList("-1", "invalid", "9999999999999")) {
+ Map<String, Object> options = options("orders");
+ options.put("kafka.config", Collections.singletonMap(key, value));
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ ConfigException exception =
+ assertThrows(ConfigException.class, () -> validate(options));
+ assertTrue(exception.getMessage().contains(key));
+ clients.verifyNoInteractions();
+ }
+ }
+ }
+
+ @Test
+ void testExplicitApiTimeoutBelowOriginalRequestTimeoutFailsBeforeClientCreation() {
+ for (Integer requestTimeout : Arrays.asList(null, 10000)) {
+ Map<String, Object> kafkaConfig = new HashMap<>();
+ kafkaConfig.put("default.api.timeout.ms", 5000);
+ if (requestTimeout != null) {
+ kafkaConfig.put("request.timeout.ms", requestTimeout);
+ }
+ Map<String, Object> options = options("orders");
+ options.put("kafka.config", kafkaConfig);
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ ConfigException exception =
+ assertThrows(ConfigException.class, () -> validate(options));
+ assertTrue(exception.getMessage().contains("default.api.timeout.ms"));
+ assertTrue(exception.getMessage().contains("request.timeout.ms"));
+ clients.verifyNoInteractions();
+ }
+ }
+ }
+
+ @Test
+ void testUnspecifiedApiTimeoutAllowsLongerRequestTimeoutBeforeCapping() throws Exception {
+ Map<String, Object> options = options("orders");
+ options.put("kafka.config", Collections.singletonMap("request.timeout.ms", 120000));
+ AdminClient admin = mock(AdminClient.class);
+ describe(admin, KafkaFuture.completedFuture(Collections.emptyMap()));
+ Properties properties = new Properties();
+ try (MockedStatic<AdminClient> clients = createClient(admin, properties)) {
+ validate(options);
+ assertEquals(30000, properties.get("default.api.timeout.ms"));
+ assertEquals(30000, properties.get("request.timeout.ms"));
+ }
+ }
+
+ @Test
+ void testMetadataFailureRestoresCallerClassLoader() {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ ClassLoader caller = new ClassLoader(original) {};
+ AdminClient admin = mock(AdminClient.class);
+ KafkaFutureImpl<Map<String, TopicDescription>> future = new KafkaFutureImpl<>();
+ future.completeExceptionally(new UnknownTopicOrPartitionException("missing topic"));
+ describe(admin, future);
+ Thread.currentThread().setContextClassLoader(caller);
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ assertThrows(ExecutionException.class, () -> validate(options("orders")));
+ assertSame(caller, Thread.currentThread().getContextClassLoader());
+ verify(admin).close(Duration.ofMillis(1));
+ } finally {
+ Thread.currentThread().setContextClassLoader(original);
+ }
+ }
+
+ @Test
+ void testInterruptionIsRestoredAndClientClosed() throws Exception {
+ AdminClient admin = mock(AdminClient.class);
+ KafkaFuture<Map<String, TopicDescription>> future = mock(KafkaFuture.class);
+ when(future.get(anyLong(), eq(TimeUnit.MILLISECONDS)))
+ .thenThrow(new InterruptedException());
+ describe(admin, future);
+ try (MockedStatic<AdminClient> clients = createClient(admin, new Properties())) {
+ try {
+ assertThrows(InterruptedException.class, () -> validate(options("orders")));
+ assertTrue(Thread.currentThread().isInterrupted());
+ verify(admin).close(Duration.ofMillis(1));
+ } finally {
+ Thread.interrupted();
+ }
+ }
+ }
+
+ @Test
+ void testAlreadyInterruptedDoesNotCreateClient() {
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ Thread.currentThread().interrupt();
+ try {
+ assertThrows(InterruptedException.class, () -> validate(options("orders")));
+ assertTrue(Thread.currentThread().isInterrupted());
+ clients.verifyNoInteractions();
+ } finally {
+ Thread.interrupted();
+ }
+ }
+ }
+
+ @Test
+ void testInvalidPatternAndEmptyTopicSetDoNotCreateClient() {
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ Map<String, Object> options = options("[");
+ options.put("pattern", true);
+ assertThrows(PatternSyntaxException.class, () -> validate(options));
+ assertThrows(IllegalArgumentException.class, () -> validate(options(",,")));
+ clients.verifyNoInteractions();
+ }
+ }
+
+ @Test
+ void testClientCreationFailureRestoresContextClassLoader() {
+ ClassLoader original = Thread.currentThread().getContextClassLoader();
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ clients.when(() -> AdminClient.create(any(Properties.class)))
+ .thenThrow(new IllegalArgumentException("invalid client configuration"));
+ assertThrows(IllegalArgumentException.class, () -> validate(options("orders")));
+ assertSame(original, Thread.currentThread().getContextClassLoader());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "json",
+ "text",
+ "native",
+ "canal_json",
+ "debezium_json",
+ "maxwell_json",
+ "ogg_json",
+ "compatible_kafka_connect_json"
+ })
+ void testInferredSchemaMatchesRuntimeIncludingHeadersAndEventTime(String format) {
+ Map<String, Object> options = options("orders");
+ options.put("format", format);
+ options.put(
+ "schema",
+ Collections.singletonMap("fields", Collections.singletonMap("id", "int")));
+ options.put("kafka_headers_fields", Collections.singletonList("trace_id"));
+ assertSchemaParity(options);
+ }
+
+ @Test
+ void testDefaultSchemaIsRealRuntimeContentSchema() {
+ List<CatalogTable> tables = assertSchemaParity(options("orders"));
+ assertEquals("content", tables.get(0).getSeaTunnelRowType().getFieldName(0));
+ assertEquals(BasicType.STRING_TYPE, tables.get(0).getSeaTunnelRowType().getFieldType(0));
+ }
+
+ @Test
+ void testAvroSchemaMatchesRuntime() {
+ Map<String, Object> options = options("orders");
+ options.put("format", "avro");
+ options.put(
+ "schema",
+ Collections.singletonMap("fields", Collections.singletonMap("id", "int")));
+ options.put(
+ "avro_schema",
+ "{\"type\":\"record\",\"name\":\"Order\",\"fields\":[{\"name\":\"id\",\"type\":\"int\"}]}");
+ options.put("strip_schema_registry_header", true);
+ assertSchemaParity(options);
+ }
+
+ @Test
+ void testProtobufSchemaMatchesRuntime() {
+ Map<String, Object> options = options("orders");
+ options.put("format", "protobuf");
+ options.put(
+ "schema",
+ Collections.singletonMap("fields", Collections.singletonMap("id", "int")));
+ options.put("protobuf_message_name", "Order");
+ options.put("protobuf_schema", "syntax = \"proto3\"; message Order { int32 id = 1; }");
+ assertSchemaParity(options);
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"tables_configs", "table_list"})
+ void testInferredMultiTableSchemasMatchRuntime(String tableOption) {
+ Map<String, Object> options = options("unused");
+ options.remove("topic");
+ Map<String, Object> second = new HashMap<>();
+ second.put("topic", "second");
+ second.put("format", "native");
+ options.put(tableOption, Arrays.asList(Collections.singletonMap("topic", "first"), second));
+ assertEquals(2, assertSchemaParity(options).size());
+ }
+
+ private List<CatalogTable> assertSchemaParity(Map<String, Object> options) {
+ ReadonlyConfig config = ReadonlyConfig.fromMap(options);
+ try (MockedStatic<AdminClient> clients = mockStatic(AdminClient.class)) {
+ List<CatalogTable> inferred =
+ factory.inferSchemaForDryRun(
+ new TableSourceFactoryContext(config, getClass().getClassLoader()));
+ List<CatalogTable> runtime = new KafkaSource(config).getProducedCatalogTables();
+ assertEquals(runtime.size(), inferred.size());
+ for (int i = 0; i < runtime.size(); i++) {
+ CatalogTable expected = runtime.get(i);
+ CatalogTable actual = inferred.get(i);
+ assertEquals(expected.getTableId(), actual.getTableId());
+ assertEquals(expected.getTableSchema(), actual.getTableSchema());
+ assertEquals(expected.getSeaTunnelRowType(), actual.getSeaTunnelRowType());
+ assertEquals(expected.getMetadataSchema(), actual.getMetadataSchema());
+ assertEquals(expected.getOptions(), actual.getOptions());
+ assertEquals(expected.getPartitionKeys(), actual.getPartitionKeys());
+ }
+ clients.verifyNoInteractions();
+ return inferred;
+ }
+ }
+
+ private void validate(Map<String, Object> options) throws Exception {
+ TableSourceFactoryContext context =
+ new TableSourceFactoryContext(
+ ReadonlyConfig.fromMap(options), getClass().getClassLoader());
+ factory.validateConnectionForDryRun(context, factory.inferSchemaForDryRun(context));
+ }
+
+ private Map<String, Object> options(String topic) {
+ Map<String, Object> options = new HashMap<>();
+ options.put("bootstrap.servers", "localhost:9092");
+ options.put("topic", topic);
+ return options;
+ }
+
+ private MockedStatic<AdminClient> createClient(AdminClient admin, Properties captured) {
+ MockedStatic<AdminClient> clients = mockStatic(AdminClient.class);
+ clients.when(() -> AdminClient.create(any(Properties.class)))
+ .thenAnswer(
+ invocation -> {
+ assertSame(
+ KafkaSourceFactory.class.getClassLoader(),
+ Thread.currentThread().getContextClassLoader());
+ captured.putAll(invocation.getArgument(0));
+ return admin;
+ });
+ return clients;
+ }
+
+ private void describe(AdminClient admin, KafkaFuture<Map<String, TopicDescription>> future) {
+ DescribeTopicsResult result = mock(DescribeTopicsResult.class);
+ when(admin.describeTopics(anySet(), any(DescribeTopicsOptions.class))).thenReturn(result);
+ when(result.allTopicNames()).thenReturn(future);
+ }
+
+ private void list(AdminClient admin, Set<String> topics) {
+ ListTopicsResult result = mock(ListTopicsResult.class);
+ when(admin.listTopics(any(ListTopicsOptions.class))).thenReturn(result);
+ when(result.names()).thenReturn(KafkaFuture.completedFuture(topics));
+ }
+}
diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaConnectDryRunIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaConnectDryRunIT.java
new file mode 100644
index 0000000000..2418ac316d
--- /dev/null
+++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-kafka-e2e/src/test/java/org/apache/seatunnel/e2e/connector/kafka/KafkaConnectDryRunIT.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.seatunnel.e2e.connector.kafka;
+
+import org.apache.seatunnel.api.configuration.ReadonlyConfig;
+import org.apache.seatunnel.api.table.factory.SupportSourceDryRunValidation;
+import org.apache.seatunnel.api.table.factory.TableSourceFactoryContext;
+import org.apache.seatunnel.connectors.seatunnel.kafka.source.KafkaSourceFactory;
+import org.apache.seatunnel.e2e.common.TestResource;
+import org.apache.seatunnel.e2e.common.TestSuiteBase;
+
+import org.apache.kafka.clients.admin.AdminClient;
+import org.apache.kafka.clients.admin.ConsumerGroupListing;
+import org.apache.kafka.clients.admin.NewTopic;
+import org.apache.kafka.clients.admin.OffsetSpec;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.TopicPartition;
+import org.apache.kafka.common.errors.AuthenticationException;
+import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
+import org.apache.kafka.common.serialization.StringSerializer;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.KafkaContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.utility.DockerImageName;
+import org.testcontainers.utility.DockerLoggerFactory;
+
+import lombok.extern.slf4j.Slf4j;
+
+import java.time.Duration;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/** Exercises the factory-level metadata contract against Kafka without submitting a job. */
+@Slf4j
+public class KafkaConnectDryRunIT extends TestSuiteBase implements TestResource {
+
+ private static final String IMAGE = "confluentinc/cp-kafka:7.0.9";
+ private static final String TOPIC = "connect-dry-run-orders";
+ private static final String PASSWORD = "test-only-password";
+ private KafkaContainer kafka;
+ private AdminClient admin;
+
+ @BeforeAll
+ @Override
+ public void startUp() throws Exception {
+ kafka =
+ new KafkaContainer(DockerImageName.parse(IMAGE))
+ .withEnv(
+ "KAFKA_LISTENER_SECURITY_PROTOCOL_MAP",
+ "BROKER:PLAINTEXT,PLAINTEXT:SASL_PLAINTEXT")
+ .withEnv("KAFKA_SASL_ENABLED_MECHANISMS", "PLAIN")
+ .withEnv(
+ "KAFKA_LISTENER_NAME_PLAINTEXT_PLAIN_SASL_JAAS_CONFIG",
+ "org.apache.kafka.common.security.plain.PlainLoginModule required "
+ + "user_test=\""
+ + PASSWORD
+ + "\";")
+ .withLogConsumer(
+ new Slf4jLogConsumer(DockerLoggerFactory.getLogger(IMAGE)));
+ kafka.start();
+ log.info("Authenticated Kafka dry-run fixture started");
+ admin = AdminClient.create(clientProperties(PASSWORD));
+ admin.createTopics(Collections.singleton(new NewTopic(TOPIC, 1, (short) 1)))
+ .all()
+ .get(30, TimeUnit.SECONDS);
+ await().atMost(60, TimeUnit.SECONDS)
+ .ignoreExceptions()
+ .untilAsserted(
+ () ->
+ assertTrue(
+ admin.describeTopics(Collections.singleton(TOPIC))
+ .allTopicNames().get(10, TimeUnit.SECONDS)
+ .get(TOPIC).partitions().stream()
+ .allMatch(
+ partition -> partition.leader() != null)));
+ Properties producerProperties = clientProperties(PASSWORD);
+ producerProperties.put("key.serializer", StringSerializer.class.getName());
+ producerProperties.put("value.serializer", StringSerializer.class.getName());
+ try (KafkaProducer<String, String> producer = new KafkaProducer<>(producerProperties)) {
+ producer.send(new ProducerRecord<>(TOPIC, "seed", "record-must-remain-untouched"))
+ .get(30, TimeUnit.SECONDS);
+ }
+ }
+
+ @AfterAll
+ @Override
+ public void tearDown() {
+ try {
+ if (admin != null) {
+ admin.close(Duration.ofSeconds(1));
+ }
+ } finally {
+ if (kafka != null) {
+ kafka.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testAuthenticatedLiteralAndPatternValidationHasNoDataOrGroupSideEffects()
+ throws Exception {
+ Set<String> topicsBefore = admin.listTopics().names().get(30, TimeUnit.SECONDS);
+ Set<String> groupsBefore = groups();
+ long earliestBefore = offset(OffsetSpec.earliest());
+ long latestBefore = offset(OffsetSpec.latest());
+
+ validate(TOPIC, false, PASSWORD);
+ validate("connect-dry-run-.*", true, PASSWORD);
+ validate("future-topic-.*", true, PASSWORD);
+
+ assertEquals(topicsBefore, admin.listTopics().names().get(30, TimeUnit.SECONDS));
+ assertEquals(groupsBefore, groups());
+ assertEquals(earliestBefore, offset(OffsetSpec.earliest()));
+ assertEquals(latestBefore, offset(OffsetSpec.latest()));
+ assertEquals(1L, latestBefore - earliestBefore);
+ }
+
+ @Test
+ public void testMissingTopicFailsWithoutAutomaticCreation() throws Exception {
+ String missing = "connect-dry-run-missing";
+ ExecutionException exception =
+ assertThrows(ExecutionException.class, () -> validate(missing, false, PASSWORD));
+ assertTrue(exception.getCause() instanceof UnknownTopicOrPartitionException);
+ assertFalse(admin.listTopics().names().get(30, TimeUnit.SECONDS).contains(missing));
+ }
+
+ @Test
+ public void testIncorrectCredentialsFailValidation() {
+ ExecutionException exception =
+ assertThrows(ExecutionException.class, () -> validate(TOPIC, false, "incorrect"));
+ assertTrue(exception.getCause() instanceof AuthenticationException);
+ }
+
+ private void validate(String topic, boolean pattern, String password) throws Exception {
+ ClassLoader classLoader = getClass().getClassLoader();
+ Map<String, Object> options = new HashMap<>();
+ options.put("bootstrap.servers", kafka.getBootstrapServers());
+ options.put("topic", topic);
+ options.put("pattern", pattern);
+ options.put("consumer.group", "dry-run-must-not-create-this-group");
+ options.put("kafka.config", new HashMap<>(clientProperties(password)));
+ TableSourceFactoryContext context =
+ new TableSourceFactoryContext(ReadonlyConfig.fromMap(options), classLoader);
+ SupportSourceDryRunValidation validation = new KafkaSourceFactory();
+ validation.validateConnectionForDryRun(context, validation.inferSchemaForDryRun(context));
+ }
+
+ private Properties clientProperties(String password) {
+ Properties properties = new Properties();
+ properties.put("bootstrap.servers", kafka.getBootstrapServers());
+ properties.put("security.protocol", "SASL_PLAINTEXT");
+ properties.put("sasl.mechanism", "PLAIN");
+ properties.put(
+ "sasl.jaas.config",
+ "org.apache.kafka.common.security.plain.PlainLoginModule required "
+ + "username=\"test\" password=\""
+ + password
+ + "\";");
+ properties.put("default.api.timeout.ms", "10000");
+ properties.put("request.timeout.ms", "10000");
+ return properties;
+ }
+
+ private long offset(OffsetSpec spec) throws Exception {
+ TopicPartition partition = new TopicPartition(TOPIC, 0);
+ return admin.listOffsets(Collections.singletonMap(partition, spec))
+ .all()
+ .get(30, TimeUnit.SECONDS)
+ .get(partition)
+ .offset();
+ }
+
+ private Set<String> groups() throws Exception {
+ return admin.listConsumerGroups().all().get(30, TimeUnit.SECONDS).stream()
+ .map(ConsumerGroupListing::groupId)
+ .collect(Collectors.toSet());
+ }
+}