修改API采集,和离线采集的 bug
这个提交包含在:
+19
-6
@@ -334,16 +334,27 @@ public class UnifiedIngestionService {
|
||||
matchCommandTarget(verified, request, item, selected);
|
||||
collections.advance(command, "TARGET_CONFIRMED", next, null, null, null);
|
||||
return;
|
||||
} catch (TableFileErrors.Reference missing) {
|
||||
} catch (TableFileErrors.MissingTarget missing) {
|
||||
if (!item.createTarget()) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_TARGET_DIRECTORY",
|
||||
"目标目录暂不可确认,请核验目标表与字段结构", missing);
|
||||
"目标表不存在,请开启自动建表后重新提交", missing);
|
||||
}
|
||||
} catch (TableFileErrors.Reference unavailable) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_TARGET_DIRECTORY",
|
||||
"目标表暂不可确认,请核验连接、权限与目标表结构", unavailable);
|
||||
}
|
||||
var ddl = commandDdl(request, item, next);
|
||||
var prepared = new CommandContext(selected, current.tableComment(), accessVersion, context.database(), layer, ddl);
|
||||
tables.reserveCommandCreate(verified, key + "-table", ddl,
|
||||
id -> collections.advance(command, "TARGET_RESERVED", prepared, null, null, id));
|
||||
try {
|
||||
tables.reserveCommandCreate(verified, key + "-table", ddl,
|
||||
id -> collections.advance(command, "TARGET_RESERVED", prepared, null, null, id));
|
||||
} catch (TableFileErrors.TargetAppeared appeared) {
|
||||
matchCommandTarget(verified, request, item, selected);
|
||||
collections.advance(command, "TARGET_CONFIRMED", next, null, null, null);
|
||||
} catch (TableFileErrors.Conflict | TableFileErrors.Reference failure) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_TARGET_CREATE_CONFLICT",
|
||||
failure.getMessage(), failure);
|
||||
}
|
||||
}
|
||||
case "TARGET_RESERVED" -> {
|
||||
if (command.ddlId() == null || context.ddl() == null) throw BatchIngestionException.conflict("原建表关联缺失");
|
||||
@@ -388,6 +399,8 @@ public class UnifiedIngestionService {
|
||||
var target = tables.targetDirectory(verified, request.targetResourceId(), request.targetSpaceId(),
|
||||
EngineType.valueOf(request.targetType().name()), item.targetTable(), null, 1, 20);
|
||||
BatchTargetWizardService.matchColumns(selected.sourceColumns(), target, targetEngine(request.targetType()));
|
||||
tables.synchronizeCommandTarget(verified, request.targetResourceId(), request.targetSpaceId(),
|
||||
EngineType.valueOf(request.targetType().name()), item.targetTable(), target);
|
||||
}
|
||||
|
||||
static CreateCommand commandDdl(SubmitRequest request, SubmitItem item, CommandContext context) {
|
||||
@@ -430,7 +443,7 @@ public class UnifiedIngestionService {
|
||||
var operation = tables.commandCreateResult(verified, key + "-table", command.ddlId(), context.ddl());
|
||||
if (operation == null)
|
||||
throw BatchIngestionException.conflict("原建表请求不可验证");
|
||||
if ("REJECTED".equals(operation.state())) {
|
||||
if ("REJECTED".equals(operation.state()) && !"EXTERNAL_TABLE_ALREADY_EXISTS".equals(operation.errorCode())) {
|
||||
collections.rejectDdl(command, operation.errorCode(), operation.errorSummary());
|
||||
return;
|
||||
}
|
||||
@@ -500,7 +513,7 @@ public class UnifiedIngestionService {
|
||||
var existing = tables.targetDirectory(resourceId, spaceId, engine, targetTable, null, 1, 20);
|
||||
BatchTargetWizardService.matchColumns(selected.sourceColumns(), existing, targetEngine);
|
||||
return new TargetPreparation(existing, null, null, null, false);
|
||||
} catch (TableFileErrors.Reference exception) {
|
||||
} catch (TableFileErrors.MissingTarget exception) {
|
||||
if (!createTarget) throw exception;
|
||||
}
|
||||
// Only actual creation needs comment authority. Existing compatible tables above remain untouched.
|
||||
|
||||
+7
@@ -15,6 +15,13 @@ import java.util.List;
|
||||
public class ApiPollController {
|
||||
private final ApiPollService service;
|
||||
private final ApiPollProfileService profiles;
|
||||
private final ApiPreviewService previews;
|
||||
|
||||
@Log(title="API采集样本预览", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission({"aixun:dataops:file-ingestion:view", "aixun:dataops:file-ingestion:create"})
|
||||
@PostMapping("/preview")
|
||||
public R<cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPreviewResult> preview(
|
||||
@RequestBody ApiPreviewService.Command command) { return R.ok(previews.preview(command)); }
|
||||
|
||||
public record EnabledCommand(boolean enabled) { }
|
||||
|
||||
|
||||
+13
-1
@@ -126,7 +126,19 @@ public class ApiPollProfileService {
|
||||
value.signingSecretRef() != null || "SIGN_ONLY".equals(value.authKind()));
|
||||
}
|
||||
|
||||
private static void validate(Command c) {
|
||||
static ApiPollProfile transientProfile(Command c, String signingRef) {
|
||||
validate(c);
|
||||
if (!"NONE".equals(c.signatureKind()) && !"SIGN_ONLY".equals(c.authKind()) && signingRef == null)
|
||||
throw FileIngestionException.validation("请输入签名密钥");
|
||||
return new ApiPollProfile(c.authKind(), c.tokenEndpoint(), c.tokenFormat(), c.clientId(),
|
||||
c.tokenClientField(), c.tokenSecretField(), c.tokenCredentialStyle(), c.tokenPath(), c.expiresPath(),
|
||||
c.requestMethod(), c.headers() == null ? Map.of() : Map.copyOf(c.headers()),
|
||||
c.queryParameters() == null ? Map.of() : Map.copyOf(c.queryParameters()), c.requestBody(),
|
||||
c.pageSize(), c.lookbackSeconds(), c.successPath(), c.successValue(), c.signatureKind(),
|
||||
c.signatureTemplate(), c.signaturePlacement(), c.signatureHeader(), c.signatureEncoding(), signingRef);
|
||||
}
|
||||
|
||||
static void validate(Command c) {
|
||||
if (!AUTH.contains(c.authKind()) || !Set.of("GET", "POST").contains(c.requestMethod()) ||
|
||||
c.pageSize() == null || c.pageSize() < 1 || c.pageSize() > 1000 ||
|
||||
c.lookbackSeconds() == null || c.lookbackSeconds() < 0 || c.lookbackSeconds() > 86400 ||
|
||||
|
||||
+10
-8
@@ -18,6 +18,8 @@ import java.util.UUID;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollService {
|
||||
@Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
private final JdbcTemplate jdbc;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
@@ -51,8 +53,8 @@ public class ApiPollService {
|
||||
return jdbc.query("""
|
||||
SELECT run_id,trigger_type,run_status,written_rows,error_code,watermark_before,
|
||||
watermark_after,started_at,completed_at FROM ing_api_poll_run
|
||||
WHERE intake_id=? AND org_scope_id=? ORDER BY started_at DESC FETCH FIRST 50 ROWS ONLY
|
||||
""", (rs, index) -> new PollRun(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getInt(4),
|
||||
WHERE intake_id=? AND org_scope_id=? ORDER BY started_at DESC
|
||||
""" + databaseDialect.sql(" FETCH FIRST 50 ROWS ONLY", " LIMIT 50"), (rs, index) -> new PollRun(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getInt(4),
|
||||
rs.getString(5), rs.getString(6), rs.getString(7), time(rs.getTimestamp(8)),
|
||||
time(rs.getTimestamp(9))), intakeId, actor.orgScopeId());
|
||||
}
|
||||
@@ -90,8 +92,8 @@ public class ApiPollService {
|
||||
SELECT intake_id,org_scope_id,actor_id FROM ing_api_poll_state
|
||||
WHERE enabled=1 AND next_due_at<=CURRENT_TIMESTAMP
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
ORDER BY next_due_at FETCH FIRST 10 ROWS ONLY
|
||||
""", (rs, index) -> new long[]{rs.getLong(1), rs.getLong(2), rs.getLong(3)});
|
||||
ORDER BY next_due_at
|
||||
""" + databaseDialect.sql(" FETCH FIRST 10 ROWS ONLY", " LIMIT 10"), (rs, index) -> new long[]{rs.getLong(1), rs.getLong(2), rs.getLong(3)});
|
||||
} catch (RuntimeException unavailable) { return; }
|
||||
for (long[] item : due) {
|
||||
try {
|
||||
@@ -109,10 +111,10 @@ public class ApiPollService {
|
||||
FileIngestionPolicy.Config config) {
|
||||
String lease = UUID.randomUUID().toString();
|
||||
int claimed = jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET lease_id=?, lease_until=DATEADD(HOUR, 2, CURRENT_TIMESTAMP),
|
||||
UPDATE ing_api_poll_state SET lease_id=?, lease_until=%s,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
""" + ("SCHEDULED".equals(trigger) ? " AND enabled=1" : ""), lease, intakeId, actor.orgScopeId());
|
||||
""".formatted(databaseDialect.sql("DATEADD(HOUR, 2, CURRENT_TIMESTAMP)", "DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 2 HOUR)")) + ("SCHEDULED".equals(trigger) ? " AND enabled=1" : ""), lease, intakeId, actor.orgScopeId());
|
||||
if (claimed != 1) throw FileIngestionException.conflict("该API采集任务正在运行");
|
||||
long runId = IdGeneratorUtil.nextLongId();
|
||||
String before = jdbc.queryForObject("SELECT watermark FROM ing_api_poll_state WHERE intake_id=?",
|
||||
@@ -141,9 +143,9 @@ public class ApiPollService {
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET watermark=?,last_status=?,last_error_code=?,
|
||||
last_written_rows=?,last_run_at=CURRENT_TIMESTAMP,
|
||||
next_due_at=DATEADD(SECOND, ?, CURRENT_TIMESTAMP),lease_id=NULL,lease_until=NULL,
|
||||
next_due_at=%s,lease_id=NULL,lease_until=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? AND lease_id=?
|
||||
""", after, success ? "SUCCEEDED" : "UNKNOWN", error, count,
|
||||
""".formatted(databaseDialect.sql("DATEADD(SECOND, ?, CURRENT_TIMESTAMP)", "DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ? SECOND)")), after, success ? "SUCCEEDED" : "UNKNOWN", error, count,
|
||||
config.periodSeconds(), intakeId, actor.orgScopeId(), lease);
|
||||
return new PollRun(runId, trigger, success ? "SUCCEEDED" : "UNKNOWN", count, error,
|
||||
before, after, null, null);
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPreviewService {
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final FileManagedCredentialGateway credentials;
|
||||
private final ApiPollProfileService profiles;
|
||||
private final IntegrationFileIngestionGateway integration;
|
||||
|
||||
public record Command(Long intakeId, String endpoint, char[] credential, String paginationMode,
|
||||
String paginationField, String responsePath, ApiPollProfileService.Command profile) {
|
||||
@Override public String toString() { return "ApiPreviewCommand[REDACTED]"; }
|
||||
}
|
||||
|
||||
public ApiPreviewResult preview(Command command) {
|
||||
if (command == null || command.profile() == null) throw FileIngestionException.validation("请完善接口请求配置");
|
||||
var actor = actors.current();
|
||||
List<String> temporary = new ArrayList<>();
|
||||
try {
|
||||
ApiPollProfileService.validate(command.profile());
|
||||
String authRef = null, signingRef = null, endpoint = command.endpoint();
|
||||
if (command.intakeId() != null) {
|
||||
var config = repository.config(actor, command.intakeId());
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅 API 采集支持接口预览");
|
||||
authRef = config.secretRef();
|
||||
if (endpoint == null || endpoint.isBlank()) endpoint = config.endpoint();
|
||||
var old = profiles.profile(actor, command.intakeId());
|
||||
signingRef = old == null ? null : old.signingSecretRef();
|
||||
}
|
||||
if (command.credential() != null && command.credential().length > 0) {
|
||||
authRef = credentials.provision(command.credential()); temporary.add(authRef);
|
||||
}
|
||||
if (authRef == null) throw FileIngestionException.validation("请填写接口凭据");
|
||||
if (command.profile().signingKey() != null && command.profile().signingKey().length > 0) {
|
||||
signingRef = credentials.provision(command.profile().signingKey()); temporary.add(signingRef);
|
||||
}
|
||||
var profile = ApiPollProfileService.transientProfile(command.profile(), signingRef);
|
||||
try {
|
||||
return integration.previewApi(new ApiPreviewRequest(actor.actorId(), actor.orgScopeId(), endpoint,
|
||||
authRef, command.paginationMode(), command.paginationField(), command.responsePath(), profile));
|
||||
} catch (RuntimeException unavailable) {
|
||||
throw FileIngestionException.validation("接口预览暂不可用,请检查连接或稍后重试");
|
||||
}
|
||||
} finally {
|
||||
if (command.credential() != null) Arrays.fill(command.credential(), '\0');
|
||||
if (command.profile().signingKey() != null) Arrays.fill(command.profile().signingKey(), '\0');
|
||||
for (String ref : temporary) {
|
||||
try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* Managed credential audit retains revocation outcome. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
@@ -16,6 +16,10 @@ import java.util.List;
|
||||
@Component
|
||||
public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
|
||||
DataCollectionIntegrationService.ApiPreviewResult previewApi(DataCollectionIntegrationService.ApiPreviewRequest request) {
|
||||
return integration.previewApi(request);
|
||||
}
|
||||
|
||||
@DubboReference(check = false, timeout = 190_000, retries = 0)
|
||||
private DataCollectionIntegrationService integration;
|
||||
|
||||
|
||||
+9
-1
@@ -20,10 +20,18 @@ public final class TableFileErrors {
|
||||
NotFound() { super("表文件不存在"); }
|
||||
}
|
||||
|
||||
public static final class Reference extends RuntimeException {
|
||||
public static class Reference extends RuntimeException {
|
||||
Reference(String message) { super(message); }
|
||||
}
|
||||
|
||||
public static final class MissingTarget extends Reference {
|
||||
public MissingTarget() { super("目标表已确认不存在"); }
|
||||
}
|
||||
|
||||
public static final class TargetAppeared extends Reference {
|
||||
public TargetAppeared() { super("目标表已出现,需要重新核验结构"); }
|
||||
}
|
||||
|
||||
public static final class DirectoryBusy extends RuntimeException {
|
||||
public DirectoryBusy() { super("目标目录访问繁忙,请稍后重试"); }
|
||||
}
|
||||
|
||||
+11
@@ -107,6 +107,17 @@ class TableFilePolicy {
|
||||
throw new TableFileErrors.Validation("外部表必须提供外部位置");
|
||||
}
|
||||
validatePartition(command.engineType(), command.objectType(), columns, command.partitionPolicy());
|
||||
if (command.uniqueKeyColumns() != null && !command.uniqueKeyColumns().isEmpty()) {
|
||||
List<String> keys = identifiers(command.uniqueKeyColumns(), "唯一字段", 1, 32);
|
||||
if (command.engineType() != EngineType.DORIS || command.objectType() != ObjectType.TABLE || keys.size() > columns.size())
|
||||
throw new TableFileErrors.Validation("唯一字段仅适用于 Doris 表");
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
ColumnDefinition column = columns.get(i);
|
||||
if (!keys.get(i).equals(column.name()) || column.nullable() ||
|
||||
java.util.Set.of("STRING", "FLOAT", "DOUBLE").contains(column.type().name()))
|
||||
throw new TableFileErrors.Validation("唯一字段必须排在表结构最前、不可空,且不能使用 STRING/FLOAT/DOUBLE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void requireCapability(EngineType engine, ObjectType objectType) {
|
||||
|
||||
+90
-2
@@ -302,16 +302,102 @@ class TableFileRepository {
|
||||
return reserveCreate(actor, key, hash, command, true);
|
||||
}
|
||||
|
||||
void synchronizeCommandTarget(TableFileActor actor, long resource, long space, EngineType engine,
|
||||
String catalog, String namespace, String name, List<ColumnDefinition> columns) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.active(jdbcTemplate,
|
||||
resource, space, actor.orgId(), actor.unrestricted());
|
||||
var ids = jdbcTemplate.query("""
|
||||
SELECT table_file_id FROM store_table_file WHERE org_id=? AND project_id IS NULL
|
||||
AND storage_resource_id=? AND storage_space_id=? AND engine_type=?
|
||||
AND catalog_name=? AND namespace_name=? AND object_name=? AND del_flag='0' FOR UPDATE
|
||||
""", (rs, n) -> rs.getLong(1), actor.orgId(), resource, space, engine.name(), catalog, namespace, name);
|
||||
for (long id : ids) {
|
||||
var before = requireDetail(actor, id);
|
||||
// Live existence cannot settle someone else's in-flight or unknown DDL outcome.
|
||||
Long unsettled = jdbcTemplate.queryForObject("""
|
||||
SELECT COUNT(*) FROM store_table_file_request WHERE table_file_id=? AND del_flag='0'
|
||||
AND action_type<>'PREVIEW' AND request_status IN ('IN_PROGRESS','UNKNOWN')
|
||||
""", Long.class, id);
|
||||
if (unsettled == null || unsettled != 0) continue;
|
||||
if (before.columns().equals(columns) && before.tableFile().executionState() == ExecutionState.CONFIRMED)
|
||||
continue;
|
||||
int changed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET columns_json=?, execution_state='CONFIRMED',
|
||||
error_code=NULL, error_summary=NULL, binding_evidence_json=NULL, last_observed_at=NOW(6),
|
||||
update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE table_file_id=? AND org_id=? AND version=? AND del_flag='0'
|
||||
""", json(columns), actor.actorId(), id, actor.orgId(), before.tableFile().version());
|
||||
if (changed != 1) throw createConflict();
|
||||
long requestId = IdGeneratorUtil.nextLongId();
|
||||
insertRequest(requestId, platformRequestId(), id, actor, "UPDATE",
|
||||
"target-sync-" + id + "-" + before.tableFile().version(), new TableFilePolicy().hash(columns), "CONFIRMED");
|
||||
insertSnapshot(requestId, id, actor, before, requireDetail(actor, id));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reservation reserveCommandCreate(TableFileActor actor, String key, String hash, CreateCommand command,
|
||||
java.util.function.Consumer<String> bind) {
|
||||
return transactionTemplate.execute(status -> {
|
||||
Reservation reservation = reserveCreate(actor, key, hash, command, false);
|
||||
Reservation reservation = replay(actor, "CREATE", key, hash);
|
||||
if (reservation == null) {
|
||||
// Serialize on the same storage identity as first-time creates, before looking up the old row.
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.active(jdbcTemplate,
|
||||
command.storageResourceId(), command.storageSpaceId(), actor.orgId(), actor.unrestricted());
|
||||
var existing = jdbcTemplate.query("""
|
||||
SELECT table_file_id FROM store_table_file
|
||||
WHERE org_id=? AND project_id IS NULL AND storage_resource_id=? AND storage_space_id=? AND engine_type=?
|
||||
AND catalog_name=? AND namespace_name=? AND object_name=? AND del_flag='0'
|
||||
FOR UPDATE
|
||||
""", (rs, n) -> rs.getLong(1), actor.orgId(), command.storageResourceId(),
|
||||
command.storageSpaceId(), command.engineType().name(), command.catalogName(),
|
||||
command.namespaceName(), command.name());
|
||||
if (existing.isEmpty()) reservation = reserveCreate(actor, key, hash, command, false);
|
||||
else if (existing.size() == 1) reservation = reserveMissingCommandTarget(actor, key, hash, command, existing.getFirst());
|
||||
else throw createConflict();
|
||||
}
|
||||
requireStored(actor, reservation.tableFileId());
|
||||
bind.accept(reservation.platformRequestId());
|
||||
return reservation;
|
||||
});
|
||||
}
|
||||
|
||||
/** Called only after live, explicit absence; keeps the original identity and immutable operation history. */
|
||||
private Reservation reserveMissingCommandTarget(TableFileActor actor, String key, String hash,
|
||||
CreateCommand command, long tableFileId) {
|
||||
var before = requireDetail(actor, tableFileId);
|
||||
var table = before.tableFile();
|
||||
if (table.objectType() != command.objectType() || !java.util.Objects.equals(table.layerId(), command.layerId()))
|
||||
throw new TableFileErrors.Conflict("旧登记的对象类型或分层不一致,请核对目标配置");
|
||||
Long unsettled = jdbcTemplate.queryForObject("""
|
||||
SELECT COUNT(*) FROM store_table_file_request WHERE table_file_id=? AND del_flag='0'
|
||||
AND action_type<>'PREVIEW' AND request_status IN ('IN_PROGRESS','UNKNOWN')
|
||||
""", Long.class, tableFileId);
|
||||
if (unsettled == null || unsettled != 0)
|
||||
throw new TableFileErrors.Conflict("目标表有正在执行或结果待确认的操作,请先核验原执行记录");
|
||||
long requestId = IdGeneratorUtil.nextLongId();
|
||||
String platformRequestId = platformRequestId();
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.reference(jdbcTemplate,
|
||||
command.storageResourceId(), command.storageSpaceId(), actor.orgId(), actor.unrestricted(), "TABLE_CREATE");
|
||||
int changed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET columns_json=?, object_comment=?, partition_policy_json=?,
|
||||
view_definition_json=?, storage_format=?, external_location=?, execution_state='UNKNOWN',
|
||||
policy_execution_state=?, external_object_id=NULL, binding_evidence_json=NULL,
|
||||
registration_origin='CREATED', error_code='TARGET_RECREATE_PENDING',
|
||||
error_summary='目标表已不存在,等待自动重建', last_observed_at=NOW(6),
|
||||
update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE table_file_id=? AND org_id=? AND version=? AND del_flag='0'
|
||||
""", json(command.columns()), command.comment(), json(command.partitionPolicy()),
|
||||
json(command.viewDefinition()), command.storageFormat().name(), command.externalLocation(),
|
||||
command.partitionPolicy() == null ? "NOT_REQUESTED" : "UNKNOWN", actor.actorId(),
|
||||
tableFileId, actor.orgId(), table.version());
|
||||
if (changed != 1) throw createConflict();
|
||||
insertRequest(requestId, platformRequestId, tableFileId, actor, "CREATE", key, hash, "IN_PROGRESS");
|
||||
insertSnapshot(requestId, tableFileId, actor, before, command);
|
||||
return new Reservation(requestId, platformRequestId, tableFileId, false, "CREATE");
|
||||
}
|
||||
|
||||
Reservation commandReservation(TableFileActor actor, String key, String hash, String platformRequestId) {
|
||||
Reservation reservation = replay(actor, "CREATE", key, hash);
|
||||
if (reservation == null || !reservation.platformRequestId().equals(platformRequestId))
|
||||
@@ -587,12 +673,14 @@ class TableFileRepository {
|
||||
boolean retryable, String externalObjectId, String errorCode,
|
||||
String errorSummary, LocalDateTime observedAt) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
jdbcTemplate.update("""
|
||||
int completed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file_request SET request_status=?, retryable=?, external_object_id=?,
|
||||
error_code=?, error_summary=?, observed_at=?, update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE request_id=? AND request_status='IN_PROGRESS' AND del_flag='0'
|
||||
""", state.name(), retryable, externalObjectId, errorCode, errorSummary, observedAt,
|
||||
actor.actorId(), reservation.requestId());
|
||||
// A delayed/replayed completion must not overwrite a newer rebuild of the same table identity.
|
||||
if (completed != 1) return;
|
||||
String policyState = "PARTITION".equals(reservation.action()) ? policyState(state, errorCode) : null;
|
||||
jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET execution_state=?, external_object_id=COALESCE(?, external_object_id),
|
||||
|
||||
+29
-2
@@ -69,6 +69,8 @@ public class TableFileService {
|
||||
var after = targetReferences(actor, resourceId, spaceId, EngineType.DORIS);
|
||||
if (!ref.equals(after)) throw new TableFileErrors.Reference("目标配置已变化,请重新选择");
|
||||
if ("目标目录访问繁忙,请稍后重试".equals(result.errorSummary())) throw new TableFileErrors.DirectoryBusy();
|
||||
if (result.state() == TableFileIntegrationService.State.REJECTED && result.confirmedMissing())
|
||||
throw new TableFileErrors.MissingTarget();
|
||||
if (result.state() != TableFileIntegrationService.State.CONFIRMED)
|
||||
throw new TableFileErrors.Reference(result.errorSummary());
|
||||
return result;
|
||||
@@ -97,11 +99,27 @@ public class TableFileService {
|
||||
var after = targetReferences(actor, resourceId, spaceId, engineType, strict);
|
||||
if (!ref.equals(after)) throw new TableFileErrors.Reference("目标配置已变化,请重新选择");
|
||||
if ("目标目录访问繁忙,请稍后重试".equals(result.errorSummary())) throw new TableFileErrors.DirectoryBusy();
|
||||
if (result.state() == TableFileIntegrationService.State.REJECTED && result.confirmedMissing())
|
||||
throw new TableFileErrors.MissingTarget();
|
||||
if (result.state() != TableFileIntegrationService.State.CONFIRMED)
|
||||
throw new TableFileErrors.Reference(result.errorSummary());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Synchronize an existing registration only after ingestion has validated the live column mapping. */
|
||||
public void synchronizeCommandTarget(VerifiedIngestionCommandActor verified, long resourceId, long spaceId,
|
||||
EngineType engine, String table, TableFileIntegrationService.DirectoryResult observed) {
|
||||
verified.check();
|
||||
if (observed == null || observed.state() != TableFileIntegrationService.State.CONFIRMED
|
||||
|| observed.total() != 1 || !List.of(table).equals(observed.tables()))
|
||||
throw new TableFileErrors.Reference("目标表实时状态未确认");
|
||||
var actor = new TableFileActor(verified.actorId(), verified.orgId(), false);
|
||||
var ref = targetReferences(actor, resourceId, spaceId, engine, true);
|
||||
var columns = new TableFileBindingPolicy(policy).columns(observed.columns(), 500);
|
||||
repository.synchronizeCommandTarget(actor, resourceId, spaceId, engine, ref.catalogName(),
|
||||
ref.externalSpaceId(), table, columns);
|
||||
}
|
||||
|
||||
private StorageTableFileReferenceDirectory.Resolution targetReferences(TableFileActor actor, long resourceId,
|
||||
long spaceId, EngineType engineType) {
|
||||
return targetReferences(actor, resourceId, spaceId, engineType, false);
|
||||
@@ -144,7 +162,7 @@ public class TableFileService {
|
||||
command = new CreateCommand(command.name(), command.objectType(), null,
|
||||
command.storageResourceId(), command.storageSpaceId(), command.engineType(), command.storageFormat(),
|
||||
direct.catalogName(), direct.externalSpaceId(), command.externalLocation(), command.comment(),
|
||||
command.columns(), command.partitionPolicy(), command.viewDefinition(), command.physicalTableComment());
|
||||
command.columns(), command.partitionPolicy(), command.viewDefinition(), command.physicalTableComment(), command.uniqueKeyColumns());
|
||||
refs = new References(direct, null);
|
||||
} else {
|
||||
refs = references(actor, command.layerId(), command.storageResourceId(),
|
||||
@@ -169,6 +187,15 @@ public class TableFileService {
|
||||
References refs = references(actor, command.layerId(), command.storageResourceId(),
|
||||
command.storageSpaceId(), command.engineType(), true);
|
||||
requireLayerContract(command, refs.layer());
|
||||
// Revalidate at the reservation boundary; callers cannot turn an ambiguous read into a rebuild.
|
||||
boolean missing = false;
|
||||
try {
|
||||
targetDirectory(verified, command.storageResourceId(), command.storageSpaceId(),
|
||||
command.engineType(), command.name(), null, 1, 20);
|
||||
} catch (TableFileErrors.MissingTarget absent) {
|
||||
missing = true;
|
||||
}
|
||||
if (!missing) throw new TableFileErrors.TargetAppeared();
|
||||
return repository.reserveCommandCreate(actor, policy.idempotencyKey(key), policy.hash(command), command, bind)
|
||||
.platformRequestId();
|
||||
}
|
||||
@@ -325,7 +352,7 @@ public class TableFileService {
|
||||
connection(command.engineType(), storageRef), enumValue(TableFileIntegrationService.ObjectType.class, command.objectType()),
|
||||
enumValue(TableFileIntegrationService.StorageFormat.class, command.storageFormat()), command.catalogName(),
|
||||
command.namespaceName(), command.name(), command.externalLocation(), columns(command.columns()),
|
||||
partition(command.partitionPolicy()), view(command.viewDefinition()), command.physicalTableComment());
|
||||
partition(command.partitionPolicy()), view(command.viewDefinition()), command.physicalTableComment(), command.uniqueKeyColumns());
|
||||
}
|
||||
|
||||
private TableFileIntegrationService.PolicyCommand policyIntegrationCommand(
|
||||
|
||||
+35
-2
@@ -34,6 +34,39 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class UnifiedIngestionRecoveryTest {
|
||||
@Test void ambiguousDirectoryFailureCannotStartAutomaticCreate() {
|
||||
var fixture = new CommentFixture("订单字段");
|
||||
fixture.tableComment = SourceTableComment.fromSource("订单表");
|
||||
var request = fixture.request(fixture.draft(StorageResourceType.DORIS).items().getFirst(), StorageResourceType.DORIS);
|
||||
fixture.submitReady(StorageResourceType.DORIS);
|
||||
var unavailable = mock(TableFileErrors.Reference.class);
|
||||
when(fixture.tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20))).thenThrow(unavailable);
|
||||
assertThatThrownBy(() -> fixture.consume(request))
|
||||
.isInstanceOf(UnifiedIngestionCommandStageException.class).hasMessageContaining("连接、权限");
|
||||
verify(fixture.tables, never()).reserveCommandCreate(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test void targetAppearingBeforeReservationIsRecheckedAndReused() {
|
||||
var fixture = new CommentFixture("订单字段");
|
||||
var request = fixture.request(fixture.draft(StorageResourceType.DORIS).items().getFirst(), StorageResourceType.DORIS);
|
||||
fixture.submitReady(StorageResourceType.DORIS);
|
||||
var directory = new DirectoryResult(State.CONFIRMED,List.of("orders"),
|
||||
List.of(new DirectoryColumn("id","BIGINT",19,0,false)),1,null);
|
||||
when(fixture.tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(new TableFileErrors.MissingTarget()).thenReturn(directory);
|
||||
when(fixture.tables.reserveCommandCreate(any(),any(),any(),any())).thenThrow(new TableFileErrors.TargetAppeared());
|
||||
fixture.consume(request);
|
||||
verify(fixture.collections).advance(any(),org.mockito.ArgumentMatchers.eq("TARGET_CONFIRMED"),any(),
|
||||
org.mockito.ArgumentMatchers.isNull(),org.mockito.ArgumentMatchers.isNull(),org.mockito.ArgumentMatchers.isNull());
|
||||
verify(fixture.tables,never()).executeCommandCreate(any(),any(),any(),any());
|
||||
verify(fixture.tables).synchronizeCommandTarget(any(),org.mockito.ArgumentMatchers.eq(30L),
|
||||
org.mockito.ArgumentMatchers.eq(40L),org.mockito.ArgumentMatchers.eq(EngineType.DORIS),
|
||||
org.mockito.ArgumentMatchers.eq("orders"),org.mockito.ArgumentMatchers.eq(directory));
|
||||
}
|
||||
@Test void realtimeDirectoryDoesNotReuseBatchPilotGateOrLoseCredentialGate() {
|
||||
var f=new CommentFixture("");
|
||||
when(f.sources.sources(1,2,List.of(),null,200)).thenReturn(new DataSourceDirectoryService.Result("AVAILABLE",List.of(
|
||||
@@ -279,11 +312,11 @@ class UnifiedIngestionRecoveryTest {
|
||||
when(tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(mock(TableFileErrors.Reference.class));
|
||||
.thenThrow(new TableFileErrors.MissingTarget());
|
||||
when(tables.targetDirectory(org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(mock(TableFileErrors.Reference.class));
|
||||
.thenThrow(new TableFileErrors.MissingTarget());
|
||||
var view = mock(TableFileView.class);
|
||||
when(view.executionState()).thenReturn(ExecutionState.REJECTED);
|
||||
var detail = mock(TableFileDetailView.class);
|
||||
|
||||
+12
-7
@@ -17,8 +17,8 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises the production polling SQL against disposable rows in the dedicated DM test schema. */
|
||||
@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST")
|
||||
/** Exercises polling with rolled-back rows in the dedicated dual-database test schema only. */
|
||||
@EnabledIfEnvironmentVariable(named = "PLATFORM_DB_URL", matches = "jdbc:(mysql|dm):.*")
|
||||
class ApiPollServiceJdbcTest {
|
||||
@BeforeAll static void identifiers() {
|
||||
var beans = new DefaultListableBeanFactory();
|
||||
@@ -28,11 +28,14 @@ class ApiPollServiceJdbcTest {
|
||||
|
||||
@Test void successfulRunCommitsWatermarkAndUnknownKeepsIt() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
ds.setDriverClassName("dm.jdbc.driver.DmDriver");
|
||||
ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"));
|
||||
ds.setUsername(System.getenv("DATAGOV_DM_USERNAME"));
|
||||
ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA"));
|
||||
String url = System.getenv("PLATFORM_DB_URL");
|
||||
boolean mysql = url.startsWith("jdbc:mysql:");
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
org.junit.jupiter.api.Assumptions.assumeTrue(mysql ? url.contains("/aixun_datagov_dualcheck_") : schema != null && schema.startsWith("AIXUN_DATAGOV_DUALCHECK_"));
|
||||
ds.setUrl(url);
|
||||
ds.setUsername(System.getenv("PLATFORM_DB_USERNAME"));
|
||||
ds.setPassword(System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
var properties = new Properties(); if (!mysql) properties.setProperty("schema", schema);
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
@@ -57,6 +60,8 @@ class ApiPollServiceJdbcTest {
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollService(jdbc, actors, repository, integration);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "databaseDialect",
|
||||
mysql ? cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.MYSQL : cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);
|
||||
assertThat(service.state(intakeId).lastStatus()).isEqualTo("NEVER");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("SUCCEEDED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class ApiPreviewServiceTest {
|
||||
@Test void unsavedPreviewUsesActorScopedReferencesAndRevokesTemporarySecret() {
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var credentials = mock(FileManagedCredentialGateway.class);
|
||||
var profiles = mock(ApiPollProfileService.class);
|
||||
var integration = mock(IntegrationFileIngestionGateway.class);
|
||||
when(actors.current()).thenReturn(new FileIngestionActor(7, 9));
|
||||
when(credentials.provision(any())).thenReturn("temporary-ref");
|
||||
when(integration.previewApi(any())).thenAnswer(call -> {
|
||||
ApiPreviewRequest request = call.getArgument(0);
|
||||
assertThat(request.actorId()).isEqualTo(7);
|
||||
assertThat(request.orgScopeId()).isEqualTo(9);
|
||||
assertThat(request.secretRef()).isEqualTo("temporary-ref");
|
||||
return new ApiPreviewResult("SUCCEEDED", null, List.of());
|
||||
});
|
||||
var profile = JsonMapper.builder().build().readValue("""
|
||||
{"authKind":"STATIC_BEARER","requestMethod":"GET","pageSize":20,"lookbackSeconds":0,"signatureKind":"NONE"}
|
||||
""", ApiPollProfileService.Command.class);
|
||||
char[] secret = "sample-test-secret".toCharArray();
|
||||
var command = new ApiPreviewService.Command(null, "https://example.test/data", secret, "PAGE_SIZE", "page", null, profile);
|
||||
var service = new ApiPreviewService(actors, repository, credentials, profiles, integration);
|
||||
assertThat(service.preview(command).status()).isEqualTo("SUCCEEDED");
|
||||
verify(credentials).revoke("temporary-ref");
|
||||
assertThat(new String(secret)).doesNotContain("sample");
|
||||
verifyNoInteractions(repository);
|
||||
doThrow(new IllegalStateException("private-internal-details")).when(integration).previewApi(any());
|
||||
assertThatThrownBy(() -> service.preview(new ApiPreviewService.Command(null, "https://example.test/data", "sample".toCharArray(), "PAGE_SIZE", "page", null, profile)))
|
||||
.isInstanceOf(FileIngestionException.class).hasMessageNotContaining("private-internal-details");
|
||||
verify(credentials, times(2)).revoke("temporary-ref");
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package cn.aixunkeji.datagov.dataops.tablefile;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.*;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class TableFileRecreationTest {
|
||||
@BeforeAll static void beans() { TableFileBindingRepositoryTest.beans(); }
|
||||
final JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
final TableFileBindingRepositoryTest.Transactions manager = spy(new TableFileBindingRepositoryTest.Transactions());
|
||||
final TableFileRepository repository = spy(new TableFileRepository(jdbc, new TransactionTemplate(manager)));
|
||||
final TableFileActorProvider.TableFileActor actor = new TableFileActorProvider.TableFileActor(10,20,false);
|
||||
final List<String> writes = new ArrayList<>();
|
||||
final TableFileView table = new TableFileView(500L,"orders",ObjectType.TABLE,20L,200L,300L,400L,
|
||||
EngineType.DORIS,StorageFormat.DORIS_NATIVE,"internal","sales",null,"internal.sales.orders",null,
|
||||
ExecutionState.CONFIRMED,null,null,4,LocalDateTime.now(),LocalDateTime.now(),"CREATED");
|
||||
final TableFileDetailView before = new TableFileDetailView(table,List.of(),null,null,
|
||||
PolicyExecutionState.NOT_REQUESTED,List.of(),null);
|
||||
|
||||
@BeforeEach @SuppressWarnings({"unchecked", "rawtypes"}) void setup() throws Exception {
|
||||
doReturn(List.of(new StorageReferenceGuard.Identity(300,20,0,"0",null)))
|
||||
.when(jdbc).query(contains("FROM store_resource"),any(RowMapper.class),any(Object[].class));
|
||||
doReturn(List.of(new StorageReferenceGuard.Identity(400,20,0,"0",300L)))
|
||||
.when(jdbc).query(contains("FROM store_space"),any(RowMapper.class),any(Object[].class));
|
||||
doReturn(List.of(500L)).when(jdbc).query(startsWith("SELECT table_file_id FROM store_table_file"),
|
||||
any(RowMapper.class),any(Object[].class));
|
||||
doReturn(before).when(repository).requireDetail(actor,500L);
|
||||
when(jdbc.query(contains("FROM store_table_file t WHERE t.table_file_id"),any(RowMapper.class),any(Object[].class)))
|
||||
.thenAnswer(call -> {
|
||||
var rs = mock(java.sql.ResultSet.class);
|
||||
when(rs.getString("object_type")).thenReturn("TABLE");
|
||||
when(rs.getString("engine_type")).thenReturn("DORIS");
|
||||
when(rs.getString("storage_format")).thenReturn("DORIS_NATIVE");
|
||||
when(rs.getString("execution_state")).thenReturn("CONFIRMED");
|
||||
when(rs.getString("policy_execution_state")).thenReturn("NOT_REQUESTED");
|
||||
return List.of(((RowMapper)call.getArgument(1)).mapRow(rs,0));
|
||||
});
|
||||
when(jdbc.queryForObject(contains("COUNT(*)"),eq(Long.class),any(Object[].class))).thenReturn(0L);
|
||||
when(jdbc.update(anyString(),any(Object[].class))).thenAnswer(call -> {
|
||||
String sql = call.getArgument(0);
|
||||
assertThat(sql.chars().filter(c -> c == '?').count()).isEqualTo(call.getArguments().length - 1);
|
||||
writes.add(sql); return 1;
|
||||
});
|
||||
}
|
||||
|
||||
@Test void missingTargetReusesIdentityAndPreservesHistoryWithAtomicCommandBinding() {
|
||||
var result = repository.reserveCommandCreate(actor,"recreate-0001","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> {
|
||||
assertThat(writes).anyMatch(sql -> sql.contains("INSERT INTO store_table_file_snapshot"));
|
||||
});
|
||||
assertThat(result.tableFileId()).isEqualTo(500L);
|
||||
assertThat(result.replayed()).isFalse();
|
||||
assertThat(writes).noneMatch(sql -> sql.contains("DELETE FROM") || sql.startsWith("INSERT INTO store_table_file("));
|
||||
assertThat(writes).anyMatch(sql -> sql.contains("TARGET_RECREATE_PENDING") && sql.contains("version=version+1"));
|
||||
verify(manager).commit(any());
|
||||
}
|
||||
|
||||
@Test void concurrentOrUnknownPreviousOperationPreventsAnotherCreate() {
|
||||
when(jdbc.queryForObject(contains("COUNT(*)"),eq(Long.class),any(Object[].class))).thenReturn(1L);
|
||||
assertThatThrownBy(() -> repository.reserveCommandCreate(actor,"recreate-0002","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> fail("must not bind")))
|
||||
.isInstanceOf(TableFileErrors.Conflict.class).hasMessageContaining("结果待确认");
|
||||
assertThat(writes).isEmpty();
|
||||
verify(manager).rollback(any());
|
||||
}
|
||||
|
||||
@Test void failedCommandBindingRollsBackRecreationReservation() {
|
||||
assertThatThrownBy(() -> repository.reserveCommandCreate(actor,"recreate-0003","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> { throw new IllegalStateException("lost command CAS"); }))
|
||||
.hasMessage("lost command CAS");
|
||||
verify(manager).rollback(any());
|
||||
verify(manager,never()).commit(any());
|
||||
}
|
||||
|
||||
@Test void delayedOldCompletionCannotOverwriteNewRegistration() {
|
||||
doReturn(0).when(jdbc).update(startsWith("UPDATE store_table_file_request SET request_status"),any(Object[].class));
|
||||
repository.completeMutation(actor,new TableFileRepository.Reservation(1,"old",500,false,"CREATE"),
|
||||
ExecutionState.CONFIRMED,false,"old-object",null,null,LocalDateTime.now());
|
||||
assertThat(writes).isEmpty();
|
||||
}
|
||||
|
||||
@Test void compatibleLiveTargetRefreshesColumnsAndAddsSnapshotWithoutDdl() {
|
||||
repository.synchronizeCommandTarget(actor,300,400,EngineType.DORIS,"internal","sales","orders",
|
||||
TableFileBindingRepositoryTest.selection().columns());
|
||||
assertThat(writes).hasSize(3);
|
||||
assertThat(writes.getFirst()).contains("columns_json=?", "execution_state='CONFIRMED'");
|
||||
assertThat(writes.getLast()).contains("store_table_file_snapshot");
|
||||
}
|
||||
}
|
||||
+14
@@ -161,6 +161,20 @@ class TableFileServiceTest {
|
||||
storage, layers, integration);
|
||||
private final TableFileActor actor = new TableFileActor(10L, 20L, false);
|
||||
|
||||
@Test void onlyExplicitLiveAbsencePermitsRecreation() {
|
||||
when(integration.browse(any())).thenReturn(new TableFileIntegrationService.DirectoryResult(
|
||||
TableFileIntegrationService.State.REJECTED,List.of(),List.of(),0,"目标表已确认不存在",true));
|
||||
assertThatThrownBy(() -> service.targetDirectory(300,400,EngineType.HIVE,"orders",null,1,20))
|
||||
.isInstanceOf(TableFileErrors.MissingTarget.class);
|
||||
for (var state : List.of(TableFileIntegrationService.State.REJECTED,TableFileIntegrationService.State.UNKNOWN)) {
|
||||
when(integration.browse(any())).thenReturn(new TableFileIntegrationService.DirectoryResult(
|
||||
state,List.of(),List.of(),0,"权限不足或连接失败"));
|
||||
assertThatThrownBy(() -> service.targetDirectory(300,400,EngineType.HIVE,"orders",null,1,20))
|
||||
.isExactlyInstanceOf(TableFileErrors.Reference.class);
|
||||
}
|
||||
org.mockito.Mockito.verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void references() {
|
||||
when(actorProvider.current()).thenReturn(actor);
|
||||
|
||||
+61
-3
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+78
@@ -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).*");
|
||||
}
|
||||
}
|
||||
+5
@@ -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) {
|
||||
|
||||
+24
-2
@@ -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());
|
||||
|
||||
+14
-1
@@ -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();
|
||||
|
||||
+23
@@ -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());
|
||||
|
||||
+31
@@ -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);
|
||||
}
|
||||
}
|
||||
+20
-2
@@ -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);
|
||||
|
||||
+13
@@ -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);
|
||||
|
||||
在新工单中引用
屏蔽一个用户