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

这个提交包含在:
apple
2026-12-02 16:42:55 +08:00
父节点 bd87d49778
当前提交 b49578022b
共修改 70 个文件,包含 1581 行新增和 45 行删除
@@ -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.
@@ -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) { }
@@ -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 ||
@@ -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);
@@ -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. */ }
}
}
}
}
@@ -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;
@@ -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("目标目录访问繁忙,请稍后重试"); }
}
@@ -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) {
@@ -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),
@@ -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(
@@ -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);
@@ -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");
@@ -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");
}
}
@@ -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");
}
}
@@ -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);