修改API采集,和离线采集的 bug

这个提交包含在:
apple
2026-12-02 16:42:55 +08:00
父节点 bd87d49778
当前提交 b49578022b
共修改 70 个文件,包含 1581 行新增和 45 行删除
@@ -30,6 +30,7 @@ import java.time.Instant;
import java.util.Base64;
import java.util.HexFormat;
import java.util.Map;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@@ -70,6 +71,50 @@ final class ApiPollExecutor {
this.http = http;
}
DataCollectionIntegrationService.ApiPreviewResult preview(DataCollectionIntegrationService.ApiPreviewRequest request) {
String cacheKey = "preview:" + java.util.UUID.randomUUID();
try {
if (request == null || request.actorId() <= 0 || request.orgScopeId() <= 0 || request.secretRef() == null ||
!Set.of("PAGE_SIZE", "OFFSET_LIMIT", "CURSOR", "LINK_HEADER").contains(request.paginationMode()) ||
!valid(request.paginationField())) throw new PollFailure("API_PREVIEW_CONFIG_INVALID");
ApiPollProfile profile = request.profile() == null ? defaults() : request.profile();
validateProfile(profile);
if (profile.queryParameters().containsKey(request.paginationField()) ||
profile.queryParameters().containsKey("size") || profile.queryParameters().containsKey("limit"))
throw new PollFailure("API_POLL_QUERY_CONFLICT");
URI uri = checked(request.endpoint());
if (dynamic(profile)) checked(profile.tokenEndpoint());
Page position = new Page(1, null, null, null, profile.pageSize());
for (var entry : profile.queryParameters().entrySet()) {
if (!"${watermark}".equals(entry.getValue())) uri = append(uri, entry.getKey(), expand(entry.getValue(), position, "RAW"));
}
if ("PAGE_SIZE".equals(request.paginationMode())) uri = append(uri, request.paginationField(), "1");
if ("OFFSET_LIMIT".equals(request.paginationMode())) uri = append(uri, request.paginationField(), "0");
if (!"LINK_HEADER".equals(request.paginationMode()))
uri = append(uri, "OFFSET_LIMIT".equals(request.paginationMode()) ? "limit" : "size", Integer.toString(profile.pageSize()));
String auth = secrets.resolve(request.secretRef());
String signing = "NONE".equals(profile.signatureKind()) ? null :
secrets.resolve(profile.signingSecretRef() == null ? request.secretRef() : profile.signingSecretRef());
var response = sendData(cacheKey, profile, checked(uri.toASCIIString()), body(profile, position), auth, signing);
if (response.statusCode() != 200) {
response.body().close(); throw new PollFailure("API_POLL_HTTP_" + response.statusCode());
}
JsonNode root = JsonUtils.getObjectMapper().readTree(new String(read(response.body(), MAX_BODY), StandardCharsets.UTF_8));
if (profile.successPath() != null) {
JsonNode success = at(root, profile.successPath());
if (success == null || !profile.successValue().equals(success.asText())) throw new PollFailure("API_POLL_BUSINESS_ERROR");
}
var datasets = ApiPreviewInference.infer(root, request.responsePath());
return new DataCollectionIntegrationService.ApiPreviewResult("SUCCEEDED", null, datasets);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
return new DataCollectionIntegrationService.ApiPreviewResult("UNKNOWN", "API_PREVIEW_INTERRUPTED", List.of());
} catch (Exception failure) {
return new DataCollectionIntegrationService.ApiPreviewResult("UNKNOWN",
failure instanceof PollFailure p ? p.code : "API_PREVIEW_FAILED", List.of());
} finally { tokenCache.remove(cacheKey); }
}
DataCollectionIntegrationService.ApiPollResult run(DataCollectionIntegrationService.ApiPollRequest request) {
try {
var source = request.snapshot();
@@ -112,7 +157,7 @@ final class ApiPollExecutor {
"?useSSL=" + target.tlsEnabled() + "&serverTimezone=UTC";
try (Connection connection = jdbcConnector.open(jdbc, target.serviceAccount(), password)) {
connection.setAutoCommit(false);
requireUniqueKey(connection, object);
requireUniqueKey(connection, object, source.schema().stream().map(f -> f.targetField()).toList());
String columns = String.join(",", source.schema().stream().map(f -> "`" + f.targetField() + "`").toList());
String placeholders = String.join(",", source.schema().stream().map(f -> "?").toList());
String sql = "INSERT INTO `" + object[0] + "`.`" + object[1] + "` (" + columns + ") VALUES (" + placeholders + ")";
@@ -204,6 +249,11 @@ final class ApiPollExecutor {
":" + profile.tokenFormat() + ":" + profile.tokenPath() + ":" + profile.expiresPath() +
":" + profile.tokenClientField() + ":" + profile.tokenSecretField() +
":" + profile.tokenCredentialStyle();
return sendData(cacheKey, profile, uri, body, authSecret, signingSecret);
}
private HttpResponse<InputStream> sendData(String cacheKey, ApiPollProfile profile, URI uri,
String body, String authSecret, String signingSecret) throws Exception {
boolean refresh = false;
for (int attempt = 0; attempt < 3; attempt++) {
boolean forceRefresh = refresh;
@@ -409,11 +459,19 @@ final class ApiPollExecutor {
}
}
private static void requireUniqueKey(Connection connection, String[] object) throws Exception {
private static void requireUniqueKey(Connection connection, String[] object, List<String> mappedColumns) throws Exception {
try (PreparedStatement statement = connection.prepareStatement("SHOW CREATE TABLE `" + object[0] + "`.`" + object[1] + "`");
ResultSet rows = statement.executeQuery()) {
if (!rows.next() || rows.getString(2) == null || !rows.getString(2).toUpperCase().contains("UNIQUE KEY"))
if (!rows.next() || rows.getString(2) == null)
throw new IllegalArgumentException("API_POLL_TARGET_NOT_UNIQUE");
var matcher = Pattern.compile("(?i)\\bUNIQUE\\s+KEY\\s*\\(([^)]+)\\)").matcher(rows.getString(2));
if (!matcher.find()) throw new IllegalArgumentException("API_POLL_TARGET_NOT_UNIQUE");
var mapped = mappedColumns.stream().map(value -> value.toLowerCase(java.util.Locale.ROOT)).toList();
if (new java.util.HashSet<>(mapped).size() != mapped.size()) throw new IllegalArgumentException("API_POLL_DUPLICATE_MAPPING");
for (String key : matcher.group(1).split(",")) {
if (!mapped.contains(key.replace("`", "").trim().toLowerCase(java.util.Locale.ROOT)))
throw new IllegalArgumentException("API_POLL_KEY_MAPPING_REQUIRED");
}
}
}
@@ -0,0 +1,78 @@
package cn.aixunkeji.datagov.integration.batchingestion;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
import tools.jackson.databind.JsonNode;
import java.util.*;
/** Bounded, conservative suggestions; never creates tables or asserts business uniqueness. */
final class ApiPreviewInference {
private static final String FIELD = "[A-Za-z_][A-Za-z0-9_]{0,63}";
static List<ApiPreviewDataset> infer(JsonNode root, String selectedPath) {
var arrays = new LinkedHashMap<String, JsonNode>();
if (selectedPath != null && !selectedPath.isBlank()) {
String path = selectedPath.replace("[*]", "");
if (!path.matches("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}")) throw new IllegalArgumentException("PATH_INVALID");
JsonNode node = root;
if (!"$".equals(path)) for (String part : path.substring(2).split("\\.")) node = node == null ? null : node.get(part);
if (node == null || !node.isArray()) throw new IllegalArgumentException("ARRAY_REQUIRED");
arrays.put(path + "[*]", node);
} else discover(root, "$", 0, arrays);
return arrays.entrySet().stream().map(e -> dataset(e.getKey(), e.getValue())).toList();
}
private static void discover(JsonNode node, String path, int depth, Map<String, JsonNode> arrays) {
if (node == null || depth > 8 || arrays.size() >= 8) return;
if (node.isArray()) {
if (node.isEmpty() || node.get(0).isObject()) arrays.put(path + "[*]", node);
} else if (node.isObject()) {
for (var entry : node.properties()) {
if (entry.getKey().matches("[A-Za-z_][A-Za-z0-9_-]*")) discover(entry.getValue(), path + "." + entry.getKey(), depth + 1, arrays);
}
}
}
private static ApiPreviewDataset dataset(String path, JsonNode array) {
List<JsonNode> samples = new ArrayList<>();
for (JsonNode row : array) {
if (!row.isObject()) throw new IllegalArgumentException("OBJECT_ROWS_REQUIRED");
samples.add(row);
if (samples.size() == 20) break;
}
Set<String> names = new LinkedHashSet<>();
for (JsonNode row : samples) for (var entry : row.properties()) {
if (names.size() >= 200 && !names.contains(entry.getKey())) throw new IllegalArgumentException("TOO_MANY_FIELDS");
names.add(entry.getKey());
}
List<ApiPreviewField> fields = new ArrayList<>();
for (String name : names) {
Set<String> types = new HashSet<>();
boolean complex = false;
for (JsonNode row : samples) {
JsonNode value = row.get(name);
if (value == null || value.isNull()) continue;
if (value.isObject() || value.isArray()) { complex = true; continue; }
types.add(value.isBoolean() ? "BOOLEAN" : value.isIntegralNumber() && value.canConvertToLong() ? "BIGINT" : "STRING");
}
boolean secret = sensitive(name);
boolean supported = name.matches(FIELD) && !complex && !secret;
String warning = secret ? "敏感认证字段不参与采集" : complex ? "嵌套对象或数组需先展开" : !name.matches(FIELD) ? "字段名暂不支持" :
types.size() != 1 ? "类型不确定,按文本处理" : types.contains("STRING") ? "按文本保留原值,可确认后调整类型" : null;
fields.add(new ApiPreviewField(name, types.size() == 1 ? types.iterator().next() : "STRING", true, supported, warning));
}
List<Map<String, String>> rows = new ArrayList<>();
for (JsonNode row : samples) {
Map<String, String> values = new LinkedHashMap<>();
for (String name : names) {
JsonNode value = row.get(name);
String text = value == null || value.isNull() ? null : sensitive(name) ? "[已隐藏]" : (value.isObject() || value.isArray()) ? "[嵌套结构]" : value.asText();
values.put(name, text == null ? null : text.substring(0, Math.min(256, text.length())));
}
rows.add(values);
}
return new ApiPreviewDataset(path, samples.size(), fields, rows);
}
private static boolean sensitive(String field) {
return field.toLowerCase(Locale.ROOT).matches(".*(password|passwd|secret|token|authorization|cookie|private.?key|api.?key).*");
}
}
@@ -114,6 +114,11 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn
: apiPoll.run(request);
}
@Override
public ApiPreviewResult previewApi(ApiPreviewRequest request) {
return apiPoll == null ? new ApiPreviewResult("UNKNOWN", "API_PREVIEW_UNAVAILABLE", java.util.List.of()) : apiPoll.preview(request);
}
@Override
public LakehouseDirectoryResult validateLakehouseDirectory(LakehouseDirectoryRequest request) {
if (lakehouse == null) {
@@ -165,7 +165,7 @@ public class TableFileIntegrationDubboService implements TableFileIntegrationSer
tables = tables.stream().distinct().sorted().toList();
if (command.objectName() != null) {
if (tables.stream().filter(command.objectName()::equals).count() != 1)
return new DirectoryResult(State.REJECTED, List.of(), List.of(), 0, "目标表不存在或不可访问,请重新选择");
return confirmMissing(connection, command);
try {
var columns = DorisColumnMetadataReader.read(connection, command.namespaceName(), command.objectName());
return new DirectoryResult(State.CONFIRMED, List.of(command.objectName()), columns, 1, null);
@@ -183,7 +183,26 @@ public class TableFileIntegrationDubboService implements TableFileIntegrationSer
}
private DirectoryResult readHiveDirectory(Connection connection, DirectoryCommand command) throws SQLException {
return HiveDirectoryReader.read(connection.getMetaData(), command);
var result = HiveDirectoryReader.read(connection.getMetaData(), command);
return command.objectName() != null && result.state() == State.REJECTED
? confirmMissing(connection, command) : result;
}
/** An empty visibility-filtered catalog is not evidence of deletion. Probe the exact object without reading data. */
static DirectoryResult confirmMissing(Connection connection, DirectoryCommand command) throws SQLException {
try (Statement probe = connection.createStatement()) {
probe.setQueryTimeout(5);
try (ResultSet ignored = probe.executeQuery("SELECT * FROM `" + command.namespaceName()
+ "`.`" + command.objectName() + "` WHERE 1=0")) {
return new DirectoryResult(State.UNKNOWN, List.of(), List.of(), 0,
"目标对象存在但目录未确认,请重新核验目标表类型与权限");
}
} catch (SQLException exception) {
// Do not classify access denied, unknown database, timeout or generic HY000 errors as absence.
if ("42S02".equals(exception.getSQLState()))
return new DirectoryResult(State.REJECTED, List.of(), List.of(), 0, "目标表已确认不存在", true);
throw exception;
}
}
@Override
@@ -543,6 +562,9 @@ public class TableFileIntegrationDubboService implements TableFileIntegrationSer
private static MutationResult sqlFailure(SQLException exception) {
String state = exception.getSQLState();
if ("42S01".equals(state))
return new MutationResult(State.REJECTED, false, null, "EXTERNAL_TABLE_ALREADY_EXISTS",
"目标表已存在,需要重新核验结构", LocalDateTime.now());
if (exception instanceof SQLTimeoutException) {
return new MutationResult(State.RETRYABLE, true, null, "EXTERNAL_TIMEOUT",
"外部控制面执行超时", LocalDateTime.now());
@@ -196,6 +196,19 @@ class TableFileSqlPolicy {
private String createDoris(CreateCommand command, String target) {
String columns = command.columns().stream().map(this::column).collect(java.util.stream.Collectors.joining(", "));
String key = quoted(command.columns().getFirst().name());
boolean unique = command.uniqueKeyColumns() != null && !command.uniqueKeyColumns().isEmpty();
if (unique) {
var keys = command.uniqueKeyColumns();
if (keys.size() > command.columns().size() || new java.util.HashSet<>(keys).size() != keys.size())
throw new IllegalArgumentException("DORIS_UNIQUE_KEY_INVALID");
for (int i = 0; i < keys.size(); i++) {
var column = command.columns().get(i);
if (!keys.get(i).equals(column.name()) || column.nullable() ||
Set.of("STRING", "FLOAT", "DOUBLE").contains(column.type().toString()))
throw new IllegalArgumentException("DORIS_UNIQUE_KEY_INVALID");
}
key = keys.stream().map(this::quoted).collect(java.util.stream.Collectors.joining(", "));
}
StringBuilder sql = new StringBuilder("CREATE TABLE ").append(target).append(" (").append(columns);
if (command.partitionSpec() != null && command.partitionSpec().indexes() != null) {
for (Index index : command.partitionSpec().indexes()) {
@@ -209,7 +222,7 @@ class TableFileSqlPolicy {
.append(") USING ").append(indexType);
}
}
sql.append(") DUPLICATE KEY(").append(key).append(")")
sql.append(unique ? ") UNIQUE KEY(" : ") DUPLICATE KEY(").append(key).append(")")
.append(columnComment(command.physicalTableComment())).append(" DISTRIBUTED BY HASH(").append(key)
.append(") BUCKETS 10 PROPERTIES (\"replication_num\"=\"1\")");
return sql.toString();
@@ -32,6 +32,29 @@ import static org.mockito.Mockito.*;
/** Runs the HTTP parsing and JDBC write path with a loopback transport and isolated JDBC doubles. */
class ApiPollExecutorTest {
@Test void previewUsesRequestProtocolWithoutOpeningTargetConnection() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
var calls = new AtomicInteger();
server.createContext("/sample", exchange -> {
calls.incrementAndGet();
byte[] body = "{\"data\":[{\"id\":\"001\"}]}".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
try (var output = exchange.getResponseBody()) { output.write(body); }
});
server.start();
try {
var secrets = mock(M2SecretReader.class);
when(secrets.resolve("sample-ref")).thenReturn("sample-token");
var executor = new ApiPollExecutor(secrets,
endpoint -> new M3HttpEndpointPolicy.Validation(true, URI.create(endpoint), 0, null),
(jdbc, user, password) -> { throw new AssertionError("Preview must not open JDBC"); }, HttpClient.newHttpClient());
var result = executor.preview(new DataCollectionIntegrationService.ApiPreviewRequest(1, 1,
"http://127.0.0.1:" + server.getAddress().getPort() + "/sample", "sample-ref", "PAGE_SIZE", "page", null, null));
assertThat(result.status()).isEqualTo("SUCCEEDED");
assertThat(result.datasets().getFirst().rows().getFirst()).containsEntry("id", "001");
assertThat(calls.get()).isEqualTo(1);
} finally { server.stop(0); }
}
@BeforeAll static void initializeJsonMapper() {
var context = new AnnotationConfigApplicationContext();
context.registerBean(JsonMapper.class, () -> JsonMapper.builder().findAndAddModules().build());
@@ -0,0 +1,31 @@
package cn.aixunkeji.datagov.integration.batchingestion;
import org.junit.jupiter.api.Test;
import tools.jackson.databind.json.JsonMapper;
import static org.assertj.core.api.Assertions.*;
class ApiPreviewInferenceTest {
private final JsonMapper json = JsonMapper.builder().build();
@Test void discoversMultipleArraysAndPreservesIdentifiersAndPrecision() {
var result = ApiPreviewInference.infer(json.readTree("""
{"data":{"orders":[{"id":"00123","amount":123.456,"flag":true,"nested":{"id":1},"access_token":"sensitive"}],"customers":[{"id":2}]}}
"""), null);
assertThat(result).hasSize(2);
var orders = result.getFirst();
assertThat(orders.path()).isEqualTo("$.data.orders[*]");
assertThat(orders.fields().stream().filter(f -> f.name().equals("id")).findFirst().orElseThrow().fieldType()).isEqualTo("STRING");
assertThat(orders.fields().stream().filter(f -> f.name().equals("amount")).findFirst().orElseThrow().fieldType()).isEqualTo("STRING");
assertThat(orders.fields().stream().filter(f -> !f.supported()).map(f -> f.name())).containsExactly("nested", "access_token");
assertThat(orders.rows().getFirst()).containsEntry("id", "00123").containsEntry("access_token", "[已隐藏]");
}
@Test void supportsSelectedRootArrayAndBoundsSamples() {
String rows = java.util.stream.IntStream.range(0, 50).mapToObj(i -> "{\"id\":" + i + "}").collect(java.util.stream.Collectors.joining(","));
var result = ApiPreviewInference.infer(json.readTree("[" + rows + "]"), "$[*]").getFirst();
assertThat(result.rows()).hasSize(20);
assertThat(result.fields().getFirst().fieldType()).isEqualTo("BIGINT");
}
@Test void rejectsMissingPathAndMixedObjectArray() {
assertThatThrownBy(() -> ApiPreviewInference.infer(json.readTree("{}"), "$.data[*]")).isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> ApiPreviewInference.infer(json.readTree("[{\"id\":1},2]"), "$[*]")).isInstanceOf(IllegalArgumentException.class);
}
}
@@ -36,9 +36,27 @@ class TableFileDirectoryTest {
verify(statement,never()).execute(anyString());verify(statement,never()).executeUpdate(anyString());
}
@Test void missingTableReturnsRejectedAndNeverSelectsRows() throws Exception {
list();assertThat(service.readDirectory(connection,command("missing",null,1,20)).state()).isEqualTo(State.REJECTED);
list();
when(statement.executeQuery("SELECT * FROM `sample_db`.`missing` WHERE 1=0"))
.thenThrow(new SQLException("fixture missing table", "42S02", 1146));
var result = service.readDirectory(connection,command("missing",null,1,20));
assertThat(result.state()).isEqualTo(State.REJECTED);
assertThat(result.confirmedMissing()).isTrue();
verify(statement,times(1)).executeQuery();
verify(statement,never()).executeQuery(anyString());
verify(statement).executeQuery("SELECT * FROM `sample_db`.`missing` WHERE 1=0");
verify(statement,never()).executeUpdate(anyString());
}
@Test void invisibleTableAndPermissionOrConnectionFailuresNeverAssertAbsence() throws Exception {
list();
String probe = "SELECT * FROM `sample_db`.`missing` WHERE 1=0";
when(statement.executeQuery(probe)).thenReturn(mock(ResultSet.class));
assertThat(service.readDirectory(connection,command("missing",null,1,20)).confirmedMissing()).isFalse();
for (String state : List.of("42000", "28000", "08001", "HY000")) {
doThrow(new SQLException("fixture", state)).when(statement).executeQuery(probe);
assertThatThrownBy(() -> TableFileIntegrationDubboService.confirmMissing(connection,command("missing",null,1,20)))
.isInstanceOf(SQLException.class);
}
assertThat(new DirectoryResult(State.REJECTED,List.of(),List.of(),0,"legacy response").confirmedMissing()).isFalse();
}
@Test void fieldsComeFromNativeDorisCatalogWithoutResultSetTypeCoercion() throws Exception {
list();var empty=mock(ResultSet.class);
@@ -22,6 +22,19 @@ class TableFileSqlPolicyTest {
private final TableFileSqlPolicy policy = new TableFileSqlPolicy();
@Test void explicitApiKeysCreateUniqueTableAndRejectNullableOrMissingKeys() {
var connection = new ConnectionProfile(EngineType.DORIS, "doris.internal", 9030, "loader", "synthetic-ref", false);
var command = new CreateCommand("0123456789abcdef0123456789abcdef", 1L, connection, ObjectType.TABLE,
StorageFormat.DORIS_NATIVE, "internal", "sales", "api_orders", null,
List.of(new Column("id", ColumnType.VARCHAR, false, 256, null), new Column("name", ColumnType.STRING, true, null, null)),
null, null, null, List.of("id"));
assertThat(policy.create(command).getFirst()).contains("UNIQUE KEY(`id`)", "`id` VARCHAR(256) NOT NULL").doesNotContain("DUPLICATE KEY");
var invalid = new CreateCommand("0123456789abcdef0123456789abcdef", 1L, connection, ObjectType.TABLE,
StorageFormat.DORIS_NATIVE, "internal", "sales", "api_orders", null,
List.of(new Column("id", ColumnType.BIGINT, true, null, null)), null, null, null, List.of("id"));
assertThatThrownBy(() -> policy.create(invalid)).isInstanceOf(IllegalArgumentException.class).hasMessage("DORIS_UNIQUE_KEY_INVALID");
}
@Test void physicalTableCommentsUseExistingSafeLiteralAtEachEnginePosition() {
for (var engine : EngineType.values()) {
var connection = new ConnectionProfile(engine, "engine.internal", 9030, "loader", "synthetic-ref", false);