修改API采集,和离线采集的 bug
这个提交包含在:
+12
-1
@@ -484,8 +484,19 @@ public final class TableFileApi {
|
||||
PartitionPolicy partitionPolicy,
|
||||
ViewDefinition viewDefinition,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
|
||||
String physicalTableComment
|
||||
String physicalTableComment,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY)
|
||||
List<String> uniqueKeyColumns
|
||||
) {
|
||||
public CreateCommand(String name, ObjectType objectType, Long layerId, Long storageResourceId,
|
||||
Long storageSpaceId, EngineType engineType, StorageFormat storageFormat,
|
||||
String catalogName, String namespaceName, String externalLocation, String comment,
|
||||
List<ColumnDefinition> columns, PartitionPolicy partitionPolicy, ViewDefinition viewDefinition,
|
||||
String physicalTableComment) {
|
||||
this(name, objectType, layerId, storageResourceId, storageSpaceId, engineType, storageFormat,
|
||||
catalogName, namespaceName, externalLocation, comment, columns, partitionPolicy, viewDefinition,
|
||||
physicalTableComment, null);
|
||||
}
|
||||
public CreateCommand(String name, ObjectType objectType, Long layerId, Long storageResourceId,
|
||||
Long storageSpaceId, EngineType engineType, StorageFormat storageFormat,
|
||||
String catalogName, String namespaceName, String externalLocation, String comment,
|
||||
|
||||
+13
@@ -51,6 +51,19 @@ public interface DataCollectionIntegrationService {
|
||||
return new ApiPollResult("UNKNOWN", 0, null, "API_POLL_ADAPTER_UNAVAILABLE");
|
||||
}
|
||||
|
||||
default ApiPreviewResult previewApi(ApiPreviewRequest request) {
|
||||
return new ApiPreviewResult("UNKNOWN", "API_PREVIEW_UNAVAILABLE", List.of());
|
||||
}
|
||||
|
||||
record ApiPreviewRequest(long actorId, long orgScopeId, String endpoint, String secretRef,
|
||||
String paginationMode, String paginationField, String responsePath,
|
||||
ApiPollProfile profile) implements Serializable { }
|
||||
record ApiPreviewField(String name, String fieldType, boolean nullable, boolean supported,
|
||||
String warning) implements Serializable { }
|
||||
record ApiPreviewDataset(String path, int sampledRows, List<ApiPreviewField> fields,
|
||||
List<Map<String, String>> rows) implements Serializable { }
|
||||
record ApiPreviewResult(String status, String errorCode, List<ApiPreviewDataset> datasets) implements Serializable { }
|
||||
|
||||
record ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark,
|
||||
FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile,
|
||||
ApiPollProfile profile) implements Serializable {
|
||||
|
||||
+15
-2
@@ -22,7 +22,12 @@ public interface TableFileIntegrationService {
|
||||
}
|
||||
}
|
||||
record DirectoryResult(State state, List<String> tables, List<DirectoryColumn> columns, int total,
|
||||
String errorSummary) implements Serializable { }
|
||||
String errorSummary, boolean confirmedMissing) implements Serializable {
|
||||
public DirectoryResult(State state, List<String> tables, List<DirectoryColumn> columns, int total,
|
||||
String errorSummary) {
|
||||
this(state, tables, columns, total, errorSummary, false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Separate, opt-in physical evidence contract. A null fact/list is unobserved, never an empty assertion. */
|
||||
default StructureResult structure(DirectoryCommand command, String expectedSha256) {
|
||||
@@ -133,8 +138,16 @@ public interface TableFileIntegrationService {
|
||||
List<Column> columns,
|
||||
PartitionSpec partitionSpec,
|
||||
ViewSpec viewSpec,
|
||||
String physicalTableComment
|
||||
String physicalTableComment,
|
||||
List<String> uniqueKeyColumns
|
||||
) implements Serializable {
|
||||
public CreateCommand(String requestId, long actorId, ConnectionProfile connection, ObjectType objectType,
|
||||
StorageFormat storageFormat, String catalogName, String namespaceName, String objectName,
|
||||
String externalLocation, List<Column> columns, PartitionSpec partitionSpec, ViewSpec viewSpec,
|
||||
String physicalTableComment) {
|
||||
this(requestId, actorId, connection, objectType, storageFormat, catalogName, namespaceName, objectName,
|
||||
externalLocation, columns, partitionSpec, viewSpec, physicalTableComment, null);
|
||||
}
|
||||
public CreateCommand(String requestId, long actorId, ConnectionProfile connection, ObjectType objectType,
|
||||
StorageFormat storageFormat, String catalogName, String namespaceName, String objectName,
|
||||
String externalLocation, List<Column> columns, PartitionSpec partitionSpec, ViewSpec viewSpec) {
|
||||
|
||||
+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);
|
||||
|
||||
@@ -53,6 +53,19 @@ export interface ApiPollProfile {
|
||||
}
|
||||
|
||||
const base = '/api/dataops/v1/api-ingestions';
|
||||
export interface ApiPreviewRequest {
|
||||
intakeId?: FileId;
|
||||
endpoint: string;
|
||||
credential?: string;
|
||||
paginationMode: string;
|
||||
paginationField: string;
|
||||
responsePath?: string;
|
||||
profile: ApiPollProfile;
|
||||
}
|
||||
export interface ApiPreviewField { name: string; fieldType: 'STRING' | 'BIGINT' | 'BOOLEAN'; nullable: boolean; supported: boolean; warning?: string }
|
||||
export interface ApiPreviewDataset { path: string; sampledRows: number; fields: ApiPreviewField[]; rows: Record<string, string | null>[] }
|
||||
export const previewApi = (data: ApiPreviewRequest): AxiosPromise<{ status: string; errorCode?: string; datasets: ApiPreviewDataset[] }> =>
|
||||
request({ url: `${base}/preview`, method: 'post', data, timeout: 190000, headers: { repeatSubmit: false } });
|
||||
export const getApiPoll = (id: FileId): AxiosPromise<ApiPollState> => request({ url: `${base}/${id}/poll`, method: 'get' });
|
||||
export const setApiPolling = (id: FileId, enabled: boolean): AxiosPromise<ApiPollState> =>
|
||||
request({ url: `${base}/${id}/poll`, method: 'put', data: { enabled } });
|
||||
|
||||
@@ -97,6 +97,7 @@ export interface TableFileQuery extends PageQuery {
|
||||
}
|
||||
|
||||
export interface CreateTableFileRequest {
|
||||
uniqueKeyColumns?: string[];
|
||||
name: string;
|
||||
objectType: ObjectType;
|
||||
layerId: string | number;
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
<template>
|
||||
<div class="api-target-setup">
|
||||
<section class="api-target-section">
|
||||
<div class="api-target-section__heading"><span class="api-target-section__number">1</span><h3>测试接口并预览数据</h3></div>
|
||||
<div class="api-target-section__actions">
|
||||
<el-button v-hasPermi="['aixun:dataops:file-ingestion:create']" :loading="busy" :disabled="disabled" @click="testApi">测试接口</el-button>
|
||||
<el-text type="info">读取第一页,最多展示 20 条样本,不写入目标表</el-text>
|
||||
</div>
|
||||
<el-alert v-if="error" :title="error" type="warning" :closable="false" show-icon />
|
||||
<template v-if="datasets.length">
|
||||
<el-form-item label="记录所在位置"><el-select v-model="path" class="w-full" @change="chooseDataset"><el-option v-for="item in datasets" :key="item.path" :value="item.path" :label="`${item.path}(样本 ${item.sampledRows} 条)`" /></el-select></el-form-item>
|
||||
<el-table v-if="dataset" :data="dataset.rows" border max-height="240" empty-text="接口没有返回记录,暂不能推断字段"><el-table-column v-for="field in dataset.fields" :key="field.name" :prop="field.name" :label="field.name" min-width="140" show-overflow-tooltip /></el-table>
|
||||
<el-text v-if="unsupported.length" type="warning">以下字段未自动加入:{{ unsupported.map(field => `${field.name}(${field.warning})`).join(';') }}</el-text>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section class="api-target-section">
|
||||
<div class="api-target-section__heading"><span class="api-target-section__number">2</span><h3>确认目标表</h3></div>
|
||||
<el-radio-group v-model="mode" :disabled="busy || creating || disabled" @change="changeMode">
|
||||
<el-radio-button value="new">新建目标表</el-radio-button><el-radio-button value="existing">写入已有表</el-radio-button>
|
||||
</el-radio-group>
|
||||
<el-alert v-if="mode === 'new'" title="根据样本生成草稿。请确认类型和唯一字段;重复唯一值会更新同一条记录。" type="info" :closable="false" />
|
||||
<template v-if="mode === 'new'">
|
||||
<el-form-item label="目标分层"><el-select v-model="layerId" class="w-full" filterable placeholder="选择 Doris 分层" @visible-change="value => value && loadLayers()"><el-option v-for="layer in layers" :key="String(layer.layerId)" :value="String(layer.layerId)" :label="`${layer.layerName} / ${layer.namespaceName}`" /></el-select></el-form-item>
|
||||
<el-form-item label="新表名称"><el-input v-model="tableName" maxlength="64" placeholder="例如 api_orders" /></el-form-item>
|
||||
</template>
|
||||
<el-form-item v-else label="目标表">
|
||||
<div class="api-target-section__select-row">
|
||||
<el-select v-model="selectedId" filterable :loading="loadingColumns" @change="selectExisting"><el-option v-for="table in tables" :key="String(table.tableFileId)" :value="String(table.tableFileId)" :label="`${table.namespaceName}.${table.name}`" /></el-select>
|
||||
<el-button link type="primary" @click="$emit('refresh')">刷新候选</el-button>
|
||||
</div>
|
||||
</el-form-item>
|
||||
<el-text v-if="mode === 'existing'" type="info">目标表必须为 UNIQUE KEY 表;执行前会核对实际表结构。类型不同的字段请人工确认。</el-text>
|
||||
</section>
|
||||
|
||||
<section class="api-target-section">
|
||||
<div class="api-target-section__heading"><span class="api-target-section__number">3</span><h3>确认字段映射</h3></div>
|
||||
<div v-if="dataset || difference" class="api-target-section__actions">
|
||||
<el-button v-if="dataset" :disabled="busy || creating || loadingColumns" @click="remap">重新匹配字段</el-button>
|
||||
<el-text v-if="difference" type="warning">{{ difference }}</el-text>
|
||||
</div>
|
||||
<el-table :data="schema" border empty-text="先测试接口,系统会自动生成字段映射">
|
||||
<el-table-column label="来源字段" min-width="140"><template #default="{ row }"><el-input v-model="row.sourceField" /></template></el-table-column>
|
||||
<el-table-column label="目标字段" min-width="140"><template #default="{ row }">
|
||||
<el-select v-if="mode === 'existing'" v-model="row.targetField" filterable placeholder="请选择对应字段" @change="value => applyColumn(row as FileSchemaField, value)"><el-option v-for="column in columns" :key="column.name" :label="`${column.name} (${column.type})`" :value="column.name" /></el-select>
|
||||
<el-input v-else v-model="row.targetField" />
|
||||
</template></el-table-column>
|
||||
<el-table-column label="类型" width="130"><template #default="{ row }"><el-select v-model="row.fieldType" :disabled="mode === 'existing'"><el-option v-for="type in types" :key="type" :label="type" :value="type" /></el-select></template></el-table-column>
|
||||
<el-table-column label="可空" width="70"><template #default="{ row }"><el-switch v-model="row.nullable" :disabled="mode === 'existing' || keys.includes(row.targetField)" /></template></el-table-column>
|
||||
<el-table-column label="操作" width="80"><template #default="{ $index }"><el-button link type="danger" @click="removeField($index)">移除</el-button></template></el-table-column>
|
||||
</el-table>
|
||||
<el-button @click="addField">添加字段</el-button>
|
||||
<template v-if="mode === 'new'">
|
||||
<el-form-item label="唯一字段"><el-select v-model="keys" multiple class="w-full" placeholder="选择一个字段或字段组合" @change="confirmKeys"><el-option v-for="field in schema.filter(item => item.targetField)" :key="field.targetField" :value="field.targetField" :label="field.targetField" /></el-select></el-form-item>
|
||||
<el-checkbox v-model="keyConfirmed">我已确认这些字段能唯一标识一条业务记录</el-checkbox>
|
||||
<div><el-button v-hasPermi="['aixun:dataops:table-file:create']" type="primary" :loading="creating" :disabled="!dataset || !keyConfirmed || busy || disabled" @click="createTarget">确认建表并采用映射</el-button></div>
|
||||
</template>
|
||||
<el-text v-if="targetId" type="success">已选择目标表,保存后可手动采集或按设置轮询。</el-text>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { previewApi } from '@/api/datagov/api-ingestion';
|
||||
import type { ApiPreviewRequest, ApiPreviewDataset } from '@/api/datagov/api-ingestion';
|
||||
import { createTableFile, getTableFile } from '@/api/datagov/table-files';
|
||||
import type { TableFileVO, ColumnDefinition, CreateTableFileRequest } from '@/api/datagov/table-files/types';
|
||||
import { pageLakehouseLayers } from '@/api/datagov/lakehouse-layers';
|
||||
import type { LayerVO } from '@/api/datagov/lakehouse-layers/types';
|
||||
import type { FileSchemaField } from '@/api/datagov/file-ingestion/types';
|
||||
import { apiDraftColumns, mappingType, matchApiFields } from './apiMapping';
|
||||
|
||||
const props = defineProps<{ request: () => ApiPreviewRequest; fingerprint: string; tables: TableFileVO[]; targetId: string; disabled: boolean; editing: boolean }>();
|
||||
const schema = defineModel<FileSchemaField[]>('schema', { required: true });
|
||||
const emit = defineEmits<{ target: [table: TableFileVO | null]; path: [path: string]; refresh: [] }>();
|
||||
const mode = ref(props.editing || props.targetId ? 'existing' : 'new');
|
||||
const selectedId = ref(props.targetId);
|
||||
const busy = ref(false), creating = ref(false), loadingColumns = ref(false), error = ref('');
|
||||
const datasets = ref<ApiPreviewDataset[]>([]), path = ref('');
|
||||
const columns = ref<ColumnDefinition[]>([]), layers = ref<LayerVO[]>([]);
|
||||
const layerId = ref(''), tableName = ref(''), keys = ref<string[]>([]), keyConfirmed = ref(false);
|
||||
const dataset = computed(() => datasets.value.find(item => item.path === path.value));
|
||||
const unsupported = computed(() => dataset.value?.fields.filter(field => !field.supported) ?? []);
|
||||
const types = ['STRING', 'BOOLEAN', 'TINYINT', 'SMALLINT', 'INT', 'BIGINT', 'FLOAT', 'DOUBLE', 'DATE', 'TIMESTAMP'];
|
||||
const difference = ref('');
|
||||
let sequence = 0;
|
||||
let createAttempt: { payload: string; key: string } | undefined;
|
||||
watch(() => props.fingerprint, () => { sequence++; datasets.value = []; path.value = ''; difference.value = ''; keyConfirmed.value = false; error.value = '请求配置已变化,请重新测试接口'; });
|
||||
watch(() => props.targetId, value => { selectedId.value = value; });
|
||||
watch(() => JSON.stringify(schema.value), () => { keyConfirmed.value = false; });
|
||||
|
||||
async function testApi() {
|
||||
busy.value = true; error.value = ''; const version = ++sequence;
|
||||
try {
|
||||
const request = props.request();
|
||||
if (!request.endpoint && !request.intakeId) throw new Error('请先填写接口地址');
|
||||
const response = await previewApi(request);
|
||||
if (version !== sequence) return;
|
||||
if (response.data.status !== 'SUCCEEDED') throw new Error(`接口预览失败:${response.data.errorCode || '结果未知'}`);
|
||||
datasets.value = response.data.datasets;
|
||||
if (!datasets.value.length) throw new Error('没有识别到记录数组,请检查接口响应和请求参数');
|
||||
path.value = datasets.value.length === 1 ? datasets.value[0].path : '';
|
||||
if (path.value) chooseDataset();
|
||||
} catch (failure) { if (version === sequence) error.value = failure instanceof Error ? failure.message : '接口预览失败'; }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
function chooseDataset() {
|
||||
emit('path', path.value);
|
||||
if (schema.value.some(field => field.sourceField)) {
|
||||
const before = new Set(schema.value.map(field => field.sourceField));
|
||||
const after = new Set(dataset.value?.fields.filter(field => field.supported).map(field => field.name));
|
||||
const added = [...after].filter(name => !before.has(name)), removed = [...before].filter(name => !after.has(name));
|
||||
const changed = dataset.value?.fields.filter(field => schema.value.some(mapping => mapping.sourceField === field.name && mapping.fieldType !== field.fieldType)).map(field => field.name) ?? [];
|
||||
difference.value = added.length || removed.length || changed.length ? `样本差异:新增 ${added.join('、') || '无'};未出现 ${removed.join('、') || '无'};类型需核对 ${changed.join('、') || '无'}。已有映射保留,不自动改表。` : '已有映射已保留,可检查类型后重新匹配。';
|
||||
} else remap();
|
||||
}
|
||||
function remap() {
|
||||
if (!dataset.value) return;
|
||||
if (mode.value === 'existing' && !columns.value.length) { error.value = '请先选择目标表并加载字段'; return; }
|
||||
schema.value = matchApiFields(dataset.value.fields, mode.value === 'existing' ? columns.value : undefined);
|
||||
difference.value = mode.value === 'existing' ? '已匹配同名字段,请处理空白项并核对类型。' : '已按样本生成草稿;文本类型保留编号、前导零和小数原值。';
|
||||
keys.value = []; keyConfirmed.value = false;
|
||||
}
|
||||
function changeMode() { emit('target', null); selectedId.value = ''; columns.value = []; if (mode.value === 'new') { remap(); void loadLayers(); } }
|
||||
async function loadLayers() {
|
||||
try { const response = await pageLakehouseLayers({ mappingStatus: 'CONFIRMED', pageNum: 1, pageSize: 100 }); layers.value = response.data.rows.filter(item => item.enabled && item.engineType === 'DORIS' && item.mappingStatus === 'CONFIRMED'); }
|
||||
catch { error.value = '目标分层加载失败,请重试'; }
|
||||
}
|
||||
async function selectExisting(id: string, preserve = false) {
|
||||
const version = ++sequence; loadingColumns.value = true; columns.value = []; emit('target', null);
|
||||
try {
|
||||
const response = await getTableFile(id);
|
||||
if (version !== sequence) return;
|
||||
if (response.data.tableFile.executionState !== 'CONFIRMED') throw new Error('目标表尚未确认');
|
||||
columns.value = response.data.columns; selectedId.value = id; emit('target', response.data.tableFile);
|
||||
if (!preserve && dataset.value) remap();
|
||||
} catch { if (version === sequence) error.value = '目标表字段加载失败,请重新选择'; }
|
||||
finally { loadingColumns.value = false; }
|
||||
}
|
||||
function applyColumn(row: FileSchemaField, name: string) { const column = columns.value.find(item => item.name === name); if (column) { row.fieldType = mappingType(column.type); row.nullable = column.nullable; } }
|
||||
function confirmKeys() { keyConfirmed.value = false; schema.value.forEach(field => { if (keys.value.includes(field.targetField)) field.nullable = false; }); }
|
||||
function removeField(index: number) { schema.value = schema.value.filter((_, i) => i !== index); }
|
||||
function addField() { schema.value = [...schema.value, { sourceField: '', targetField: '', fieldType: 'STRING', nullable: true }]; }
|
||||
async function createTarget() {
|
||||
if (!keyConfirmed.value || !dataset.value) return;
|
||||
creating.value = true; error.value = '';
|
||||
try {
|
||||
const layer = layers.value.find(item => String(item.layerId) === layerId.value);
|
||||
if (!layer || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(tableName.value)) throw new Error('请选择目标分层并填写有效表名');
|
||||
const definitions = apiDraftColumns(schema.value, keys.value);
|
||||
const payload: CreateTableFileRequest = { name: tableName.value, objectType: 'TABLE', layerId: layer.layerId,
|
||||
storageResourceId: layer.storageResourceId, storageSpaceId: layer.storageSpaceId, engineType: 'DORIS', storageFormat: 'DORIS_NATIVE',
|
||||
catalogName: layer.catalogName, namespaceName: layer.namespaceName, columns: definitions, uniqueKeyColumns: [...keys.value] };
|
||||
const encoded = JSON.stringify(payload);
|
||||
const mappingAtSubmit = JSON.stringify(schema.value);
|
||||
if (createAttempt && createAttempt.payload !== encoded) throw new Error('上次建表请求尚未确认,请先到表管理核对结果,避免重复创建');
|
||||
await ElMessageBox.confirm(`将在 ${layer.namespaceName} 创建 ${tableName.value},包含 ${definitions.length} 个字段,唯一字段为 ${keys.value.join('、')}。是否确认?`, '确认创建目标表');
|
||||
createAttempt ??= { payload: encoded, key: `api-table:${crypto.randomUUID()}` };
|
||||
const response = await createTableFile(payload, createAttempt.key);
|
||||
const result = response.data.result;
|
||||
if (result?.tableFile?.executionState !== 'CONFIRMED') throw new Error('建表结果尚未确认,请到表管理核对;不要重复新建');
|
||||
createAttempt = undefined;
|
||||
if (JSON.stringify(schema.value) !== mappingAtSubmit) { emit('refresh'); throw new Error('目标表已创建,但映射已修改。请选择已有表并重新核对映射'); }
|
||||
columns.value = result.columns; mode.value = 'existing';
|
||||
selectedId.value = String(result.tableFile.tableFileId); emit('target', result.tableFile); ElMessage.success('目标表已创建并采用字段映射');
|
||||
} catch (failure) { if (failure !== 'cancel' && failure !== 'close') error.value = failure instanceof Error ? failure.message : '建表结果未知,请到表管理核对'; }
|
||||
finally { creating.value = false; }
|
||||
}
|
||||
function validate() {
|
||||
if (busy.value || creating.value || loadingColumns.value) return '请等待当前操作完成';
|
||||
if (!props.editing && !dataset.value) return '请先测试接口并选择记录所在位置';
|
||||
if (mode.value !== 'existing' || !props.targetId || !columns.value.length) return '请先创建目标表或选择已有表';
|
||||
if (schema.value.some(field => !columns.value.some(column => column.name === field.targetField))) return '请完成目标字段映射';
|
||||
if (new Set(schema.value.map(field => field.targetField)).size !== schema.value.length) return '目标字段不能重复映射';
|
||||
const missing = columns.value.filter(column => !column.nullable && !schema.value.some(field => field.targetField === column.name));
|
||||
if (missing.length) return `请映射必填目标字段:${missing.map(column => column.name).join('、')}`;
|
||||
return '';
|
||||
}
|
||||
defineExpose({ validate });
|
||||
if (props.targetId) void selectExisting(props.targetId, true);
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.api-target-setup { display: grid; gap: 16px; width: 100%; margin-top: 16px; }
|
||||
.api-target-section { display: flex; flex-direction: column; align-items: flex-start; gap: 16px; min-width: 0; padding: 20px; border: 1px solid var(--el-border-color-light); border-radius: 8px; background: var(--el-fill-color-blank); }
|
||||
.api-target-section__heading { display: flex; align-items: center; gap: 10px; width: 100%; }
|
||||
.api-target-section__heading h3 { margin: 0; color: var(--el-text-color-primary); font-size: 15px; font-weight: 600; line-height: 24px; }
|
||||
.api-target-section__number { display: inline-flex; align-items: center; justify-content: center; flex: 0 0 24px; height: 24px; border-radius: 50%; background: var(--el-color-primary-light-9); color: var(--el-color-primary); font-size: 13px; font-weight: 600; }
|
||||
.api-target-section__actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 12px; width: 100%; }
|
||||
.api-target-section__select-row { display: flex; align-items: center; gap: 12px; width: 100%; min-width: 0; }
|
||||
.api-target-section__select-row > :deep(.el-select) { flex: 1; min-width: 0; }
|
||||
.api-target-section > :deep(.el-form-item), .api-target-section > :deep(.el-table), .api-target-section > :deep(.el-alert) { width: 100%; margin: 0; }
|
||||
.api-target-section > :deep(.el-text) { line-height: 1.5; }
|
||||
</style>
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { apiDraftColumns, matchApiFields } from './apiMapping';
|
||||
|
||||
describe('API mapping and table suggestions', () => {
|
||||
it('matches existing columns case insensitively and leaves missing mappings explicit', () => {
|
||||
const fields = ['id', 'missing'].map(name => ({ name, fieldType: 'STRING' as const, nullable: true, supported: true }));
|
||||
const mappings = matchApiFields(fields, [{ name: 'ID', type: 'BIGINT', nullable: false }]);
|
||||
expect(mappings[0]).toMatchObject({ sourceField: 'id', targetField: 'ID', fieldType: 'BIGINT', nullable: false });
|
||||
expect(mappings[1].targetField).toBe('');
|
||||
});
|
||||
it('requires explicit keys, moves them first and preserves textual IDs', () => {
|
||||
const fields = [{ sourceField: 'name', targetField: 'name', fieldType: 'STRING' as const, nullable: true },
|
||||
{ sourceField: 'id', targetField: 'id', fieldType: 'STRING' as const, nullable: true }];
|
||||
expect(() => apiDraftColumns(fields, [])).toThrow();
|
||||
expect(apiDraftColumns(fields, ['id'])[0]).toEqual({ name: 'id', type: 'VARCHAR', nullable: false, precision: 256 });
|
||||
expect(() => apiDraftColumns(fields, ['absent'])).toThrow();
|
||||
expect(() => apiDraftColumns([...fields, fields[0]], ['id'])).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { ApiPreviewField } from '@/api/datagov/api-ingestion';
|
||||
import type { ColumnDefinition } from '@/api/datagov/table-files/types';
|
||||
import type { FileSchemaField } from '@/api/datagov/file-ingestion/types';
|
||||
|
||||
export function mappingType(type: string): FileSchemaField['fieldType'] {
|
||||
if (['CHAR', 'VARCHAR', 'DECIMAL', 'STRING'].includes(type)) return 'STRING';
|
||||
if (type === 'DATETIME') return 'TIMESTAMP';
|
||||
return type as FileSchemaField['fieldType'];
|
||||
}
|
||||
|
||||
export function matchApiFields(fields: ApiPreviewField[], columns?: ColumnDefinition[]): FileSchemaField[] {
|
||||
return fields.filter(field => field.supported).map(field => {
|
||||
const candidates = columns?.filter(column => column.name.toLowerCase() === field.name.toLowerCase()) ?? [];
|
||||
const target = candidates.length === 1 ? candidates[0] : undefined;
|
||||
return { sourceField: field.name, targetField: columns ? target?.name ?? '' : field.name,
|
||||
fieldType: target ? mappingType(target.type) : field.fieldType, nullable: target?.nullable ?? field.nullable };
|
||||
});
|
||||
}
|
||||
|
||||
export function apiDraftColumns(schema: FileSchemaField[], keys: string[]): ColumnDefinition[] {
|
||||
if (!keys.length || new Set(keys).size !== keys.length) throw new Error('请选择能唯一标识记录的字段');
|
||||
const names = schema.map(field => field.targetField);
|
||||
if (!schema.length || schema.length > 200 || names.some(name => !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(name)) || new Set(names.map(name => name.toLowerCase())).size !== names.length)
|
||||
throw new Error('请填写不重复的有效目标字段名');
|
||||
if (keys.some(key => !names.includes(key))) throw new Error('唯一字段已发生变化,请重新选择');
|
||||
const columns = schema.map(field => {
|
||||
const key = keys.includes(field.targetField);
|
||||
if (key && ['FLOAT', 'DOUBLE', 'BYTES'].includes(field.fieldType)) throw new Error('唯一字段不能使用浮点或二进制类型');
|
||||
if (field.fieldType === 'BYTES') throw new Error('API 建表暂不支持二进制字段');
|
||||
return { name: field.targetField, type: key && field.fieldType === 'STRING' ? 'VARCHAR' : field.fieldType,
|
||||
nullable: key ? false : field.nullable, ...(key && field.fieldType === 'STRING' ? { precision: 256 } : {}) } as ColumnDefinition;
|
||||
});
|
||||
return [...keys.map(key => columns.find(column => column.name === key)!), ...columns.filter(column => !keys.includes(column.name))];
|
||||
}
|
||||
@@ -171,7 +171,7 @@
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
|
||||
<el-col :span="24">
|
||||
<el-col v-if="activeKind === 'file'" :span="24">
|
||||
<el-form-item label="目标表" prop="targetTableFileId">
|
||||
<el-select v-model="configForm.targetTableFileId" class="w-full" filterable :loading="targetTablesLoading" placeholder="请选择已确认的 Doris 表" @change="onTargetTableChanged">
|
||||
<el-option v-for="item in targetTables" :key="String(item.tableFileId)" :label="targetTableLabel(item)" :value="String(item.tableFileId)" />
|
||||
@@ -180,7 +180,7 @@
|
||||
<el-button v-if="targetTablesError" link type="primary" @click="loadTargetTables">刷新候选</el-button>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
<el-col :span="24">
|
||||
<el-col v-if="activeKind === 'file'" :span="24">
|
||||
<el-form-item label="字段结构" prop="schema">
|
||||
<div class="w-full">
|
||||
<el-table :data="configForm.schema" border size="small" empty-text="请添加字段">
|
||||
@@ -268,11 +268,16 @@
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</el-col>
|
||||
<el-col v-if="activeKind === 'api' && configDialogVisible" :span="24">
|
||||
<ApiTargetSetup ref="apiTargetSetup" v-model:schema="configForm.schema" :request="apiPreviewRequest"
|
||||
:fingerprint="apiPreviewFingerprint" :tables="targetTables" :target-id="configForm.targetTableFileId"
|
||||
:disabled="saving" :editing="!!editingIntakeId" @target="adoptApiTarget" @path="configForm.responseContentField = $event" @refresh="loadTargetTables" />
|
||||
</el-col>
|
||||
</el-row>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<div class="dialog-footer">
|
||||
<el-button type="primary" :loading="saving" @click="saveConfig">确 定</el-button>
|
||||
<el-button type="primary" :loading="saving" @click="saveConfig">保存配置</el-button>
|
||||
<el-button @click="closeConfigDialog">取 消</el-button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -398,6 +403,8 @@
|
||||
import WorkbenchOrigin from '@/components/WorkbenchOrigin/index.vue';
|
||||
import EngineeringAssist from '../../ai-workbench/EngineeringAssist.vue';
|
||||
import FilePreview from './FilePreview.vue';
|
||||
import ApiTargetSetup from '../api-ingestion/ApiTargetSetup.vue';
|
||||
import type { ApiPreviewRequest } from '@/api/datagov/api-ingestion';
|
||||
import { mergePreviewMappings } from './filePreview';
|
||||
import type { FormInstance, FormRules } from 'element-plus';
|
||||
import { listTableFiles } from '@/api/datagov/table-files';
|
||||
@@ -825,7 +832,31 @@ const removeSchemaField = (index: number) => {
|
||||
configForm.schema.splice(index, 1);
|
||||
};
|
||||
|
||||
const apiTargetSetup = ref<InstanceType<typeof ApiTargetSetup>>();
|
||||
const apiPreviewFingerprint = computed(() => JSON.stringify({ endpoint: configForm.endpoint,
|
||||
password: configForm.password, paginationMode: configForm.paginationMode, paginationField: configForm.paginationField,
|
||||
profile: profileForm, headers: requestHeadersText.value, query: requestQueryText.value }));
|
||||
function apiPreviewRequest(): ApiPreviewRequest {
|
||||
const { signingKeyConfigured, ...profile } = profileForm;
|
||||
void signingKeyConfigured;
|
||||
return { intakeId: editingIntakeId.value || undefined, endpoint: configForm.endpoint?.trim() || '',
|
||||
credential: configForm.password || undefined, paginationMode: configForm.paginationMode || 'PAGE_SIZE',
|
||||
paginationField: configForm.paginationField || 'page',
|
||||
profile: { ...profile, headers: requestMap(requestHeadersText.value), queryParameters: requestMap(requestQueryText.value),
|
||||
requestBody: profile.requestMethod === 'POST' ? profile.requestBody : undefined,
|
||||
successPath: profile.successPath?.trim() || undefined, successValue: profile.successValue?.trim() || undefined,
|
||||
signingKey: profile.signatureKind === 'NONE' || profile.authKind === 'SIGN_ONLY' ? undefined : profile.signingKey || undefined } };
|
||||
}
|
||||
function adoptApiTarget(target: TableFileVO | null) {
|
||||
if (target && !targetTables.value.some(item => String(item.tableFileId) === String(target.tableFileId))) targetTables.value.push(target);
|
||||
onTargetTableChanged(target ? String(target.tableFileId) : '');
|
||||
}
|
||||
|
||||
const saveConfig = async () => {
|
||||
if (activeKind.value === 'api') {
|
||||
const message = apiTargetSetup.value?.validate();
|
||||
if (message) { ElMessage.warning(message); return; }
|
||||
}
|
||||
if (!await configFormRef.value?.validate().catch(() => false)) return;
|
||||
let profilePayload: ApiPollProfile | undefined;
|
||||
if (activeKind.value === 'api') {
|
||||
|
||||
+40
-1
@@ -1,5 +1,5 @@
|
||||
-- Fresh-install DM schema; target 8.4.4.80 Pack89.
|
||||
-- Source fingerprint: d8933a8e96162fc66fca00c60ae5c0846d5af745a3cf8e4ad787dea89ce4a903
|
||||
-- Source fingerprint: 97402abfb36c6df25ab27f7e616fe279d2d9d55ca0bf1527d365e8203a0618b0
|
||||
-- @statement sys_social
|
||||
CREATE TABLE sys_social (
|
||||
id bigint not null comment '主键',
|
||||
@@ -20638,3 +20638,42 @@ CREATE TABLE ing_api_poll_profile (
|
||||
profile_json CLOB NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- @statement ing_api_poll_state
|
||||
CREATE TABLE ing_api_poll_state (
|
||||
intake_id BIGINT PRIMARY KEY,
|
||||
org_scope_id BIGINT NOT NULL,
|
||||
actor_id BIGINT NOT NULL,
|
||||
enabled INT DEFAULT 0 NOT NULL,
|
||||
watermark VARCHAR(64 CHAR),
|
||||
next_due_at TIMESTAMP NULL,
|
||||
lease_id VARCHAR(64 CHAR),
|
||||
lease_until TIMESTAMP NULL,
|
||||
last_status VARCHAR(32 CHAR) DEFAULT 'NEVER' NOT NULL,
|
||||
last_error_code VARCHAR(128 CHAR),
|
||||
last_written_rows INT DEFAULT 0 NOT NULL,
|
||||
last_run_at TIMESTAMP NULL,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
-- @statement ing_api_poll_state
|
||||
CREATE INDEX idx_api_poll_due ON ing_api_poll_state(enabled, next_due_at);
|
||||
|
||||
-- @statement ing_api_poll_run
|
||||
CREATE TABLE ing_api_poll_run (
|
||||
run_id BIGINT PRIMARY KEY,
|
||||
intake_id BIGINT NOT NULL,
|
||||
org_scope_id BIGINT NOT NULL,
|
||||
actor_id BIGINT NOT NULL,
|
||||
trigger_type VARCHAR(32 CHAR) NOT NULL,
|
||||
run_status VARCHAR(32 CHAR) NOT NULL,
|
||||
written_rows INT DEFAULT 0 NOT NULL,
|
||||
error_code VARCHAR(128 CHAR),
|
||||
watermark_before VARCHAR(64 CHAR),
|
||||
watermark_after VARCHAR(64 CHAR),
|
||||
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
completed_at TIMESTAMP NULL
|
||||
);
|
||||
|
||||
-- @statement ing_api_poll_run
|
||||
CREATE INDEX idx_api_poll_run_intake ON ing_api_poll_run(org_scope_id, intake_id, started_at);
|
||||
|
||||
@@ -1086,3 +1086,7 @@ migrations:
|
||||
ownerUnit: dataops
|
||||
path: db/migration/dataops/V20261126.278__create_api_poll_profile.sql
|
||||
sha256: 25118201e1d723c82410db673af46a68ecc9be53c1a61a2a1762b2110013cc72
|
||||
- version: '20261202.279'
|
||||
ownerUnit: dataops
|
||||
path: db/migration/dataops/V20261202.279__create_api_poll_runtime.sql
|
||||
sha256: b4aa57147e3bb32e3d6e8baa9eb12adcb95175aac89f805d844602fc35ee89fc
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE ing_api_poll_state (
|
||||
intake_id BIGINT PRIMARY KEY,
|
||||
org_scope_id BIGINT NOT NULL,
|
||||
actor_id BIGINT NOT NULL,
|
||||
enabled INT DEFAULT 0 NOT NULL,
|
||||
watermark VARCHAR(64),
|
||||
next_due_at TIMESTAMP NULL,
|
||||
lease_id VARCHAR(64),
|
||||
lease_until TIMESTAMP NULL,
|
||||
last_status VARCHAR(32) DEFAULT 'NEVER' NOT NULL,
|
||||
last_error_code VARCHAR(128),
|
||||
last_written_rows INT DEFAULT 0 NOT NULL,
|
||||
last_run_at TIMESTAMP NULL,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||
);
|
||||
CREATE TABLE ing_api_poll_run (
|
||||
run_id BIGINT PRIMARY KEY,
|
||||
intake_id BIGINT NOT NULL,
|
||||
org_scope_id BIGINT NOT NULL,
|
||||
actor_id BIGINT NOT NULL,
|
||||
trigger_type VARCHAR(32) NOT NULL,
|
||||
run_status VARCHAR(32) NOT NULL,
|
||||
written_rows INT DEFAULT 0 NOT NULL,
|
||||
error_code VARCHAR(128),
|
||||
watermark_before VARCHAR(64),
|
||||
watermark_after VARCHAR(64),
|
||||
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
completed_at TIMESTAMP NULL
|
||||
);
|
||||
CREATE INDEX idx_api_poll_due ON ing_api_poll_state(enabled, next_due_at);
|
||||
CREATE INDEX idx_api_poll_run_intake ON ing_api_poll_run(org_scope_id, intake_id, started_at);
|
||||
@@ -0,0 +1,20 @@
|
||||
-- MySQL counterpart of db/dameng/realtime.sql; explicit forward installation.
|
||||
CREATE TABLE ing_realtime_task (
|
||||
id BIGINT PRIMARY KEY, owner_id BIGINT NOT NULL, org_id BIGINT NOT NULL,
|
||||
create_key VARCHAR(80) NOT NULL, config_json LONGTEXT NOT NULL,
|
||||
source_id BIGINT NOT NULL, server_id BIGINT NOT NULL, target_key VARCHAR(180) NOT NULL,
|
||||
status VARCHAR(24) NOT NULL, version BIGINT NOT NULL, attempt BIGINT NOT NULL,
|
||||
external_id VARCHAR(64), fingerprint VARCHAR(64), checkpoint_id VARCHAR(64), summary VARCHAR(1000),
|
||||
read_rows BIGINT, write_rows BIGINT, observed_at DATETIME, busy_until DATETIME,
|
||||
created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL,
|
||||
CONSTRAINT uq_rt_create UNIQUE(org_id,owner_id,create_key),
|
||||
CONSTRAINT uq_rt_server UNIQUE(source_id,server_id),
|
||||
CONSTRAINT uq_rt_target UNIQUE(target_key)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
CREATE TABLE ing_realtime_event (
|
||||
id BIGINT PRIMARY KEY, task_id BIGINT NOT NULL, request_key VARCHAR(80) NOT NULL,
|
||||
action VARCHAR(16) NOT NULL, status VARCHAR(24) NOT NULL, summary VARCHAR(1000),
|
||||
created_at DATETIME NOT NULL,
|
||||
CONSTRAINT uq_rt_action UNIQUE(task_id,request_key),
|
||||
CONSTRAINT fk_rt_event FOREIGN KEY(task_id) REFERENCES ing_realtime_task(id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
@@ -16733,3 +16733,36 @@ CREATE TABLE `ing_api_poll_profile` (
|
||||
`profile_json` LONGTEXT NOT NULL,
|
||||
`updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
|
||||
CREATE TABLE `ing_api_poll_state` (
|
||||
`intake_id` BIGINT PRIMARY KEY,
|
||||
`org_scope_id` BIGINT NOT NULL,
|
||||
`actor_id` BIGINT NOT NULL,
|
||||
`enabled` INT DEFAULT 0 NOT NULL,
|
||||
`watermark` VARCHAR(64),
|
||||
`next_due_at` TIMESTAMP NULL,
|
||||
`lease_id` VARCHAR(64),
|
||||
`lease_until` TIMESTAMP NULL,
|
||||
`last_status` VARCHAR(32) DEFAULT 'NEVER' NOT NULL,
|
||||
`last_error_code` VARCHAR(128),
|
||||
`last_written_rows` INT DEFAULT 0 NOT NULL,
|
||||
`last_run_at` TIMESTAMP NULL,
|
||||
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
INDEX idx_api_poll_due (enabled, next_due_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
|
||||
CREATE TABLE `ing_api_poll_run` (
|
||||
`run_id` BIGINT PRIMARY KEY,
|
||||
`intake_id` BIGINT NOT NULL,
|
||||
`org_scope_id` BIGINT NOT NULL,
|
||||
`actor_id` BIGINT NOT NULL,
|
||||
`trigger_type` VARCHAR(32) NOT NULL,
|
||||
`run_status` VARCHAR(32) NOT NULL,
|
||||
`written_rows` INT DEFAULT 0 NOT NULL,
|
||||
`error_code` VARCHAR(128),
|
||||
`watermark_before` VARCHAR(64),
|
||||
`watermark_after` VARCHAR(64),
|
||||
`started_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||
`completed_at` TIMESTAMP NULL,
|
||||
INDEX idx_api_poll_run_intake (org_scope_id, intake_id, started_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# API 采集目标设置排版(2026-12-02)
|
||||
|
||||
结论:新增 API 采集弹窗中「测试接口并预览数据」「确认目标表」「确认字段映射」改为独立区块,统一步骤标题、边框和内部留白;「写入已有表」的目标表选择与刷新按钮保持同一行。仅调整 `aixun-ui/src/views/datagov/dataops/api-ingestion/ApiTargetSetup.vue` 的布局与样式,测试、建表、映射和保存逻辑未改。
|
||||
|
||||
验证:`./script/quality/check.sh --frontend src/views/datagov/dataops/api-ingestion/ApiTargetSetup.vue`、`--frontend-build`、`--files` 均 PASS。已登录本地 Browser 检查新增弹窗,两种目标表模式的步骤间距、控件排列和固定底部操作区显示正常;未发送测试接口请求、未建表或保存配置。
|
||||
|
||||
本地发布:Frontend 镜像 `aixun-datagov/frontend:api-target-layout-20261202-r2` 经 `script/datagov/deploy.sh` plan/apply 发布,制品读回 PASS;结果见 `script/datagov/deployment/releases/api-target-layout-20261202-r2-frontend-result.json`。本任务开始前镜像 ID 见 `api-target-layout-20261202-frontend-result.json` 的 `recoveryImageId`;撤回时按局部发布脚本对目标服务单独生成恢复计划,不修改其他服务或数据卷。
|
||||
@@ -0,0 +1,44 @@
|
||||
# API 采集自动建表与映射(2026-12-02)
|
||||
|
||||
结果:**PASS_WITH_LIMITATION**。按用户“按照推荐的方案进行修改”实现并发布本地 Integration、DataOps、Frontend;真实业务 API 到 Doris 的完整采集验收 **NOT_RUN**。
|
||||
|
||||
## 行为
|
||||
|
||||
- 新增 API 采集按“测试接口并预览 → 确认目标表 → 确认字段映射”操作。新建目标表为默认方式;接口第一页最多展示 20 条样本,最多识别 8 组记录数组、每组 200 个字段,响应大小上限 2 MiB。多数组由用户选择。
|
||||
- 样本推断保留编号、前导零和小数原值,无法明确判断的类型按文本处理;嵌套对象/数组及认证敏感字段不自动加入。首次采样生成同名映射;再次采样保留原映射并提示新增、未出现和类型差异,不自动修改已有表。
|
||||
- 新建表复用分层选择、表文件创建、组织权限、幂等请求和结果确认。用户明确选择唯一字段并确认后创建 Doris UNIQUE KEY 表;唯一字段置前且非空,文本唯一字段用 VARCHAR(256)。不推断业务唯一性。已有普通建表仍默认 DUPLICATE KEY。
|
||||
- 已有表加载登记的列结构并匹配同名字段;未匹配项必须处理,不重复写入同一目标列;必填列不能遗漏。运行时读取实际建表定义,要求 UNIQUE KEY 且所有唯一字段均已映射。
|
||||
- 接口请求配置改变后旧样本失效;修改映射后唯一字段确认失效。建表结果未知时保留本次幂等键,先核对表管理结果,不自动换键重建。
|
||||
- 新增预览接口在 DataOps 校验当前用户和组织,临时凭据使用既有受管凭据入口并在结束时撤销,只传 secretRef 给 Integration。复用现有 HTTPS 地址策略、认证和签名协议,不打开目标 JDBC、不建表、不启动轮询;审计不记录请求和响应体。
|
||||
|
||||
主要文件:`aixun-ui/src/views/datagov/dataops/api-ingestion/ApiTargetSetup.vue`、`apiMapping.ts`、`file-ingestion/index.vue`;DataOps `ApiPreviewService/ApiPollController/ApiPollProfileService/ApiPollService`、TableFile 创建契约;Integration `ApiPreviewInference/ApiPollExecutor/TableFileSqlPolicy` 及对应 Dubbo 契约。
|
||||
|
||||
## 数据库和验证
|
||||
|
||||
发现并修复 API 轮询的 MySQL 分页、时间表达式兼容;新增 `db/migration/dataops/V20261202.279__create_api_poll_runtime.sql`,补齐当前业务库和独立测试库原先缺失的 `ing_api_poll_state`、`ing_api_poll_run` 及两个查询索引。执行前确认两表不存在,执行后核对 2 表、2 索引。没有清空业务数据或重新导入种子。迁移摘要:`b4aa57147e3bb32e3d6e8baa9eb12adcb95175aac89f805d844602fc35ee89fc`。
|
||||
|
||||
迁移已登记 catalog;基线生成器增加受限普通列索引语法支持,重新生成 DM/MySQL 全新部署 SQL,现为 640 张所需表;种子仍为 1,521 条。
|
||||
|
||||
| 检查 | 结果 |
|
||||
| --- | --- |
|
||||
| 后端定向测试 | 37 项通过:推断 3、HTTP 预览/采集 4、建表 SQL 11、预览凭据 1、MySQL 轮询事务 1、建表服务/策略/重试 17 |
|
||||
| 前端映射测试 | 2 项通过 |
|
||||
| 前端定向 lint | PASS |
|
||||
| 全量 vue-tsc | 非 PASS:121 项错误位于其他现有页面/组件;最终本次改动文件 0 项错误,未扩大修改范围 |
|
||||
| 后端打包、前端生产构建 | PASS;无 clean 或依赖重装 |
|
||||
| 本地发布制品读回 | Integration、DataOps、Frontend 均通过部署入口 plan/apply,绑定当前制品 |
|
||||
| 后端 health/readiness | Integration、DataOps 均 UP,重启次数 0,无最近启动异常类型 |
|
||||
| 浏览器交互 | NOT_RUN:浏览器 URL 安全策略拒绝访问,没有绕过策略 |
|
||||
| 真实 API→Doris、低权限页面、线上达梦 Pack89 | NOT_RUN |
|
||||
|
||||
MySQL 事务测试只在 `aixun_datagov_dualcheck_20261201` 使用回滚行;没有向业务 API/Doris 写入测试数据。HTTP 预览测试用进程内测试服务验证首次请求和不打开 JDBC;这不等于真实外部链路验收。
|
||||
|
||||
主要命令:`script/quality/check.sh --backend <Integration,DataOps> <定向测试类>`;私有配置包装器执行 `ApiPollServiceJdbcTest`;`pnpm exec vitest run .../apiMapping.test.ts`;定向 `check.sh --frontend`、`vue-tsc --noEmit`、`check.sh --frontend-build`;`./mvnw -B -pl aixun-modules/aixun-integration,aixun-modules/aixun-dataops -am -DskipTests package`;显式执行迁移;三个服务 `deploy.sh --plan/--apply`。检查命令没有应用迁移。
|
||||
|
||||
## 制品与恢复
|
||||
|
||||
- 发布版本:`api-setup-20261202`;计划和恢复镜像身份在 `script/datagov/deployment/releases/api-setup-20261202-*`。
|
||||
- Integration JAR:`aixun-modules/aixun-integration/target/aixun-integration.jar`,SHA256 `540d8acdac5b25b57a34fe6dfb2e43553976750ce6d933d4a47808579bf3fb9a`。
|
||||
- DataOps JAR:`aixun-modules/aixun-dataops/target/aixun-dataops.jar`,SHA256 `5c45fdc9864ac7554d31afeb3f2dc37501199b625c4aef581605d9b777df0152`。
|
||||
- 前端:`aixun-ui/dist`。自动生成声明随构建保留。未创建重复部署压缩包或镜像导出包。
|
||||
- 保留原容器环境、MySQL 连接、网络、挂载、端口;未更改其他服务。恢复应用使用对应发布记录中的原镜像通过部署入口执行,新增两表默认保留前向迁移,不删除其运行记录。
|
||||
@@ -35,3 +35,5 @@
|
||||
本地发布版本 `docx-bugs-20261202`;部署状态和精确恢复镜像以 `script/datagov/deployment/releases/docx-bugs-20261202-{frontend,integration,dataops}-result.json` 为准。未执行数据库迁移,未修改其他项目容器及业务数据。需要恢复时,使用记录内 recoveryImageId 通过同一 deploy.sh plan/apply 回退对应服务;不整栈重启。
|
||||
|
||||
三个服务均已执行 plan/apply,制品读回及 check-config PASS,容器状态 running。应用就绪及业务 UAT 为 NOT_RUN。初始 Docker 守护进程未启动,已使用 `docker desktop start` 恢复;没有执行整栈启动或全局清理。临时截图提取目录和完整构建日志已清理,仅保留本记录、有效构建及部署/恢复记录。
|
||||
|
||||
2026-12-02 用户要求“重新部署一下本地 docker”:复用上述有效制品,对 frontend、integration、dataops 再次执行 `deploy.sh --plan`、`--apply`,发布记录为 `docx-bugs-20261202-redeploy-{服务}-result.json`。三个服务制品读回和 `--check-config` 均 PASS,容器均 running;未改源码、未重复构建、未执行迁移。此次恢复镜像为重部署前同版本镜像,前一版本恢复引用仍保留在原发布记录中。应用就绪和业务 UAT:NOT_RUN;交付结论 PASS_WITH_LIMITATION。
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# 本地服务恢复(2026-12-02)
|
||||
|
||||
结果:PASS_WITH_LIMITATION。按用户“帮我重新启动一下服务”恢复本地运行环境;登录和业务流程验收 NOT_RUN。
|
||||
|
||||
- 起因:Docker Desktop 未运行,Docker daemon 不可连接。执行 `open -a Docker` 后,现有 DataGov 容器按原重启策略自动启动。
|
||||
- Nacos 冷启动期间部分应用首次启动失败并自动重试;资源服务启动失败后进程未退出,待 Nacos 健康后单独执行 `docker restart --time 15 aixun-datagov-resource`。操作前核对项目标签,操作后确认容器 ID、Config、HostConfig、Mounts 均保持。
|
||||
- 最终验证:System、Resource、Integration、DataOps、Governance、DataProduct、Auth、Gateway 的带监控鉴权 health/readiness 全部 UP;MySQL、Redis、Nacos、SeaTunnel 均 healthy;前端登录页 HTTP 200。
|
||||
- 保留当前 MySQL 配置、镜像及持久数据;未修改源码或配置,未执行迁移、重新构建、初始化或清理。未启动已停用的历史 POC/旧元数据组件,未主动操作其他项目容器。
|
||||
- 恢复方式:本次仅启动原容器及重启 Resource,无新制品或配置需要回滚;后续应用发布继续使用 `script/datagov/deploy.sh`。
|
||||
@@ -0,0 +1,47 @@
|
||||
# 采集目标表重建修复
|
||||
|
||||
2026-12-02,状态:PASS_WITH_LIMITATION。用户授权按“实时检查目标库、缺表自动建表、同步登记”的方案修改。源码与定向检查、JAR 构建完成;本次未发布本地或线上服务,未修改线上数据,未重跑历史采集。
|
||||
|
||||
## 原因与改动
|
||||
|
||||
线上 `PROD_ODS.ods_prod_equipment`、`PROD_ODS.ods_prod_product` 已被用户从目标库删除,但平台保留创建成功登记。2026-12-02 15:17、15:27 的采集在 VALIDATED 阶段发生 Conflict;四条明细均未创建 task/run/新 DDL 请求。
|
||||
|
||||
- 目录查询增加 `confirmedMissing` 证据,旧响应默认 false。空目录必须再对精确对象进行不读取业务行的查询;仅 SQLState 42S02 确认缺表。权限、网络、超时、一般 HY000 错误保持不可确认,不能触发自动建表。
|
||||
- 统一采集只在明确缺表且开启自动建表时创建。预留建表请求前再次核验;目标已出现时重新匹配字段后复用。CREATE 明确返回已存在(42S01)时保留原拒绝记录,经真实结构读回后继续,不覆盖外部表。
|
||||
- 实际表已删除时,锁定存储身份及原登记,保留 table_file_id,新增 CREATE 请求和重建前后快照,更新本次结构及状态。正在执行或结果 UNKNOWN 的旧操作阻止重复创建;采集命令绑定与登记预留同事务提交。
|
||||
- 已有目标表通过采集结构校验后,更新已有登记的列及状态,追加 UPDATE 审计快照;不以登记代替实时目录,不自动建立未登记对象的额外管理关系。
|
||||
- 完成回写增加原请求状态 CAS 检查,避免旧请求重复完成覆盖后续重建结果。历史失败采集、历史建表请求不自动重跑或改写。
|
||||
|
||||
本次不增加定时全量同步、独立同步按钮或迁移;采用用户最终选定的采集时核验方案。表文件管理会在采集核验/重建时更新,而非目标库外部删除后立即同步。
|
||||
|
||||
## 文件
|
||||
|
||||
- `aixun-api/aixun-api-integration/.../api/tablefile/TableFileIntegrationService.java`:目录证据契约,保留五参数构造兼容。
|
||||
- `aixun-modules/aixun-integration/.../tablefile/TableFileIntegrationDubboService.java`:缺表核验与建表竞争分类。
|
||||
- `aixun-modules/aixun-dataops/.../tablefile/TableFileErrors.java`、`TableFileService.java`、`TableFileRepository.java`:明确缺表/目标出现、登记重建、审计与完成回写。
|
||||
- `aixun-modules/aixun-dataops/.../batchingestion/UnifiedIngestionService.java`:采集状态机分支。
|
||||
- 定向测试:`TableFileDirectoryTest`、`TableFileRecreationTest`、`TableFileServiceTest`、`UnifiedIngestionRecoveryTest`。
|
||||
|
||||
## 验证与制品
|
||||
|
||||
执行:
|
||||
|
||||
```sh
|
||||
./script/quality/check.sh --backend aixun-modules/aixun-dataops,aixun-modules/aixun-integration 'TableFile*Test,UnifiedIngestion*Test,BatchTarget*Test'
|
||||
./script/quality/check.sh --backend aixun-modules/aixun-dataops 'UnifiedIngestionRecoveryTest,TableFileServiceTest'
|
||||
./script/quality/check.sh --files <本次六个主源码文件与新增 TableFileRecreationTest.java>
|
||||
./mvnw -B -pl aixun-modules/aixun-dataops,aixun-modules/aixun-integration -am package -DskipTests
|
||||
```
|
||||
|
||||
首轮新增测试夹具的问题已修正;受影响测试补跑通过。按两次最终测试结果合并去重:40 个测试类、221 项,214 PASS、7 SKIPPED、0 失败/错误。跳过项为需额外运行环境的既有 JDBC/生命周期测试,不能作为真实数据库并发验收。显式文件检查 PASS,两个服务及依赖模块打包 PASS;打包不重复执行已通过测试。
|
||||
|
||||
当前有效制品:
|
||||
|
||||
| 制品 | SHA-256 |
|
||||
| --- | --- |
|
||||
| `aixun-modules/aixun-integration/target/aixun-integration.jar` | `74e22adba758399d9be9e7edb6cda378c45f4f041cabcf4d7a25208a9340626c` |
|
||||
| `aixun-modules/aixun-dataops/target/aixun-dataops.jar` | `70ee51b7c479115d53d822182d9d19061cac8080a30384f5749323f2fdcddb89` |
|
||||
|
||||
本地部署、线上部署、真实 Doris/Hive 缺表与权限验证、真实并发事务、Browser/RBAC、采集落数:NOT_RUN。未声称线上问题已恢复。此次无数据库迁移和运行变更,运行环境无需恢复;未来发布需绑定这两个服务的实际制品并记录原镜像恢复引用。
|
||||
|
||||
错误分类参考:[Apache Gravitino 的 Doris 缺表错误适配提交](https://www.mail-archive.com/commits@gravitino.apache.org/msg65356.html)。本实现保守依赖明确 SQLState,不通过模糊错误文字判断表已删除。
|
||||
@@ -0,0 +1,17 @@
|
||||
# 采集菜单恢复
|
||||
|
||||
用户授权:按原来的菜单调整当前本地数据库。结果 PASS_WITH_LIMITATION。
|
||||
|
||||
在本地 DataGov MySQL `aixun_datagov_system` 显式执行 `script/database/restore-mysql-ingestion-menus-20261202.sql`,事务已提交。恢复离线采集、实时采集、API采集、文件采集,排序分别为 4、5、6、7。沿用原 RealtimeMenu.java 和 ApiIngestionMenu.java 的 ID、路由、权限和授权规则;新增实时查看/管理、API 菜单各关联两个现有符合条件的角色,无全角色授权。
|
||||
|
||||
只读核验 PASS:四菜单名称、路由、排序、启用/可见状态及三项新增授权数量正确。未修改采集业务表,无源码构建或容器重新部署。Browser 和人工角色功能验收 NOT_RUN;刷新页面加载菜单,如旧会话权限未更新则退出后重新登录。
|
||||
|
||||
恢复材料:`runtime/dev-private/menu-restore-20261202/{sys_menu,sys_role_menu}-before.sql`,仅受影响行,权限 0600。需撤回时先核对后续是否出现新授权或菜单变更,仅撤回本次新增的 2810/2811/2820 菜单及关联,恢复原 0080/0090 行;禁止整库导入覆盖。数据库 ID 均以 SQL 文件完整值为准。
|
||||
|
||||
## 实时采集页面缺表修复
|
||||
|
||||
用户反馈页面报错,DataOps 日志确认列表接口因 `ing_realtime_task` 不存在抛出 BadSqlGrammarException。切库时遗漏了 catalog 之外的 `db/dameng/realtime.sql` 两张表,上述菜单恢复亦未检查配套表。
|
||||
|
||||
新增 MySQL 对应脚本 `db/mysql/realtime.sql`,使用 LONGTEXT、DATETIME 和 utf8mb4_bin,保留原字段、唯一约束和外键。只读确认两表均不存在后,在当前 `aixun_datagov_system` 显式执行建表成功;任务表 21 列、事件表 7 列。页面同形的计数、分页列表、历史查询均执行 PASS,当前任务数量 0。未迁入达梦历史任务,无既有业务数据改写;无应用变更,无需重建或重启容器。端到端页面和真实 CDC 执行 NOT_RUN。
|
||||
|
||||
本次为前向建表,恢复应用时保留表。若需删除,须先确认是否已有新业务数据并另获授权,不自动 DROP。
|
||||
@@ -81,7 +81,17 @@ def collect():
|
||||
tables[name][key] = node
|
||||
else:
|
||||
raise ValueError("unhandled ALTER in " + str(path.relative_to(ROOT)) + ": " + clause[:100])
|
||||
elif re.match(r"(?:DROP TABLE|RENAME TABLE|CREATE\s+(?:UNIQUE\s+)?INDEX)\b", sql, re.I):
|
||||
elif re.match(r"CREATE\s+(?:UNIQUE\s+)?INDEX\b", sql, re.I):
|
||||
index = re.fullmatch(r"CREATE\s+(UNIQUE\s+)?INDEX\s+(\w+)\s+ON\s+(\w+)\s*(\([\w\s,]+\))", sql, re.I)
|
||||
if not index or index.group(3).lower() not in tables:
|
||||
raise ValueError("unsupported index statement: " + sql[:100])
|
||||
name = index.group(3).lower()
|
||||
node = (index.group(1) or "") + "INDEX " + index.group(2) + " " + index.group(4)
|
||||
key = node_key(node)
|
||||
if key in tables[name]:
|
||||
raise ValueError("duplicate index: " + name + "." + key)
|
||||
tables[name][key] = node
|
||||
elif re.match(r"(?:DROP TABLE|RENAME TABLE)\b", sql, re.I):
|
||||
raise ValueError("unhandled schema statement: " + sql[:100])
|
||||
return tables, source_digests
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
-- Scoped restoration of the previously approved DM navigation in local MySQL.
|
||||
-- Apply only to aixun_datagov_system after identity checks and row backup.
|
||||
START TRANSACTION;
|
||||
UPDATE sys_menu SET menu_name='离线采集',order_num=4 WHERE menu_id=1761490000000000080 AND path='/unified-ingestion';
|
||||
UPDATE sys_menu SET menu_name='文件采集',order_num=7 WHERE menu_id=1761490000000000090 AND path='/file-ingestion';
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_time)
|
||||
SELECT 1761490000000002810,'实时采集',1761490000000002010,5,'/realtime-ingestion','datagov/dataops/realtime-ingestion/index','N','N','C','0','0','aixun:dataops:realtime:view','link',CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE menu_id=1761490000000002810);
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_time)
|
||||
SELECT 1761490000000002811,'实时采集管理',1761490000000002810,1,'#','','N','N','F','0','0','aixun:dataops:realtime:manage','link',CURRENT_TIMESTAMP
|
||||
WHERE NOT EXISTS(SELECT 1 FROM sys_menu WHERE menu_id=1761490000000002811);
|
||||
INSERT INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,is_frame,is_cache,menu_type,visible,status,perms,icon,create_time)
|
||||
SELECT 1761490000000002820,'API采集',parent_id,6,'/api-ingestion','datagov/dataops/api-ingestion/index','N','N','C','0','0',perms,'link',CURRENT_TIMESTAMP
|
||||
FROM sys_menu WHERE menu_id=1761490000000000090 AND NOT EXISTS(SELECT 1 FROM sys_menu WHERE menu_id=1761490000000002820);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id)
|
||||
SELECT DISTINCT r.role_id,ids.menu_id FROM sys_role_menu r JOIN sys_menu m ON m.menu_id=r.menu_id
|
||||
CROSS JOIN (SELECT 1761490000000002810 menu_id UNION ALL SELECT 1761490000000002811) ids
|
||||
WHERE m.perms='aixun:dataops:batch-ingestion:submit'
|
||||
AND NOT EXISTS(SELECT 1 FROM sys_role_menu x WHERE x.role_id=r.role_id AND x.menu_id=ids.menu_id);
|
||||
INSERT INTO sys_role_menu(role_id,menu_id)
|
||||
SELECT role_id,1761490000000002820 FROM sys_role_menu r WHERE menu_id=1761490000000000090
|
||||
AND NOT EXISTS(SELECT 1 FROM sys_role_menu x WHERE x.role_id=r.role_id AND x.menu_id=1761490000000002820);
|
||||
COMMIT;
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "789dc1fb25362396b0399cf5872d7c8d4d035e018f3b5562f4dffb1e93add48a",
|
||||
"imageId": "sha256:ace20493d20dc597bdd947bb4073784674877987b5f2031cef78c35dc5f38e76",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u6309\u7167\u63a8\u8350\u65b9\u6848\u4fee\u6539 API \u91c7\u96c6\u5e76\u5b8c\u6210\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1796197048.037544
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "dataops",
|
||||
"containerId": "a99bcf0a3114db03e346868fe3a3d1f72a7a75ef89fa93f7106312fef1852a0d",
|
||||
"imageId": "sha256:ace20493d20dc597bdd947bb4073784674877987b5f2031cef78c35dc5f38e76",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "dataops",
|
||||
"release": "api-setup-20261202",
|
||||
"imageTag": "aixun-datagov/dataops:api-setup-20261202",
|
||||
"imageId": "sha256:ace20493d20dc597bdd947bb4073784674877987b5f2031cef78c35dc5f38e76",
|
||||
"artifactSha256": "5c45fdc9864ac7554d31afeb3f2dc37501199b625c4aef581605d9b777df0152",
|
||||
"sourceContainerId": "789dc1fb25362396b0399cf5872d7c8d4d035e018f3b5562f4dffb1e93add48a",
|
||||
"sourceImageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"sourceImageTag": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"sourceStateSha256": "f472c4e5f83a81db90d78f9fa57d24f86563d5935885028b11502033c21bbabc",
|
||||
"modelSha256": "076890aca8097c9a21fbbaed9ccc39e3c423d4489cd01569f73cd4a910d04f6f",
|
||||
"identitySha256": "67614e7d93746b5a22a5d41862c4abc089ad5d200b51f64fbf26fa791345b8d5"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "e4c61d1a8a947b5d96446ac5cd86121c173ebaa5b61302bb3ace168894af9b6e",
|
||||
"imageId": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u6309\u7167\u63a8\u8350\u65b9\u6848\u4fee\u6539 API \u91c7\u96c6\u5e76\u5b8c\u6210\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1796197087.143861
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "86ee703ffd2069918402c6358414c760d386e159a6d1b6f7151a0efb2a470f96",
|
||||
"imageId": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "api-setup-20261202",
|
||||
"imageTag": "aixun-datagov/frontend:api-setup-20261202",
|
||||
"imageId": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4",
|
||||
"artifactSha256": "c7f9b5c46e097d046f5280421a311d817445d9d2af537ba91573190aab7a4e36",
|
||||
"sourceContainerId": "e4c61d1a8a947b5d96446ac5cd86121c173ebaa5b61302bb3ace168894af9b6e",
|
||||
"sourceImageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"sourceImageTag": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"sourceStateSha256": "cb2005fbb8ce228b3a12bc113526bdfce015fd1c88a53168eb069c4e9aa35ec7",
|
||||
"modelSha256": "dee9f95261f07e401fdfbc286fdad50af85d589c432b9ada3c4c4f015e921775",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "371636f5bd030e1e4b8914481da70d4ce847b74317f7a35a5e89d6e499a275a5",
|
||||
"imageId": "sha256:6edb0654cfa5912374d62760a8f48959ea85b0c0c65434a3c69d81e2b4854861",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u6309\u7167\u63a8\u8350\u65b9\u6848\u4fee\u6539 API \u91c7\u96c6\u5e76\u5b8c\u6210\u672c\u5730\u4ea4\u4ed8",
|
||||
"startedAt": 1796196998.297046
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "integration",
|
||||
"containerId": "cf60b4f32b4bbfc752f0182f64522cf85c56aec8e5b4dd77a1ec81508fe57658",
|
||||
"imageId": "sha256:6edb0654cfa5912374d62760a8f48959ea85b0c0c65434a3c69d81e2b4854861",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "integration",
|
||||
"release": "api-setup-20261202",
|
||||
"imageTag": "aixun-datagov/integration:api-setup-20261202",
|
||||
"imageId": "sha256:6edb0654cfa5912374d62760a8f48959ea85b0c0c65434a3c69d81e2b4854861",
|
||||
"artifactSha256": "540d8acdac5b25b57a34fe6dfb2e43553976750ce6d933d4a47808579bf3fb9a",
|
||||
"sourceContainerId": "371636f5bd030e1e4b8914481da70d4ce847b74317f7a35a5e89d6e499a275a5",
|
||||
"sourceImageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"sourceImageTag": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"sourceStateSha256": "b79f4f58ac31ded9b2fb79c3ea27912ce97db28754c14bad175a3e6f98cdde32",
|
||||
"modelSha256": "cd2795d0a7ee96460d8e8a72a9c9733fc67fab827ecbcb576ed4e550272415b2",
|
||||
"identitySha256": "0927fc120834a47a1af316dbf405bc7a67399b92503e786749f5806d0afdedbf"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "86ee703ffd2069918402c6358414c760d386e159a6d1b6f7151a0efb2a470f96",
|
||||
"imageId": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u4fee\u6539API\u91c7\u96c6\u65b0\u589e\u5f39\u7a97\u4e2d\u6d4b\u8bd5\u4e0e\u76ee\u6807\u8868\u533a\u57df\u6837\u5f0f",
|
||||
"startedAt": 1796200600.901112
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "4ec2ff606c8cd63dba589bd0f114bba616518fbea0e7a2c85216cab7cbe8b974",
|
||||
"imageId": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "api-target-layout-20261202",
|
||||
"imageTag": "aixun-datagov/frontend:api-target-layout-20261202",
|
||||
"imageId": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e",
|
||||
"artifactSha256": "4700d6b40f8525876016954fb5d0e0eae0a9d0bf6bd3a62239e275a3c16863cc",
|
||||
"sourceContainerId": "86ee703ffd2069918402c6358414c760d386e159a6d1b6f7151a0efb2a470f96",
|
||||
"sourceImageId": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4",
|
||||
"sourceImageTag": "sha256:af95eeb0e9de99ab2c03a42429fba597603b745457ba60389eb8e1842453dca4",
|
||||
"sourceStateSha256": "edbceeeb249afc01f2978e97fa817e64954c3ade690522e1f5aa27ba462cfeda",
|
||||
"modelSha256": "8e59184c409c40eb5dcdf8cc6dd0da7bd5b81db88a180f8402fe4bc2f388f38f",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "4ec2ff606c8cd63dba589bd0f114bba616518fbea0e7a2c85216cab7cbe8b974",
|
||||
"imageId": "sha256:26393bdc9cb5f76855e6cc707bed7e2e238730e89c912933ed4e7ede26bb4844",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u4fee\u6539API\u91c7\u96c6\u65b0\u589e\u5f39\u7a97\u4e2d\u6d4b\u8bd5\u4e0e\u76ee\u6807\u8868\u533a\u57df\u6837\u5f0f",
|
||||
"startedAt": 1796200768.666551
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "75a274ec42a7fe17436faa55e503ed71d3c8f12688897a0f9de832a0ed4e8699",
|
||||
"imageId": "sha256:26393bdc9cb5f76855e6cc707bed7e2e238730e89c912933ed4e7ede26bb4844",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "api-target-layout-20261202-r2",
|
||||
"imageTag": "aixun-datagov/frontend:api-target-layout-20261202-r2",
|
||||
"imageId": "sha256:26393bdc9cb5f76855e6cc707bed7e2e238730e89c912933ed4e7ede26bb4844",
|
||||
"artifactSha256": "1d5147623eb8c2e1fde7d0d81b64a8e07acafe1e6beeb8d493cbe4268472724e",
|
||||
"sourceContainerId": "4ec2ff606c8cd63dba589bd0f114bba616518fbea0e7a2c85216cab7cbe8b974",
|
||||
"sourceImageId": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e",
|
||||
"sourceImageTag": "sha256:358599e978d1fcb19bad692f3143c0777d9c85d53773966ba4c71619a456357e",
|
||||
"sourceStateSha256": "b693f29e7dd680dd53f6a594972c16ca67890d760c1e9375661e5d319faa1972",
|
||||
"modelSha256": "dd66a9c6f427062d60266f20500ec3e3b6251fb09e1ca96c967c31ae84c85625",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "9a06392c641b31d680d95b38067a7ba5302b58eb76245d3de088b70085f68392",
|
||||
"imageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u91cd\u65b0\u90e8\u7f72\u672c\u5730 Docker",
|
||||
"startedAt": 1796182302.041471
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "dataops",
|
||||
"containerId": "789dc1fb25362396b0399cf5872d7c8d4d035e018f3b5562f4dffb1e93add48a",
|
||||
"imageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "dataops",
|
||||
"release": "docx-bugs-20261202-redeploy",
|
||||
"imageTag": "aixun-datagov/dataops:docx-bugs-20261202",
|
||||
"imageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"artifactSha256": "53c2075543de1f39a74078b59a4e3c9e01b0b0dcffd2bf97ddcedf5e74d85754",
|
||||
"sourceContainerId": "9a06392c641b31d680d95b38067a7ba5302b58eb76245d3de088b70085f68392",
|
||||
"sourceImageId": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"sourceImageTag": "sha256:27f238c1f4b3d02ddc8095871c2eba42b76fc195d3f3fb38ba9bf06dc77596fb",
|
||||
"sourceStateSha256": "538b5d161fa7e714eb36266546e876e813cf90d2bffc5313de54ec14e7a8c4d6",
|
||||
"modelSha256": "1e6f2ddbb1022b79ae5929a242ead5e65c180e141fdf159b48095f8303fb8ab5",
|
||||
"identitySha256": "67614e7d93746b5a22a5d41862c4abc089ad5d200b51f64fbf26fa791345b8d5"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "6d7aab747ae61a951bb41b27578d284fa82f144b568965c8fb0b86d3882ebbe2",
|
||||
"imageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u91cd\u65b0\u90e8\u7f72\u672c\u5730 Docker",
|
||||
"startedAt": 1796182254.955754
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "frontend",
|
||||
"containerId": "e4c61d1a8a947b5d96446ac5cd86121c173ebaa5b61302bb3ace168894af9b6e",
|
||||
"imageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "frontend",
|
||||
"release": "docx-bugs-20261202-redeploy",
|
||||
"imageTag": "aixun-datagov/frontend:docx-bugs-20261202",
|
||||
"imageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"artifactSha256": "401d222abbf2058f31dc20d3c022ad24c61562c11fb1fb4508fb7613b21422d3",
|
||||
"sourceContainerId": "6d7aab747ae61a951bb41b27578d284fa82f144b568965c8fb0b86d3882ebbe2",
|
||||
"sourceImageId": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"sourceImageTag": "sha256:7cacdb345fd9d4d033027079244847a81c9032aee8e48bea863b0dca245d6ca7",
|
||||
"sourceStateSha256": "ebb774cc643c9c837f577fdcaef14d15f4f6475cfe8db17e1fc24d5daad1c76b",
|
||||
"modelSha256": "6b5645b1af60dc54db2d9d14a7a57bfcf16b87f16fa3e4b3968ce0b416ae2896",
|
||||
"identitySha256": "d0c9630a8fcfc59276ca59df8adcf0043ee76a2c5f5ca0eb6745651a651c1f9f",
|
||||
"artifactPath": "/opt/aixun-datagov/frontend-current"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"sourceContainerId": "665bfa48b77dd01a493bb0789bd8a979d7457bd0ddeefcafcd5f223605e88f4e",
|
||||
"imageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"authorizedBy": "\u7528\u6237\u8981\u6c42\u91cd\u65b0\u90e8\u7f72\u672c\u5730 Docker",
|
||||
"startedAt": 1796182275.029655
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"service": "integration",
|
||||
"containerId": "371636f5bd030e1e4b8914481da70d4ce847b74317f7a35a5e89d6e499a275a5",
|
||||
"imageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"status": "DEPLOYED_FUNCTIONAL_UAT_NOT_RUN",
|
||||
"artifactReadback": "PASS",
|
||||
"applicationReadiness": "NOT_RUN",
|
||||
"recoveryImageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126"
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"version": 1,
|
||||
"service": "integration",
|
||||
"release": "docx-bugs-20261202-redeploy",
|
||||
"imageTag": "aixun-datagov/integration:docx-bugs-20261202",
|
||||
"imageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"artifactSha256": "b815410c7ea1891db28f68025d6e8a99710dd041c264d03e68a01acc4e1074c3",
|
||||
"sourceContainerId": "665bfa48b77dd01a493bb0789bd8a979d7457bd0ddeefcafcd5f223605e88f4e",
|
||||
"sourceImageId": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"sourceImageTag": "sha256:f7fd464f3723e7ba15d7c9af076e99e98d29e7c74db9bdb9bc8eeecd80e7a126",
|
||||
"sourceStateSha256": "f476c93ef2785907996e9beff49f0b5e8346ac6e0fa12238e61c420f025ffbf8",
|
||||
"modelSha256": "d4ed2e6bbce8c755997779d08cc1ed4cb17a000a1b984a63f7a53a393c64874d",
|
||||
"identitySha256": "0927fc120834a47a1af316dbf405bc7a67399b92503e786749f5806d0afdedbf"
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户