比较提交
6
次代码提交
main
..
CDC-Collect
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
|
|
b49578022b | ||
|
|
bd87d49778 | ||
|
|
17e80cef9c | ||
|
|
1146b30509 | ||
|
|
2e2910ce2e | ||
|
|
c252f40172 |
@@ -10,6 +10,9 @@ docs
|
||||
outputs
|
||||
tmp
|
||||
.cache
|
||||
/runtime/dev-private
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/node_modules
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
+2
-2
@@ -8,7 +8,8 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
# Generated packages and build outputs (existing tracked dependencies stay tracked).
|
||||
# Local delivery bundles and generated build output
|
||||
/deliverables/
|
||||
dist/
|
||||
node_modules/
|
||||
coverage/
|
||||
@@ -20,7 +21,6 @@ coverage/
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
/deliverables/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
- 使用aixun-datagov-local、归属明确的aixun-datagov-*容器及专属网络、卷、端口、schema、Redis/Nacos、账号与浏览器存储。拒绝其他项目引用和latest镜像。
|
||||
- 不打印或写入证据密码、token、私钥、连接串和真实.env。保留MIT LICENSE及第三方署名。
|
||||
- 四业务服务保持integration、dataops、governance、dataproduct;适配器位于integration。复用RCP6鉴权、组织、角色、菜单、文件、日志和公共UI;新业务包cn.aixunkeji.datagov.<context>。
|
||||
- DolphinScheduler负责数据DAG,Spring/达梦锁负责内部维护。平台自身数据库全新部署仅支持达梦;外部数据源适配器的MySQL等类型保留。使用批准的外部API/适配器,不直读写产品库;未知观测如实UNKNOWN。
|
||||
- DolphinScheduler负责数据DAG,Spring/平台数据库锁负责内部维护。按用户本次授权,平台自身数据库支持达梦与MySQL通过配置切换;切换需目标库完成初始化并重启服务,不自动迁移业务数据。外部数据源适配器类型保留。使用批准的外部API/适配器,不直读写产品库;未知观测如实UNKNOWN。
|
||||
- 采集节点V1只登记/授权/监控SeaTunnel,不安装或远程运维节点,不执行任意Shell/SSH,不新增DataGov Agent。保留Dubbo,Seata仍关闭。
|
||||
- start-docs下四份原始输入只读。产品、架构和安全结论未明确修订时保持;旧开发过程限制由本规则和ADR-0033替代。
|
||||
- 源码完成、本地部署、人工功能验收分别报告。结果使用PASS / PASS_WITH_LIMITATION / BLOCKED,未运行写NOT_RUN;不推导生产批准。
|
||||
|
||||
@@ -37,4 +37,4 @@ D-020保持:只操作aixun-datagov-local与本项目专属对象,禁止复
|
||||
|
||||
源码完成、本地部署和功能验收分别报告;M0~M6历史结果及其限制保持,不等于当前所有功能已通过或生产批准。四业务单元、RCP6公共能力、DolphinScheduler数据调度、内部维护数据库锁及外部适配器边界保持。
|
||||
|
||||
平台自身数据库的全新部署现适配达梦;连接、初始化和验证边界见[达梦全新部署记录](docs/runbook/达梦全新部署适配-20261118.md)。外部数据源类型不受此切换限制。
|
||||
平台自身数据库支持达梦与MySQL通过连接配置切换,同一套后端制品包含两种驱动;切换后重启服务,数据迁移须单独执行。连接、初始化和验证边界见[达梦与MySQL配置切换](docs/runbook/达梦与MySQL配置切换.md)。外部数据源类型不受此切换限制。
|
||||
|
||||
+1
-10
@@ -28,19 +28,10 @@ public final class UnifiedIngestionApi {
|
||||
public record SourceSelection(long sourceId, long sourceVersion, String sourceName,
|
||||
String sourceDatabase, String table) { }
|
||||
public record DraftRequest(List<SourceSelection> items, StorageResourceType targetType) { }
|
||||
public record FieldCompatibility(String field, String nativeType, String conversion, String error) { }
|
||||
public record DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
|
||||
String sourceTable, String targetTable, String sourceFingerprint,
|
||||
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings,
|
||||
String errorSummary, String sourceTableComment, String sourceTableCommentState,
|
||||
List<FieldCompatibility> fieldCompatibility) {
|
||||
public DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
|
||||
String sourceTable, String targetTable, String sourceFingerprint,
|
||||
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings, String errorSummary,
|
||||
String sourceTableComment, String sourceTableCommentState) {
|
||||
this(sourceId, sourceVersion, sourceName, sourceDatabase, sourceTable, targetTable, sourceFingerprint,
|
||||
columns, mappings, errorSummary, sourceTableComment, sourceTableCommentState, List.of());
|
||||
}
|
||||
String errorSummary, String sourceTableComment, String sourceTableCommentState) {
|
||||
public DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
|
||||
String sourceTable, String targetTable, String sourceFingerprint,
|
||||
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings, String errorSummary) {
|
||||
|
||||
+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,
|
||||
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package cn.aixunkeji.datagov.dataproduct.api.reporting;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/** Authorized fixed dataset references; complete reads and non-snapshot previews remain distinct. */
|
||||
public interface ReportingDatasetDirectory {
|
||||
String VERSION = "1.0.0";
|
||||
String GROUP = "aixun-datagov-reporting-dataset";
|
||||
Page candidates(String keyword, int page, int size);
|
||||
Dataset resolve(String datasetId);
|
||||
default Rows read(Read request) { throw new IllegalStateException("REPORTING_READ_UNAVAILABLE"); }
|
||||
default Rows preview(Read request) { throw new IllegalStateException("REPORTING_PREVIEW_UNAVAILABLE"); }
|
||||
default void authorize(Read request,String authorizationSha256) { throw new IllegalStateException("REPORTING_AUTHORIZATION_UNAVAILABLE"); }
|
||||
record Filter(String field,String operator,List<String> values) implements Serializable { }
|
||||
record Read(Dataset dataset,List<String> columns,List<Filter> filters) implements Serializable { }
|
||||
record Rows(Dataset dataset,List<String> columns,List<java.util.Map<String,String>> rows,
|
||||
String authorizationSha256,String observedAt,boolean complete) implements Serializable { }
|
||||
record Field(String name, String label, String type, boolean nullable) implements Serializable { }
|
||||
record Dataset(String id, String code, String name, long version, String releaseId,
|
||||
String schemaVersionId, String schemaSha256, List<Field> fields) implements Serializable { }
|
||||
record Page(List<Dataset> rows, long total) implements Serializable { }
|
||||
}
|
||||
+1
-6
@@ -10,13 +10,8 @@ public interface NativeQueryPolicyApi {
|
||||
String GROUP="aixun-datagov-native-query-policy";
|
||||
Decision prepare(Request request);
|
||||
Receipt complete(Completion completion);
|
||||
/** Current authorization only; no query ticket or execution receipt is created. */
|
||||
default Decision authorize(Request request) { throw new IllegalStateException("POLICY_REAUTHORIZATION_UNAVAILABLE"); }
|
||||
record Request(long actorId,long departmentId,String tableId,long sourceVersion,long metadataRevision,
|
||||
String engineType,String action,List<String> sourceColumns,String querySha256,String purpose,boolean completeRead) implements Serializable {
|
||||
public Request(long actorId,long departmentId,String tableId,long sourceVersion,long metadataRevision,String engineType,String action,List<String> sourceColumns,String querySha256,String purpose) {
|
||||
this(actorId,departmentId,tableId,sourceVersion,metadataRevision,engineType,action,sourceColumns,querySha256,purpose,false);
|
||||
}
|
||||
String engineType,String action,List<String> sourceColumns,String querySha256,String purpose) implements Serializable {
|
||||
public Request(long actorId,long departmentId,String tableId,long sourceVersion,long metadataRevision,
|
||||
String engineType,String action,List<String> sourceColumns,String querySha256) {
|
||||
this(actorId,departmentId,tableId,sourceVersion,metadataRevision,engineType,action,sourceColumns,querySha256,"BI_QUERY");
|
||||
|
||||
+40
@@ -46,6 +46,46 @@ public interface DataCollectionIntegrationService {
|
||||
|
||||
FileSubmissionResult submitFile(FileSubmissionRequest request);
|
||||
|
||||
/** API polling is executed inside Integration so source credentials never enter a SeaTunnel job. */
|
||||
default ApiPollResult pollApi(ApiPollRequest request) {
|
||||
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 {
|
||||
public ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark,
|
||||
FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile) {
|
||||
this(actorId, orgScopeId, intakeId, watermark, snapshot, targetProfile, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only references to managed secrets cross the service boundary. */
|
||||
record ApiPollProfile(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
String signingSecretRef) implements Serializable { }
|
||||
|
||||
record ApiPollResult(String status, int writtenRows, String watermark, String errorCode)
|
||||
implements Serializable { }
|
||||
|
||||
FileBatchResult observeFileBatches(FileBatchRequest request);
|
||||
|
||||
FileActionResult quarantineFile(FileActionRequest request);
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package cn.aixunkeji.datagov.integration.api;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/** Internal owner-authorized CDC execution contract; never exposed as a public request. */
|
||||
public interface RealtimeCollectionService {
|
||||
Check check(Command command);
|
||||
Check prepare(Command command);
|
||||
Result execute(Command command, String action, String externalId, String restoreId);
|
||||
List<RelayOption> relays(long actorId,long orgId,long sourceId);
|
||||
SourceDefaults sourceDefaults(long actorId,long orgId,long sourceId);
|
||||
record SourceDefaults(long sourceVersion,String sourceSchema,String oracleDatabase,String oraclePdb,
|
||||
String oracleCdbService,String warning) implements Serializable { }
|
||||
record RelayOption(String id,String name,String schema,String table,String format) implements Serializable { }
|
||||
record Spec(String name, long sourceId, long sourceVersion, String sourceDatabase, String sourceTable,
|
||||
long targetResourceId, long targetSpaceId, String targetTable, int httpPort,
|
||||
String startupMode, int checkpointSeconds, long serverId, String sourceSchema,
|
||||
String oracleDatabase,String cdcChannel,String oraclePdb,String oracleCdbService) implements Serializable {
|
||||
public Spec(String name,long sourceId,long sourceVersion,String sourceDatabase,String sourceTable,
|
||||
long targetResourceId,long targetSpaceId,String targetTable,int httpPort,String startupMode,
|
||||
int checkpointSeconds,long serverId,String sourceSchema,String oracleDatabase,String cdcChannel) {
|
||||
this(name,sourceId,sourceVersion,sourceDatabase,sourceTable,targetResourceId,targetSpaceId,targetTable,
|
||||
httpPort,startupMode,checkpointSeconds,serverId,sourceSchema,oracleDatabase,cdcChannel,null,null);
|
||||
}
|
||||
public Spec(String name,long sourceId,long sourceVersion,String sourceDatabase,String sourceTable,
|
||||
long targetResourceId,long targetSpaceId,String targetTable,int httpPort,String startupMode,
|
||||
int checkpointSeconds,long serverId,String sourceSchema,String oracleDatabase) {
|
||||
this(name,sourceId,sourceVersion,sourceDatabase,sourceTable,targetResourceId,targetSpaceId,targetTable,
|
||||
httpPort,startupMode,checkpointSeconds,serverId,sourceSchema,oracleDatabase,null);
|
||||
}
|
||||
public Spec(String name, long sourceId, long sourceVersion, String sourceDatabase, String sourceTable,
|
||||
long targetResourceId, long targetSpaceId, String targetTable, int httpPort,
|
||||
String startupMode, int checkpointSeconds, long serverId) {
|
||||
this(name, sourceId, sourceVersion, sourceDatabase, sourceTable, targetResourceId, targetSpaceId,
|
||||
targetTable, httpPort, startupMode, checkpointSeconds, serverId, null, null);
|
||||
}
|
||||
/** Keep existing MySQL checkpoint fingerprints stable across the contract extension. */
|
||||
public String fingerprintText() {
|
||||
String legacy = "Spec[name="+name+", sourceId="+sourceId+", sourceVersion="+sourceVersion+
|
||||
", sourceDatabase="+sourceDatabase+", sourceTable="+sourceTable+", targetResourceId="+targetResourceId+
|
||||
", targetSpaceId="+targetSpaceId+", targetTable="+targetTable+", httpPort="+httpPort+
|
||||
", startupMode="+startupMode+", checkpointSeconds="+checkpointSeconds+", serverId="+serverId+"]";
|
||||
if(oraclePdb!=null || oracleCdbService!=null)return toString();
|
||||
String previous=toString().replace(", oraclePdb=null, oracleCdbService=null]","]");
|
||||
if(cdcChannel!=null)return previous;
|
||||
return sourceSchema == null && oracleDatabase == null ? legacy : previous.replace(", cdcChannel=null]","]");
|
||||
}
|
||||
}
|
||||
record Command(long actorId, long orgId, long taskId, long attempt, Spec spec,
|
||||
DataCollectionIntegrationService.StorageExecutionProfile target, String fingerprint,
|
||||
RecoveryEvidence recovery) implements Serializable {
|
||||
public Command(long actorId,long orgId,long taskId,long attempt,Spec spec,
|
||||
DataCollectionIntegrationService.StorageExecutionProfile target,String fingerprint) {
|
||||
this(actorId,orgId,taskId,attempt,spec,target,fingerprint,null);
|
||||
}
|
||||
}
|
||||
/** Supplied only by DataOps from its locked, owner-authorized persisted task. */
|
||||
record RecoveryEvidence(String jobId,String status,String checkpointId) implements Serializable { }
|
||||
record Check(boolean ready, String summary, String fingerprint, List<String> fields, List<String> primaryKeys)
|
||||
implements Serializable { }
|
||||
record Result(String status, String externalId, String summary, String checkpointId, Long readRows,
|
||||
Long writeRows) implements Serializable { }
|
||||
static String identity(long org, long task, long attempt) { return "realtime:" + org + ':' + task + ':' + attempt; }
|
||||
static String jobName(long task, long attempt) { return "aixun_cdc_" + task + '_' + attempt; }
|
||||
static String jobId(long org, long task, long attempt) {
|
||||
return Long.toString(DataCollectionIntegrationService.stableJobId(identity(org, task, attempt)));
|
||||
}
|
||||
}
|
||||
-88
@@ -1,88 +0,0 @@
|
||||
package cn.aixunkeji.datagov.integration.api.datasource;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import static cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
|
||||
|
||||
/** Explicit value-preserving carriers for types without a common Hive/Doris scalar type.
|
||||
* Native metadata is retained in the execution snapshot; this never casts to a bounded string.
|
||||
*/
|
||||
public final class BatchTextTypes {
|
||||
private BatchTextTypes() { }
|
||||
public record Carrier(String expression, boolean binary, String description) { }
|
||||
|
||||
public static Carrier carrier(Column c, String identifier) {
|
||||
if (c == null) return null;
|
||||
String raw = c.nativeType() == null ? c.type() : c.nativeType();
|
||||
if (raw == null) return null;
|
||||
raw = raw.toUpperCase(Locale.ROOT).trim();
|
||||
String dialect = raw.contains(":") ? raw.substring(0, raw.indexOf(':')) : "MYSQL";
|
||||
String type = raw.contains(":") ? raw.substring(raw.indexOf(':') + 1) : raw;
|
||||
String base = type.replaceAll("\\([^)]*\\)", "").replace(" UNSIGNED", "").trim().replaceAll("\\s+", " ");
|
||||
String x = identifier;
|
||||
if (dialect.equals("MYSQL")) {
|
||||
if (Set.of("TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT", "STRING").contains(base)) return text(x, "文本完整保存");
|
||||
if (Set.of("BINARY", "VARBINARY", "TINYBLOB", "BLOB", "MEDIUMBLOB", "LONGBLOB").contains(base)) return text("HEX("+x+")", "二进制保存为十六进制,可逆还原");
|
||||
if (Set.of("GEOMETRY", "POINT", "LINESTRING", "POLYGON", "MULTIPOINT", "MULTILINESTRING", "MULTIPOLYGON", "GEOMETRYCOLLECTION", "GEOMCOLLECTION").contains(base))
|
||||
return text("HEX("+x+")", "空间数据保存为含SRID的MySQL内部二进制十六进制");
|
||||
if (Set.of("JSON", "ENUM", "SET", "TIME").contains(base) || wideDecimal(base,c,type))
|
||||
return text("CAST("+x+" AS CHAR CHARACTER SET utf8mb4)", "原始值以文本保存,不保留源类型约束");
|
||||
if (base.equals("BIT") && !Integer.valueOf(1).equals(dimension(c,type)))
|
||||
return text("CAST(CAST("+x+" AS UNSIGNED) AS CHAR)", "位值保存为无符号十进制文本,位宽保留在源结构");
|
||||
} else if (dialect.equals("SQLSERVER")) {
|
||||
if (Set.of("TEXT", "NTEXT", "XML").contains(base) ||
|
||||
Set.of("VARCHAR", "NVARCHAR").contains(base) && (type.contains("MAX") || c.precision()!=null && c.precision()>65535))
|
||||
return text("CONVERT(nvarchar(max),"+x+")", "文本/XML完整保存");
|
||||
if (base.equals("IMAGE") || base.equals("VARBINARY") && (type.contains("MAX") || c.precision()==null || c.precision()>8000))
|
||||
return text("CONVERT(varchar(max),"+x+",2)", "二进制保存为十六进制,可逆还原");
|
||||
if (Set.of("GEOMETRY", "GEOGRAPHY").contains(base))
|
||||
return text("CONVERT(varchar(max),"+x+".Serialize(),2)", "空间对象完整序列化为十六进制(含SRID)");
|
||||
if (base.equals("HIERARCHYID")) return text(x+".ToString()", "层级路径保存为文本");
|
||||
} else if (dialect.equals("ORACLE") || dialect.equals("DAMENG")) {
|
||||
if (Set.of("CLOB", "NCLOB", "TEXT", "LONG", "LONGVARCHAR").contains(base)) return text(x, "大文本完整保存");
|
||||
if (Set.of("BLOB", "LONG RAW", "LONGVARBINARY").contains(base)) return binary(x);
|
||||
if (dialect.equals("ORACLE") && base.equals("RAW")) return text("RAWTOHEX("+x+")", "二进制保存为十六进制,可逆还原");
|
||||
if (dialect.equals("DAMENG") && Set.of("BINARY", "VARBINARY", "RAW").contains(base) &&
|
||||
(c.precision()==null || c.precision()>16383)) return binary(x);
|
||||
if (Set.of("NUMBER", "NUMERIC", "DECIMAL").contains(base) &&
|
||||
(c.precision()==null || c.precision()<1 || c.precision()>38 || c.scale()==null || c.scale()<0 || c.scale()>c.precision()))
|
||||
return text("TO_CHAR("+x+",'TM9','NLS_NUMERIC_CHARACTERS=''.,''')", "数值保存为完整精度文本");
|
||||
if (base.startsWith("TIMESTAMP") && (base.contains("TIME ZONE") || c.scale()==null || c.scale()>6)) {
|
||||
String format = "YYYY-MM-DD\"T\"HH24:MI:SS.FF9"+(base.contains("TIME ZONE") ? " TZH:TZM" : "");
|
||||
return text("TO_CHAR("+x+",'"+format+"')", "时间保存为含小数秒/时区的文本");
|
||||
}
|
||||
if (base.startsWith("INTERVAL")) return text("TO_CHAR("+x+")", "时间间隔保存为文本");
|
||||
if (Set.of("ROWID", "UROWID").contains(base)) return text("TO_CHAR("+x+")", "行标识保存为文本");
|
||||
if (base.equals("XMLTYPE")) return text("XMLSERIALIZE(CONTENT "+x+" AS CLOB)", "XML完整保存");
|
||||
if (base.equals("JSON")) return text("JSON_SERIALIZE("+x+" RETURNING CLOB)", "JSON完整保存为文本");
|
||||
if (dialect.equals("DAMENG") && base.equals("DATE")) return text("TO_CHAR("+x+",'YYYY-MM-DD HH24:MI:SS')", "日期时间保存为文本,保留兼容模式下的时分秒");
|
||||
if (dialect.equals("DAMENG") && (base.equals("TIME") || base.startsWith("TIME "))) return text("CAST("+x+" AS VARCHAR(64))", "时间保存为完整精度文本");
|
||||
} else if (dialect.equals("KINGBASE")) {
|
||||
if (Set.of("VARCHAR", "CHARACTER VARYING", "CHAR", "BPCHAR").contains(base) &&
|
||||
(c.precision()==null || c.precision()<1 || c.precision()>65535))
|
||||
return text("CAST("+x+" AS TEXT)", "无界或大容量字符字段完整保存为文本");
|
||||
if (Set.of("BYTEA", "BLOB", "RAW", "BINARY", "VARBINARY").contains(base)) return binary(x);
|
||||
if (Set.of("TEXT", "CLOB", "NCLOB", "JSON", "JSONB", "XML", "UUID", "BOOL", "BOOLEAN", "REAL", "FLOAT4", "FLOAT8", "DOUBLE PRECISION", "FLOAT", "TIMESTAMP", "TIMESTAMPTZ", "TIMESTAMP WITHOUT TIME ZONE", "TIMESTAMP WITH TIME ZONE", "TIME", "TIMETZ", "TIME WITHOUT TIME ZONE", "TIME WITH TIME ZONE", "INTERVAL", "MONEY", "INET", "CIDR", "MACADDR", "MACADDR8", "BIT", "VARBIT", "BIT VARYING", "POINT", "LINE", "LSEG", "BOX", "PATH", "POLYGON", "CIRCLE", "TSVECTOR", "TSQUERY", "INT4RANGE", "INT8RANGE", "NUMRANGE", "TSRANGE", "TSTZRANGE", "DATERANGE").contains(base) ||
|
||||
base.startsWith("_") || base.endsWith("[]") ||
|
||||
Set.of("NUMERIC", "DECIMAL", "NUMBER").contains(base) && (c.precision()==null || c.precision()<1 || c.precision()>38 || c.scale()==null || c.scale()<0 || c.scale()>c.precision()))
|
||||
return text("CAST("+x+" AS TEXT)", "使用数据库完整文本表示,保留值及精度");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Integer dimension(Column c, String type) {
|
||||
var m=java.util.regex.Pattern.compile("^[A-Z]+\\(([0-9]+)").matcher(type);
|
||||
return m.find() ? Integer.valueOf(m.group(1)) : c.precision();
|
||||
}
|
||||
private static boolean wideDecimal(String base, Column c, String type) {
|
||||
if (!Set.of("DECIMAL", "NUMERIC").contains(base)) return false;
|
||||
Integer p=dimension(c,type);
|
||||
return p!=null && p>38 && p<=65;
|
||||
}
|
||||
private static Carrier text(String expression, String description) { return new Carrier(expression,false,description); }
|
||||
private static Carrier binary(String expression) { return new Carrier(expression,true,"二进制通过采集引擎完整编码为十六进制,可逆还原"); }
|
||||
public static MysqlTargetType mapping(Column c, TargetEngine engine) {
|
||||
Carrier carrier=carrier(c,"field");
|
||||
return carrier==null ? null : new MysqlTargetType(c.name(),c.nativeType()==null?c.type():c.nativeType(),engine,true,"STRING","string",null,null);
|
||||
}
|
||||
}
|
||||
-3
@@ -10,9 +10,6 @@ public interface DataSourceBiQueryApi {
|
||||
String VERSION = "1.0.0";
|
||||
String GROUP = "aixun-datagov-native-bi-query";
|
||||
AnalyticsQuery.Result query(Query query);
|
||||
/** One complete export statement; rejects overflow rather than returning a preview page. */
|
||||
default AnalyticsQuery.Result complete(Query query) { throw new IllegalStateException("COMPLETE_READ_UNAVAILABLE"); }
|
||||
default String authorizeComplete(Query query) { throw new IllegalStateException("COMPLETE_READ_AUTHORIZATION_UNAVAILABLE"); }
|
||||
record Query(long actorId, long departmentId, String tableId, List<String> allowedColumns,
|
||||
AnalyticsQuery.Plan plan,String action,AnalyticsExecution execution) implements Serializable {
|
||||
public Query(long actorId,long departmentId,String tableId,List<String> allowedColumns,AnalyticsQuery.Plan plan,String action){
|
||||
|
||||
-4
@@ -97,10 +97,6 @@ public final class DataSourceObjects {
|
||||
String errorCode, String errorSummary) implements java.io.Serializable { }
|
||||
|
||||
public static MysqlTargetType mysqlTargetType(Column column, TargetEngine engine) {
|
||||
if (column != null && engine != null && column.name() != null && !column.name().isBlank()) {
|
||||
MysqlTargetType text = BatchTextTypes.mapping(column, engine);
|
||||
if (text != null) return text;
|
||||
}
|
||||
if (column != null && engine != null && column.nativeType() != null &&
|
||||
column.nativeType().startsWith(KingbaseBatchTypes.PREFIX)) {
|
||||
return KingbaseBatchTypes.targetType(column, engine);
|
||||
|
||||
+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) {
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@ public interface PrivateBusinessFileOwner {
|
||||
String bytesSha256, long byteLength, String mime,
|
||||
String derivedFromFileId, String derivationPolicyVersion) implements Serializable {
|
||||
public Target {
|
||||
if (!java.util.Set.of("dataproduct", "governance", "dataops", "integration").contains(businessOwner)) throw invalid();
|
||||
if (!java.util.Set.of("dataproduct", "governance", "dataops").contains(businessOwner)) throw invalid();
|
||||
text(objectType); text(objectId); positive(artifactVersion); Objects.requireNonNull(use);
|
||||
text(purpose); text(recipientRef); text(originalName); sha(bytesSha256); positive(byteLength); text(mime);
|
||||
if (originalName.length() > 255 || originalName.contains("/") || originalName.contains("\\")
|
||||
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
package cn.aixunkeji.resource.api.assetupgrade;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** The explicit 32-character MD5 attachment convention; never guesses a 16-character variant. */
|
||||
public final class ReportingAttachmentPolicy {
|
||||
private ReportingAttachmentPolicy() { }
|
||||
public static final int MAX_FILES = 50;
|
||||
public static final int MAX_BYTES = 8 * 1024 * 1024;
|
||||
private static final Map<String,String> TYPES = Map.ofEntries(
|
||||
Map.entry("pdf","application/pdf"),Map.entry("png","image/png"),
|
||||
Map.entry("jpg","image/jpeg"),Map.entry("jpeg","image/jpeg"),
|
||||
Map.entry("txt","text/plain"),Map.entry("csv","text/csv"),Map.entry("json","application/json"),
|
||||
Map.entry("doc","application/msword"),
|
||||
Map.entry("docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
|
||||
public static String originalName(String packagedName) {
|
||||
if(packagedName==null||!packagedName.matches("[A-F0-9]{32}_[^/\\\\\\p{Cntrl}]{1,160}")
|
||||
||packagedName.contains("..")||packagedName.contains(":"))throw invalid();
|
||||
String original=packagedName.substring(33);
|
||||
if(!original.equals(original.strip())||original.startsWith(".")||original.endsWith("."))throw invalid();
|
||||
mime(original);return original;
|
||||
}
|
||||
public static String mime(String original) {
|
||||
if(original==null||original.lastIndexOf('.')<1)throw invalid();
|
||||
String type=TYPES.get(original.substring(original.lastIndexOf('.')+1).toLowerCase(Locale.ROOT));
|
||||
if(type==null)throw invalid();return type;
|
||||
}
|
||||
public static String md5(byte[] bytes) {
|
||||
try{return HexFormat.of().withUpperCase().formatHex(MessageDigest.getInstance("MD5").digest(bytes));}
|
||||
catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}
|
||||
}
|
||||
public static void verify(String packagedName,byte[] bytes) {
|
||||
originalName(packagedName);
|
||||
if(bytes==null||bytes.length==0||bytes.length>MAX_BYTES||!packagedName.startsWith(md5(bytes)+"_"))throw invalid();
|
||||
}
|
||||
private static IllegalArgumentException invalid(){return new IllegalArgumentException("REPORTING_ATTACHMENT_INVALID");}
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
package cn.aixunkeji.common.core.enums;
|
||||
|
||||
/** Platform storage only; external connector dialects are independent. */
|
||||
/** Platform persistence dialect, determined once from the configured JDBC datasource. */
|
||||
public enum PlatformDatabaseDialect {
|
||||
DAMENG, MYSQL;
|
||||
|
||||
@@ -11,6 +11,6 @@ public enum PlatformDatabaseDialect {
|
||||
public static PlatformDatabaseDialect fromProduct(String product) {
|
||||
if ("MySQL".equalsIgnoreCase(product)) return MYSQL;
|
||||
if ("DM DBMS".equalsIgnoreCase(product) || "DM".equalsIgnoreCase(product)) return DAMENG;
|
||||
throw new IllegalArgumentException("Unsupported platform database; expected Dameng or MySQL");
|
||||
throw new IllegalArgumentException("Unsupported platform database product");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</parent>
|
||||
|
||||
<artifactId>aixun-common-maintenance</artifactId>
|
||||
<description>DataGov internal maintenance scheduling and MySQL lease-lock foundation</description>
|
||||
<description>DataGov internal maintenance scheduling and JDBC lease-lock foundation for DM and MySQL</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@ import java.util.Optional;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/** MySQL implementation using one conditional UPDATE as the lease-acquisition linearization point. */
|
||||
/** JDBC implementation using one conditional UPDATE as the lease-acquisition linearization point. */
|
||||
public final class JdbcMaintenanceLeaseRepository implements MaintenanceLeaseRepository {
|
||||
private final cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect;
|
||||
|
||||
@@ -20,8 +20,8 @@ public final class JdbcMaintenanceLeaseRepository implements MaintenanceLeaseRep
|
||||
}
|
||||
|
||||
public JdbcMaintenanceLeaseRepository(JdbcTemplate jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.databaseDialect = databaseDialect;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.databaseDialect = java.util.Objects.requireNonNull(databaseDialect);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-satoken</artifactId>
|
||||
@@ -49,11 +53,8 @@
|
||||
<version>${dynamic-ds.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Both platform drivers ship in the same artifact; selection follows the JDBC URL. -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<!-- Platform database. Reuse the pinned driver already used by Integration;
|
||||
target Pack89 compatibility must be verified against a real server. -->
|
||||
<dependency>
|
||||
<groupId>com.dameng</groupId>
|
||||
<artifactId>DmJdbcDriver18</artifactId>
|
||||
|
||||
-1
@@ -6,7 +6,6 @@ import org.springframework.context.annotation.Bean;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/** Resolve once at startup from the configured platform datasource, never a global mutable flag. */
|
||||
@AutoConfiguration
|
||||
public class PlatformDatabaseConfiguration {
|
||||
@Bean
|
||||
|
||||
+23
-21
@@ -10,33 +10,35 @@ import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class PlatformDatabaseConfigurationTest {
|
||||
static class Consumer {
|
||||
@org.springframework.beans.factory.annotation.Autowired PlatformDatabaseDialect dialect;
|
||||
}
|
||||
@Test void sameApplicationWiringSelectsBothDatabasesAndClosesProbeConnection() throws Exception {
|
||||
@Test void springResolvesActualConfiguredDatabaseAndClosesProbeConnection() throws Exception {
|
||||
for (String product : new String[]{"DM DBMS", "MySQL"}) {
|
||||
var ds=mock(DataSource.class);var connection=mock(Connection.class);var metadata=mock(DatabaseMetaData.class);
|
||||
when(ds.getConnection()).thenReturn(connection);when(connection.getMetaData()).thenReturn(metadata);
|
||||
DataSource source = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
DatabaseMetaData metadata = mock(DatabaseMetaData.class);
|
||||
when(source.getConnection()).thenReturn(connection);
|
||||
when(connection.getMetaData()).thenReturn(metadata);
|
||||
when(metadata.getDatabaseProductName()).thenReturn(product);
|
||||
try(var context=new AnnotationConfigApplicationContext()) {
|
||||
context.registerBean(DataSource.class,()->ds);
|
||||
context.register(PlatformDatabaseConfiguration.class,Consumer.class);context.refresh();
|
||||
var dialect=context.getBean(Consumer.class).dialect;
|
||||
assertThat(dialect).isEqualTo(PlatformDatabaseDialect.fromProduct(product));
|
||||
assertThat(dialect.sql("MERGE INTO test", "INSERT INTO test"))
|
||||
.isEqualTo(product.equals("MySQL")?"INSERT INTO test":"MERGE INTO test");
|
||||
try (var context = new AnnotationConfigApplicationContext()) {
|
||||
context.registerBean(DataSource.class, () -> source);
|
||||
context.register(PlatformDatabaseConfiguration.class);
|
||||
context.refresh();
|
||||
assertThat(context.getBean(PlatformDatabaseDialect.class)).isEqualTo(PlatformDatabaseDialect.fromProduct(product));
|
||||
verify(connection).close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test void unknownEngineCannotSilentlySelectMysql() throws Exception {
|
||||
var ds=mock(DataSource.class);var c=mock(Connection.class);var m=mock(DatabaseMetaData.class);
|
||||
when(ds.getConnection()).thenReturn(c);when(c.getMetaData()).thenReturn(m);when(m.getDatabaseProductName()).thenReturn("PostgreSQL");
|
||||
assertThatThrownBy(()->new PlatformDatabaseConfiguration().platformDatabaseDialect(ds)).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(c).close();
|
||||
@Test void unknownDatabaseFailsWithoutSilentlyUsingMysql() throws Exception {
|
||||
DataSource source = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
DatabaseMetaData metadata = mock(DatabaseMetaData.class);
|
||||
when(source.getConnection()).thenReturn(connection);
|
||||
when(connection.getMetaData()).thenReturn(metadata);
|
||||
when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL");
|
||||
assertThatThrownBy(() -> new PlatformDatabaseConfiguration().platformDatabaseDialect(source)).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(connection).close();
|
||||
}
|
||||
@Test void bothDriversArePresentInTheSameDependencyGraph() throws Exception {
|
||||
assertThat(Class.forName("dm.jdbc.driver.DmDriver")).isAssignableTo(java.sql.Driver.class);
|
||||
assertThat(Class.forName("com.mysql.cj.jdbc.Driver")).isAssignableTo(java.sql.Driver.class);
|
||||
@Test void sameClasspathIncludesBothJdbcDrivers() throws Exception {
|
||||
assertThat(Class.forName("dm.jdbc.driver.DmDriver")).isNotNull();
|
||||
assertThat(Class.forName("com.mysql.cj.jdbc.Driver")).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,8 @@ public class GatewayHttpClientConfig {
|
||||
private static final String CONNECTION_TEST_SUFFIX = "/connection-tests";
|
||||
private static final String UNIFIED_INGESTION_DRAFT_PATH = "/api/dataops/v1/unified-ingestions/draft";
|
||||
private static final String UNIFIED_INGESTION_SUBMIT_PATH = "/api/dataops/v1/unified-ingestions/submit";
|
||||
private static final Pattern REALTIME_INGESTION_ACTION_PATH = Pattern.compile(
|
||||
"/api/dataops/v1/realtime-ingestions/[1-9][0-9]*/(?:CHECK|START|REFRESH|STOP|RESUME|ARCHIVE|DELETE|RECREATE)");
|
||||
private static final String DATA_PROFILE_CREATE_PATH = "/api/governance/v1/data-profiles";
|
||||
private static final String DATA_PROFILE_RETRY_PATH_PREFIX = "/api/governance/v1/data-profiles/";
|
||||
private static final Pattern NUMERIC_ID = Pattern.compile("[0-9]+");
|
||||
@@ -86,8 +88,10 @@ public class GatewayHttpClientConfig {
|
||||
&& isPositive(properties.getStandardAdoptionAiMatchResponseTimeout());
|
||||
boolean runOperationAiDiagnosis = isRunOperationAiDiagnosis(method, uri)
|
||||
&& isPositive(properties.getRunOperationAiDiagnosisResponseTimeout());
|
||||
boolean realtimeIngestionAction = isRealtimeIngestionAction(method, uri)
|
||||
&& isPositive(properties.getRealtimeIngestionActionResponseTimeout());
|
||||
return createRequestContext(uri, properties, dataProfileExecution, metadataCatalogAiDraft,
|
||||
standardAdoptionAiMatch, runOperationAiDiagnosis);
|
||||
standardAdoptionAiMatch, runOperationAiDiagnosis, realtimeIngestionAction);
|
||||
}
|
||||
|
||||
static HttpClientContext createRequestContext(HttpMethod method, URI uri, GatewayHttpClientProperties properties) {
|
||||
@@ -95,21 +99,22 @@ public class GatewayHttpClientConfig {
|
||||
}
|
||||
|
||||
static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties) {
|
||||
return createRequestContext(uri, properties, false, false, false, false);
|
||||
return createRequestContext(uri, properties, false, false, false, false, false);
|
||||
}
|
||||
|
||||
private static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties,
|
||||
boolean dataProfileExecution,
|
||||
boolean metadataCatalogAiDraft,
|
||||
boolean standardAdoptionAiMatch,
|
||||
boolean runOperationAiDiagnosis) {
|
||||
boolean runOperationAiDiagnosis,
|
||||
boolean realtimeIngestionAction) {
|
||||
boolean m2StageCallback = isM2StageCallback(uri);
|
||||
boolean dataSourceConnectionTest = isDataSourceConnectionTest(uri);
|
||||
boolean unifiedIngestionDraft = isUnifiedIngestionDraft(uri);
|
||||
boolean unifiedIngestionSubmit = isUnifiedIngestionSubmit(uri);
|
||||
if (!dataProfileExecution && !m2StageCallback && !dataSourceConnectionTest && !unifiedIngestionDraft
|
||||
&& !unifiedIngestionSubmit && !metadataCatalogAiDraft && !standardAdoptionAiMatch
|
||||
&& !runOperationAiDiagnosis) return null;
|
||||
&& !runOperationAiDiagnosis && !realtimeIngestionAction) return null;
|
||||
|
||||
RequestConfig.Builder requestConfig = RequestConfig.custom();
|
||||
if (properties.getConnectionRequestTimeout() != null) {
|
||||
@@ -139,6 +144,9 @@ public class GatewayHttpClientConfig {
|
||||
if (runOperationAiDiagnosis) {
|
||||
requestConfig.setResponseTimeout(Timeout.of(properties.getRunOperationAiDiagnosisResponseTimeout()));
|
||||
}
|
||||
if (realtimeIngestionAction) {
|
||||
requestConfig.setResponseTimeout(Timeout.of(properties.getRealtimeIngestionActionResponseTimeout()));
|
||||
}
|
||||
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setRequestConfig(requestConfig.build());
|
||||
@@ -175,6 +183,11 @@ public class GatewayHttpClientConfig {
|
||||
&& RUN_OPERATION_AI_DIAGNOSIS_PATH.matcher(uri.getPath()).matches();
|
||||
}
|
||||
|
||||
static boolean isRealtimeIngestionAction(String method, URI uri) {
|
||||
return "POST".equalsIgnoreCase(method) && uri != null && uri.getPath() != null
|
||||
&& REALTIME_INGESTION_ACTION_PATH.matcher(uri.getPath()).matches();
|
||||
}
|
||||
|
||||
private static boolean isPositive(Duration value) {
|
||||
return value != null && !value.isZero() && !value.isNegative();
|
||||
}
|
||||
|
||||
+5
@@ -57,6 +57,11 @@ public class GatewayHttpClientProperties {
|
||||
*/
|
||||
private Duration unifiedIngestionSubmitResponseTimeout = Duration.ofSeconds(180);
|
||||
|
||||
/**
|
||||
* 实时采集操作包含源端校验与外部作业提交,须长于 DataOps 的 120 秒 Dubbo 调用时限。
|
||||
*/
|
||||
private Duration realtimeIngestionActionResponseTimeout = Duration.ofSeconds(135);
|
||||
|
||||
/**
|
||||
* 数据画像创建及数字ID重试等待Governance同步执行完成的超时时间
|
||||
*/
|
||||
|
||||
@@ -30,12 +30,31 @@ class GatewayHttpClientConfigTest {
|
||||
assertThat(properties.getDataSourceConnectionTestResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getUnifiedIngestionDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
|
||||
assertThat(properties.getUnifiedIngestionSubmitResponseTimeout()).isEqualTo(Duration.ofSeconds(180));
|
||||
assertThat(properties.getRealtimeIngestionActionResponseTimeout()).isEqualTo(Duration.ofSeconds(135));
|
||||
assertThat(properties.getDataProfileExecutionResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
|
||||
assertThat(properties.getMetadataCatalogAiDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getStandardAdoptionAiMatchResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getRunOperationAiDiagnosisResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
}
|
||||
|
||||
@Test
|
||||
void realtimeActionsHaveBoundedLongTimeoutWithoutChangingOtherRoutes() {
|
||||
for (String action : List.of("CHECK", "START", "REFRESH", "STOP", "RESUME", "ARCHIVE", "DELETE", "RECREATE")) {
|
||||
URI uri = URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/" + action);
|
||||
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
|
||||
assertThat(context.getRequestConfig().getResponseTimeout().toDuration()).isEqualTo(Duration.ofSeconds(135));
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("GET", uri, properties)).isNull();
|
||||
}
|
||||
for (String path : List.of("/api/dataops/v1/realtime-ingestions/0/START",
|
||||
"/api/dataops/v1/realtime-ingestions/19/START/", "/api/dataops/v1/realtime-ingestions/19/start",
|
||||
"/api/dataops/v1/realtime-ingestions/19/START-extra")) {
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("POST", URI.create("http://aixun-dataops" + path), properties)).isNull();
|
||||
}
|
||||
properties.setRealtimeIngestionActionResponseTimeout(Duration.ZERO);
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("POST",
|
||||
URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/START"), properties)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsBoundedLongTimeoutOnlyForExactRunOperationAiDiagnosisPost() {
|
||||
for (String source : List.of("SCHEDULING", "BATCH_INGESTION", "FILE_INGESTION", "M2_GOLDEN")) {
|
||||
|
||||
+35
-19
@@ -75,6 +75,14 @@ public class UnifiedIngestionService {
|
||||
}
|
||||
|
||||
public SourcePage sources(String keyword) {
|
||||
return sources(keyword, false);
|
||||
}
|
||||
|
||||
public SourcePage realtimeSources(String keyword) {
|
||||
return sources(keyword, true);
|
||||
}
|
||||
|
||||
private SourcePage sources(String keyword, boolean realtime) {
|
||||
BatchActor actor = actors.current();
|
||||
var result = sources.sources(actor.actorId(), actor.orgScopeId(), List.of(), keyword, 200);
|
||||
if (result == null || !"AVAILABLE".equals(result.status()) || result.entries() == null)
|
||||
@@ -86,8 +94,12 @@ public class UnifiedIngestionService {
|
||||
&& Set.of("ORACLE", "DAMENG", "KINGBASE").contains(item.type().toUpperCase(java.util.Locale.ROOT));
|
||||
boolean available = mysql && item.previewEligible() || (sqlServer || pilot) && item.credentialConfigured()
|
||||
&& "SUCCEEDED".equals(item.status()) && item.databaseName() != null && !item.databaseName().isBlank();
|
||||
if (realtime) available = Set.of("MYSQL","SQLSERVER","ORACLE","DAMENG","KINGBASE").contains(item.type())
|
||||
&& item.credentialConfigured() && "SUCCEEDED".equals(item.status())
|
||||
&& item.databaseName() != null && !item.databaseName().isBlank();
|
||||
String reason = mysql ? item.previewReason() : sqlServer ? "请先配置数据库凭据并通过连接测试"
|
||||
: "该数据源类型暂不可用于数据采集";
|
||||
if (realtime) reason = "请在数据源管理中配置凭据并通过连接测试";
|
||||
return new Source(item.id(), item.name(), item.type(), item.status(), item.databaseName(), available,
|
||||
available ? null : reason, item.version());
|
||||
}).toList();
|
||||
@@ -163,7 +175,7 @@ public class UnifiedIngestionService {
|
||||
throw BatchIngestionException.validation("请选择Hive或Doris目标");
|
||||
var page = storage.page(null, type, true, 1, 100);
|
||||
List<Target> rows = page.getRows().stream().map(resource -> {
|
||||
var detail = storage.detail(resource.resourceId());
|
||||
var detail = storage.selectionDetail(resource.resourceId());
|
||||
List<TargetDatabase> databases = detail.spaces().stream().filter(space -> space.enabled())
|
||||
.map(space -> new TargetDatabase(space.spaceId(), space.name(), space.externalObjectId(), space.version()))
|
||||
.toList();
|
||||
@@ -211,18 +223,9 @@ public class UnifiedIngestionService {
|
||||
try {
|
||||
verifySource(actor, item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase());
|
||||
var schema = schema(actor, item.sourceId(), item.sourceDatabase(), item.table());
|
||||
List<FieldCompatibility> compatibility = new ArrayList<>();
|
||||
List<Column> supported = new ArrayList<>();
|
||||
for (Column column : schema.columns()) {
|
||||
var mapped = cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.mysqlTargetType(column, targetEngine);
|
||||
var carrier = cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.carrier(column, "field");
|
||||
compatibility.add(new FieldCompatibility(column.name(), column.nativeType() == null ? column.type() : column.nativeType(),
|
||||
carrier == null ? "按目标类型保存" : carrier.description(), mapped.supported() ? null : mapped.errorSummary()));
|
||||
if (mapped.supported()) supported.add(column);
|
||||
}
|
||||
List<ColumnDefinition> columns = supported.stream()
|
||||
List<ColumnDefinition> columns = schema.columns().stream()
|
||||
.map(column -> BatchTargetTypePolicy.propose(column, targetEngine)).toList();
|
||||
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(supported,
|
||||
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(schema.columns(),
|
||||
new cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult(
|
||||
cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.State.CONFIRMED,
|
||||
List.of(item.table()), columns.stream().map(UnifiedIngestionService::directoryColumn).toList(), 1, null),
|
||||
@@ -231,7 +234,7 @@ public class UnifiedIngestionService {
|
||||
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
|
||||
item.table(), target, fingerprint(item.sourceId(), item.sourceDatabase(), item.table(),
|
||||
schema.columns(), schema.tableComment()), columns, mappings, null,
|
||||
schema.tableComment().value(), schema.tableComment().state().name(), List.copyOf(compatibility)));
|
||||
schema.tableComment().value(), schema.tableComment().state().name()));
|
||||
} catch (RuntimeException exception) {
|
||||
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
|
||||
item.table(), item.table().replace('.', '_').toLowerCase(Locale.ROOT), null, List.of(), List.of(),
|
||||
@@ -331,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("原建表关联缺失");
|
||||
@@ -385,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) {
|
||||
@@ -427,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;
|
||||
}
|
||||
@@ -497,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.
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/dataops/v1/api-ingestions")
|
||||
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) { }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId) { return R.ok(profiles.view(intakeId)); }
|
||||
|
||||
@Log(title="API采集请求配置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId,
|
||||
@RequestBody ApiPollProfileService.Command command) {
|
||||
return R.ok(profiles.save(intakeId, command));
|
||||
}
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> state(@PathVariable long intakeId) { return R.ok(service.state(intakeId)); }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll/runs")
|
||||
public R<List<ApiPollService.PollRun>> runs(@PathVariable long intakeId) { return R.ok(service.runs(intakeId)); }
|
||||
|
||||
@Log(title="API采集轮询设置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> enabled(@PathVariable long intakeId, @RequestBody EnabledCommand command) {
|
||||
return R.ok(service.setEnabled(intakeId, command.enabled()));
|
||||
}
|
||||
|
||||
@Log(title="API采集立即运行", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:submit")
|
||||
@PostMapping("/{intakeId}/poll/run")
|
||||
public R<ApiPollService.PollRun> run(@PathVariable long intakeId) { return R.ok(service.runNow(intakeId)); }
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollProfileService {
|
||||
private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}");
|
||||
private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}");
|
||||
private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}");
|
||||
private static final Set<String> AUTH = Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY");
|
||||
private static final Set<String> SIGN = Set.of("NONE", "HMAC_SHA256", "RSA_SHA256");
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final FileManagedCredentialGateway credentials;
|
||||
|
||||
public record Command(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
char[] signingKey) {
|
||||
@Override public String toString() { return "ApiPollProfileCommand[signingKey=REDACTED]"; }
|
||||
}
|
||||
|
||||
public record View(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
boolean signingKeyConfigured) { }
|
||||
|
||||
public View view(long intakeId) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
return view(profile(actor, intakeId));
|
||||
}
|
||||
|
||||
ApiPollProfile profile(FileIngestionActor actor, long intakeId) {
|
||||
requireApi(actor, intakeId);
|
||||
var rows = jdbc.query("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=? AND org_scope_id=?",
|
||||
(rs, index) -> rs.getString(1), intakeId, actor.orgScopeId());
|
||||
if (rows.isEmpty()) return null;
|
||||
try { return json.readValue(rows.getFirst(), ApiPollProfile.class); }
|
||||
catch (Exception failure) { throw FileIngestionException.validation("API高级配置无效"); }
|
||||
}
|
||||
|
||||
public View save(long intakeId, Command command) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
if (command == null) throw FileIngestionException.validation("API高级配置不能为空");
|
||||
ApiPollProfile current = profile(actor, intakeId);
|
||||
String newRef = null;
|
||||
char[] supplied = command.signingKey();
|
||||
try {
|
||||
validate(command);
|
||||
String kind = command.signatureKind() == null ? "NONE" : command.signatureKind();
|
||||
String signingRef = "NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind())
|
||||
? null : current == null ? null : current.signingSecretRef();
|
||||
if (supplied != null && supplied.length > 0) {
|
||||
if ("NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("此认证方式无需单独提供签名密钥");
|
||||
newRef = credentials.provision(supplied);
|
||||
signingRef = newRef;
|
||||
}
|
||||
if (!"NONE".equals(kind) && signingRef == null && !"SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("请输入签名密钥");
|
||||
var profile = new ApiPollProfile(command.authKind(), command.tokenEndpoint(), command.tokenFormat(),
|
||||
command.clientId(), command.tokenClientField(), command.tokenSecretField(),
|
||||
command.tokenCredentialStyle(), command.tokenPath(), command.expiresPath(), command.requestMethod(),
|
||||
command.headers() == null ? Map.of() : Map.copyOf(command.headers()),
|
||||
command.queryParameters() == null ? Map.of() : Map.copyOf(command.queryParameters()),
|
||||
command.requestBody(), command.pageSize(), command.lookbackSeconds(), command.successPath(),
|
||||
command.successValue(), kind, command.signatureTemplate(), command.signaturePlacement(), command.signatureHeader(),
|
||||
command.signatureEncoding(), signingRef);
|
||||
String encoded = json.writeValueAsString(profile);
|
||||
int updated = jdbc.update("UPDATE ing_api_poll_profile SET profile_json=?,updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?",
|
||||
encoded, intakeId, actor.orgScopeId());
|
||||
if (updated == 0) jdbc.update("INSERT INTO ing_api_poll_profile(intake_id,org_scope_id,profile_json) VALUES (?,?,?)",
|
||||
intakeId, actor.orgScopeId(), encoded);
|
||||
newRef = null;
|
||||
if (current != null && current.signingSecretRef() != null &&
|
||||
!current.signingSecretRef().equals(signingRef)) safeRevoke(current.signingSecretRef());
|
||||
return view(profile);
|
||||
} catch (RuntimeException failure) {
|
||||
if (newRef != null) safeRevoke(newRef);
|
||||
throw failure;
|
||||
} finally {
|
||||
if (supplied != null) Arrays.fill(supplied, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private void requireApi(FileIngestionActor actor, long intakeId) {
|
||||
if (repository.config(actor, intakeId).sourceType() != FileSourceType.API_SAAS)
|
||||
throw FileIngestionException.validation("仅API采集可配置请求协议");
|
||||
}
|
||||
|
||||
private static View view(ApiPollProfile value) {
|
||||
if (value == null) return new View("STATIC_BEARER", null, "FORM", null,
|
||||
"client_id", "client_secret", "BODY", "$.access_token",
|
||||
"$.expires_in", "GET", Map.of(), Map.of(), null, 100, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", false);
|
||||
return new View(value.authKind(), value.tokenEndpoint(), value.tokenFormat(), value.clientId(),
|
||||
value.tokenClientField(), value.tokenSecretField(), value.tokenCredentialStyle(),
|
||||
value.tokenPath(), value.expiresPath(), value.requestMethod(), value.headers(),
|
||||
value.queryParameters(), value.requestBody(), value.pageSize(), value.lookbackSeconds(),
|
||||
value.successPath(), value.successValue(), value.signatureKind(), value.signatureTemplate(),
|
||||
value.signaturePlacement(), value.signatureHeader(), value.signatureEncoding(),
|
||||
value.signingSecretRef() != null || "SIGN_ONLY".equals(value.authKind()));
|
||||
}
|
||||
|
||||
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 ||
|
||||
!SIGN.contains(c.signatureKind() == null ? "NONE" : c.signatureKind()))
|
||||
throw FileIngestionException.validation("API请求配置无效");
|
||||
if ("SIGN_ONLY".equals(c.authKind()) && (c.signatureKind() == null || "NONE".equals(c.signatureKind())))
|
||||
throw FileIngestionException.validation("仅签名认证必须开启请求签名");
|
||||
if (!"STATIC_BEARER".equals(c.authKind()) && !"API_KEY_HEADER".equals(c.authKind()) &&
|
||||
!"SIGN_ONLY".equals(c.authKind())) {
|
||||
try {
|
||||
URI uri = URI.create(c.tokenEndpoint());
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null ||
|
||||
uri.getRawQuery() != null || uri.getFragment() != null) throw new IllegalArgumentException();
|
||||
} catch (RuntimeException failure) { throw FileIngestionException.validation("认证接口必须是无密钥参数的HTTPS地址"); }
|
||||
if (!Set.of("FORM", "JSON").contains(c.tokenFormat()) ||
|
||||
c.clientId() == null || c.clientId().isBlank() || c.clientId().length() > 256 ||
|
||||
!FIELD.matcher(c.tokenClientField() == null ? "" : c.tokenClientField()).matches() ||
|
||||
!FIELD.matcher(c.tokenSecretField() == null ? "" : c.tokenSecretField()).matches() ||
|
||||
!Set.of("BODY", "BASIC").contains(c.tokenCredentialStyle()) ||
|
||||
("PASSWORD_TOKEN".equals(c.authKind()) && "BASIC".equals(c.tokenCredentialStyle())) ||
|
||||
!path(c.tokenPath()) || (c.expiresPath() != null && !path(c.expiresPath())))
|
||||
throw FileIngestionException.validation("动态Token配置无效");
|
||||
}
|
||||
checkMap(c.headers(), true);
|
||||
checkMap(c.queryParameters(), false);
|
||||
if (c.requestBody() != null && (c.requestBody().length() > 8192 ||
|
||||
(!"POST".equals(c.requestMethod()) && !c.requestBody().isBlank())))
|
||||
throw FileIngestionException.validation("请求体配置无效");
|
||||
if (c.successPath() != null && (!path(c.successPath()) || c.successValue() == null ||
|
||||
c.successValue().length() > 128)) throw FileIngestionException.validation("业务状态路径无效");
|
||||
if (!"NONE".equals(c.signatureKind())) {
|
||||
if (c.signatureTemplate() == null || c.signatureTemplate().isBlank() ||
|
||||
c.signatureTemplate().length() > 2048 || !c.signatureTemplate().matches("(?s)[A-Za-z0-9_{}$./?&=+%\\n\\r :|-]*") ||
|
||||
!Set.of("HEADER", "QUERY").contains(c.signaturePlacement()) ||
|
||||
!("HEADER".equals(c.signaturePlacement()) ? HEADER : FIELD)
|
||||
.matcher(c.signatureHeader() == null ? "" : c.signatureHeader()).matches() ||
|
||||
Set.of("authorization", "cookie", "host").contains(c.signatureHeader().toLowerCase()) ||
|
||||
!Set.of("BASE64", "HEX").contains(c.signatureEncoding()))
|
||||
throw FileIngestionException.validation("签名配置无效");
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkMap(Map<String, String> values, boolean headers) {
|
||||
if (values == null) return;
|
||||
if (values.size() > 20) throw FileIngestionException.validation("请求参数过多");
|
||||
for (var item : values.entrySet()) {
|
||||
String name = item.getKey(), value = item.getValue();
|
||||
if (name == null || value == null || value.length() > 1024 || value.contains("\r") || value.contains("\n") ||
|
||||
!(headers ? HEADER : FIELD).matcher(name).matches() ||
|
||||
(headers && Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key")
|
||||
.contains(name.toLowerCase())) ||
|
||||
(!headers && Set.of("token", "access_token", "secret", "password", "api_key").contains(name.toLowerCase())))
|
||||
throw FileIngestionException.validation("请求参数包含不允许的字段");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); }
|
||||
private void safeRevoke(String ref) { try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* retained safely */ } }
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** API-only polling ownership, leases and committed watermarks. */
|
||||
@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;
|
||||
private final IntegrationFileIngestionGateway integration;
|
||||
@Autowired(required = false)
|
||||
private ApiPollProfileService profiles;
|
||||
|
||||
public record PollState(long intakeId, boolean enabled, String watermark, LocalDateTime nextDueAt,
|
||||
String lastStatus, String lastErrorCode, int lastWrittenRows,
|
||||
LocalDateTime lastRunAt) { }
|
||||
public record PollRun(long runId, String triggerType, String status, int writtenRows,
|
||||
String errorCode, String watermarkBefore, String watermarkAfter,
|
||||
LocalDateTime startedAt, LocalDateTime completedAt) { }
|
||||
|
||||
public PollState state(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
List<PollState> rows = jdbc.query("""
|
||||
SELECT intake_id,enabled,watermark,next_due_at,last_status,last_error_code,
|
||||
last_written_rows,last_run_at FROM ing_api_poll_state
|
||||
WHERE intake_id=? AND org_scope_id=?
|
||||
""", (rs, index) -> new PollState(rs.getLong(1), rs.getInt(2) == 1, rs.getString(3),
|
||||
time(rs.getTimestamp(4)), rs.getString(5), rs.getString(6), rs.getInt(7),
|
||||
time(rs.getTimestamp(8))), intakeId, actor.orgScopeId());
|
||||
return rows.isEmpty() ? new PollState(intakeId, false, null, null, "NEVER", null, 0, null) : rows.getFirst();
|
||||
}
|
||||
|
||||
public List<PollRun> runs(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
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
|
||||
""" + 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());
|
||||
}
|
||||
|
||||
public PollState setEnabled(long intakeId, boolean enabled) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (enabled && !supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled,next_due_at)
|
||||
SELECT ?,?,?,?,CURRENT_TIMESTAMP FROM DUAL WHERE NOT EXISTS
|
||||
(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), enabled ? 1 : 0, intakeId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET enabled=?, actor_id=?,
|
||||
next_due_at=CASE WHEN ?=1 THEN CURRENT_TIMESTAMP ELSE next_due_at END,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
""", enabled ? 1 : 0, actor.actorId(), enabled ? 1 : 0, intakeId, actor.orgScopeId());
|
||||
return state(intakeId);
|
||||
}
|
||||
|
||||
public PollRun runNow(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (!supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
ensureState(actor, intakeId);
|
||||
return execute(actor, intakeId, "MANUAL", config);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${datagov.api-poll.scan-delay-ms:15000}")
|
||||
public void scan() {
|
||||
List<long[]> due;
|
||||
try {
|
||||
due = jdbc.query("""
|
||||
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
|
||||
""" + 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 {
|
||||
FileIngestionActor actor = new FileIngestionActor(item[2], item[1]);
|
||||
FileIngestionPolicy.Config config = requireApi(actor, item[0]);
|
||||
if (supported(config)) execute(actor, item[0], "SCHEDULED", config);
|
||||
else disableInvalid(item[0], item[1]);
|
||||
} catch (RuntimeException failure) {
|
||||
try { disableInvalid(item[0], item[1]); } catch (RuntimeException unavailable) { /* retry on next scan */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PollRun execute(FileIngestionActor actor, long intakeId, String trigger,
|
||||
FileIngestionPolicy.Config config) {
|
||||
String lease = UUID.randomUUID().toString();
|
||||
int claimed = jdbc.update("""
|
||||
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)
|
||||
""".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=?",
|
||||
String.class, intakeId);
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_run(run_id,intake_id,org_scope_id,actor_id,trigger_type,
|
||||
started_at,run_status,watermark_before)
|
||||
VALUES(?,?,?,?,?,CURRENT_TIMESTAMP,'RUNNING',?)
|
||||
""", runId, intakeId, actor.orgScopeId(), actor.actorId(), trigger, before);
|
||||
DataCollectionIntegrationService.ApiPollResult result;
|
||||
try {
|
||||
result = integration.pollApi(actor, intakeId, config, before,
|
||||
profiles == null ? null : profiles.profile(actor, intakeId));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
result = new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_GATEWAY_UNKNOWN");
|
||||
}
|
||||
boolean success = result != null && "SUCCEEDED".equals(result.status());
|
||||
String error = success ? null : result == null ? "API_POLL_RESPONSE_MISSING" :
|
||||
FileIngestionPolicy.safeErrorCode(result.errorCode(), "API_POLL_UNKNOWN");
|
||||
String after = success ? result.watermark() : before;
|
||||
int count = success ? Math.max(0, result.writtenRows()) : 0;
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_run SET completed_at=CURRENT_TIMESTAMP,run_status=?,written_rows=?,
|
||||
error_code=?,watermark_after=? WHERE run_id=?
|
||||
""", success ? "SUCCEEDED" : "UNKNOWN", count, error, after, runId);
|
||||
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=%s,lease_id=NULL,lease_until=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? AND lease_id=?
|
||||
""".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);
|
||||
}
|
||||
|
||||
private void ensureState(FileIngestionActor actor, long intakeId) {
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled)
|
||||
SELECT ?,?,?,0 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), intakeId);
|
||||
}
|
||||
|
||||
private FileIngestionPolicy.Config requireApi(FileIngestionActor actor, long intakeId) {
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅API来源可执行轮询");
|
||||
return config;
|
||||
}
|
||||
|
||||
private static boolean supported(FileIngestionPolicy.Config config) {
|
||||
return config.apiConnector() != null && "GENERIC_HTTPS_JSON".equals(config.apiConnector().name()) &&
|
||||
config.authMode() != null && "BEARER".equals(config.authMode().name()) &&
|
||||
config.paginationMode() != null &&
|
||||
config.maxPages() != null && config.maxPages() >= 1 && config.maxPages() <= 100 &&
|
||||
config.periodSeconds() != null && config.periodSeconds() >= 60 &&
|
||||
config.secretRef() != null;
|
||||
}
|
||||
|
||||
private void disableInvalid(long intakeId, long orgId) {
|
||||
jdbc.update("UPDATE ing_api_poll_state SET enabled=0,last_status='UNKNOWN',last_error_code='API_POLL_CONFIG_INVALID',updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?", intakeId, orgId);
|
||||
}
|
||||
|
||||
private static LocalDateTime time(Timestamp value) { return value == null ? null : value.toLocalDateTime(); }
|
||||
}
|
||||
+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. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -259,6 +259,9 @@ public class FileIngestionService {
|
||||
throw FileIngestionException.conflict("仅草稿或就绪配置可执行能力校验");
|
||||
}
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
String code = FileIngestionPolicy.deferredAdapterCode(config);
|
||||
String summary = FileIngestionPolicy.deferredAdapterSummary(config);
|
||||
@@ -309,6 +312,9 @@ public class FileIngestionService {
|
||||
FileIngestionActor actor = actorProvider.current();
|
||||
String key = FileIngestionPolicy.requireIdempotencyKey(idempotencyKey);
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
repository.markCapability(actor, intakeId, AggregateCapabilityStatus.UNSUPPORTED);
|
||||
throw FileIngestionException.external(FileIngestionPolicy.deferredAdapterSummary(config));
|
||||
|
||||
+19
-2
@@ -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;
|
||||
|
||||
@@ -35,6 +39,19 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
public IntegrationFileIngestionGateway() {
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark) {
|
||||
return pollApi(actor, intakeId, config, watermark, null);
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark,
|
||||
DataCollectionIntegrationService.ApiPollProfile profile) {
|
||||
return integration.pollApi(new DataCollectionIntegrationService.ApiPollRequest(actor.actorId(),
|
||||
actor.orgScopeId(), intakeId, watermark, snapshot(config),
|
||||
targetProfile(actor.actorId(), actor.orgScopeId(), config), profile));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CapabilityResult checkCapability(CapabilityRequest request) {
|
||||
try {
|
||||
@@ -166,7 +183,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
"文件动作证据暂不可用");
|
||||
}
|
||||
|
||||
private DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
long actorId, long orgScopeId, FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (storageReferences == null || config == null || config.targetStorageResourceId() == null ||
|
||||
@@ -180,7 +197,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
resolved.serviceAccount(), resolved.secretRef(), resolved.tlsEnabled());
|
||||
}
|
||||
|
||||
private static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (config == null) return null;
|
||||
|
||||
+2
-2
@@ -30,8 +30,8 @@ public class GoldenReconciliationMaintenance implements AutoCloseable {
|
||||
public GoldenReconciliationMaintenance(
|
||||
GoldenRunRepository repository,
|
||||
GoldenRunWorker worker,
|
||||
JdbcTemplate jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect
|
||||
) {
|
||||
JdbcTemplate jdbcTemplate
|
||||
, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.repository = repository;
|
||||
this.worker = worker;
|
||||
this.runner = new MaintenanceJobRunner("aixun-dataops-m2", new JdbcMaintenanceLeaseRepository(jdbcTemplate, databaseDialect), clock);
|
||||
|
||||
+1
-1
@@ -391,7 +391,7 @@ public class LakehouseLayerRepository {
|
||||
WHEN NOT MATCHED THEN INSERT (dependency_id,layer_id,upstream_layer_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.dependency_id,s.layer_id,s.upstream_layer_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO store_layer_dependency(dependency_id,layer_id,upstream_layer_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.dependency_id,s.layer_id,s.upstream_layer_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS dependency_id, ? AS layer_id, ? AS upstream_layer_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version, ? AS dg_update_arg_0 FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE del_flag='0', update_by=s.dg_update_arg_0, update_time=NOW(), version=store_layer_dependency.version+1"""), IdGeneratorUtil.nextLongId(), layerId, upstreamLayerId, orgId, actor.actorId(),
|
||||
INSERT INTO store_layer_dependency(dependency_id,layer_id,upstream_layer_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.dependency_id,s.layer_id,s.upstream_layer_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS dependency_id, ? AS layer_id, ? AS upstream_layer_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version, ? AS dg_update_arg_0 FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE del_flag='0', update_by=s.dg_update_arg_0, update_time=NOW(), version=store_layer_dependency.version+1"""), IdGeneratorUtil.nextLongId(), layerId, upstreamLayerId, orgId, actor.actorId(),
|
||||
actor.actorId(), actor.actorId());
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ public class LakehouseTableFileReferenceDirectory {
|
||||
}
|
||||
|
||||
public Resolution resolveForIngestion(long actorId, long orgId, long layerId) {
|
||||
return resolve(actorId, orgId, layerId, LoginHelper.isSuperAdmin(actorId));
|
||||
return resolve(actorId, orgId, layerId, false);
|
||||
}
|
||||
|
||||
private Resolution resolve(long actorId, long orgId, long layerId, boolean unrestricted) {
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/dataops/v1/realtime-ingestions")
|
||||
public class RealtimeController {
|
||||
private final RealtimeService service;
|
||||
public RealtimeController(RealtimeService service){this.service=service;}
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.datagov.dataops.batchingestion.UnifiedIngestionService directory;
|
||||
@GetMapping("/source-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.SourcePage> sources(@RequestParam(required=false) String keyword){return R.ok(directory.realtimeSources(keyword));}
|
||||
@GetMapping("/relay-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<java.util.List<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.RelayOption>> relays(@RequestParam long sourceId){return R.ok(service.relays(sourceId));}
|
||||
@GetMapping("/source-defaults") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.SourceDefaults> sourceDefaults(@RequestParam long sourceId){return R.ok(service.sourceDefaults(sourceId));}
|
||||
@GetMapping @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.Page> list(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.list(pageNum,pageSize));}
|
||||
@GetMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.View> get(@PathVariable long id){return R.ok(service.get(id));}
|
||||
@PostMapping @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集创建",businessType=BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> create(@RequestBody Spec spec,@RequestHeader("Idempotency-Key") String key){return R.ok(service.create(spec,key));}
|
||||
@PostMapping("/{id}/{action}") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集操作",businessType=BusinessType.OTHER,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> action(@PathVariable long id,@PathVariable String action,@RequestBody RealtimeService.Action request){return R.ok(service.action(id,action,request));}
|
||||
@PutMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集修改",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> update(@PathVariable long id,@RequestBody RealtimeService.Update request){return R.ok(service.update(id,request));}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.*;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.StorageExecutionProfile;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class RealtimeService {
|
||||
private final JdbcTemplate db;
|
||||
private final TransactionTemplate tx;
|
||||
private final StorageTableFileReferenceDirectory targets;
|
||||
@DubboReference(check=false,timeout=120000,retries=0) private RealtimeCollectionService integration;
|
||||
public RealtimeService(JdbcTemplate db,TransactionTemplate tx,StorageTableFileReferenceDirectory targets) {
|
||||
this.db=db;this.tx=tx;this.targets=targets;
|
||||
}
|
||||
public record View(String id,Spec spec,String status,long version,long attempt,String externalId,
|
||||
String checkpointId,String summary,Long readRows,Long writeRows,LocalDateTime observedAt,
|
||||
List<Map<String,Object>> history) { }
|
||||
public record Page(List<View> rows,long total) { }
|
||||
public record Action(long version,String key) { }
|
||||
public record Update(long version,Spec spec) { }
|
||||
record Row(long id,long owner,long org,Spec spec,String status,long version,long attempt,String external,
|
||||
String fingerprint,String checkpoint,String summary,Long readRows,Long writeRows,
|
||||
LocalDateTime observedAt,LocalDateTime busyUntil) { }
|
||||
private long actor() {Long id=LoginHelper.getUserId();if(id==null)throw new ServiceException("请先登录");return id;}
|
||||
private long org() {Long id=LoginHelper.getDeptId();if(id==null)throw new ServiceException("缺少组织信息");return id;}
|
||||
private static void key(String k) {if(k==null||!k.matches("[A-Za-z0-9_-]{16,80}"))throw new ServiceException("请求标识无效");}
|
||||
public Page list(int page,int size) {
|
||||
if(page<1||size<1||size>100)throw new ServiceException("分页参数无效");
|
||||
long a=actor(),o=org();
|
||||
long total=db.queryForObject("SELECT COUNT(*) FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND status<>'ARCHIVED'",Long.class,o,a);
|
||||
var rows=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND status<>'ARCHIVED' ORDER BY updated_at DESC,id DESC LIMIT ? OFFSET ?",
|
||||
(rs,n)->map(rs),o,a,size,(long)(page-1)*size);
|
||||
return new Page(rows.stream().map(r->view(r,false)).toList(),total);
|
||||
}
|
||||
public View get(long id) {return view(require(id,false),true);}
|
||||
public List<RelayOption> relays(long sourceId){return integration.relays(actor(),org(),sourceId);}
|
||||
public SourceDefaults sourceDefaults(long sourceId){return integration.sourceDefaults(actor(),org(),sourceId);}
|
||||
private Row require(long id,boolean lock) {
|
||||
var rows=db.query("SELECT * FROM ing_realtime_task WHERE id=? AND org_id=? AND owner_id=?"+(lock?" FOR UPDATE":""),
|
||||
(rs,n)->map(rs),id,org(),actor());
|
||||
if(rows.size()!=1)throw new ServiceException("任务不存在或无权访问");return rows.getFirst();
|
||||
}
|
||||
public View create(Spec p,String key) {
|
||||
key(key); validate(p);
|
||||
return tx.execute(status->{
|
||||
var old=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND create_key=?",(rs,n)->map(rs),org(),actor(),key);
|
||||
if(!old.isEmpty()) {if(!old.getFirst().spec().equals(p))throw new ServiceException("请求标识已用于其他配置");return view(old.getFirst(),false);}
|
||||
long id=IdGeneratorUtil.nextLongId();
|
||||
// Resolve the owner-approved target before storing a public configuration.
|
||||
target(actor(),org(),p);
|
||||
try {db.update("INSERT INTO ing_realtime_task(id,owner_id,org_id,create_key,config_json,source_id,server_id,target_key,status,version,attempt,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?, 'DRAFT',0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
|
||||
id,actor(),org(),key,JsonUtils.toJsonString(p),p.sourceId(),p.serverId(),p.targetResourceId()+":"+p.targetSpaceId()+":"+p.targetTable());}
|
||||
catch(org.springframework.dao.DuplicateKeyException ex){throw new ServiceException("同一源库的server-id或目标表已被实时任务占用,请检查已有任务");}
|
||||
return view(require(id,false),false);
|
||||
});
|
||||
}
|
||||
static void validate(Spec p) {
|
||||
if(p==null||p.name()==null||p.name().isBlank()||p.name().length()>100||p.sourceId()<1||p.sourceVersion()<0||
|
||||
p.targetResourceId()<1||p.targetSpaceId()<1||p.httpPort()<1||p.httpPort()>65535||p.serverId()<1||p.serverId()>4294967295L||
|
||||
p.checkpointSeconds()<10||p.checkpointSeconds()>3600||p.startupMode()==null||!Set.of("initial","latest").contains(p.startupMode()))
|
||||
throw new ServiceException("实时采集配置不完整或超出允许范围");
|
||||
if(p.sourceDatabase()==null||!p.sourceDatabase().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}"))
|
||||
throw new ServiceException("来源数据库或服务名格式无效");
|
||||
for(String v:Arrays.asList(p.sourceTable(),p.targetTable()))
|
||||
if(v==null||!v.matches("[A-Za-z_][A-Za-z0-9_]{0,63}"))throw new ServiceException("库表名称只支持字母、数字和下划线");
|
||||
for(String v:Arrays.asList(p.sourceSchema(),p.oracleDatabase(),p.oraclePdb()))
|
||||
if(v!=null&&!v.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))throw new ServiceException("架构、Oracle数据库或PDB名称格式无效");
|
||||
if(p.cdcChannel()!=null&&!p.cdcChannel().matches("[A-Za-z0-9_-]{1,64}"))throw new ServiceException("日志通道标识无效");
|
||||
if(p.oracleCdbService()!=null&&!p.oracleCdbService().matches("[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}"))
|
||||
throw new ServiceException("CDB根容器服务名格式无效");
|
||||
}
|
||||
public View update(long id,Update request) {
|
||||
if(request==null)throw new ServiceException("请求不能为空");validate(request.spec());
|
||||
return tx.execute(status->{
|
||||
var r=require(id,true);allowed(r,"CHECK");
|
||||
if(r.version()!=request.version() || r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))
|
||||
throw new ServiceException("任务已变化或正在处理,请刷新");
|
||||
var p=request.spec();target(r.owner(),r.org(),p);
|
||||
try {db.update("UPDATE ing_realtime_task SET config_json=?,source_id=?,server_id=?,target_key=?,fingerprint=NULL,status='DRAFT',summary=NULL,version=version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
JsonUtils.toJsonString(p),p.sourceId(),p.serverId(),p.targetResourceId()+":"+p.targetSpaceId()+":"+p.targetTable(),id);}
|
||||
catch(org.springframework.dao.DuplicateKeyException e){throw new ServiceException("server-id或目标表已被其他任务占用");}
|
||||
return view(require(id,false),false);
|
||||
});
|
||||
}
|
||||
public View action(long id,String action,Action request) {
|
||||
if(request==null)throw new ServiceException("请求不能为空");key(request.key());
|
||||
if(!Set.of("CHECK","START","RETRY","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效");
|
||||
Row prior=require(id,false);
|
||||
Row reserved=tx.execute(status->{
|
||||
Row r=require(id,true);
|
||||
var previous=db.queryForList("SELECT action FROM ing_realtime_event WHERE task_id=? AND request_key=?",id,request.key());
|
||||
if(!previous.isEmpty()) {
|
||||
if(!action.equals(previous.getFirst().get("ACTION"))&&!action.equals(previous.getFirst().get("action")))throw new ServiceException("请求标识已被其他操作使用");
|
||||
return null;
|
||||
}
|
||||
if(r.version()!=request.version())throw new ServiceException("任务版本已变化,请刷新");
|
||||
if(r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))throw new ServiceException("操作仍在处理中,请稍后刷新");
|
||||
allowed(r,action);
|
||||
// SeaTunnel 2.3.13 restores the same job ID; a new ID would start a new snapshot.
|
||||
long nextAttempt=r.attempt()+(Set.of("START","RETRY").contains(action)?1:0);
|
||||
String external=nextAttempt>0?RealtimeCollectionService.jobId(r.org(),r.id(),nextAttempt):null;
|
||||
String state=Set.of("START","RETRY","RESUME").contains(action)?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status();
|
||||
db.update("UPDATE ing_realtime_task SET status=?,version=version+1,attempt=?,external_id=?,busy_until=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",state,nextAttempt,external,LocalDateTime.now().plusMinutes(3),id);
|
||||
db.update("INSERT INTO ing_realtime_event(id,task_id,request_key,action,status,created_at) VALUES(?,?,?,?, 'PENDING',CURRENT_TIMESTAMP)",IdGeneratorUtil.nextId(),id,request.key(),action);
|
||||
return require(id,false);
|
||||
});
|
||||
if(reserved==null) {
|
||||
if("RECREATE".equals(action)) {
|
||||
var replacement=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND create_key=?",
|
||||
(rs,n)->map(rs),org(),actor(),request.key());
|
||||
if(!replacement.isEmpty())return view(replacement.getFirst(),true);
|
||||
}
|
||||
return get(id);
|
||||
}
|
||||
Row r=reserved;
|
||||
String state="UNKNOWN",summary="外部结果待确认,请刷新状态",fingerprint=r.fingerprint(),checkpoint=r.checkpoint();
|
||||
Long read=r.readRows(),written=r.writeRows(); long attempt=r.attempt(); String external=r.external();
|
||||
boolean invoked=false;
|
||||
try {
|
||||
if(action.equals("ARCHIVE") || action.equals("DELETE") && r.attempt()==0) {
|
||||
state="ARCHIVED";summary=action.equals("DELETE")?"任务已删除,历史操作记录保留":"草稿已归档";
|
||||
}
|
||||
else {
|
||||
var command=new Command(r.owner(),r.org(),r.id(),r.attempt(),r.spec(),
|
||||
Set.of("CHECK","START","RETRY","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(),
|
||||
Set.of("RESUME","RETRY").contains(action)?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null);
|
||||
if(action.equals("CHECK")) {
|
||||
var c=integration.prepare(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint();
|
||||
} else {
|
||||
invoked=true;
|
||||
var result=integration.execute(command,action.equals("DELETE")?"REFRESH":action,r.external(),action.equals("RESUME")?
|
||||
r.external():null);
|
||||
if(result==null || !Objects.equals(r.external(),result.externalId()))throw new IllegalStateException("CDC_RESULT_IDENTITY_MISMATCH");
|
||||
result=retainConfirmedTerminal(action,prior,result);
|
||||
state=result.status();summary=result.summary();checkpoint=result.checkpointId();read=result.readRows();written=result.writeRows();
|
||||
if("UNKNOWN".equals(state) && checkpoint==null && prior.checkpoint()!=null) {
|
||||
checkpoint=prior.checkpoint();read=prior.readRows();written=prior.writeRows();
|
||||
summary=(summary==null?"外部结果待确认":summary)+";保留上次已确认检查点,恢复时仍须验证原作业已结束和检查点有效";
|
||||
}
|
||||
if(action.equals("DELETE")) {
|
||||
if(terminal(state)) {state="ARCHIVED";summary="任务已删除,历史操作记录保留";}
|
||||
else summary="未删除:外部作业尚未确认结束,请同步状态后重试";
|
||||
}
|
||||
if("REJECTED".equals(state)) {
|
||||
attempt=prior.attempt();state=prior.status();external=prior.external();checkpoint=prior.checkpoint();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(RuntimeException ex) {
|
||||
if(action.equals("CHECK")) {state="DRAFT";fingerprint=null;summary="检查并准备未完成,请检查来源、目标授权和集成服务;如已建表会保留,请重新检查确认";}
|
||||
else if(!invoked && Set.of("START","RETRY","RESUME").contains(action)) {
|
||||
state=prior.status();attempt=prior.attempt();external=prior.external();checkpoint=prior.checkpoint();
|
||||
summary="来源或目标授权检查未通过,未提交外部作业";
|
||||
}
|
||||
}
|
||||
final String finalState=state, finalSummary=summary, finalFingerprint=fingerprint, finalCheckpoint=checkpoint,finalExternal=external;
|
||||
final Long finalRead=read, finalWritten=written;final long finalAttempt=attempt;
|
||||
return tx.execute(status->{
|
||||
boolean recreate="RECREATE".equals(action) && "ABSENT".equals(finalState);
|
||||
String storedState=recreate?"ARCHIVED":finalState;
|
||||
int changed=db.update("UPDATE ing_realtime_task SET status=?,summary=?,fingerprint=?,checkpoint_id=?,read_rows=?,write_rows=?,attempt=?,external_id=?,observed_at=CURRENT_TIMESTAMP,busy_until=NULL,version=version+1,updated_at=CURRENT_TIMESTAMP WHERE id=? AND version=?",
|
||||
storedState,finalSummary,finalFingerprint,finalCheckpoint,finalRead,finalWritten,finalAttempt,finalExternal,id,r.version());
|
||||
db.update("UPDATE ing_realtime_event SET status=?,summary=? WHERE task_id=? AND request_key=?",
|
||||
changed==1?storedState:"STALE",finalSummary,id,request.key());
|
||||
if(changed==1 && "ARCHIVED".equals(storedState)) db.update("UPDATE ing_realtime_task SET target_key=?,server_id=? WHERE id=?","archived:"+id,-id,id);
|
||||
if(changed==1 && recreate) return create(r.spec(),request.key());
|
||||
return get(id);
|
||||
});
|
||||
}
|
||||
static RealtimeCollectionService.Result retainConfirmedTerminal(String action,Row prior,RealtimeCollectionService.Result observed) {
|
||||
if("REFRESH".equals(action) && terminal(prior.status()) && "UNKNOWN".equals(observed.status()))
|
||||
return new RealtimeCollectionService.Result(prior.status(),observed.externalId(),
|
||||
"保留上次已确认的终态;本次引擎状态未能核实。检查点及计数为历史记录,恢复前仍须验证:"+
|
||||
(observed.summary()==null?"外部记录不可查询":observed.summary()),
|
||||
prior.checkpoint(),prior.readRows(),prior.writeRows());
|
||||
return observed;
|
||||
}
|
||||
static void allowed(Row r,String action) {
|
||||
if("ARCHIVED".equals(r.status()))throw new ServiceException("任务已删除或归档");
|
||||
boolean ok=switch(action) {
|
||||
case "CHECK","ARCHIVE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status());
|
||||
case "DELETE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status()) || terminal(r.status());
|
||||
case "START" -> r.attempt()==0 && "READY".equals(r.status()) && r.fingerprint()!=null;
|
||||
case "RETRY" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()==null && r.fingerprint()!=null;
|
||||
case "RESUME" -> r.attempt()>0 && (Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null || "UNKNOWN".equals(r.status()));
|
||||
case "STOP","REFRESH" -> r.attempt()>0;
|
||||
case "RECREATE" -> r.attempt()>0 && "UNKNOWN".equals(r.status()) && r.checkpoint()==null;
|
||||
default -> false;
|
||||
};
|
||||
if(!ok)throw new ServiceException("当前状态不允许此操作;恢复需要原作业终止且有已完成checkpoint");
|
||||
}
|
||||
static boolean terminal(String state) {return Set.of("FAILED","CANCELED","SUCCEEDED").contains(state);}
|
||||
private StorageExecutionProfile target(long a,long o,Spec p) {
|
||||
var t=targets.resolveForIngestion(a,o,p.targetResourceId(),p.targetSpaceId());
|
||||
if(t.status()!=StorageTableFileReferenceDirectory.Status.AUTHORIZED||!"DORIS".equals(t.resourceType()))
|
||||
throw new ServiceException("目标Doris资源或数据库未授权或未启用");
|
||||
return new StorageExecutionProfile(p.targetResourceId(),p.targetSpaceId(),t.resourceType(),t.catalogName(),t.externalSpaceId(),t.locationUri(),t.endpointHost(),t.endpointPort(),t.serviceAccount(),t.secretRef(),t.tlsEnabled());
|
||||
}
|
||||
private View view(Row r,boolean history) {
|
||||
return new View(Long.toString(r.id()),r.spec(),r.status(),r.version(),r.attempt(),r.external(),r.checkpoint(),r.summary(),r.readRows(),r.writeRows(),r.observedAt(),
|
||||
history?db.queryForList("SELECT action,status,summary,created_at FROM ing_realtime_event WHERE task_id=? ORDER BY created_at DESC,id DESC LIMIT 50",r.id()):List.of());
|
||||
}
|
||||
private Row map(java.sql.ResultSet rs)throws java.sql.SQLException {
|
||||
var observed=rs.getTimestamp("observed_at");var busy=rs.getTimestamp("busy_until");
|
||||
return new Row(rs.getLong("id"),rs.getLong("owner_id"),rs.getLong("org_id"),JsonUtils.parseObject(rs.getString("config_json"),Spec.class),
|
||||
rs.getString("status"),rs.getLong("version"),rs.getLong("attempt"),rs.getString("external_id"),rs.getString("fingerprint"),rs.getString("checkpoint_id"),rs.getString("summary"),
|
||||
rs.getObject("read_rows")==null?null:rs.getLong("read_rows"),rs.getObject("write_rows")==null?null:rs.getLong("write_rows"),
|
||||
observed==null?null:observed.toLocalDateTime(),busy==null?null:busy.toLocalDateTime());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -617,7 +617,7 @@ class SchedulingJdbcRepository {
|
||||
s.external_definition_code,s.external_instance_id,s.source_status,s.last_sync_at,
|
||||
s.org_id,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO dev_schedule_external_mapping(mapping_id,schedule_id,snapshot_id,run_id,external_project_code,
|
||||
INSERT INTO dev_schedule_external_mapping(mapping_id,schedule_id,snapshot_id,run_id,external_project_code,
|
||||
external_definition_code,external_instance_id,source_status,last_sync_at,
|
||||
org_id,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.mapping_id,s.schedule_id,s.snapshot_id,s.run_id,s.external_project_code,
|
||||
s.external_definition_code,s.external_instance_id,s.source_status,s.last_sync_at,
|
||||
@@ -665,7 +665,7 @@ class SchedulingJdbcRepository {
|
||||
WHEN NOT MATCHED THEN INSERT (evidence_id,run_id,schedule_id,snapshot_id,external_project_code,external_definition_code,external_instance_id,business_date,source_status,normalized_status,evidence_ref,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.external_project_code,s.external_definition_code,s.external_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO dev_schedule_external_instance_evidence(evidence_id,run_id,schedule_id,snapshot_id,external_project_code,external_definition_code,external_instance_id,business_date,source_status,normalized_status,evidence_ref,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.external_project_code,s.external_definition_code,s.external_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS evidence_id, ? AS run_id, ? AS schedule_id, ? AS snapshot_id, ? AS external_project_code, ? AS external_definition_code, ? AS external_instance_id, ? AS business_date, ? AS source_status, ? AS normalized_status, ? AS evidence_ref, ? AS observed_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE business_date=s.business_date,
|
||||
INSERT INTO dev_schedule_external_instance_evidence(evidence_id,run_id,schedule_id,snapshot_id,external_project_code,external_definition_code,external_instance_id,business_date,source_status,normalized_status,evidence_ref,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.external_project_code,s.external_definition_code,s.external_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS evidence_id, ? AS run_id, ? AS schedule_id, ? AS snapshot_id, ? AS external_project_code, ? AS external_definition_code, ? AS external_instance_id, ? AS business_date, ? AS source_status, ? AS normalized_status, ? AS evidence_ref, ? AS observed_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE business_date=s.business_date,
|
||||
source_status=s.source_status, normalized_status=s.normalized_status,
|
||||
evidence_ref=s.evidence_ref, observed_at=s.observed_at,
|
||||
update_by=s.update_by, update_time=NOW(), version=dev_schedule_external_instance_evidence.version+1"""), IdGeneratorUtil.nextLongId(), runId, scope.scheduleId(), scope.snapshotId(),
|
||||
@@ -696,7 +696,7 @@ class SchedulingJdbcRepository {
|
||||
WHEN NOT MATCHED THEN INSERT (evidence_id,run_id,schedule_id,snapshot_id,evidence_kind,node_key,node_type,reference_id,owner_version,owner_sha256,external_project_code,external_definition_code,external_instance_id,external_task_code,external_task_instance_id,business_date,source_status,normalized_status,evidence_ref,error_code,error_summary,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.evidence_kind,s.node_key,s.node_type,s.reference_id,s.owner_version,s.owner_sha256,s.external_project_code,s.external_definition_code,s.external_instance_id,s.external_task_code,s.external_task_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.error_code,s.error_summary,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO dev_schedule_node_execution_evidence(evidence_id,run_id,schedule_id,snapshot_id,evidence_kind,node_key,node_type,reference_id,owner_version,owner_sha256,external_project_code,external_definition_code,external_instance_id,external_task_code,external_task_instance_id,business_date,source_status,normalized_status,evidence_ref,error_code,error_summary,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.evidence_kind,s.node_key,s.node_type,s.reference_id,s.owner_version,s.owner_sha256,s.external_project_code,s.external_definition_code,s.external_instance_id,s.external_task_code,s.external_task_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.error_code,s.error_summary,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS evidence_id, ? AS run_id, ? AS schedule_id, ? AS snapshot_id, 'OBSERVATION' AS evidence_kind, ? AS node_key, ? AS node_type, ? AS reference_id, NULL AS owner_version, NULL AS owner_sha256, ? AS external_project_code, ? AS external_definition_code, ? AS external_instance_id, ? AS external_task_code, ? AS external_task_instance_id, ? AS business_date, ? AS source_status, ? AS normalized_status, ? AS evidence_ref, ? AS error_code, ? AS error_summary, ? AS observed_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE source_status=s.source_status,
|
||||
INSERT INTO dev_schedule_node_execution_evidence(evidence_id,run_id,schedule_id,snapshot_id,evidence_kind,node_key,node_type,reference_id,owner_version,owner_sha256,external_project_code,external_definition_code,external_instance_id,external_task_code,external_task_instance_id,business_date,source_status,normalized_status,evidence_ref,error_code,error_summary,observed_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.evidence_id,s.run_id,s.schedule_id,s.snapshot_id,s.evidence_kind,s.node_key,s.node_type,s.reference_id,s.owner_version,s.owner_sha256,s.external_project_code,s.external_definition_code,s.external_instance_id,s.external_task_code,s.external_task_instance_id,s.business_date,s.source_status,s.normalized_status,s.evidence_ref,s.error_code,s.error_summary,s.observed_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS evidence_id, ? AS run_id, ? AS schedule_id, ? AS snapshot_id, 'OBSERVATION' AS evidence_kind, ? AS node_key, ? AS node_type, ? AS reference_id, NULL AS owner_version, NULL AS owner_sha256, ? AS external_project_code, ? AS external_definition_code, ? AS external_instance_id, ? AS external_task_code, ? AS external_task_instance_id, ? AS business_date, ? AS source_status, ? AS normalized_status, ? AS evidence_ref, ? AS error_code, ? AS error_summary, ? AS observed_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE source_status=s.source_status,
|
||||
normalized_status=s.normalized_status, evidence_ref=s.evidence_ref,
|
||||
error_code=s.error_code, error_summary=s.error_summary,
|
||||
observed_at=s.observed_at, update_by=s.update_by,
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ class SchedulingReadRetryWorker implements SmartLifecycle {
|
||||
private Attempt claim() {
|
||||
return transactions.execute(status -> {
|
||||
var rows = jdbc.query("""
|
||||
SELECT *,deadline_at<=NOW(6) AS expired FROM dev_schedule_read_attempt
|
||||
SELECT dev_schedule_read_attempt.*, CASE WHEN deadline_at<=NOW(6) THEN 1 ELSE 0 END AS expired FROM dev_schedule_read_attempt
|
||||
WHERE attempt_status IN ('PENDING','DISPATCHING','RUNNING','UNKNOWN') AND next_observe_at<=NOW(6)
|
||||
AND del_flag='0' ORDER BY next_observe_at,attempt_id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
""",(rs,n)->new Attempt(rs.getLong("attempt_id"),policy.read(rs.getString("command_json"),Command.class),
|
||||
|
||||
+1
@@ -222,6 +222,7 @@ class SchedulingService {
|
||||
String requestHash = policy.requestHash(normalized);
|
||||
RunView replay = repository.replayRun(actor, RunAction.SUBMIT, idempotencyKey, requestHash);
|
||||
if (replay != null) return replay;
|
||||
reconcileAutomaticPrevious(actor, scheduleId);
|
||||
validateReferences(actor, toDefinition(definition), scheduleId);
|
||||
requireExecutionDependencies(actor, scheduleId, toDefinition(definition));
|
||||
requireExecutable(toDefinition(definition));
|
||||
|
||||
+1
-2
@@ -30,8 +30,7 @@ class SchedulingSignalStore {
|
||||
record Signal(long id, long registrationId, long sourceRunId, String sourceInstanceId, LocalDate businessDate,
|
||||
Long targetRunId, String state, String errorCode, String errorSummary) {}
|
||||
|
||||
static void enqueueWatch(JdbcTemplate jdbc, Actor actor, long runId, long scheduleId, long snapshotId,
|
||||
cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
static void enqueueWatch(JdbcTemplate jdbc, Actor actor, long runId, long scheduleId, long snapshotId, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_schedule_trigger_watch) */ INTO dev_schedule_trigger_watch(run_id,schedule_id,snapshot_id,org_id,actor_id,next_observe_at,create_dept,create_by,update_by)
|
||||
SELECT ?,?,?,?,?,TIMESTAMPADD(SECOND,15,NOW(6)),?,?,? FROM DUAL WHERE EXISTS (
|
||||
|
||||
+34
-9
@@ -30,7 +30,9 @@ import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Repository
|
||||
@@ -123,6 +125,8 @@ public class StorageResourceRepository {
|
||||
}
|
||||
|
||||
private void assertUnused(long resourceId, Long spaceId) {
|
||||
rejectUsed(count("SELECT COUNT(*) FROM ing_realtime_task WHERE target_key LIKE ?",
|
||||
resourceId + ":" + (spaceId == null ? "" : spaceId + ":") + "%"));
|
||||
if (spaceId == null && count("SELECT COUNT(*) FROM store_space WHERE resource_id=? AND del_flag='0'", resourceId) != 0)
|
||||
throw new StorageConflictException("请先删除未使用的空间登记");
|
||||
String[][] references = {
|
||||
@@ -458,7 +462,17 @@ public class StorageResourceRepository {
|
||||
"SELECT " + CAPACITY_COLUMNS + " FROM store_capacity_snapshot " +
|
||||
"WHERE resource_id=? AND del_flag='0' ORDER BY snapshot_id DESC LIMIT ?",
|
||||
(resultSet, rowNumber) -> mapCapacity(resultSet), resourceId, limit);
|
||||
return snapshots.stream().map(this::withDimensions).toList();
|
||||
if (snapshots.isEmpty()) return snapshots;
|
||||
String placeholders = String.join(",", java.util.Collections.nCopies(snapshots.size(), "?"));
|
||||
Map<Long, List<StorageCapacityDimensionView>> dimensions = new HashMap<>();
|
||||
jdbcTemplate.query("SELECT snapshot_id, " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id IN (" + placeholders +
|
||||
") AND del_flag='0' ORDER BY snapshot_id, dimension_name", rs -> {
|
||||
dimensions.computeIfAbsent(rs.getLong("snapshot_id"), ignored -> new ArrayList<>())
|
||||
.add(mapDimension(rs));
|
||||
}, snapshots.stream().map(StorageCapacitySnapshotView::snapshotId).toArray());
|
||||
return snapshots.stream().map(snapshot -> attachDimensions(snapshot,
|
||||
dimensions.getOrDefault(snapshot.snapshotId(), List.of()))).toList();
|
||||
}
|
||||
|
||||
void lockCapacityWindow(long resourceId) {
|
||||
@@ -861,14 +875,21 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "previous_snapshot_id"), resultSet.getString("contract_version"), List.of());
|
||||
}
|
||||
|
||||
private static final String DIMENSION_COLUMNS = """
|
||||
dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
""";
|
||||
|
||||
private StorageCapacitySnapshotView withDimensions(StorageCapacitySnapshotView snapshot) {
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("""
|
||||
SELECT dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
FROM store_capacity_dimension
|
||||
WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name
|
||||
""", (resultSet, rowNumber) -> new StorageCapacityDimensionView(
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("SELECT " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name",
|
||||
(resultSet, rowNumber) -> mapDimension(resultSet), snapshot.snapshotId());
|
||||
return attachDimensions(snapshot, dimensions);
|
||||
}
|
||||
|
||||
private static StorageCapacityDimensionView mapDimension(ResultSet resultSet) throws SQLException {
|
||||
return new StorageCapacityDimensionView(
|
||||
StorageTelemetryDimensionType.valueOf(resultSet.getString("dimension_name")),
|
||||
StorageTelemetryMetricState.valueOf(resultSet.getString("metric_status")),
|
||||
resultSet.getString("source_type"), resultSet.getString("source_identity"),
|
||||
@@ -879,7 +900,11 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "total_bytes"), nullableLong(resultSet, "used_bytes"),
|
||||
nullableLong(resultSet, "available_bytes"), nullableLong(resultSet, "value_bytes"),
|
||||
resultSet.getBigDecimal("value_percent"), resultSet.getString("comparison_fingerprint"),
|
||||
resultSet.getString("algorithm_version")), snapshot.snapshotId());
|
||||
resultSet.getString("algorithm_version"));
|
||||
}
|
||||
|
||||
private static StorageCapacitySnapshotView attachDimensions(StorageCapacitySnapshotView snapshot,
|
||||
List<StorageCapacityDimensionView> dimensions) {
|
||||
if (dimensions.isEmpty()) {
|
||||
dimensions = legacyDimensions(snapshot);
|
||||
}
|
||||
|
||||
+10
-2
@@ -83,10 +83,18 @@ public class StorageResourceService {
|
||||
return detail(currentActor(), resourceId);
|
||||
}
|
||||
|
||||
/** Server-derived identity only; use the same owner policy for viewing and ingestion. */
|
||||
/** Selection lists need registered references, not capacity history and its per-snapshot dimensions. */
|
||||
public StorageResourceDetailView selectionDetail(long resourceId) {
|
||||
StorageActor actor = currentActor();
|
||||
StorageResourceView resource = repository.requireResource(actor, positiveId(resourceId, "资源ID"));
|
||||
return new StorageResourceDetailView(resource, List.copyOf(repository.spaces(resourceId)),
|
||||
repository.accessProfile(resourceId), List.of());
|
||||
}
|
||||
|
||||
/** Server-derived identity only; ingestion never inherits the administrator scope bypass. */
|
||||
public StorageResourceDetailView detailForIngestion(long actorId, long orgId, long resourceId) {
|
||||
if (actorId <= 0 || orgId <= 0) throw new StorageScopeException();
|
||||
return detail(new StorageActor(actorId, orgId, LoginHelper.isSuperAdmin(actorId)), resourceId);
|
||||
return detail(new StorageActor(actorId, orgId, false), resourceId);
|
||||
}
|
||||
|
||||
private StorageResourceDetailView detail(StorageActor actor, long resourceId) {
|
||||
|
||||
+2
-2
@@ -18,7 +18,7 @@ public class StorageTableFileReferenceDirectory {
|
||||
}
|
||||
|
||||
public Resolution resolveForIngestion(long actorId, long orgId, long resourceId, long spaceId) {
|
||||
return resolve(actorId, orgId, resourceId, spaceId, LoginHelper.isSuperAdmin(actorId));
|
||||
return resolve(actorId, orgId, resourceId, spaceId, false);
|
||||
}
|
||||
|
||||
private Resolution resolve(long actorId, long orgId, long resourceId, long spaceId, boolean unrestricted) {
|
||||
@@ -54,7 +54,7 @@ public class StorageTableFileReferenceDirectory {
|
||||
}
|
||||
|
||||
public ObjectResolution resolveObjectForIngestion(long actorId, long orgId, long resourceId, String externalObjectId) {
|
||||
return resolveObject(actorId, orgId, resourceId, externalObjectId, LoginHelper.isSuperAdmin(actorId));
|
||||
return resolveObject(actorId, orgId, resourceId, externalObjectId, false);
|
||||
}
|
||||
|
||||
private ObjectResolution resolveObject(long actorId, long orgId, long resourceId, String externalObjectId,
|
||||
|
||||
+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(
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package cn.aixunkeji.datagov.dataops;
|
||||
|
||||
import cn.aixunkeji.common.core.enums.PlatformDatabaseDialect;
|
||||
import cn.aixunkeji.common.mybatis.config.PlatformDatabaseConfiguration;
|
||||
import cn.aixunkeji.datagov.maintenance.*;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Explicit opt-in test, writes only inside a transaction rolled back in a dedicated test database. */
|
||||
@EnabledIfEnvironmentVariable(named="DATAGOV_DUAL_DB_TEST", matches="true")
|
||||
class PlatformDatabaseJdbcTest {
|
||||
@Test void actualDriverSelectionLeaseFencingUpsertAndRollback() throws Exception {
|
||||
String url = System.getenv("PLATFORM_DB_URL");
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
assertThat(url.contains("/aixun_datagov_dualcheck_") || (schema != null && schema.startsWith("AIXUN_DATAGOV_DUALCHECK_"))).isTrue();
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setJdbcUrl(url);
|
||||
config.setUsername(System.getenv("PLATFORM_DB_USERNAME"));
|
||||
config.setPassword(System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
config.setMaximumPoolSize(1);
|
||||
config.setMinimumIdle(0);
|
||||
if (schema != null && !schema.isBlank()) config.setSchema(schema);
|
||||
try (HikariDataSource source = new HikariDataSource(config)) {
|
||||
PlatformDatabaseDialect dialect = new PlatformDatabaseConfiguration().platformDatabaseDialect(source);
|
||||
assertThat(dialect).isEqualTo(url.startsWith("jdbc:mysql:") ? PlatformDatabaseDialect.MYSQL : PlatformDatabaseDialect.DAMENG);
|
||||
JdbcTemplate jdbc = new JdbcTemplate(source);
|
||||
var repository = new JdbcMaintenanceLeaseRepository(jdbc, dialect);
|
||||
String name = "dual-db-check-" + UUID.randomUUID();
|
||||
Instant now = Instant.now();
|
||||
long id = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
|
||||
var first = new MaintenanceLeaseRequest(id, name, MaintenanceJobKind.STATUS_RECONCILIATION,
|
||||
"first", "first-token", "first-command", MaintenanceTriggerType.SCHEDULED, 0, null, now, now.plusSeconds(60));
|
||||
var second = new MaintenanceLeaseRequest(id, name, MaintenanceJobKind.STATUS_RECONCILIATION,
|
||||
"second", "second-token", "second-command", MaintenanceTriggerType.SCHEDULED, 0, null, now, now.plusSeconds(60));
|
||||
new TransactionTemplate(new DataSourceTransactionManager(source)).executeWithoutResult(status -> {
|
||||
status.setRollbackOnly();
|
||||
assertThat(repository.tryAcquire(first)).isTrue();
|
||||
assertThat(repository.tryAcquire(second)).isFalse();
|
||||
assertThatThrownBy(() -> repository.finish(name, "wrong-token", MaintenanceRunOutcome.SUCCESS, now, true)).isInstanceOf(IllegalStateException.class);
|
||||
repository.finish(name, "first-token", MaintenanceRunOutcome.SUCCESS, now, true);
|
||||
assertThat(repository.tryAcquire(first)).isFalse();
|
||||
assertThat(repository.tryAcquire(second)).isTrue();
|
||||
try {
|
||||
String encoded = Files.readAllLines(Path.of(System.getenv("DUAL_DB_SQL_FILE"))).stream()
|
||||
.filter(line -> line.startsWith("MetricFormulaStore.java:")).findFirst().orElseThrow().split("\t",2)[1];
|
||||
String sql = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
|
||||
jdbc.update(sql, id, id, id, 11L, 11L);
|
||||
jdbc.update(sql, id, id, id, 22L, 22L);
|
||||
assertThat(jdbc.queryForObject("SELECT version FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isEqualTo(1L);
|
||||
assertThat(jdbc.queryForObject("SELECT update_by FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isEqualTo(22L);
|
||||
} catch (java.io.IOException error) { throw new IllegalStateException(error); }
|
||||
String hash = jdbc.queryForObject(dialect.sql("SELECT LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST('abc' AS CLOB),DBMS_CRYPTO.HASH_SH256))) FROM DUAL", "SELECT SHA2('abc',256)"), String.class);
|
||||
assertThat(hash).isEqualTo("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
});
|
||||
assertThat(repository.find(name)).isEmpty();
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isZero();
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -80,7 +80,7 @@ class BatchTargetTypePolicyTest {
|
||||
assertThat(BatchTargetWizardService.matchColumns(List.of(source("TEXT",65535,0,65535L,true)),directory).getFirst().targetType()).isEqualTo("STRING");
|
||||
}
|
||||
assertThat(BatchTargetTypePolicy.propose(source("BIT",1,0,null,false)).type()).isEqualTo(ColumnType.BOOLEAN);
|
||||
assertThat(BatchTargetTypePolicy.propose(source("BIT",8,0,null,false)).type()).isEqualTo(ColumnType.STRING);
|
||||
assertThatThrownBy(()->BatchTargetTypePolicy.propose(source("BIT",8,0,null,false))).isInstanceOf(BatchIngestionException.class);
|
||||
assertThatThrownBy(()->BatchTargetTypePolicy.requireFits(target(ColumnType.VARCHAR,400,null,true),target(ColumnType.VARCHAR,399,null,true)))
|
||||
.hasMessageContaining("value").hasMessageContaining("VARCHAR(400)").hasMessageContaining("VARCHAR(399)").hasMessageContaining("字节长度不足");
|
||||
assertThatThrownBy(()->BatchTargetTypePolicy.requireFits(target(ColumnType.DECIMAL,20,6,true),target(ColumnType.DECIMAL,20,8,true))).hasMessageContaining("整数位或小数位容量不足");
|
||||
@@ -128,15 +128,15 @@ class BatchTargetTypePolicyTest {
|
||||
assertThat(BatchTargetTypePolicy.propose(utf8, TargetEngine.DORIS).type()).isEqualTo(ColumnType.STRING);
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",null,null,null,true), TargetEngine.HIVE))
|
||||
.hasMessageContaining("DECIMAL精度未知");
|
||||
assertThat(BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS).type()).isEqualTo(ColumnType.STRING);
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS))
|
||||
.hasMessageContaining("value").hasMessageContaining("JSON");
|
||||
}
|
||||
@Test void decimalRequiresBothIntegralAndFractionalCapacity() {
|
||||
var input=BatchTargetTypePolicy.propose(source("DECIMAL",20,6,null,true));
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,22,8,true))).isTrue();
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,20,8,true))).isFalse();
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,22,5,true))).isFalse();
|
||||
for(int precision:List.of(0,66)) assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
for(int precision:List.of(39,65)) assertThat(BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true)).type()).isEqualTo(ColumnType.STRING);
|
||||
for(int precision:List.of(0,39,65)) assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.DECIMAL,38,39,true))).isFalse();
|
||||
}
|
||||
@Test void narrowingNullabilityUnknownAndFractionalTimeFailClosed() {
|
||||
@@ -144,7 +144,7 @@ class BatchTargetTypePolicyTest {
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.BIGINT,null,null,false))).isFalse();
|
||||
assertThat(BatchTargetTypePolicy.fits(input,target(ColumnType.INT,null,null,true))).isFalse();
|
||||
for(String type:List.of("BLOB","JSON","MEDIUMTEXT","LONGTEXT","TIME","GEOMETRY"))
|
||||
assertThat(BatchTargetTypePolicy.propose(source(type,100,0,null,true)).type()).isEqualTo(ColumnType.STRING);
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source(type,100,0,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
for(Integer scale:java.util.Arrays.asList(null,-1,7))
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DATETIME",26,scale,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
assertThat(BatchTargetTypePolicy.propose(source("TIMESTAMP",19,0,null,false)).type()).isEqualTo(ColumnType.DATETIME);
|
||||
|
||||
+45
-2
@@ -34,6 +34,49 @@ 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(
|
||||
new DataSourceDirectoryService.Entry(7L,"dm","DAMENG","SUCCEEDED",true,false,null,"APP",1),
|
||||
new DataSourceDirectoryService.Entry(8L,"kb","KINGBASE","SUCCEEDED",false,false,null,"app",1),
|
||||
new DataSourceDirectoryService.Entry(9L,"bad","KINGBASE","FAILED",true,false,null,"app",1))));
|
||||
assertThat(f.service.sources(null).rows()).allMatch(x->!x.available());
|
||||
assertThat(f.service.realtimeSources(null).rows()).extracting(x->x.available()).containsExactly(true,false,false);
|
||||
verify(f.sources,org.mockito.Mockito.times(2)).sources(1,2,List.of(),null,200);
|
||||
}
|
||||
|
||||
@Test void absentOrFalseConsumerSettingRejectsNewRequestsWithoutReservationOrRpc() {
|
||||
var fixture = new CommentFixture("原注释");
|
||||
@@ -269,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);
|
||||
|
||||
-39
@@ -1,39 +0,0 @@
|
||||
package cn.aixunkeji.datagov.dataops.batchingestion;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.UnifiedIngestionSourceService.SchemaResult;
|
||||
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceType;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class UnifiedIngestionTypeCompatibilityTest {
|
||||
@Test void longtextNoLongerErasesTableAndUnknownFieldRemainsExplicit() {
|
||||
var f=new UnifiedIngestionRecoveryTest.CommentFixture(null);
|
||||
var text=new Column("award_name","LONGVARCHAR",2,true,false,"LONGTEXT",Integer.MAX_VALUE,null,4294967295L,null,SourceColumnComment.fromSource(null));
|
||||
var unknown=new Column("special","OTHER",3,true,false,"CUSTOM_OBJECT",null,null,null,null,SourceColumnComment.fromSource(null));
|
||||
when(f.sources.schema(1,2,3,"source_db","orders")).thenReturn(new SchemaResult("AVAILABLE",List.of(f.column,text,unknown),null,f.tableComment));
|
||||
for (var target:List.of(StorageResourceType.HIVE,StorageResourceType.DORIS)) {
|
||||
var draft=f.draft(target).items().getFirst();
|
||||
assertThat(draft.errorSummary()).isNull();
|
||||
assertThat(draft.columns()).extracting(c->c.name()).containsExactly("id","award_name");
|
||||
assertThat(draft.mappings()).hasSize(2);
|
||||
assertThat(draft.fieldCompatibility()).hasSize(3);
|
||||
assertThat(draft.fieldCompatibility().get(1).nativeType()).isEqualTo("LONGTEXT");
|
||||
assertThat(draft.fieldCompatibility().get(2).error()).contains("special");
|
||||
assertThat(draft.sourceFingerprint()).isNotBlank();
|
||||
var selected=UnifiedIngestionService.selectedFields(List.of(f.column,text,unknown),f.item(draft,true),target);
|
||||
assertThat(selected.sourceColumns()).hasSize(2);
|
||||
}
|
||||
verifyNoInteractions(f.tables,f.collections);
|
||||
}
|
||||
@Test void allUnknownColumnsStillReturnFieldReasonsAndCannotSubmitEmptyMapping() {
|
||||
var f=new UnifiedIngestionRecoveryTest.CommentFixture(null);
|
||||
f.column=new Column("special","OTHER",1,true,false,"CUSTOM_OBJECT",null,null,null);
|
||||
var draft=f.draft(StorageResourceType.DORIS).items().getFirst();
|
||||
assertThat(draft.columns()).isEmpty();
|
||||
assertThat(draft.fieldCompatibility()).singleElement().satisfies(x->assertThat(x.error()).isNotBlank());
|
||||
assertThatThrownBy(()->UnifiedIngestionService.selectedFields(List.of(f.column),f.item(draft,true),StorageResourceType.DORIS)).isInstanceOf(BatchIngestionException.class);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises profile persistence and secret-reference handling against the dedicated DM test schema. */
|
||||
@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST")
|
||||
class ApiPollProfileJdbcTest {
|
||||
@Test void savesRedactedProfileAndRevokesReplacedSigningKey() {
|
||||
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"));
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var credentials = mock(FileManagedCredentialGateway.class);
|
||||
var actor = new FileIngestionActor(900009L, 900009L);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, -900009L)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(credentials.provision(any(char[].class))).thenReturn("file:///managed/api-sign?version=v1");
|
||||
char[] signingKey = "test-signing-material".toCharArray();
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollProfileService(jdbc, JsonMapper.builder().findAndAddModules().build(),
|
||||
actors, repository, credentials);
|
||||
var first = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of("X-Tenant", "example"), Map.of("status", "paid"), "{\"page\":${page}}",
|
||||
50, 60, "$.success", "true", "HMAC_SHA256", "${method}\n${pathQuery}\n${timestamp}\n${nonce}",
|
||||
"HEADER", "X-Sign", "BASE64", signingKey);
|
||||
assertThat(service.save(-900009L, first).signingKeyConfigured()).isTrue();
|
||||
assertThat(signingKey).containsOnly('\0');
|
||||
String stored = jdbc.queryForObject("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=?",
|
||||
String.class, -900009L);
|
||||
assertThat(stored).contains("file:///managed/api-sign?version=v1").doesNotContain("test-signing-material");
|
||||
assertThat(service.view(-900009L).requestMethod()).isEqualTo("POST");
|
||||
var second = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of(), Map.of(), null, 50, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", null);
|
||||
assertThat(service.save(-900009L, second).signingKeyConfigured()).isFalse();
|
||||
verify(credentials).revoke("file:///managed/api-sign?version=v1");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.*;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** 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();
|
||||
beans.registerSingleton("identifierGenerator", com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance());
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(beans);
|
||||
}
|
||||
|
||||
@Test void successfulRunCommitsWatermarkAndUnknownKeepsIt() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
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);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var integration = mock(IntegrationFileIngestionGateway.class);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
var actor = new FileIngestionActor(900008L, 900008L);
|
||||
long intakeId = -900008L;
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, intakeId)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(config.apiConnector()).thenReturn(FileApiConnector.GENERIC_HTTPS_JSON);
|
||||
when(config.authMode()).thenReturn(FileAuthMode.BEARER);
|
||||
when(config.paginationMode()).thenReturn(FilePaginationMode.PAGE_SIZE);
|
||||
when(config.maxPages()).thenReturn(2);
|
||||
when(config.periodSeconds()).thenReturn(60);
|
||||
when(config.secretRef()).thenReturn("file:///managed/data-source/test?version=v1");
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), isNull(), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", 2, "2026-11-26T00:00:00Z", null));
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), eq("2026-11-26T00:00:00Z"), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_HTTP_503"));
|
||||
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");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("UNKNOWN");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.runs(intakeId)).hasSize(2);
|
||||
assertThat(service.setEnabled(intakeId, true).enabled()).isTrue();
|
||||
service.scan();
|
||||
assertThat(service.runs(intakeId)).hasSize(3);
|
||||
assertThat(service.runs(intakeId).getFirst().triggerType()).isEqualTo("SCHEDULED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.setEnabled(intakeId, false).enabled()).isFalse();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+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");
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.*;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Executes production DM repository SQL; every test rolls its synthetic records back. */
|
||||
@EnabledIfEnvironmentVariable(named="DATAGOV_DM_SCHEMA",matches="AIXUN_DATAGOV_DM_TEST")
|
||||
class RealtimeJdbcTest {
|
||||
@BeforeAll static void beans(){
|
||||
var b=new DefaultListableBeanFactory();
|
||||
b.registerSingleton("identifierGenerator",com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance());
|
||||
b.registerSingleton("jsonMapper",JsonMapper.builder().findAndAddModules().build());
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(b);
|
||||
}
|
||||
@Test void durableLifecycleReplayVersionAndScope() throws Exception {
|
||||
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 props=new Properties();props.setProperty("schema",System.getenv("DATAGOV_DM_SCHEMA"));ds.setConnectionProperties(props);
|
||||
var db=new JdbcTemplate(ds);var tx=new TransactionTemplate(new DataSourceTransactionManager(ds));
|
||||
var targets=mock(StorageTableFileReferenceDirectory.class);var provider=mock(RealtimeCollectionService.class);
|
||||
when(targets.resolveForIngestion(anyLong(),anyLong(),anyLong(),anyLong())).thenReturn(new StorageTableFileReferenceDirectory.Resolution(
|
||||
StorageTableFileReferenceDirectory.Status.AUTHORIZED,"DORIS","test","test",null,"test.local",9030,"test","secret:test",false));
|
||||
var service=new RealtimeService(db,tx,targets);
|
||||
var field=RealtimeService.class.getDeclaredField("integration");field.setAccessible(true);field.set(service,provider);
|
||||
try(var login=mockStatic(LoginHelper.class)){
|
||||
login.when(LoginHelper::getUserId).thenReturn(900001L);login.when(LoginHelper::getDeptId).thenReturn(900002L);
|
||||
tx.executeWithoutResult(status->{
|
||||
status.setRollbackOnly();
|
||||
var spec=new Spec("CDC rollback test",900001,1,"source","orders",900003,900004,"target",8030,"initial",30,900005);
|
||||
String createKey=UUID.randomUUID().toString();var created=service.create(spec,createKey);
|
||||
assertThat(service.create(spec,createKey).id()).isEqualTo(created.id());
|
||||
long id=Long.parseLong(created.id());
|
||||
when(provider.prepare(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id")));
|
||||
var ready=service.action(id,"CHECK",action(created));assertThat(ready.status()).isEqualTo("READY");
|
||||
var startKey=UUID.randomUUID().toString();
|
||||
when(provider.execute(any(),eq("START"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"unknown",null,null,null));
|
||||
var unknown=service.action(id,"START",new RealtimeService.Action(ready.version(),startKey));
|
||||
assertThat(unknown.status()).isEqualTo("UNKNOWN");assertThat(unknown.attempt()).isEqualTo(1);
|
||||
assertThat(service.action(id,"START",new RealtimeService.Action(ready.version(),startKey)).attempt()).isEqualTo(1);
|
||||
verify(provider,times(1)).execute(any(),eq("START"),any(),isNull());
|
||||
when(provider.execute(any(),eq("REFRESH"),any(),isNull())).thenAnswer(i->new Result("RUNNING",i.getArgument(2),null,"10",12L,12L));
|
||||
var running=service.action(id,"REFRESH",action(unknown));assertThat(running.writeRows()).isEqualTo(12L);
|
||||
when(provider.execute(any(),eq("STOP"),any(),isNull())).thenAnswer(i->new Result("CANCELED",i.getArgument(2),null,"11",12L,12L));
|
||||
var stopped=service.action(id,"STOP",action(running));assertThat(stopped.status()).isEqualTo("CANCELED");
|
||||
when(provider.execute(any(),eq("RESUME"),any(),anyString())).thenAnswer(i->new Result("RUNNING",i.getArgument(2),null,null,null,null));
|
||||
var resumed=service.action(id,"RESUME",action(stopped));assertThat(resumed.attempt()).isEqualTo(1);
|
||||
assertThat(resumed.externalId()).isEqualTo(stopped.externalId());
|
||||
verify(provider).execute(argThat(c->c.recovery()!=null && c.recovery().checkpointId().equals("11") &&
|
||||
c.recovery().status().equals("CANCELED") && c.recovery().jobId().equals(stopped.externalId())),eq("RESUME"),eq(stopped.externalId()),eq(stopped.externalId()));
|
||||
assertThatThrownBy(()->service.action(id,"DELETE",action(resumed))).hasMessageContaining("当前状态");
|
||||
var ended=service.action(id,"STOP",action(resumed));
|
||||
// A stale terminal record cannot hide a still-running external job.
|
||||
var denied=service.action(id,"DELETE",action(ended));
|
||||
assertThat(denied.status()).isEqualTo("RUNNING");
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
ended=service.action(id,"STOP",action(denied));
|
||||
when(provider.execute(any(),eq("REFRESH"),any(),isNull())).thenAnswer(i->new Result("FAILED",i.getArgument(2),"failed",null,12L,12L));
|
||||
var deleteRequest=action(ended);
|
||||
var deleted=service.action(id,"DELETE",deleteRequest);
|
||||
assertThat(deleted.status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.action(id,"DELETE",deleteRequest).status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.list(1,20).total()).isZero();
|
||||
assertThat(deleted.history()).isNotEmpty();
|
||||
assertThatThrownBy(()->service.action(id,"REFRESH",action(deleted))).hasMessageContaining("已删除");
|
||||
// Source server-id and target reservation must both be reusable.
|
||||
var replacement=service.create(spec,UUID.randomUUID().toString());
|
||||
assertThat(replacement.status()).isEqualTo("DRAFT");
|
||||
long replacementId=Long.parseLong(replacement.id());
|
||||
var readyAgain=service.action(replacementId,"CHECK",action(replacement));
|
||||
var unknownAgain=service.action(replacementId,"START",action(readyAgain));
|
||||
when(provider.execute(any(),eq("RECREATE"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"engine busy",null,null,null));
|
||||
var refused=service.action(replacementId,"RECREATE",action(unknownAgain));
|
||||
assertThat(refused.status()).isEqualTo("UNKNOWN");
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
when(provider.execute(any(),eq("RECREATE"),any(),isNull())).thenAnswer(i->new Result("ABSENT",i.getArgument(2),"verified absent",null,null,null));
|
||||
var recreateRequest=action(refused);
|
||||
var rebuilt=service.action(replacementId,"RECREATE",recreateRequest);
|
||||
assertThat(rebuilt.id()).isNotEqualTo(replacement.id());
|
||||
assertThat(rebuilt.spec()).isEqualTo(spec);
|
||||
assertThat(rebuilt.status()).isEqualTo("DRAFT");
|
||||
assertThat(rebuilt.attempt()).isZero();
|
||||
assertThat(service.get(replacementId).status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.action(replacementId,"RECREATE",recreateRequest).id()).isEqualTo(rebuilt.id());
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
login.when(LoginHelper::getUserId).thenReturn(900009L);
|
||||
assertThat(service.list(1,20).rows()).isEmpty();
|
||||
assertThatThrownBy(()->service.get(id)).hasMessageContaining("无权访问");
|
||||
});
|
||||
}
|
||||
}
|
||||
private static RealtimeService.Action action(RealtimeService.View view){return new RealtimeService.Action(view.version(),UUID.randomUUID().toString());}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
class RealtimePolicyTest {
|
||||
@Test void retryRequiresConfirmedTerminalWithoutCheckpoint(){
|
||||
for(String state:java.util.List.of("FAILED","CANCELED"))
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,1,null),"RETRY")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("UNKNOWN","RUNNING","SUBMITTING","STOPPING","READY","SUCCEEDED","ARCHIVED"))
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",1,"1041"),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",0,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void recreateOnlyUnknownWithoutCheckpoint() {
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RECREATE")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("RUNNING","SUBMITTING","STOPPING","DRAFT","ARCHIVED"))
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RECREATE")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"458"),"RECREATE")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void refreshPreservesConfirmedTerminalEvidenceButNeverMasksLiveOrDeleteResult(){
|
||||
var missing=new cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Result("UNKNOWN","10","历史记录不可查询",null,null,null);
|
||||
var saved=RealtimeService.retainConfirmedTerminal("REFRESH",row("CANCELED",1,"458"),missing);
|
||||
assertThat(saved.status()).isEqualTo("CANCELED");
|
||||
assertThat(saved.checkpointId()).isEqualTo("458");
|
||||
assertThat(saved.summary()).contains("历史记录","本次引擎状态未能核实");
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("REFRESH",row("RUNNING",1,"458"),missing)).isSameAs(missing);
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("DELETE",row("CANCELED",1,"458"),missing)).isSameAs(missing);
|
||||
var live=new cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Result("RUNNING","10",null,null,null,null);
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("REFRESH",row("CANCELED",1,"458"),live)).isSameAs(live);
|
||||
}
|
||||
@Test void deleteOnlyDraftOrConfirmedTerminalAndCannotResurrectDeletedTask(){
|
||||
for(String state:java.util.List.of("DRAFT","READY"))
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,0,null),"DELETE")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("FAILED","CANCELED","SUCCEEDED")) {
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,1,null),"DELETE")).doesNotThrowAnyException();
|
||||
assertThat(RealtimeService.terminal(state)).isTrue();
|
||||
}
|
||||
for(String state:java.util.List.of("RUNNING","UNKNOWN","SUBMITTING","STOPPING","PENDING","ARCHIVED")) {
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"DELETE")).isInstanceOf(RuntimeException.class);
|
||||
assertThat(RealtimeService.terminal(state)).isFalse();
|
||||
}
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("ARCHIVED",1,null),"REFRESH")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
static RealtimeService.Row row(String status,long attempt,String checkpoint){return new RealtimeService.Row(1,2,3,null,status,0,attempt,null,"a".repeat(64),checkpoint,null,null,null,null,null);}
|
||||
@Test void unknownJobCanOnlyBeRecoveredThroughGuardedSavepointPath(){
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"START")).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("RUNNING",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void resumeRequiresTerminalAndCheckpoint(){
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("CANCELED",1,null),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.allowed(row("CANCELED",1,"2"),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"REFRESH")).doesNotThrowAnyException();
|
||||
}
|
||||
@Test void rejectsSqlIdentifiersAndMissingHttpPort(){
|
||||
assertThatThrownBy(()->RealtimeService.validate(spec("orders;DROP TABLE x",8030))).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.validate(spec("orders",0))).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.validate(spec("orders",8030))).doesNotThrowAnyException();
|
||||
}
|
||||
static Spec spec(String table,int port){return new Spec("同步",1,0,"sales",table,2,3,"orders",port,"initial",30,1001);}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package cn.aixunkeji.datagov.dataops.storage;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class StorageSelectionDetailTest {
|
||||
@Test void selectionDoesNotLoadTelemetryHistoryAndPreservesScope() {
|
||||
var repository=mock(StorageResourceRepository.class);
|
||||
var service=new StorageResourceService(repository,mock(StorageTelemetryGateway.class),mock(StorageManagedCredentialGateway.class));
|
||||
var actor=new StorageActor(10,20,false);
|
||||
var resource=mock(StorageResourceView.class);
|
||||
when(repository.requireResource(actor,30)).thenReturn(resource);
|
||||
when(repository.spaces(30)).thenReturn(List.of());
|
||||
try(var login=mockStatic(LoginHelper.class)) {
|
||||
login.when(LoginHelper::getUserId).thenReturn(10L);
|
||||
login.when(LoginHelper::getDeptId).thenReturn(20L);
|
||||
assertThat(service.selectionDetail(30).resource()).isSameAs(resource);
|
||||
verify(repository).requireResource(actor,30);
|
||||
verify(repository).spaces(30);
|
||||
verify(repository).accessProfile(30);
|
||||
verifyNoMoreInteractions(repository);
|
||||
}
|
||||
}
|
||||
@Test void deniedResourceNeverReadsSpacesOrCredentials() {
|
||||
var repository=mock(StorageResourceRepository.class);
|
||||
var service=new StorageResourceService(repository,mock(StorageTelemetryGateway.class),mock(StorageManagedCredentialGateway.class));
|
||||
when(repository.requireResource(any(),eq(30L))).thenThrow(new StorageScopeException());
|
||||
try(var login=mockStatic(LoginHelper.class)) {
|
||||
login.when(LoginHelper::getUserId).thenReturn(10L);
|
||||
assertThatThrownBy(()->service.selectionDetail(30)).isInstanceOf(StorageScopeException.class);
|
||||
verify(repository).requireResource(any(),eq(30L));
|
||||
verifyNoMoreInteractions(repository);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-20
@@ -16,40 +16,27 @@ import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class StorageTableFileReferenceDirectoryTest {
|
||||
private static final long ADMIN=cn.aixunkeji.common.core.constant.SystemConstants.SUPER_ADMIN_USER_ID;
|
||||
|
||||
private final StorageResourceRepository repository = mock(StorageResourceRepository.class);
|
||||
private final StorageTableFileReferenceDirectory directory = new StorageTableFileReferenceDirectory(repository);
|
||||
|
||||
@Test void ingestionUsesSameTrustedAdministratorPolicyAsViewing() {
|
||||
@Test void ingestionAlwaysUsesStrictOrganizationEvenForAdministratorId() {
|
||||
when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L)))
|
||||
.thenThrow(new StorageScopeException());
|
||||
assertThat(directory.resolveForIngestion(ADMIN, 20, 30, 40).status())
|
||||
assertThat(directory.resolveForIngestion(1, 20, 30, 40).status())
|
||||
.isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE);
|
||||
assertThat(directory.resolveObjectForIngestion(ADMIN, 20, 30, "sales").status())
|
||||
assertThat(directory.resolveObjectForIngestion(1, 20, 30, "sales").status())
|
||||
.isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE);
|
||||
var capture = org.mockito.ArgumentCaptor.forClass(StorageActor.class);
|
||||
org.mockito.Mockito.verify(repository, org.mockito.Mockito.times(2))
|
||||
.requireResource(capture.capture(), org.mockito.ArgumentMatchers.eq(30L));
|
||||
assertThat(capture.getAllValues()).allSatisfy(actor -> {
|
||||
assertThat(actor.actorId()).isEqualTo(ADMIN);
|
||||
assertThat(actor.actorId()).isEqualTo(1);
|
||||
assertThat(actor.departmentId()).isEqualTo(20);
|
||||
assertThat(actor.unrestricted()).isTrue();
|
||||
assertThat(actor.unrestricted()).isFalse();
|
||||
});
|
||||
}
|
||||
|
||||
@Test void ordinaryActorCannotUseAdministratorScopeAcrossOrganizations() {
|
||||
when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L)))
|
||||
.thenAnswer(invocation -> {
|
||||
StorageActor actor=invocation.getArgument(0);
|
||||
assertThat(actor.unrestricted()).isFalse();
|
||||
assertThat(actor.departmentId()).isEqualTo(20);
|
||||
throw new StorageScopeException();
|
||||
});
|
||||
assertThat(directory.resolveForIngestion(8,20,30,40).status()).isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE);
|
||||
assertThat(directory.resolveObjectForIngestion(8,20,30,"sales").status()).isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesOwnerResourceSpaceAndReturnsOnlySecretReferenceMetadata() {
|
||||
when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L))).thenReturn(new StorageResourceView(
|
||||
@@ -66,7 +53,5 @@ class StorageTableFileReferenceDirectoryTest {
|
||||
assertThat(result.status()).isEqualTo(StorageTableFileReferenceDirectory.Status.AUTHORIZED);
|
||||
assertThat(result.secretRef()).isEqualTo("file:///hive-password?version=1");
|
||||
assertThat(result.toString()).doesNotContain("hive-password").contains("REDACTED");
|
||||
assertThat(directory.resolveForIngestion(10L,20L,30L,40L)).isEqualTo(result);
|
||||
assertThat(directory.resolveForIngestion(ADMIN,99L,30L,40L).status()).isEqualTo(StorageTableFileReferenceDirectory.Status.AUTHORIZED);
|
||||
}
|
||||
}
|
||||
|
||||
+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);
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ class BiRepository {
|
||||
private String access(BiActorProvider.Actor actor) {
|
||||
String roleIds=actor.roles().isEmpty()?"'0'":actor.roles().stream().map(String::valueOf).map(s->"'"+s+"'").collect(java.util.stream.Collectors.joining(","));
|
||||
// All interpolated values are server-derived positive numeric identities.
|
||||
return "(o.owner_id="+actor.id()+" OR (o.published_version IS NOT NULL AND o.lifecycle<>'ARCHIVED' AND "+BiManagement.activeSql("o.state_json", databaseDialect)+" AND EXISTS(SELECT 1 FROM svc_bi_version pv WHERE pv.object_id=o.object_id AND pv.object_version=o.published_version AND "+BiManagement.activeSql("pv.state_json", databaseDialect)+") AND EXISTS(SELECT 1 FROM svc_bi_share s WHERE s.object_id=o.object_id AND s.revoked=0 AND s.del_flag='0' AND s.expires_at>NOW() AND ((s.subject_type='USER' AND s.subject_id='"+actor.id()+"') OR (s.subject_type='ROLE' AND s.subject_id IN ("+roleIds+"))))))";
|
||||
return "(o.owner_id="+actor.id()+" OR (o.published_version IS NOT NULL AND o.lifecycle<>'ARCHIVED' AND "+BiManagement.activeSql("o.state_json",databaseDialect)+" AND EXISTS(SELECT 1 FROM svc_bi_version pv WHERE pv.object_id=o.object_id AND pv.object_version=o.published_version AND "+BiManagement.activeSql("pv.state_json",databaseDialect)+") AND EXISTS(SELECT 1 FROM svc_bi_share s WHERE s.object_id=o.object_id AND s.revoked=0 AND s.del_flag='0' AND s.expires_at>NOW() AND ((s.subject_type='USER' AND s.subject_id='"+actor.id()+"') OR (s.subject_type='ROLE' AND s.subject_id IN ("+roleIds+"))))))";
|
||||
}
|
||||
private String visibleState(BiActorProvider.Actor actor){return "(CASE WHEN o.owner_id="+actor.id()+" THEN o.state_json ELSE (SELECT vs.state_json FROM svc_bi_version vs WHERE vs.object_id=o.object_id AND vs.object_version=o.published_version) END)";}
|
||||
private ObjectView readerVersion(ObjectView value,BiActorProvider.Actor actor) {
|
||||
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package cn.aixunkeji.datagov.dataproduct.datasetpublication;
|
||||
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceBiQueryApi;
|
||||
import cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery;
|
||||
import java.util.List;
|
||||
|
||||
/** Reuses published catalog and current source permissions; callers never supply identity or SQL. */
|
||||
@DubboService(version = ReportingDatasetDirectory.VERSION, group = ReportingDatasetDirectory.GROUP)
|
||||
@RequiredArgsConstructor
|
||||
public class ReportingDatasetDubboService implements ReportingDatasetDirectory {
|
||||
private final DatasetPublicationActorProvider actors;
|
||||
private final PublishedDatasetCatalog catalog;
|
||||
private final DatasetPublicationJdbcRepository repository;
|
||||
private final DatasetSourceSchemaDirectory sources;
|
||||
private final DatasetPublicationPolicy policy;
|
||||
@DubboReference(version=DataSourceBiQueryApi.VERSION,group=DataSourceBiQueryApi.GROUP,check=false,timeout=30000,retries=0)
|
||||
private DataSourceBiQueryApi queries;
|
||||
@Override public Page candidates(String keyword, int page, int size) {
|
||||
if (page < 1 || page > 100000 || size < 1 || size > 100 || keyword != null && keyword.length() > 100) throw DatasetPublicationDomainException.validation("分页范围无效");
|
||||
var actor = actors.sourceActor("VIEW", false);
|
||||
var result = catalog.pageUsable(scope(actor), keyword, page, size);
|
||||
// A candidate is only a published metadata reference. resolve rechecks source and structure before binding.
|
||||
var rows = result.rows().stream().map(d -> new Dataset(Long.toString(d.datasetId()),d.datasetCode(),d.datasetName(),d.datasetVersion(),
|
||||
Long.toString(d.releaseId()),Long.toString(d.schemaVersionId()),d.schemaSha256(),List.of())).toList();
|
||||
actors.requireSourceActor(actor, "VIEW", false);
|
||||
return new Page(rows,result.total());
|
||||
}
|
||||
@Override public Dataset resolve(String rawId) {
|
||||
if (rawId == null || !rawId.matches("[1-9][0-9]{0,18}")) throw DatasetPublicationDomainException.validation("数据集标识无效");
|
||||
long id; try { id = Long.parseLong(rawId); } catch (NumberFormatException e) { throw DatasetPublicationDomainException.validation("数据集标识无效"); }
|
||||
var actor = actors.sourceActor("VIEW", false);
|
||||
var published = catalog.findUsable(scope(actor),id).orElseThrow(DatasetPublicationDomainException::forbidden);
|
||||
var definition = repository.dataset(id,actor);
|
||||
var source = sources.sourceSchema(actor, definition);
|
||||
var schema = repository.currentSchema(id);
|
||||
if (schema == null || schema.schemaVersionId() != published.schemaVersionId() || !schema.schemaSha().equals(published.schemaSha256()) || definition.version()!=published.datasetVersion())
|
||||
throw DatasetPublicationDomainException.conflict("数据集定义或发布结构已变化,请重新选择");
|
||||
policy.requireCurrentSource(schema,source);
|
||||
var result = new Dataset(rawId,published.datasetCode(),published.datasetName(),published.datasetVersion(),Long.toString(published.releaseId()),
|
||||
Long.toString(schema.schemaVersionId()),schema.schemaSha(),schema.fields().stream().map(f -> new Field(f.fieldName(),f.semantic(),f.dataType(),f.nullable())).toList());
|
||||
actors.requireSourceActor(actor,"VIEW",false);
|
||||
if (!catalog.findUsable(scope(actor),id).filter(published::equals).isPresent()) throw DatasetPublicationDomainException.conflict("数据集发布状态已变化");
|
||||
return result;
|
||||
}
|
||||
@Override public Rows read(Read request){
|
||||
var query=readQuery(request);var before=request.dataset();
|
||||
var result=queries.complete(query);
|
||||
if(result==null||!"SUCCEEDED".equals(result.state())||result.truncated()||result.authorizationSha256()==null||result.observedAt()==null||!request.columns().equals(result.columns()))throw DatasetPublicationDomainException.conflict("完整读取未完成、超限或权限不足;请核对查询/导出权限、行列策略及读取范围");
|
||||
if(!before.equals(resolve(before.id())))throw DatasetPublicationDomainException.conflict("读取期间数据集版本或权限已变化");
|
||||
return new Rows(before,result.columns(),result.rows(),result.authorizationSha256(),result.observedAt().toString(),true);
|
||||
}
|
||||
@Override public void authorize(Read request,String authorizationSha256){
|
||||
if(authorizationSha256==null||!authorizationSha256.matches("[a-f0-9]{64}")||!authorizationSha256.equals(queries.authorizeComplete(readQuery(request))))throw DatasetPublicationDomainException.forbidden();
|
||||
}
|
||||
@Override public Rows preview(Read request){
|
||||
var base=readQuery(request);var p=base.plan();
|
||||
var result=queries.query(new DataSourceBiQueryApi.Query(base.actorId(),base.departmentId(),base.tableId(),base.allowedColumns(),new AnalyticsQuery.Plan(p.columns(),List.of(),List.of(),p.filters(),List.of(),5),"SELECT"));
|
||||
if(result==null||!"SUCCEEDED".equals(result.state())||result.authorizationSha256()==null||result.observedAt()==null||result.rows().size()>5||!request.columns().equals(result.columns())||!request.dataset().equals(resolve(request.dataset().id())))throw DatasetPublicationDomainException.conflict("样例读取失败、权限或数据集版本已变化");
|
||||
return new Rows(request.dataset(),result.columns(),result.rows(),result.authorizationSha256(),result.observedAt().toString(),false);
|
||||
}
|
||||
private DataSourceBiQueryApi.Query readQuery(Read request){
|
||||
if(request==null||request.dataset()==null||request.columns()==null||request.columns().isEmpty()||request.columns().size()>500||new java.util.HashSet<>(request.columns()).size()!=request.columns().size()||request.filters()==null||request.filters().size()>20)throw DatasetPublicationDomainException.validation("完整读取参数无效");
|
||||
var before=resolve(request.dataset().id());
|
||||
if(!before.equals(request.dataset())||!before.fields().stream().map(Field::name).toList().containsAll(request.columns()))throw DatasetPublicationDomainException.conflict("数据集固定版本已变化");
|
||||
var actor=actors.sourceActor("VIEW",false);var published=catalog.findUsable(scope(actor),Long.parseLong(before.id())).orElseThrow(DatasetPublicationDomainException::forbidden);
|
||||
if(published.sourceRef()==null||!published.sourceRef().matches("table:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"))throw DatasetPublicationDomainException.conflict("此数据集尚无受控完整表读取,请绑定已完成治理注册的表数据集");
|
||||
var filters=request.filters().stream().map(f->{if(f==null||!before.fields().stream().anyMatch(v->v.name().equals(f.field())))throw DatasetPublicationDomainException.validation("过滤字段不属于数据集");return new AnalyticsQuery.Filter(f.field(),f.operator(),f.values());}).toList();
|
||||
var plan=new AnalyticsQuery.Plan(request.columns(),List.of(),List.of(),filters,List.of(),100000);
|
||||
return new DataSourceBiQueryApi.Query(actor.actorId(),actor.departmentId(),published.sourceRef().substring(6),before.fields().stream().map(Field::name).toList(),plan,"EXPORT");
|
||||
}
|
||||
private static PublishedDatasetCatalog.ActorScope scope(DatasetPublicationActorProvider.Actor a) { return new PublishedDatasetCatalog.ActorScope(a.actorId(),a.organizationId(),a.departmentId()); }
|
||||
}
|
||||
+16
-16
@@ -18,14 +18,14 @@ class GatewayPolicyDiffRepository {
|
||||
private String CURRENT_SELECT() { return databaseDialect.sql("""
|
||||
SELECT g.gateway_id,g.version,NULL AS snapshot_id,NULL AS snapshot_version,g.update_time AS recorded_at,
|
||||
g.api_id,g.api_version,g.model_sha256,g.dataset_schema_sha256,g.http_method,g.relative_path,
|
||||
LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(JSON_OBJECT('apiId',g.api_id,'apiVersion',g.api_version,'model',g.model_sha256,'schema',g.dataset_schema_sha256,
|
||||
'method',g.http_method,'path',g.relative_path,'auth',g.auth_modes_json,'issuer',g.issuer,'audience',g.audience,
|
||||
'scopes',g.caller_scopes_json,'secret',g.secret_ref,'traffic',g.traffic_policy_json,'security',g.security_requirements_json,
|
||||
'policyStatus',g.policy_status,'applicationStatus',g.application_status) AS CLOB),DBMS_CRYPTO.HASH_SH256))) AS stored_sha,
|
||||
LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(JSON_OBJECT('apiId' VALUE g.api_id,'apiVersion' VALUE g.api_version,'model' VALUE g.model_sha256,'schema' VALUE g.dataset_schema_sha256,
|
||||
'method' VALUE g.http_method,'path' VALUE g.relative_path,'auth' VALUE g.auth_modes_json,'issuer' VALUE g.issuer,'audience' VALUE g.audience,
|
||||
'scopes' VALUE g.caller_scopes_json,'secret' VALUE g.secret_ref,'traffic' VALUE g.traffic_policy_json,'security' VALUE g.security_requirements_json,
|
||||
'policyStatus' VALUE g.policy_status,'applicationStatus' VALUE g.application_status) AS CLOB),DBMS_CRYPTO.HASH_SH256))) AS stored_sha,
|
||||
g.auth_modes_json AS auth_json,g.traffic_policy_json AS traffic_json,g.security_requirements_json AS security_json,
|
||||
(NULLIF(TRIM(g.issuer),'') IS NOT NULL) AS issuer_configured,
|
||||
(NULLIF(TRIM(g.audience),'') IS NOT NULL) AS audience_configured,
|
||||
(NULLIF(TRIM(g.secret_ref),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.issuer),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.audience),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.secret_ref),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(TRIM(scope_value) AS CLOB),DBMS_CRYPTO.HASH_SH256))) END),JSON_ARRAY())
|
||||
@@ -39,9 +39,9 @@ class GatewayPolicyDiffRepository {
|
||||
'scopes',g.caller_scopes_json,'secret',g.secret_ref,'traffic',g.traffic_policy_json,'security',g.security_requirements_json,
|
||||
'policyStatus',g.policy_status,'applicationStatus',g.application_status),256) AS stored_sha,
|
||||
g.auth_modes_json AS auth_json,g.traffic_policy_json AS traffic_json,g.security_requirements_json AS security_json,
|
||||
(NULLIF(TRIM(g.issuer),'') IS NOT NULL) AS issuer_configured,
|
||||
(NULLIF(TRIM(g.audience),'') IS NOT NULL) AS audience_configured,
|
||||
(NULLIF(TRIM(g.secret_ref),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.issuer),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.audience),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.secret_ref),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
@@ -55,9 +55,9 @@ class GatewayPolicyDiffRepository {
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.authModes') AS auth_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.traffic') AS traffic_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.security') AS security_json,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL) AS issuer_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL) AS audience_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(TRIM(scope_value) AS CLOB),DBMS_CRYPTO.HASH_SH256))) END),JSON_ARRAY())
|
||||
@@ -71,9 +71,9 @@ class GatewayPolicyDiffRepository {
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.authModes') AS auth_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.traffic') AS traffic_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.security') AS security_json,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL) AS issuer_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL) AS audience_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
package cn.aixunkeji.datagov.dataproduct.datasetpublication;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static cn.aixunkeji.datagov.dataproduct.datasetpublication.DatasetPublicationApi.*;
|
||||
|
||||
class ReportingDatasetDubboServiceTest {
|
||||
final DatasetPublicationActorProvider actors=mock(DatasetPublicationActorProvider.class);
|
||||
final PublishedDatasetCatalog catalog=mock(PublishedDatasetCatalog.class);
|
||||
final DatasetPublicationJdbcRepository repo=mock(DatasetPublicationJdbcRepository.class);
|
||||
final DatasetSourceSchemaDirectory sources=mock(DatasetSourceSchemaDirectory.class);
|
||||
final ReportingDatasetDubboService service=new ReportingDatasetDubboService(actors,catalog,repo,sources,mock(DatasetPublicationPolicy.class));
|
||||
final DatasetPublicationActorProvider.Actor actor=new DatasetPublicationActorProvider.Actor(7,9,9,Set.of(),Set.of());
|
||||
final PublishedDatasetCatalog.ActorScope scope=new PublishedDatasetCatalog.ActorScope(7,9,9);
|
||||
final PublishedDatasetCatalog.PublishedDataset published=new PublishedDatasetCatalog.PublishedDataset(42,"D","数据集",100,"a".repeat(64),200,3,"MODEL_TABLE","source","b".repeat(64));
|
||||
final DatasetView definition=mock(DatasetView.class);
|
||||
final SchemaVersionView schema=mock(SchemaVersionView.class);
|
||||
@BeforeEach void setup(){when(actors.sourceActor("VIEW",false)).thenReturn(actor);when(catalog.findUsable(scope,42)).thenReturn(Optional.of(published));when(repo.dataset(42,actor)).thenReturn(definition);when(definition.version()).thenReturn(3L);when(repo.currentSchema(42)).thenReturn(schema);when(schema.schemaVersionId()).thenReturn(100L);when(schema.schemaSha()).thenReturn("a".repeat(64));when(schema.fields()).thenReturn(List.of(new SchemaFieldView(1,100,0,"id","BIGINT",false,"标识",SensitivityLevel.INTERNAL)));}
|
||||
@Test void resolvesOnlyPublishedAuthorizedCurrentSourceAndSchema(){var result=service.resolve("42");assertEquals("200",result.releaseId());assertEquals(3,result.version());assertEquals("id",result.fields().getFirst().name());verify(sources).sourceSchema(actor,definition);verify(actors).requireSourceActor(actor,"VIEW",false);verify(catalog,times(2)).findUsable(scope,42);verify(actors,never()).current();}
|
||||
@Test void crossOrganizationOrUnpublishedDatasetCannotReadRepository(){when(catalog.findUsable(scope,42)).thenReturn(Optional.empty());assertThrows(DatasetPublicationDomainException.class,()->service.resolve("42"));verifyNoInteractions(repo,sources);}
|
||||
@Test void schemaChangeCannotBindAnOldRelease(){when(schema.schemaSha()).thenReturn("c".repeat(64));assertThrows(DatasetPublicationDomainException.class,()->service.resolve("42"));}
|
||||
@Test void sourcePermissionRevocationStopsBinding(){when(sources.sourceSchema(actor,definition)).thenThrow(DatasetPublicationDomainException.forbidden());assertThrows(DatasetPublicationDomainException.class,()->service.resolve("42"));verify(repo,never()).currentSchema(anyLong());}
|
||||
@Test void permissionAndReleaseRecheckedAfterRead(){when(catalog.findUsable(scope,42)).thenReturn(Optional.of(published),Optional.empty());assertThrows(DatasetPublicationDomainException.class,()->service.resolve("42"));verify(actors).requireSourceActor(actor,"VIEW",false);}
|
||||
@Test void invalidIdentifiersDoNotReachOwners(){assertThrows(DatasetPublicationDomainException.class,()->service.resolve("9223372036854775808"));assertThrows(DatasetPublicationDomainException.class,()->service.resolve("1 OR 1=1"));verifyNoInteractions(actors,catalog,repo,sources);}
|
||||
@Test void incompleteRowsCannotBecomeReportingSnapshot(){
|
||||
var nativeSource=new PublishedDatasetCatalog.PublishedDataset(42,"D","数据集",100,"a".repeat(64),200,3,"MODEL_TABLE","table:123e4567-e89b-42d3-a456-426614174000","b".repeat(64));when(catalog.findUsable(scope,42)).thenReturn(Optional.of(nativeSource));
|
||||
var query=mock(cn.aixunkeji.datagov.integration.api.datasource.DataSourceBiQueryApi.class);org.springframework.test.util.ReflectionTestUtils.setField(service,"queries",query);
|
||||
var dataset=service.resolve("42");var read=new cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory.Read(dataset,List.of("id"),List.of());
|
||||
when(query.complete(any())).thenReturn(new cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery.Result("SUCCEEDED",List.of("id"),List.of(Map.of("id","1")),true,java.time.LocalDateTime.now(),null,1L,null,"a".repeat(64)));
|
||||
assertThrows(DatasetPublicationDomainException.class,()->service.read(read));
|
||||
verify(query).complete(argThat(q->q.plan().limit()==100000&&"EXPORT".equals(q.action())));
|
||||
}
|
||||
@Test void completeRowsRequireFixedVersionAndCurrentAuthorization(){
|
||||
var nativeSource=new PublishedDatasetCatalog.PublishedDataset(42,"D","数据集",100,"a".repeat(64),200,3,"MODEL_TABLE","table:123e4567-e89b-42d3-a456-426614174000","b".repeat(64));when(catalog.findUsable(scope,42)).thenReturn(Optional.of(nativeSource));
|
||||
var query=mock(cn.aixunkeji.datagov.integration.api.datasource.DataSourceBiQueryApi.class);org.springframework.test.util.ReflectionTestUtils.setField(service,"queries",query);
|
||||
var read=new cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory.Read(service.resolve("42"),List.of("id"),List.of());
|
||||
when(query.complete(any())).thenReturn(new cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery.Result("SUCCEEDED",List.of("id"),List.of(Map.of("id","1")),false,java.time.LocalDateTime.now(),null,1L,null,"a".repeat(64)));
|
||||
assertTrue(service.read(read).complete());when(query.authorizeComplete(any())).thenReturn("b".repeat(64));assertThrows(DatasetPublicationDomainException.class,()->service.authorize(read,"a".repeat(64)));
|
||||
}
|
||||
@Test void previewRemainsFiveRowsAndNeverClaimsCompleteSnapshot(){
|
||||
var nativeSource=new PublishedDatasetCatalog.PublishedDataset(42,"D","数据集",100,"a".repeat(64),200,3,"MODEL_TABLE","table:123e4567-e89b-42d3-a456-426614174000","b".repeat(64));when(catalog.findUsable(scope,42)).thenReturn(Optional.of(nativeSource));
|
||||
var query=mock(cn.aixunkeji.datagov.integration.api.datasource.DataSourceBiQueryApi.class);org.springframework.test.util.ReflectionTestUtils.setField(service,"queries",query);
|
||||
var read=new cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory.Read(service.resolve("42"),List.of("id"),List.of());
|
||||
when(query.query(any())).thenReturn(new cn.aixunkeji.datagov.integration.api.tablefile.AnalyticsQuery.Result("SUCCEEDED",List.of("id"),List.of(Map.of("id","1")),true,java.time.LocalDateTime.now(),null,1L,null,"a".repeat(64)));
|
||||
assertFalse(service.preview(read).complete());verify(query).query(argThat(q->q.plan().limit()==5&&"SELECT".equals(q.action())));verify(query,never()).complete(any());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -33,8 +33,8 @@ import tools.jackson.core.type.TypeReference;
|
||||
version = DatasetPublicationEvidenceDirectory.VERSION, retries = 0)
|
||||
@RequiredArgsConstructor
|
||||
public class DatasetPublicationEvidenceDirectoryService implements DatasetPublicationEvidenceDirectory {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DatasetPublicationEvidenceDirectoryService.class);
|
||||
private static final int MAX_AGE_DAYS = 7;
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ class MetadataCatalogRepository {
|
||||
WHEN NOT MATCHED THEN INSERT (projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,description,owners_json,glossary_terms_json,domains_json,life_cycle_json,security_tags_json,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.description,s.owners_json,s.glossary_terms_json,s.domains_json,s.life_cycle_json,s.security_tags_json,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO md_catalog_projection(projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,description,owners_json,glossary_terms_json,domains_json,life_cycle_json,security_tags_json,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.description,s.owners_json,s.glossary_terms_json,s.domains_json,s.life_cycle_json,s.security_tags_json,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS projection_id, ? AS external_entity_id, ? AS entity_type, ? AS fully_qualified_name, ? AS entity_name, ? AS description, ? AS owners_json, ? AS glossary_terms_json, ? AS domains_json, ? AS life_cycle_json, ? AS security_tags_json, ? AS external_version, ? AS external_updated_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE fully_qualified_name=s.fully_qualified_name,entity_name=s.entity_name,description=s.description,owners_json=s.owners_json,glossary_terms_json=s.glossary_terms_json,domains_json=s.domains_json,life_cycle_json=s.life_cycle_json,security_tags_json=s.security_tags_json,external_version=s.external_version,external_updated_at=s.external_updated_at,update_by=s.update_by,update_time=NOW(),version=md_catalog_projection.version+1"""),IdGeneratorUtil.nextLongId(),d.item().externalId(),d.item().entityType().name(),d.item().fullyQualifiedName(),d.item().name(),d.business().description(),JsonUtils.toJsonString(d.management().owners()),JsonUtils.toJsonString(d.business().glossaryTerms()),JsonUtils.toJsonString(d.management().domains()),d.management().lifeCycleJson(),JsonUtils.toJsonString(d.management().securityTags()),d.item().externalVersion(),d.item().updatedAt(),actor.orgId(),actor.orgId(),actor.actorId(),actor.actorId());}
|
||||
INSERT INTO md_catalog_projection(projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,description,owners_json,glossary_terms_json,domains_json,life_cycle_json,security_tags_json,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.description,s.owners_json,s.glossary_terms_json,s.domains_json,s.life_cycle_json,s.security_tags_json,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS projection_id, ? AS external_entity_id, ? AS entity_type, ? AS fully_qualified_name, ? AS entity_name, ? AS description, ? AS owners_json, ? AS glossary_terms_json, ? AS domains_json, ? AS life_cycle_json, ? AS security_tags_json, ? AS external_version, ? AS external_updated_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE fully_qualified_name=s.fully_qualified_name,entity_name=s.entity_name,description=s.description,owners_json=s.owners_json,glossary_terms_json=s.glossary_terms_json,domains_json=s.domains_json,life_cycle_json=s.life_cycle_json,security_tags_json=s.security_tags_json,external_version=s.external_version,external_updated_at=s.external_updated_at,update_by=s.update_by,update_time=NOW(),version=md_catalog_projection.version+1"""),IdGeneratorUtil.nextLongId(),d.item().externalId(),d.item().entityType().name(),d.item().fullyQualifiedName(),d.item().name(),d.business().description(),JsonUtils.toJsonString(d.management().owners()),JsonUtils.toJsonString(d.business().glossaryTerms()),JsonUtils.toJsonString(d.management().domains()),d.management().lifeCycleJson(),JsonUtils.toJsonString(d.management().securityTags()),d.item().externalVersion(),d.item().updatedAt(),actor.orgId(),actor.orgId(),actor.actorId(),actor.actorId());}
|
||||
private Record find(long actor,String path,String key){return jdbc.query("SELECT request_id,request_sha256,request_status FROM md_catalog_request WHERE actor_id=? AND request_method='PATCH' AND request_path=? AND idempotency_key=? AND del_flag='0'",(rs,row)->new Record(rs.getString(1),rs.getString(2),rs.getString(3)),actor,path,key).stream().findFirst().orElse(null);}
|
||||
private static Ticket replay(Record r,String hash){if(!r.hash.equals(hash))throw MetadataCatalogDomainException.conflict("Idempotency-Key已用于不同请求");if(!"COMPLETED".equals(r.status))throw MetadataCatalogDomainException.conflict("幂等请求正在处理中或已失败");return new Ticket(r.id,true);}
|
||||
private static String safe(String value){return value!=null&&value.matches("[A-Z0-9_]{3,64}")?value:"OPENMETADATA_UNKNOWN";}
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ class NativeMetadataPolicyScheduler {
|
||||
long policy=number(p,"policy_id"),version=number(p,"version"),epoch=mode.state().epoch();
|
||||
return tx.execute(s->{
|
||||
mode.requireWrite(epoch);
|
||||
var rows=jdbc.queryForList(databaseDialect.sql("SELECT md_native_schedule.*,CASE WHEN next_at<=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) THEN 1 ELSE 0 END AS due FROM md_native_schedule WHERE policy_id=? FOR UPDATE", "SELECT md_native_schedule.*,CASE WHEN next_at<=UTC_TIMESTAMP(6) THEN 1 ELSE 0 END AS due FROM md_native_schedule WHERE policy_id=? FOR UPDATE"),policy);
|
||||
var rows=jdbc.queryForList(databaseDialect.sql("SELECT md_native_schedule.*, CASE WHEN next_at<=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) THEN 1 ELSE 0 END AS due FROM md_native_schedule WHERE policy_id=? FOR UPDATE", "SELECT md_native_schedule.*, CASE WHEN next_at<=UTC_TIMESTAMP(6) THEN 1 ELSE 0 END AS due FROM md_native_schedule WHERE policy_id=? FOR UPDATE"),policy);
|
||||
if(rows.isEmpty()){
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_schedule) */ INTO md_native_schedule(policy_id,policy_version,next_at) VALUES(?,?,?)", "INSERT IGNORE INTO md_native_schedule(policy_id,policy_version,next_at) VALUES(?,?,?)"),policy,version,next((String)p.get("schedule_interval"),(String)p.get("timezone"),Instant.now()));return null;
|
||||
}
|
||||
|
||||
+1
-1
@@ -120,7 +120,7 @@ class MetadataQualityRepository {
|
||||
WHEN NOT MATCHED THEN INSERT (projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,claim_state,owner_kind,owner_external_id,claim_reason,claimed_at,security_tags_json,check_state,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.claim_state,s.owner_kind,s.owner_external_id,s.claim_reason,s.claimed_at,s.security_tags_json,s.check_state,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", """
|
||||
INSERT INTO md_quality_projection(projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,claim_state,owner_kind,owner_external_id,claim_reason,claimed_at,security_tags_json,check_state,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.claim_state,s.owner_kind,s.owner_external_id,s.claim_reason,s.claimed_at,s.security_tags_json,s.check_state,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS projection_id, ? AS external_entity_id, ? AS entity_type, ? AS fully_qualified_name, ? AS entity_name, ? AS claim_state, ? AS owner_kind, ? AS owner_external_id, ? AS claim_reason, CASE WHEN ?='CLAIMED' THEN NOW() ELSE NULL END AS claimed_at, ? AS security_tags_json, 'NOT_CHECKED' AS check_state, ? AS external_version, ? AS external_updated_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version, ? AS dg_update_arg_0, ? AS dg_update_arg_1, ? AS dg_update_arg_2, ? AS dg_update_arg_3, ? AS dg_update_arg_4 FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE fully_qualified_name=s.fully_qualified_name,entity_name=s.entity_name,
|
||||
INSERT INTO md_quality_projection(projection_id,external_entity_id,entity_type,fully_qualified_name,entity_name,claim_state,owner_kind,owner_external_id,claim_reason,claimed_at,security_tags_json,check_state,external_version,external_updated_at,org_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.projection_id,s.external_entity_id,s.entity_type,s.fully_qualified_name,s.entity_name,s.claim_state,s.owner_kind,s.owner_external_id,s.claim_reason,s.claimed_at,s.security_tags_json,s.check_state,s.external_version,s.external_updated_at,s.org_id,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS projection_id, ? AS external_entity_id, ? AS entity_type, ? AS fully_qualified_name, ? AS entity_name, ? AS claim_state, ? AS owner_kind, ? AS owner_external_id, ? AS claim_reason, CASE WHEN ?='CLAIMED' THEN NOW() ELSE NULL END AS claimed_at, ? AS security_tags_json, 'NOT_CHECKED' AS check_state, ? AS external_version, ? AS external_updated_at, ? AS org_id, ? AS create_dept, ? AS create_by, NOW() AS create_time, ? AS update_by, NOW() AS update_time, '0' AS del_flag, 0 AS version, ? AS dg_update_arg_0, ? AS dg_update_arg_1, ? AS dg_update_arg_2, ? AS dg_update_arg_3, ? AS dg_update_arg_4 FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE fully_qualified_name=s.fully_qualified_name,entity_name=s.entity_name,
|
||||
claim_state=IF(s.dg_update_arg_0 IS NULL,md_quality_projection.claim_state,s.claim_state),owner_kind=IF(s.dg_update_arg_1 IS NULL,md_quality_projection.owner_kind,s.owner_kind),
|
||||
owner_external_id=IF(s.dg_update_arg_2 IS NULL,md_quality_projection.owner_external_id,s.owner_external_id),
|
||||
claim_reason=IF(s.dg_update_arg_3 IS NULL,md_quality_projection.claim_reason,s.claim_reason),claimed_at=IF(s.dg_update_arg_4='CLAIMED',NOW(),md_quality_projection.claimed_at),
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ public class NativeMetadataWorker {
|
||||
var rows=jdbc.queryForList(databaseDialect.sql("SELECT * FROM md_native_job WHERE job_id=? AND (state='PENDING' OR (state='RUNNING' AND heartbeat_at<TIMESTAMPADD(SECOND,-45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))))", "SELECT * FROM md_native_job WHERE job_id=? AND (state='PENDING' OR (state='RUNNING' AND heartbeat_at<TIMESTAMPADD(SECOND,-45,UTC_TIMESTAMP(6))))"),id);
|
||||
if(rows.isEmpty())return null;var r=rows.getFirst();long org=num(r,"org_id"),source=num(r,"source_id");
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_source_lease) */ INTO md_native_source_lease(org_id,source_id,job_id,expires_at) VALUES(?,?,?,TIMESTAMPADD(SECOND,-1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))))", "INSERT IGNORE INTO md_native_source_lease(org_id,source_id,job_id,expires_at) VALUES(?,?,?,TIMESTAMPADD(SECOND,-1,UTC_TIMESTAMP(6)))"),org,source,id);
|
||||
var leases=jdbc.queryForList(databaseDialect.sql("SELECT fence_token,CASE WHEN expires_at<CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) THEN 1 ELSE 0 END AS expired FROM md_native_source_lease WHERE org_id=? AND source_id=? FOR UPDATE", "SELECT fence_token,CASE WHEN expires_at<UTC_TIMESTAMP(6) THEN 1 ELSE 0 END AS expired FROM md_native_source_lease WHERE org_id=? AND source_id=? FOR UPDATE"),org,source);
|
||||
var leases=jdbc.queryForList(databaseDialect.sql("SELECT fence_token, CASE WHEN expires_at<CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) THEN 1 ELSE 0 END AS expired FROM md_native_source_lease WHERE org_id=? AND source_id=? FOR UPDATE", "SELECT fence_token, CASE WHEN expires_at<UTC_TIMESTAMP(6) THEN 1 ELSE 0 END AS expired FROM md_native_source_lease WHERE org_id=? AND source_id=? FOR UPDATE"),org,source);
|
||||
if(((Number)leases.getFirst().get("expired")).intValue()!=1)return null;
|
||||
long fence=num(leases.getFirst(),"fence_token")+1;
|
||||
jdbc.update(databaseDialect.sql("UPDATE md_native_source_lease SET job_id=?,fence_token=?,expires_at=TIMESTAMPADD(SECOND,45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))) WHERE org_id=? AND source_id=?", "UPDATE md_native_source_lease SET job_id=?,fence_token=?,expires_at=TIMESTAMPADD(SECOND,45,UTC_TIMESTAMP(6)) WHERE org_id=? AND source_id=?"),id,fence,org,source);
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ final class ClassificationResourceGuard {
|
||||
|
||||
record Label(long id,long version,String classification,String level) { }
|
||||
static String sha(String value){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException impossible){throw new IllegalStateException(impossible);}}
|
||||
static void lock(JdbcTemplate jdbc,SecurityClassificationActorProvider.Actor a,List<String> refs,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect){
|
||||
static void lock(JdbcTemplate jdbc,SecurityClassificationActorProvider.Actor a,List<String> refs, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect){
|
||||
if(!TransactionSynchronizationManager.isActualTransactionActive())throw SecurityClassificationDomainException.conflict("资源确认须在原事务中执行");
|
||||
for(String ref:refs.stream().distinct().sorted(Comparator.comparing(ClassificationResourceGuard::sha)).toList()){
|
||||
if(ref==null||ref.isBlank()||ref.length()>512)throw SecurityClassificationDomainException.validation("资源标识无效");String sha=sha(ref);
|
||||
@@ -26,7 +26,7 @@ final class ClassificationResourceGuard {
|
||||
(r,n)->new Label(r.getLong(1),r.getLong(2),r.getString(3),r.getString(4)),a.organizationId(),a.departmentId(),ref);
|
||||
if(rows.size()>500)throw SecurityClassificationDomainException.conflict("资源标签过多,请先核对");return List.copyOf(rows);
|
||||
}
|
||||
static void confirm(JdbcTemplate jdbc,SecurityClassificationActorProvider.Actor a,SecurityClassificationApi.CandidateView c,SecurityClassificationApi.ReviewCommand command,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect){
|
||||
static void confirm(JdbcTemplate jdbc,SecurityClassificationActorProvider.Actor a,SecurityClassificationApi.CandidateView c,SecurityClassificationApi.ReviewCommand command, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect){
|
||||
lock(jdbc,a,List.of(c.resourceRef()),databaseDialect);var existing=labels(jdbc,a,c.resourceRef(),true);
|
||||
if(c.basisKind()==SecurityClassificationApi.BasisKind.SEMANTIC_METADATA?!existing.isEmpty():existing.stream().anyMatch(l->!l.classification().equals(command.classificationCode())||!l.level().equals(command.levelCode())))
|
||||
throw SecurityClassificationDomainException.conflict("资源已有标签,与本次确认冲突;不能覆盖或降密");
|
||||
|
||||
+2
-11
@@ -34,14 +34,6 @@ public class NativeQueryPolicyService implements NativeQueryPolicyApi {
|
||||
return decision;
|
||||
}
|
||||
@Override public Receipt complete(Completion completed){
|
||||
return completeObserved(completed);
|
||||
}
|
||||
@Override public Decision authorize(Request request){
|
||||
if(request==null||request.querySha256()==null||!request.querySha256().matches("[a-f0-9]{64}")||request.sourceColumns()==null)throw NativePolicyRules.denied();
|
||||
var current=snapshot(request);var r=current.rules();
|
||||
return new Decision("AUTHORIZATION_ONLY",current.fingerprint(),current.source().reference(),r.columns(),r.filters(),r.masks(),r.versions());
|
||||
}
|
||||
private Receipt completeObserved(Completion completed){
|
||||
if(completed==null||completed.queryId()==null)return new Receipt(false,"POLICY_RECEIPT_INVALID");
|
||||
NativeQueryTickets.Pending work;
|
||||
try {work=tickets.read(completed.queryId());}
|
||||
@@ -49,8 +41,8 @@ public class NativeQueryPolicyService implements NativeQueryPolicyApi {
|
||||
if(work==null)return new Receipt(false,"POLICY_RECEIPT_UNKNOWN");
|
||||
if(work.request().actorId()!=completed.actorId()||work.request().departmentId()!=completed.departmentId()
|
||||
||!work.decision().fingerprint().equals(completed.fingerprint())||!work.request().querySha256().equals(completed.querySha256())
|
||||
||completed.returnedRows()<0||completed.returnedRows()>(work.request().completeRead()?100000:1000)
|
||||
||completed.returnedColumns()==null||completed.returnedColumns().size()>(work.request().completeRead()?500:200)
|
||||
||completed.returnedRows()<0||completed.returnedRows()>1000
|
||||
||completed.returnedColumns()==null||completed.returnedColumns().size()>200
|
||||
||completed.returnedColumns().stream().anyMatch(Objects::isNull)
|
||||
||new java.util.HashSet<>(completed.returnedColumns()).size()!=completed.returnedColumns().size()
|
||||
||!work.decision().columns().containsAll(completed.returnedColumns())
|
||||
@@ -75,7 +67,6 @@ public class NativeQueryPolicyService implements NativeQueryPolicyApi {
|
||||
} catch(RuntimeException unavailable){return new Receipt(false,"POLICY_CHANGED_OR_REVOKED");}
|
||||
}
|
||||
private Snapshot snapshot(Request request){
|
||||
if(request.completeRead()&&(!"EXPORT".equals(request.action())||!"BI_QUERY".equals(request.purpose())))throw NativePolicyRules.denied();
|
||||
if(request.purpose()==null||!Set.of("BI_QUERY","API_QUERY","API_DEBUG").contains(request.purpose()))throw NativePolicyRules.denied();
|
||||
var identity="BI_QUERY".equals(request.purpose())?users.resolveDataPolicySubjects(request.actorId(),request.departmentId())
|
||||
:users.resolveApiQuerySubjects(request.actorId(),request.departmentId(),request.purpose());Instant now=Instant.now();
|
||||
|
||||
-8
@@ -48,14 +48,6 @@ class NativeQueryPolicyServiceTest {
|
||||
verify(access).lock(7,10,TABLE);verify(protection).lock(7,10,TABLE);verify(protection).record(eq(7L),eq(10L),eq(new NativeQueryPolicyApi.Version("PROTECTION",9,2)),any());
|
||||
assertThat(service.complete(completion(decision)).accepted()).isFalse();
|
||||
}
|
||||
@Test void reauthorizationCreatesNoQueryTicketOrExecutionReceipt(){
|
||||
var decision=service.authorize(request());assertThat(decision.queryId()).isEqualTo("AUTHORIZATION_ONLY");assertThat(decision.fingerprint()).hasSize(64);verifyNoInteractions(tickets,transactions);verify(access,never()).record(anyLong(),anyLong(),any(),any());verify(protection,never()).record(anyLong(),anyLong(),any(),any());
|
||||
}
|
||||
@Test void completeReadCannotUseSelectOrApiPurpose(){
|
||||
assertThatThrownBy(()->service.prepare(new NativeQueryPolicyApi.Request(7,10,TABLE,3,1,"MYSQL","SELECT",List.of("label"),"a".repeat(64),"BI_QUERY",true))).isInstanceOf(IllegalStateException.class);
|
||||
assertThatThrownBy(()->service.prepare(new NativeQueryPolicyApi.Request(7,10,TABLE,3,1,"MYSQL","EXPORT",List.of("label"),"a".repeat(64),"API_QUERY",true))).isInstanceOf(IllegalStateException.class);
|
||||
verifyNoInteractions(tickets);
|
||||
}
|
||||
@Test void roleRevocationDuringQueryDiscardsCompletion(){
|
||||
var decision=service.prepare(request());when(users.resolveDataPolicySubjects(7,10)).thenReturn(identity(List.of("USER:7")));
|
||||
assertThat(service.complete(completion(decision)).accepted()).isFalse();verify(protection,never()).record(anyLong(),anyLong(),any(),any());
|
||||
|
||||
@@ -11,12 +11,6 @@
|
||||
<artifactId>aixun-integration</artifactId>
|
||||
<description>DataGov external integration boundary and internal adapters</description>
|
||||
<dependencies>
|
||||
<dependency><groupId>cn.aixunkeji</groupId><artifactId>aixun-api-resource</artifactId></dependency>
|
||||
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>3.0.8</version></dependency>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-excel</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>jakarta.mail</groupId>
|
||||
<artifactId>jakarta.mail-api</artifactId>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# 达梦、金仓原生 CDC 交付记录
|
||||
|
||||
2026-11-24 更新:达梦归档窗口已改为连续分批推进,取消累计 2000 文件上限;本地插件及页面已发布,原任务从保存点 67 恢复后完成检查点 68–70。详见 `evidence/dameng-window-20261124.md`(项目根目录)。下文原始发布记录保留其当时验收边界。
|
||||
|
||||
2026-11-23,用户授权“继续补齐达梦和金仓的功能”。自研插件运行在现有 SeaTunnel 2.3.13,不新增常驻服务,不依赖 DMHS、FlySync 或 Kafka。代码、部署和真实业务验收分别记录。
|
||||
|
||||
## 实现
|
||||
|
||||
- Dameng-Native-CDC:通过 DBMS_LOGMNR 读取达梦归档日志;Kingbase-Native-CDC:通过金仓 JDBC 复制协议读取 test_decoding 槽。
|
||||
- 增删改转为 SeaTunnel RowKind,沿用 Doris Unique Key、删除及两阶段提交。
|
||||
- initial:保存日志低水位,按组合主键每页读取 500 行,分页位置与日志起点一起进入检查点;完成快照后重放扫描期间的日志。追平前可能暂时看到旧值,不能将快照中间状态作为一致性验收。
|
||||
- latest:达梦从启动时 CUR_LSN 开始;金仓从专用复制槽确认位置继续,页面明确区分语义。
|
||||
- 检查点保存位置、数据库身份、结构/主键签名、快照分页位置和归档清单;金仓仅在成功检查点后反馈 WAL。缺日志、换库、结构变化时停止,不自动跳过。
|
||||
- 页面、任务生成、只读前置检查、中文错误提示已接入。日志通道改为可选,现有 MySQL/Oracle/SQL Server 路径保留。
|
||||
- 新增 realtime-ingestions/source-options,复用组织授权目录,保留凭据和连接成功限制;实时采集不再使用批量采集试点 ID 名单。批量入口规则不变。
|
||||
|
||||
## 支持边界与剩余工作
|
||||
|
||||
1. 单表、并行度 1、有主键;目标列名及顺序一致,Doris Unique Key 与源主键一致。首次全量目标必须为空,恢复沿用原检查点。
|
||||
2. 普通数字、字符串、日期时间;小数精度不超过 38。LOB、二进制、数组、带时区字段和自动 DDL 不支持,校验拒绝。标识符限字母、数字、下划线、美元符和井号。
|
||||
3. 达梦按检查点连续推进归档窗口,每轮最多加入 64 个新文件,另外保留未结束事务需要的旧文件及边界文件;不再限制累计历史文件为 2000。缺失所需日志、事务边界或提交位置无法确认时停止,不跳到最新日志。仅缩小插件读取范围,不删除源库归档;每批约 20000 行和查询超时限制仍保留。归档生成频率决定同步延迟。真实长事务及跨重启仍需验收。
|
||||
4. 金仓单事务最多 10000 变更事件。实际版本的系统视图、复制协议和提交位置语义需真实源库验收。
|
||||
5. 真实源库断网、跨重启恢复和数据一致性未验收,不以序列化测试推导业务 exactly-once。
|
||||
|
||||
## 源库准备
|
||||
|
||||
- 达梦:本地归档,ARCH_INI=1、RLOG_APPEND_LOGIC=2、RLOG_LLOG_COMPRESS=0、LOGMNR_DELAY_ANALYZE=0,源表/日志视图/LogMiner 权限。程序不自动调整全局参数或授权。
|
||||
- 金仓:wal_level=logical、源表 REPLICA IDENTITY FULL、复制权限和专用 test_decoding 槽。槽名由源 ID/架构/表的 SHA-256 稳定生成,校验提示具体名称,由 DBA 预建;不能共用或提前推进。
|
||||
- 页面已确认“企管_达梦”连接成功,可列出 ENTERPRISE_MANAGEMENT 的 10 张表。当前授权目录无金仓数据源。此前平台测试库的日志参数检查不能代替此业务源检查。
|
||||
|
||||
依据:[达梦 LogMiner 官方说明](https://eco.dameng.com/document/dm/zh-cn/pm/dbms_logmnr-package)、[达梦日志视图](https://eco.dameng.com/document/dm/zh-cn/pm/dm8-admin-manual-appendix2.html)。金仓使用现有官方驱动的 KBConnection/KBReplicationStream API,兼容性以实际版本测试为准。
|
||||
|
||||
## 验证
|
||||
|
||||
- PASS:独立 Java 8 插件构建,14 项测试,含完整事务、失败检查点不反馈、组合主键分页续读、结束快照保持日志低水位。
|
||||
- PASS:后端定向测试及新增目录测试。原批次有 8 项数据库/进程测试跳过,未计作通过。
|
||||
- PASS:前端定向 lint 和生产构建。前端制品首次比对仅发现 Finder 的 .DS_Store 差异,清理该文件后比对通过。
|
||||
- PASS:实际 SeaTunnel 2.3.13 离线发现两个插件及驱动;镜像包含插件映射。
|
||||
- NOT_RUN:真实金仓;达梦/金仓增删改落库、事务回滚、快照期间写入、长事务、跨重启及完整人工 UAT。未执行业务源 DML、DDL 或全局参数调整。
|
||||
|
||||
构建入口:script/quality/check.sh --native-cdc。插件 JAR 位于本模块 target/;Docker 构建使用 --build-context native_cdc=aixun-modules/aixun-integration/seatunnel-native-cdc/target,避免重复复制 JAR。
|
||||
|
||||
## 发布与恢复
|
||||
|
||||
应用服务使用 script/datagov/deploy.sh;SeaTunnel 使用现有 deploy-seatunnel-cdc.py,在无运行/待提交任务时更换镜像,保留网络、IP、端口、挂载和秘密。无需迁移。
|
||||
|
||||
本地发布 PASS(制品读回、配置保持通过):
|
||||
|
||||
| 服务 | 最终镜像标签 | image ID 前缀 |
|
||||
| --- | --- | --- |
|
||||
| SeaTunnel | 2.3.13-native-vendor-20261123-r3 | d6104ac41277 |
|
||||
| integration | native-vendor-cdc-20261123-r3 | 36520937a13b |
|
||||
| dataops | native-vendor-cdc-20261123 | 8d4c7594844d |
|
||||
| frontend | native-vendor-cdc-20261123-r3 | 81059f83dfdc |
|
||||
|
||||
17:54 Browser 实测:达梦选项可选、默认架构带入、全量选项可用;创建“达梦CDC前置校验(未启动)”并执行只读 CHECK,实际业务源返回 **ARCH_INI 应为 1,当前为 0**。外部作业为空,未启动写入。草稿目标 cdc_dm_probe 仅是校验占位,未创建该表;正式测试前须编辑为真实兼容目标表。截图:evidence/native-cdc-20261123.png。
|
||||
|
||||
真实 CDC 验收 BLOCKED:业务达梦未启用归档,当前无金仓数据源;未调整业务库全局配置。源码/本地发布 PASS_WITH_LIMITATION,仍有上文归档窗口长期运行缺口,不报告“全部完成”。
|
||||
|
||||
应用恢复引用各服务发布结果中的 recoveryImageId(integration c3e40cd9f6d7、dataops a85f41c94e47、frontend fed48622ed22);SeaTunnel 可恢复本次工作前的 2.3.13-cdc-complete-20261123(f9a236287c22)。不删除源表、目标表、数据卷和检查点。
|
||||
|
||||
2026-11-24 Oracle 更新:已补齐官方 Oracle-CDC 2.3.13 的 CDB/PDB 配置、前置检查及元数据/快照会话适配;真实 Oracle 端到端仍为 NOT_RUN。详见项目根目录 evidence/oracle-pdb-20261124.md。
|
||||
@@ -0,0 +1,16 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>cn.aixunkeji.datagov.integration</groupId>
|
||||
<artifactId>connector-aixun-native-cdc</artifactId>
|
||||
<version>2.3.13-1</version>
|
||||
<properties><maven.compiler.release>8</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>com.kingbase8</groupId><artifactId>kingbase8</artifactId><version>9.0.1.jre7</version><scope>system</scope><systemPath>${project.basedir}/../../../script/datagov/m2/seatunnel/local/artifacts/kingbase8-9.0.1.jre7.jar</systemPath></dependency>
|
||||
<dependency><groupId>org.apache.seatunnel</groupId><artifactId>seatunnel-api</artifactId><version>2.3.13</version><scope>provided</scope></dependency>
|
||||
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.12.2</version><scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
<build><plugins>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.15.0</version></plugin>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.5.3</version></plugin>
|
||||
</plugins></build>
|
||||
</project>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Transaction framing independent of driver or engine, with a hard memory limit. */
|
||||
public final class CommittedBatch {
|
||||
public static final class Transaction {
|
||||
public final String lsn;
|
||||
public final List<KingbaseChangeDecoder.Change> changes;
|
||||
Transaction(String lsn,List<KingbaseChangeDecoder.Change> changes){this.lsn=lsn;this.changes=Collections.unmodifiableList(changes);}
|
||||
}
|
||||
private final KingbaseChangeDecoder decoder=new KingbaseChangeDecoder();
|
||||
private final int maxChanges;
|
||||
private List<KingbaseChangeDecoder.Change> pending;
|
||||
private String xid;
|
||||
public CommittedBatch(int maxChanges){if(maxChanges<1)throw new IllegalArgumentException();this.maxChanges=maxChanges;}
|
||||
public Transaction accept(String lsn,String message){
|
||||
LogPosition.lsn(lsn);
|
||||
if(message.matches("BEGIN [0-9]+")){
|
||||
if(pending!=null)throw new IllegalArgumentException("Overlapping transactions");
|
||||
xid=message.substring(6);pending=new ArrayList<>();return null;
|
||||
}
|
||||
if(message.startsWith("COMMIT ")){
|
||||
if(pending==null||!message.equals("COMMIT "+xid))throw new IllegalArgumentException("Mismatched commit");
|
||||
Transaction result=new Transaction(lsn,pending);pending=null;xid=null;return result;
|
||||
}
|
||||
if(pending==null)throw new IllegalArgumentException("Change outside transaction");
|
||||
if(pending.size()>=maxChanges)throw new IllegalArgumentException("Transaction exceeds configured change limit");
|
||||
pending.add(decoder.decode(message));return null;
|
||||
}
|
||||
public void requireComplete(){if(pending!=null)throw new IllegalArgumentException("Incomplete transaction; no position acknowledged");}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Inclusive DM LSN ranges; sequence continuity, not an assumed LSN increment, detects gaps. */
|
||||
final class DamengArchiveWindow {
|
||||
static final int NEW_FILES_PER_POLL=64;
|
||||
static final class File {
|
||||
final String name;
|
||||
final long sequence,first,last;
|
||||
File(String name,long sequence,long first,long last) {
|
||||
if(name==null||name.isEmpty()||first<0||last<first)throw new IllegalArgumentException("达梦归档元数据不完整");
|
||||
this.name=name;this.sequence=sequence;this.first=first;this.last=last;
|
||||
}
|
||||
}
|
||||
static List<File> select(List<File> catalog,NativeLogSource.Split state) {
|
||||
if(catalog.isEmpty())throw new IllegalArgumentException("达梦没有可挖掘的归档日志");
|
||||
catalog=new ArrayList<>(catalog);catalog.sort(Comparator.comparingLong(f->f.sequence));
|
||||
int start=0;
|
||||
if(state.anchor!=null) {
|
||||
start=-1;
|
||||
for(int i=0;i<catalog.size();i++)if(state.anchor.equals(catalog.get(i).name)){start=i;break;}
|
||||
if(start<0)throw new IllegalArgumentException("恢复所需起始归档已清理,禁止跳过日志");
|
||||
}
|
||||
Set<String> names=new HashSet<>();for(File f:catalog)names.add(f.name);
|
||||
if(!names.containsAll(state.archives))throw new IllegalArgumentException("检查点所需归档存在缺口,停止采集");
|
||||
List<File> result=new ArrayList<>();int fresh=0;File previous=null;
|
||||
for(int i=start;i<catalog.size();i++) {
|
||||
File f=catalog.get(i);
|
||||
// The next window includes pinned old files plus at most 64 newly scanned files.
|
||||
if(state.archiveSequence==null || f.sequence>state.archiveSequence) {
|
||||
if(fresh==NEW_FILES_PER_POLL)break;
|
||||
fresh++;
|
||||
}
|
||||
if(previous!=null&&(f.sequence!=previous.sequence+1||f.first<previous.first||f.last<previous.last))
|
||||
throw new IllegalArgumentException("达梦归档序号不连续或存在重复归档,禁止跳过日志");
|
||||
result.add(f);previous=f;
|
||||
}
|
||||
if(state.archiveSequence!=null && result.get(result.size()-1).sequence<state.archiveSequence)
|
||||
throw new IllegalArgumentException("检查点之后的归档记录发生回退");
|
||||
return result;
|
||||
}
|
||||
static List<File> retain(List<File> scanned,Long earliestOpen) {
|
||||
int index=scanned.size()-1; // Keep the boundary file to validate continuity on the next poll.
|
||||
if(earliestOpen!=null) {
|
||||
index=-1;
|
||||
for(int i=0;i<scanned.size();i++) {
|
||||
File f=scanned.get(i);
|
||||
if(f.first<=earliestOpen && f.last>=earliestOpen){index=i;break;}
|
||||
}
|
||||
if(index<0)throw new IllegalArgumentException("未结束事务的起始归档不完整,禁止推进日志范围");
|
||||
}
|
||||
return new ArrayList<>(scanned.subList(index,scanned.size()));
|
||||
}
|
||||
static List<String> names(List<File> files){List<String> names=new ArrayList<>();for(File f:files)names.add(f.name);return names;}
|
||||
|
||||
/** Rebuilt from the pinned prefix on every poll, so in-flight transactions need no row buffer. */
|
||||
static final class Transactions {
|
||||
final Map<String,Long> open=new HashMap<>();
|
||||
final Set<String> missingStart=new HashSet<>();
|
||||
final Set<String> missingCommit=new HashSet<>();
|
||||
final Set<String> committed=new HashSet<>();
|
||||
final long first,cutoff,end;
|
||||
Transactions(long first,long cutoff){this(first,cutoff,Long.MAX_VALUE);}
|
||||
Transactions(long first,long cutoff,long end){this.first=first;this.cutoff=cutoff;this.end=end;}
|
||||
void accept(String xid,String operation,long scn,Long start,Long commit,boolean target) {
|
||||
if("INTERNAL".equals(operation))return;
|
||||
if(xid==null||xid.isEmpty())throw new IllegalArgumentException("日志缺少事务标识,不能安全推进归档范围");
|
||||
if(start!=null && start>0 && start<=scn && start>=first)open.merge(xid,start,Math::min);
|
||||
if("START".equals(operation)) {open.put(xid,scn);missingStart.remove(xid);committed.remove(xid);missingCommit.remove(xid);return;}
|
||||
if(!open.containsKey(xid)) {open.put(xid,scn);missingStart.add(xid);}
|
||||
if(target && (commit==null||commit<=0))missingCommit.add(xid);
|
||||
if(target && commit!=null && commit>cutoff && (missingStart.contains(xid)||(start!=null&&start>0&&start<first)))
|
||||
throw new IllegalArgumentException("待同步事务的起始日志缺失,禁止输出不完整事务");
|
||||
if(commit!=null&&commit>0&&commit<=end)committed.add(xid);
|
||||
if("COMMIT".equals(operation)||"ROLLBACK".equals(operation)||"XA_COMMIT".equals(operation)) {
|
||||
if(!"ROLLBACK".equals(operation)&&scn>cutoff&&missingCommit.contains(xid))
|
||||
throw new IllegalArgumentException("达梦未返回完整提交位置,禁止跳过已提交变更");
|
||||
open.remove(xid);missingStart.remove(xid);missingCommit.remove(xid);
|
||||
}
|
||||
}
|
||||
Long earliestOpen() {
|
||||
for(String xid:committed){
|
||||
if(missingCommit.contains(xid))throw new IllegalArgumentException("达梦提交位置不完整,禁止推进归档范围");
|
||||
open.remove(xid);missingStart.remove(xid);
|
||||
}
|
||||
if(!missingStart.isEmpty())throw new IllegalArgumentException("未结束事务缺少起始日志,不能安全推进归档范围");
|
||||
return open.isEmpty()?null:Collections.min(open.values());
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
import org.apache.seatunnel.api.source.SeaTunnelSource;
|
||||
import org.apache.seatunnel.api.table.factory.TableSourceFactory;
|
||||
import org.apache.seatunnel.api.configuration.util.OptionRule;
|
||||
public final class DamengFactory implements TableSourceFactory {
|
||||
public String factoryIdentifier(){return "Dameng-Native-CDC";}
|
||||
public Class<? extends SeaTunnelSource> getSourceClass(){return DamengSource.class;}
|
||||
public OptionRule optionRule(){return OptionRule.builder().build();}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
public final class DamengSource extends NativeLogSource {
|
||||
public String getPluginName(){return "Dameng-Native-CDC";}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Strict decoder for the test_decoding text contract; unknown messages fail closed. */
|
||||
public final class KingbaseChangeDecoder {
|
||||
public static final class Change {
|
||||
public final String schema,table,operation;
|
||||
public final Map<String,String> before,after;
|
||||
Change(String schema,String table,String operation,Map<String,String> before,Map<String,String> after){
|
||||
this.schema=schema;this.table=table;this.operation=operation;this.before=before;this.after=after;
|
||||
}
|
||||
}
|
||||
public Change decode(String text) {
|
||||
Cursor c=new Cursor(text);c.expect("table ");String schema=c.identifier();c.expect(".");
|
||||
String table=c.identifier();c.expect(": ");String op=c.until(':');c.expect(":");c.space();
|
||||
Map<String,String> old=Collections.emptyMap(), next=Collections.emptyMap();
|
||||
switch(op){
|
||||
case "INSERT": next=c.fields(false);break;
|
||||
case "DELETE": old=c.fields(false);break;
|
||||
case "UPDATE":
|
||||
c.expect("old-key: ");old=c.fields(true);c.expect("new-tuple: ");next=c.fields(false);break;
|
||||
default: throw new IllegalArgumentException("Unsupported logical operation (including TRUNCATE)");
|
||||
}
|
||||
c.space();if(!c.end())throw new IllegalArgumentException("Unparsed logical message");
|
||||
return new Change(schema,table,op,old,next);
|
||||
}
|
||||
private static final class Cursor {
|
||||
final String text;int pos;
|
||||
Cursor(String text){this.text=Objects.requireNonNull(text);}
|
||||
boolean end(){return pos==text.length();}
|
||||
void space(){while(!end()&&text.charAt(pos)==' ')pos++;}
|
||||
void expect(String s){if(!text.startsWith(s,pos))throw new IllegalArgumentException("Unsupported logical decoding syntax");pos+=s.length();}
|
||||
String until(char ch){int start=pos;while(!end()&&text.charAt(pos)!=ch)pos++;if(end())throw new IllegalArgumentException("Truncated logical message");return text.substring(start,pos);}
|
||||
String quoted(char quote){
|
||||
pos++;StringBuilder result=new StringBuilder();
|
||||
while(!end()){
|
||||
char ch=text.charAt(pos++);
|
||||
if(ch==quote){if(!end()&&text.charAt(pos)==quote){pos++;result.append(ch);}else return result.toString();}
|
||||
else result.append(ch);
|
||||
}
|
||||
throw new IllegalArgumentException("Unterminated logical value");
|
||||
}
|
||||
String identifier(){
|
||||
if(!end()&&text.charAt(pos)=='"')return quoted('"');
|
||||
int start=pos;while(!end()&&(Character.isLetterOrDigit(text.charAt(pos))||"_$".indexOf(text.charAt(pos))>=0))pos++;
|
||||
if(start==pos)throw new IllegalArgumentException("Invalid logical identifier");return text.substring(start,pos);
|
||||
}
|
||||
Map<String,String> fields(boolean stopAtNew){
|
||||
Map<String,String> values=new LinkedHashMap<>();
|
||||
while(true){
|
||||
space();if(end()||stopAtNew&&text.startsWith("new-tuple: ",pos))return values;
|
||||
String name=identifier();expect("[");until(']');expect("]:");
|
||||
String value;
|
||||
if(!end()&&text.charAt(pos)=='\'')value=quoted('\'');
|
||||
else {int start=pos;while(!end()&&text.charAt(pos)!=' ')pos++;value=text.substring(start,pos);
|
||||
if("null".equals(value))value=null;
|
||||
else if(!value.matches("[-+0-9.eE]+|true|false|t|f"))throw new IllegalArgumentException("Unsupported logical value or unchanged TOAST");}
|
||||
if(values.containsKey(name))throw new IllegalArgumentException("Duplicate logical column");
|
||||
values.put(name,value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
import org.apache.seatunnel.api.source.SeaTunnelSource;
|
||||
import org.apache.seatunnel.api.table.factory.TableSourceFactory;
|
||||
import org.apache.seatunnel.api.configuration.util.OptionRule;
|
||||
public final class KingbaseFactory implements TableSourceFactory {
|
||||
public String factoryIdentifier(){return "Kingbase-Native-CDC";}
|
||||
public Class<? extends SeaTunnelSource> getSourceClass(){return KingbaseSource.class;}
|
||||
public OptionRule optionRule(){return OptionRule.builder().build();}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
public final class KingbaseSource extends NativeLogSource {
|
||||
public String getPluginName(){return "Kingbase-Native-CDC";}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
|
||||
/** Committed position only. Never checkpoint a half-decoded transaction. */
|
||||
public final class LogPosition implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final String position;
|
||||
public final String identity;
|
||||
public LogPosition(String position, String identity) {
|
||||
if (position == null || identity == null) throw new IllegalArgumentException("Missing log identity");
|
||||
this.position = position; this.identity = identity;
|
||||
}
|
||||
public static BigInteger lsn(String value) {
|
||||
if (value == null || !value.matches("[0-9A-Fa-f]{1,8}/[0-9A-Fa-f]{1,8}"))
|
||||
throw new IllegalArgumentException("Invalid WAL position");
|
||||
String[] parts=value.split("/");
|
||||
return new BigInteger(parts[0],16).shiftLeft(32).add(new BigInteger(parts[1],16));
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import org.apache.seatunnel.api.source.*;
|
||||
import org.apache.seatunnel.api.table.type.*;
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import com.kingbase8.KBConnection;
|
||||
import com.kingbase8.replication.KBReplicationStream;
|
||||
import com.kingbase8.replication.LogSequenceNumber;
|
||||
|
||||
/** The durable engine checkpoint owns progress; source acknowledgement always follows completion. */
|
||||
final class NativeLogReader implements SourceReader<SeaTunnelRow,NativeLogSource.Split> {
|
||||
private final NativeLogSource source;
|
||||
private Connection db;
|
||||
private Connection replicationConnection;
|
||||
private KBReplicationStream stream;
|
||||
private final CommittedBatch frames=new CommittedBatch(10000);
|
||||
private volatile NativeLogSource.Split state;
|
||||
private volatile boolean closed;
|
||||
private final NavigableMap<Long,NativeLogSource.Split> snapshots=new TreeMap<>();
|
||||
NativeLogReader(NativeLogSource source){this.source=source;}
|
||||
public void open()throws Exception{db=source.connect();}
|
||||
public void addSplits(List<NativeLogSource.Split> splits){if(splits.size()!=1||state!=null)throw new IllegalArgumentException("Duplicate source split");state=splits.get(0).copy();}
|
||||
public void handleNoMoreSplits(){}
|
||||
public void close()throws IOException{
|
||||
closed=true;
|
||||
try{if(stream!=null)stream.close();}catch(SQLException ignored){}
|
||||
try{if(replicationConnection!=null)replicationConnection.close();}catch(SQLException ignored){}
|
||||
if(db!=null)try{db.close();}catch(SQLException e){throw new IOException("Native CDC close failed");}
|
||||
}
|
||||
public synchronized List<NativeLogSource.Split> snapshotState(long id){
|
||||
if(state==null)return Collections.emptyList();NativeLogSource.Split copy=state.copy();
|
||||
if(copy.cursor==null)throw new IllegalStateException("日志起始位置尚未建立,不能完成检查点");
|
||||
snapshots.put(id,copy);return Collections.singletonList(copy);
|
||||
}
|
||||
public synchronized void notifyCheckpointAborted(long id){snapshots.remove(id);}
|
||||
public synchronized void notifyCheckpointComplete(long id)throws Exception{
|
||||
NativeLogSource.Split saved=snapshots.get(id);
|
||||
if(saved!=null&&saved.cursor!=null&&stream!=null){
|
||||
synchronized(stream){
|
||||
LogSequenceNumber lsn=LogSequenceNumber.valueOf(saved.cursor);
|
||||
stream.setAppliedLSN(lsn);stream.setFlushedLSN(lsn);stream.forceUpdateStatus();
|
||||
}
|
||||
}
|
||||
snapshots.headMap(id,true).clear();
|
||||
}
|
||||
public void pollNext(Collector<SeaTunnelRow> output)throws Exception{
|
||||
if(closed)return;if(state==null){Thread.sleep(100);return;}
|
||||
try{
|
||||
NativeLogSource.Split next=state.copy();
|
||||
if(next.schemaSignature!=null&&!next.schemaSignature.equals(source.schemaSignature))throw new IllegalArgumentException("恢复时源表结构发生变化");
|
||||
next.schemaSignature=source.schemaSignature;source.checkSchema(db);
|
||||
boolean initializing=next.cursor==null;
|
||||
if(initializing)next.snapshotting=source.initial;
|
||||
// Establish and checkpoint the log low watermark before publishing snapshot pages.
|
||||
List<SeaTunnelRow> rows="KINGBASE".equals(source.kind)?kingbase(next,initializing||next.snapshotting):dameng(next,initializing||next.snapshotting);
|
||||
if(!initializing&&next.snapshotting)rows=snapshot(next);
|
||||
// Same lock as the engine barrier: events and the matching offset cannot be separated.
|
||||
synchronized(output.getCheckpointLock()){
|
||||
for(SeaTunnelRow row:rows)output.collect(row);
|
||||
state=next;
|
||||
}
|
||||
if(rows.isEmpty())Thread.sleep(1000);
|
||||
}catch(SQLException e){throw new IllegalStateException("原生CDC日志接口失败,SQLState="+e.getSQLState()+",错误码="+e.getErrorCode());}
|
||||
}
|
||||
private List<SeaTunnelRow> kingbase(NativeLogSource.Split next,boolean positionOnly)throws SQLException{
|
||||
if(stream==null){
|
||||
try(Statement st=db.createStatement()){
|
||||
st.setQueryTimeout(30);
|
||||
try(ResultSet rs=st.executeQuery("SHOW wal_level")){if(!rs.next()||!"logical".equals(rs.getString(1)))throw new IllegalArgumentException("金仓需启用logical WAL");}
|
||||
}
|
||||
try(PreparedStatement ps=db.prepareStatement("SELECT plugin, database, active, restart_lsn, confirmed_flush_lsn FROM sys_replication_slots WHERE slot_name=?")){
|
||||
ps.setQueryTimeout(30);ps.setString(1,source.slot);
|
||||
try(ResultSet rs=ps.executeQuery()){
|
||||
if(!rs.next()||!"test_decoding".equals(rs.getString(1))||rs.getBoolean(3))throw new IllegalArgumentException("金仓需要预建专用且未被占用的test_decoding逻辑复制槽");
|
||||
if(!Objects.equals(rs.getString(2),db.getCatalog()))throw new IllegalArgumentException("复制槽不属于当前源数据库");
|
||||
if(next.cursor==null){
|
||||
// First start is from the slot's current confirmed position, never a guessed WAL location.
|
||||
next.cursor=rs.getString(5);next.anchor=next.cursor;
|
||||
if(next.cursor==null)throw new IllegalArgumentException("复制槽缺少已确认位置");
|
||||
}else if(LogPosition.lsn(rs.getString(5)).compareTo(LogPosition.lsn(next.cursor))>0)
|
||||
throw new IllegalArgumentException("复制槽已被其他消费者推进,无法从原检查点恢复");
|
||||
if(rs.getString(4)==null||LogPosition.lsn(rs.getString(4)).compareTo(LogPosition.lsn(next.cursor))>0)
|
||||
throw new IllegalArgumentException("所需WAL已不可用,禁止跳过数据");
|
||||
}
|
||||
}
|
||||
Properties props=new Properties();props.setProperty("user",source.user);props.setProperty("password",source.password);
|
||||
props.setProperty("replication","database");props.setProperty("preferQueryMode","simple");
|
||||
replicationConnection=DriverManager.getConnection(source.url,props);
|
||||
try(Statement st=replicationConnection.createStatement();ResultSet rs=st.executeQuery("IDENTIFY_SYSTEM")){
|
||||
if(!rs.next())throw new IllegalArgumentException("金仓复制协议不能提供实例身份");
|
||||
String identity=rs.getString(1)+":"+rs.getString(2)+":"+source.slot+":"+source.schema+":"+source.table;
|
||||
if(next.identity!=null&&!next.identity.equals(identity))throw new IllegalArgumentException("金仓实例或时间线变化,禁止直接恢复");
|
||||
if(next.identity==null&&next.snapshotting)next.cursor=rs.getString(3);
|
||||
next.identity=identity;
|
||||
}
|
||||
stream=replicationConnection.unwrap(KBConnection.class).getReplicationAPI().replicationStream().logical()
|
||||
.withSlotName(source.slot).withStartPosition(LogSequenceNumber.valueOf(next.cursor))
|
||||
.withSlotOption("include-xids",true).withSlotOption("include-timestamp",false).start();
|
||||
}
|
||||
if(positionOnly)return Collections.emptyList();
|
||||
// The replication stream holds the slot exclusively. Only completed checkpoints acknowledge WAL.
|
||||
List<SeaTunnelRow> rows=new ArrayList<>();
|
||||
for(int messageCount=0;messageCount<10000;messageCount++){
|
||||
ByteBuffer bytes;String lsn;
|
||||
synchronized(stream){bytes=stream.readPending();lsn=stream.getLastReceiveLSN().asString();}
|
||||
if(bytes==null)break;
|
||||
CommittedBatch.Transaction tx=frames.accept(lsn,StandardCharsets.UTF_8.decode(bytes).toString());
|
||||
if(tx==null||LogPosition.lsn(tx.lsn).compareTo(LogPosition.lsn(next.cursor))<=0)continue;
|
||||
for(KingbaseChangeDecoder.Change c:tx.changes){
|
||||
if(!source.schema.equals(c.schema)||!source.table.equals(c.table))continue;
|
||||
if(rows.size()>20000)throw new IllegalArgumentException("CDC batch exceeds supported memory limit");
|
||||
if("INSERT".equals(c.operation))rows.add(source.row(c.after,RowKind.INSERT));
|
||||
else if("DELETE".equals(c.operation))rows.add(source.row(c.before,RowKind.DELETE));
|
||||
else {rows.add(source.row(c.before,RowKind.UPDATE_BEFORE));rows.add(source.row(c.after,RowKind.UPDATE_AFTER));}
|
||||
}
|
||||
next.cursor=tx.lsn;
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
private List<SeaTunnelRow> dameng(NativeLogSource.Split next,boolean positionOnly)throws SQLException{
|
||||
List<DamengArchiveWindow.File> catalog=new ArrayList<>();
|
||||
try(Statement st=db.createStatement()){
|
||||
st.setQueryTimeout(30);
|
||||
try(ResultSet rs=st.executeQuery("SELECT DB_MAGIC, CUR_LSN FROM V$RLOG")){
|
||||
if(!rs.next())throw new IllegalArgumentException("无法核实达梦实例身份");
|
||||
String identity=rs.getString(1)+":"+source.schema+":"+source.table;
|
||||
if(next.identity!=null&&!next.identity.equals(identity))throw new IllegalArgumentException("达梦数据库身份变化,禁止恢复");
|
||||
next.identity=identity;
|
||||
if(next.cursor==null)next.cursor=rs.getString(2);
|
||||
}
|
||||
try(ResultSet rs=st.executeQuery("SELECT PARA_NAME, PARA_VALUE FROM V$DM_INI WHERE PARA_NAME IN ('RLOG_APPEND_LOGIC','RLOG_LLOG_COMPRESS','LOGMNR_DELAY_ANALYZE')")){
|
||||
Map<String,String> p=new HashMap<>();while(rs.next())p.put(rs.getString(1),rs.getString(2));
|
||||
if(!"2".equals(p.get("RLOG_APPEND_LOGIC"))||!"0".equals(p.get("RLOG_LLOG_COMPRESS"))||!"0".equals(p.get("LOGMNR_DELAY_ANALYZE")))
|
||||
throw new IllegalArgumentException("达梦需要RLOG_APPEND_LOGIC=2、RLOG_LLOG_COMPRESS=0、LOGMNR_DELAY_ANALYZE=0");
|
||||
}
|
||||
try(ResultSet rs=st.executeQuery("SELECT NAME, SEQUENCE#, FIRST_CHANGE#, NEXT_CHANGE# FROM V$ARCHIVED_LOG ORDER BY SEQUENCE#, NAME")){
|
||||
while(rs.next()){
|
||||
String name=rs.getString(1);long sequence=rs.getLong(2);
|
||||
if(rs.wasNull())throw new IllegalArgumentException("达梦归档缺少文件序号");
|
||||
long first=rs.getLong(3);if(rs.wasNull())throw new IllegalArgumentException("达梦归档缺少起始LSN");
|
||||
long last=rs.getLong(4);if(rs.wasNull())throw new IllegalArgumentException("达梦归档缺少结束LSN");
|
||||
catalog.add(new DamengArchiveWindow.File(name,sequence,first,last));
|
||||
}
|
||||
}
|
||||
}
|
||||
List<DamengArchiveWindow.File> selected=DamengArchiveWindow.select(catalog,next);
|
||||
List<String> files=DamengArchiveWindow.names(selected);
|
||||
if(next.anchor==null){next.anchor=files.get(0);next.archives=new ArrayList<>(Collections.singletonList(next.anchor));}
|
||||
if(positionOnly)return Collections.emptyList();
|
||||
long cutoff=Long.parseLong(next.cursor),end=selected.get(selected.size()-1).last;
|
||||
try{
|
||||
for(int i=0;i<files.size();i++)try(CallableStatement ps=db.prepareCall(damengAddLogSql(i==0))){
|
||||
ps.setQueryTimeout(30);ps.setString(1,files.get(i));ps.execute();
|
||||
}
|
||||
// Include unfinished transactions; COMMITTED_DATA_ONLY would hide the very prefix we must pin.
|
||||
try(CallableStatement ps=db.prepareCall("CALL DBMS_LOGMNR.START_LOGMNR(OPTIONS=>2128, ENDSCN=>?)")){ps.setQueryTimeout(60);ps.setLong(1,end);ps.execute();}
|
||||
DamengArchiveWindow.Transactions transactions=new DamengArchiveWindow.Transactions(selected.get(0).first,cutoff,end);
|
||||
try(Statement st=db.createStatement()){
|
||||
st.setQueryTimeout(60);
|
||||
try(ResultSet rs=st.executeQuery("SELECT XID, OPERATION, SCN, START_SCN, COMMIT_SCN, SEG_OWNER, TABLE_NAME, STATUS, ROLL_BACK FROM V$LOGMNR_CONTENTS ORDER BY SCN, SSN")){
|
||||
while(rs.next()){
|
||||
if(rs.getInt(8)!=0)throw new IllegalArgumentException("达梦事务边界不可解析,禁止推进日志范围");
|
||||
byte[] xid=rs.getBytes(1);String key=xid==null?null:Base64.getEncoder().encodeToString(xid);
|
||||
long scn=rs.getLong(3);if(rs.wasNull()||scn>end)throw new IllegalArgumentException("达梦日志位置超出已确认归档范围");
|
||||
long start=rs.getLong(4);Long startScn=rs.wasNull()?null:start;
|
||||
long commit=rs.getLong(5);Long commitScn=rs.wasNull()?null:commit;
|
||||
transactions.accept(key,rs.getString(2),scn,startScn,commitScn,
|
||||
source.schema.equals(rs.getString(6))&&source.table.equals(rs.getString(7))&&rs.getInt(9)==0);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<DamengArchiveWindow.File> retained=DamengArchiveWindow.retain(selected,transactions.earliestOpen());
|
||||
StringBuilder sql=new StringBuilder("SELECT OPERATION, COMMIT_SCN, STATUS");
|
||||
for(String name:source.names){
|
||||
String column=source.schema+"."+source.table+"."+name;
|
||||
sql.append(", DBMS_LOGMNR.COLUMN_PRESENT(UNDO_VALUE,'").append(column).append("'), DBMS_LOGMNR.MINE_VALUE(UNDO_VALUE,'").append(column)
|
||||
.append("'), DBMS_LOGMNR.COLUMN_PRESENT(REDO_VALUE,'").append(column).append("'), DBMS_LOGMNR.MINE_VALUE(REDO_VALUE,'").append(column).append("')");
|
||||
}
|
||||
// A committed transaction can contain statements rolled back to a savepoint.
|
||||
sql.append(" FROM V$LOGMNR_CONTENTS WHERE SEG_OWNER=? AND TABLE_NAME=? AND COMMIT_SCN>? AND COMMIT_SCN<=? AND ROLL_BACK=0 ORDER BY COMMIT_SCN, SCN, SSN");
|
||||
List<SeaTunnelRow> rows=new ArrayList<>();
|
||||
try(PreparedStatement ps=db.prepareStatement(sql.toString())){
|
||||
ps.setQueryTimeout(60);ps.setString(1,source.schema);ps.setString(2,source.table);ps.setLong(3,cutoff);ps.setLong(4,end);
|
||||
try(ResultSet rs=ps.executeQuery()){
|
||||
while(rs.next()){
|
||||
if(rows.size()>20000)throw new IllegalArgumentException("达梦CDC批次超过首版内存限制");
|
||||
if(rs.getInt(3)!=0)throw new IllegalArgumentException("达梦日志结构不可解析,禁止跳过");
|
||||
String op=rs.getString(1);Map<String,String> before=new LinkedHashMap<>(),after=new LinkedHashMap<>();
|
||||
for(int i=0;i<source.names.size();i++){
|
||||
int n=4+i*4;if(rs.getInt(n)==1)before.put(source.names.get(i),rs.getString(n+1));
|
||||
if(rs.getInt(n+2)==1)after.put(source.names.get(i),rs.getString(n+3));
|
||||
}
|
||||
if("INSERT".equals(op))rows.add(source.row(after,RowKind.INSERT));
|
||||
else if("DELETE".equals(op))rows.add(source.row(before,RowKind.DELETE));
|
||||
else if("UPDATE".equals(op)){rows.add(source.row(before,RowKind.UPDATE_BEFORE));rows.add(source.row(after,RowKind.UPDATE_AFTER));}
|
||||
else throw new IllegalArgumentException("达梦CDC遇到未支持操作或DDL,需人工处理");
|
||||
next.cursor=rs.getString(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
next.cursor=Long.toString(Math.max(cutoff,end));
|
||||
next.archiveSequence=selected.get(selected.size()-1).sequence;
|
||||
next.archives=DamengArchiveWindow.names(retained);next.anchor=next.archives.get(0);
|
||||
endDamengSession(db);
|
||||
return rows;
|
||||
}catch(SQLException|RuntimeException failure){
|
||||
// Cleanup must never hide the first failure (DM -2846 means no active session).
|
||||
try{endDamengSession(db);}catch(SQLException cleanup){failure.addSuppressed(cleanup);}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
static String damengAddLogSql(boolean first){
|
||||
return "CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR."+(first?"\"NEW\"":"ADDFILE")+")";
|
||||
}
|
||||
|
||||
static void endDamengSession(Connection connection)throws SQLException{
|
||||
try(CallableStatement ps=connection.prepareCall("CALL DBMS_LOGMNR.END_LOGMNR()")){
|
||||
ps.setQueryTimeout(30);ps.execute();
|
||||
}catch(SQLException error){
|
||||
// Already absent is an idempotent cleanup outcome; all other errors remain failures.
|
||||
if(error.getErrorCode()!=-2846)throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Keyset snapshot; replay from the saved low watermark repairs concurrent writes/deletes. */
|
||||
List<SeaTunnelRow> snapshot(NativeLogSource.Split next)throws SQLException {
|
||||
StringBuilder sql=new StringBuilder("SELECT * FROM ").append(source.qualified());
|
||||
List<Object> params=new ArrayList<>();
|
||||
if(next.snapshotKey!=null){
|
||||
sql.append(" WHERE ");
|
||||
for(int i=0;i<source.primaryKeys.size();i++){
|
||||
if(i>0)sql.append(" OR ");sql.append('(');
|
||||
for(int j=0;j<=i;j++){
|
||||
if(j>0)sql.append(" AND ");
|
||||
sql.append('"').append(source.primaryKeys.get(j)).append('"').append(j==i?">?":"=?");
|
||||
params.add(next.snapshotKey[j]);
|
||||
}
|
||||
sql.append(')');
|
||||
}
|
||||
}
|
||||
sql.append(" ORDER BY ");
|
||||
for(int i=0;i<source.primaryKeys.size();i++){
|
||||
if(i>0)sql.append(',');sql.append('"').append(source.primaryKeys.get(i)).append('"');
|
||||
}
|
||||
sql.append("DAMENG".equals(source.kind)?" FETCH FIRST 500 ROWS ONLY":" LIMIT 500");
|
||||
List<SeaTunnelRow> rows=new ArrayList<>();
|
||||
try(PreparedStatement ps=db.prepareStatement(sql.toString())){
|
||||
ps.setQueryTimeout(60);
|
||||
for(int i=0;i<params.size();i++)ps.setObject(i+1,params.get(i));
|
||||
try(ResultSet rs=ps.executeQuery()){
|
||||
while(rs.next()){
|
||||
Map<String,String> values=new LinkedHashMap<>();
|
||||
for(String name:source.names)values.put(name,rs.getString(name));
|
||||
rows.add(source.row(values,RowKind.INSERT));
|
||||
next.snapshotKey=new Object[source.primaryKeys.size()];
|
||||
for(int i=0;i<source.primaryKeys.size();i++)next.snapshotKey[i]=rs.getObject(source.primaryKeys.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
if(rows.size()<500){next.snapshotting=false;next.snapshotKey=null;}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import org.apache.seatunnel.api.source.*;
|
||||
import org.apache.seatunnel.api.table.catalog.*;
|
||||
import org.apache.seatunnel.api.table.type.*;
|
||||
import org.apache.seatunnel.shade.com.typesafe.config.Config;
|
||||
import java.io.*;
|
||||
import java.sql.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.*;
|
||||
|
||||
/** Single-reader native log source. Database changes and slot lifecycle belong to the DBA. */
|
||||
public abstract class NativeLogSource implements SeaTunnelSource<SeaTunnelRow,NativeLogSource.Split,Boolean> {
|
||||
private static final long serialVersionUID=1L;
|
||||
String url,user,password,schema,table,slot,kind;
|
||||
List<String> names=new ArrayList<>();List<Integer> types=new ArrayList<>();
|
||||
CatalogTable catalog;
|
||||
String schemaSignature;
|
||||
boolean initial;
|
||||
List<String> primaryKeys=new ArrayList<>();
|
||||
public static class Split implements SourceSplit {
|
||||
private static final long serialVersionUID=1L;
|
||||
public String cursor,anchor,identity;
|
||||
public String schemaSignature;
|
||||
public List<String> archives=new ArrayList<>();
|
||||
public Long archiveSequence;
|
||||
public boolean snapshotting;
|
||||
public Object[] snapshotKey;
|
||||
public String splitId(){return "single-native-log";}
|
||||
Split copy(){Split s=new Split();s.cursor=cursor;s.anchor=anchor;s.identity=identity;s.schemaSignature=schemaSignature;s.archives=new ArrayList<>(archives);s.archiveSequence=archiveSequence;s.snapshotting=snapshotting;s.snapshotKey=snapshotKey==null?null:snapshotKey.clone();return s;}
|
||||
}
|
||||
public Boundedness getBoundedness(){return Boundedness.UNBOUNDED;}
|
||||
public List<CatalogTable> getProducedCatalogTables(){return Collections.singletonList(catalog);}
|
||||
public void prepare(Config c){
|
||||
url=c.getString("url");user=c.getString("username");password=c.getString("password");
|
||||
schema=identifier(c.getString("source_schema"));table=identifier(c.getString("source_table"));
|
||||
kind=getPluginName().startsWith("Dameng")?"DAMENG":"KINGBASE";
|
||||
String startup=c.getString("startup.mode");
|
||||
if(!Arrays.asList("initial","latest").contains(startup))throw new IllegalArgumentException("Unsupported startup mode");
|
||||
initial="initial".equals(startup);
|
||||
if("KINGBASE".equals(kind))slot=identifier(c.getString("slot_name"));
|
||||
names.clear();types.clear();
|
||||
try(Connection db=connect();Statement st=db.createStatement()){
|
||||
SortedMap<Short,String> keys=new TreeMap<>();
|
||||
try(ResultSet pk=db.getMetaData().getPrimaryKeys("DAMENG".equals(kind)?null:db.getCatalog(),schema,table)){
|
||||
while(pk.next())keys.put(pk.getShort("KEY_SEQ"),pk.getString("COLUMN_NAME"));
|
||||
}
|
||||
if(keys.isEmpty())throw new IllegalArgumentException("原生CDC要求源表有主键,以正确同步更新和删除");
|
||||
primaryKeys=new ArrayList<>(keys.values());
|
||||
st.setQueryTimeout(30);
|
||||
try(ResultSet rs=st.executeQuery("SELECT * FROM "+qualified()+" WHERE 1=0")){
|
||||
ResultSetMetaData m=rs.getMetaData();schemaSignature=signature(m)+"|PK="+primaryKeys;TableSchema.Builder b=TableSchema.builder();
|
||||
for(int i=1;i<=m.getColumnCount();i++){
|
||||
String n=identifier(m.getColumnName(i));int t=m.getColumnType(i);
|
||||
names.add(n);types.add(t);
|
||||
b.column(PhysicalColumn.of(n,dataType(t,m.getPrecision(i),m.getScale(i)),(Long)null,true,null,null));
|
||||
}
|
||||
b.primaryKey(PrimaryKey.of("source_pk",new ArrayList<>(keys.values())));
|
||||
catalog=CatalogTable.of(TableIdentifier.of("aixun",db.getCatalog(),schema,table),b.build(),Collections.emptyMap(),Collections.emptyList(),"");
|
||||
}
|
||||
}catch(SQLException ex){throw new IllegalStateException("原生CDC源表结构读取失败,SQLState="+ex.getSQLState());}
|
||||
}
|
||||
static String signature(ResultSetMetaData m)throws SQLException{
|
||||
StringBuilder s=new StringBuilder();
|
||||
for(int i=1;i<=m.getColumnCount();i++)s.append(m.getColumnName(i)).append(':').append(m.getColumnType(i)).append(':').append(m.getPrecision(i)).append(':').append(m.getScale(i)).append(';');
|
||||
return s.toString();
|
||||
}
|
||||
void checkSchema(Connection db)throws SQLException{
|
||||
SortedMap<Short,String> keys=new TreeMap<>();
|
||||
try(ResultSet pk=db.getMetaData().getPrimaryKeys("DAMENG".equals(kind)?null:db.getCatalog(),schema,table)){
|
||||
while(pk.next())keys.put(pk.getShort("KEY_SEQ"),pk.getString("COLUMN_NAME"));
|
||||
}
|
||||
try(Statement st=db.createStatement()){
|
||||
st.setQueryTimeout(30);
|
||||
try(ResultSet rs=st.executeQuery("SELECT * FROM "+qualified()+" WHERE 1=0")){
|
||||
if(!schemaSignature.equals(signature(rs.getMetaData())+"|PK="+new ArrayList<>(keys.values())))throw new IllegalArgumentException("源表结构或主键已变化,直连CDC停止,禁止按旧结构写入");
|
||||
}
|
||||
}
|
||||
}
|
||||
Connection connect()throws SQLException{
|
||||
try{Class.forName("DAMENG".equals(kind)?"dm.jdbc.driver.DmDriver":"com.kingbase8.Driver");}
|
||||
catch(ClassNotFoundException e){throw new SQLException("缺少原生CDC JDBC驱动");}
|
||||
return DriverManager.getConnection(url,user,password);
|
||||
}
|
||||
String qualified(){return "\""+schema+"\".\""+table+"\"";}
|
||||
static String identifier(String v){if(v==null||!v.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))throw new IllegalArgumentException("Unsupported identifier");return v;}
|
||||
static SeaTunnelDataType<?> dataType(int t,int p,int s){
|
||||
switch(t){
|
||||
case Types.SMALLINT:return BasicType.SHORT_TYPE;case Types.TINYINT:return BasicType.BYTE_TYPE;
|
||||
case Types.INTEGER:return BasicType.INT_TYPE;case Types.BIGINT:return BasicType.LONG_TYPE;
|
||||
case Types.FLOAT:case Types.REAL:return BasicType.FLOAT_TYPE;case Types.DOUBLE:return BasicType.DOUBLE_TYPE;
|
||||
case Types.NUMERIC:case Types.DECIMAL:if(p<1||p>38||s<0||s>p)throw new IllegalArgumentException("Unsupported decimal precision");return new DecimalType(p,s);
|
||||
case Types.CHAR:case Types.VARCHAR:case Types.NCHAR:case Types.NVARCHAR:return BasicType.STRING_TYPE;
|
||||
case Types.BOOLEAN:case Types.BIT:return BasicType.BOOLEAN_TYPE;
|
||||
case Types.DATE:return LocalTimeType.LOCAL_DATE_TYPE;case Types.TIME:return LocalTimeType.LOCAL_TIME_TYPE;case Types.TIMESTAMP:return LocalTimeType.LOCAL_DATE_TIME_TYPE;
|
||||
default:throw new IllegalArgumentException("原生CDC暂不支持LOB、二进制、数组或带时区字段");
|
||||
}
|
||||
}
|
||||
SeaTunnelRow row(Map<String,String> values,RowKind rowKind){
|
||||
if(values.size()!=names.size()||!values.keySet().containsAll(names))throw new IllegalArgumentException("日志缺少完整行镜像或表结构已变化,拒绝丢字段写入");
|
||||
Object[] fields=new Object[names.size()];
|
||||
for(int i=0;i<fields.length;i++)fields[i]=convert(values.get(names.get(i)),types.get(i));
|
||||
SeaTunnelRow row=new SeaTunnelRow(fields);row.setRowKind(rowKind);row.setTableId(catalog.getTablePath().toString());return row;
|
||||
}
|
||||
static Object convert(String v,int t){
|
||||
if(v==null)return null;
|
||||
switch(t){
|
||||
case Types.TINYINT:return Byte.valueOf(v);case Types.SMALLINT:return Short.valueOf(v);case Types.INTEGER:return Integer.valueOf(v);case Types.BIGINT:return Long.valueOf(v);
|
||||
case Types.FLOAT:case Types.REAL:return Float.valueOf(v);case Types.DOUBLE:return Double.valueOf(v);
|
||||
case Types.DECIMAL:case Types.NUMERIC:return new BigDecimal(v);
|
||||
case Types.BOOLEAN:case Types.BIT:
|
||||
if(Arrays.asList("true","t","1").contains(v))return true;
|
||||
if(Arrays.asList("false","f","0").contains(v))return false;throw new IllegalArgumentException("Invalid boolean value");
|
||||
case Types.DATE:return java.time.LocalDate.parse(v);case Types.TIME:return java.time.LocalTime.parse(v);
|
||||
case Types.TIMESTAMP:return java.time.LocalDateTime.parse(v.replace(' ','T'));
|
||||
default:return v;
|
||||
}
|
||||
}
|
||||
public SourceReader<SeaTunnelRow,Split> createReader(SourceReader.Context ctx){
|
||||
if(ctx.getIndexOfSubtask()!=0)throw new IllegalArgumentException("原生CDC仅支持并行度1");
|
||||
return new NativeLogReader(this);
|
||||
}
|
||||
public SourceSplitEnumerator<Split,Boolean> createEnumerator(SourceSplitEnumerator.Context<Split> ctx){return new Enumerator(ctx,false);}
|
||||
public SourceSplitEnumerator<Split,Boolean> restoreEnumerator(SourceSplitEnumerator.Context<Split> ctx,Boolean state){return new Enumerator(ctx,state);}
|
||||
static final class Enumerator implements SourceSplitEnumerator<Split,Boolean>{
|
||||
final Context<Split> context;boolean assigned;List<Split> returned=new ArrayList<>();
|
||||
Enumerator(Context<Split> context,boolean assigned){this.context=context;this.assigned=assigned;if(context.currentParallelism()!=1)throw new IllegalArgumentException("Parallelism must be 1");}
|
||||
public void open(){}public void close(){}public void notifyCheckpointComplete(long id){}
|
||||
public synchronized void run(){for(int id:context.registeredReaders())registerReader(id);}
|
||||
public synchronized void registerReader(int id){
|
||||
if(!returned.isEmpty()){context.assignSplit(id,new ArrayList<>(returned));returned.clear();}
|
||||
else if(!assigned){context.assignSplit(id,Collections.singletonList(new Split()));assigned=true;}
|
||||
context.signalNoMoreSplits(id);
|
||||
}
|
||||
public synchronized void addSplitsBack(List<Split> splits,int id){returned.addAll(splits);assigned=true;}
|
||||
public synchronized int currentUnassignedSplitSize(){return returned.size()+(assigned?0:1);}
|
||||
public void handleSplitRequest(int id){registerReader(id);}
|
||||
public synchronized Boolean snapshotState(long id){if(!returned.isEmpty())throw new IllegalStateException("Unassigned recovery state");return assigned;}
|
||||
}
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
cn.aixunkeji.datagov.integration.cdc.DamengSource
|
||||
cn.aixunkeji.datagov.integration.cdc.KingbaseSource
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
cn.aixunkeji.datagov.integration.cdc.DamengFactory
|
||||
cn.aixunkeji.datagov.integration.cdc.KingbaseFactory
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class DamengArchiveWindowTest {
|
||||
List<DamengArchiveWindow.File> files(int n){
|
||||
List<DamengArchiveWindow.File> list=new ArrayList<>();
|
||||
for(int i=1;i<=n;i++)list.add(new DamengArchiveWindow.File("f"+i,i,i*100L,i*100L+99));
|
||||
return list;
|
||||
}
|
||||
@Test void moreThan2000ArchivesAreProcessedInOrderWithoutSkipping() {
|
||||
List<DamengArchiveWindow.File> catalog=files(3000);NativeLogSource.Split state=new NativeLogSource.Split();
|
||||
long previous=0;
|
||||
while(previous<3000){
|
||||
List<DamengArchiveWindow.File> batch=DamengArchiveWindow.select(catalog,state);
|
||||
long end=batch.get(batch.size()-1).sequence;
|
||||
assertTrue(end>previous);assertTrue(end-previous<=64);
|
||||
assertEquals(previous==0?1:previous,batch.get(0).sequence);
|
||||
List<DamengArchiveWindow.File> retained=DamengArchiveWindow.retain(batch,null);
|
||||
state.anchor=retained.get(0).name;state.archives=DamengArchiveWindow.names(retained);state.archiveSequence=end;
|
||||
previous=end;
|
||||
}
|
||||
}
|
||||
@Test void longTransactionPinsPrefixBeyond2000Files() {
|
||||
List<DamengArchiveWindow.File> catalog=files(3000);NativeLogSource.Split state=new NativeLogSource.Split();state.anchor="f1";state.archiveSequence=2500L;
|
||||
List<DamengArchiveWindow.File> batch=DamengArchiveWindow.select(catalog,state);
|
||||
assertEquals(2564,batch.size());
|
||||
assertEquals("f1",DamengArchiveWindow.retain(batch,110L).get(0).name);
|
||||
assertEquals("f2564",DamengArchiveWindow.retain(batch,null).get(0).name);
|
||||
}
|
||||
@Test void checkpointsPinRequiredFilesButAllowRetiredFilesToDisappear() {
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.anchor="f100";state.archiveSequence=100L;state.archives=Arrays.asList("f100");
|
||||
List<DamengArchiveWindow.File> catalog=files(200);catalog.subList(0,99).clear();
|
||||
assertEquals("f100",DamengArchiveWindow.select(catalog,state).get(0).name);
|
||||
catalog.remove(0);assertThrows(IllegalArgumentException.class,()->DamengArchiveWindow.select(catalog,state));
|
||||
}
|
||||
@Test void refusesMiddleGapDuplicateAndMissingPinnedFile() {
|
||||
List<DamengArchiveWindow.File> catalog=files(10);catalog.remove(3);
|
||||
assertThrows(IllegalArgumentException.class,()->DamengArchiveWindow.select(catalog,new NativeLogSource.Split()));
|
||||
List<DamengArchiveWindow.File> duplicate=files(10);duplicate.add(duplicate.get(1));
|
||||
assertThrows(IllegalArgumentException.class,()->DamengArchiveWindow.select(duplicate,new NativeLogSource.Split()));
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.archives=Arrays.asList("lost");
|
||||
assertThrows(IllegalArgumentException.class,()->DamengArchiveWindow.select(files(10),state));
|
||||
}
|
||||
@Test void tracksInterleavedCommitRollbackAndXaWithoutDroppingOpenTransaction() {
|
||||
DamengArchiveWindow.Transactions tx=new DamengArchiveWindow.Transactions(100,100);
|
||||
tx.accept("a","START",110,null,null,false);tx.accept("b","START",120,null,null,false);
|
||||
tx.accept("b","COMMIT",130,120L,130L,false);
|
||||
assertEquals(Long.valueOf(110),tx.earliestOpen());
|
||||
tx.accept("a","ROLLBACK",140,110L,null,false);assertNull(tx.earliestOpen());
|
||||
tx.accept("c","START",150,null,null,false);tx.accept("c","PRE_COMMIT",160,150L,null,false);
|
||||
assertEquals(Long.valueOf(150),tx.earliestOpen());
|
||||
tx.accept("c","XA_COMMIT",170,150L,170L,false);assertNull(tx.earliestOpen());
|
||||
}
|
||||
@Test void missingTransactionStartAndUnknownCommitFailClosed() {
|
||||
DamengArchiveWindow.Transactions tx=new DamengArchiveWindow.Transactions(100,100);
|
||||
assertThrows(IllegalArgumentException.class,()->tx.accept("a","UPDATE",150,90L,160L,true));
|
||||
DamengArchiveWindow.Transactions unresolved=new DamengArchiveWindow.Transactions(100,100);
|
||||
unresolved.accept("b","UPDATE",150,null,null,true);
|
||||
assertThrows(IllegalArgumentException.class,unresolved::earliestOpen);
|
||||
DamengArchiveWindow.Transactions missingCommit=new DamengArchiveWindow.Transactions(100,100);
|
||||
missingCommit.accept("c","START",110,null,null,false);
|
||||
missingCommit.accept("c","UPDATE",120,110L,null,true);
|
||||
assertThrows(IllegalArgumentException.class,()->missingCommit.accept("c","COMMIT",130,110L,130L,false));
|
||||
}
|
||||
@Test void checkpointRoundTripAndCopyPreserveIndependentWindow()throws Exception {
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.cursor="150";state.archiveSequence=7L;state.anchor="f3";state.archives.add("f3");
|
||||
ByteArrayOutputStream bytes=new ByteArrayOutputStream();new ObjectOutputStream(bytes).writeObject(state);
|
||||
NativeLogSource.Split restored=(NativeLogSource.Split)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject();
|
||||
assertEquals(state.archiveSequence,restored.archiveSequence);assertEquals(state.cursor,restored.cursor);
|
||||
NativeLogSource.Split copy=restored.copy();copy.archives.clear();assertEquals(1,restored.archives.size());
|
||||
}
|
||||
@Test void legacyCheckpointStartsFromItsAnchorAndDoesNotJumpToLatest() {
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.anchor="f20";state.cursor="290000";
|
||||
assertEquals("f20",DamengArchiveWindow.select(files(3000),state).get(0).name);
|
||||
assertEquals("f83",DamengArchiveWindow.select(files(3000),state).get(63).name);
|
||||
}
|
||||
@Test void transactionCrossingWindowStaysPinnedUntilCommitIsCovered() {
|
||||
DamengArchiveWindow.Transactions first=new DamengArchiveWindow.Transactions(100,100,199);
|
||||
first.accept("a","START",110,null,null,false);
|
||||
first.accept("a","UPDATE",120,110L,250L,true);
|
||||
assertEquals(Long.valueOf(110),first.earliestOpen());
|
||||
DamengArchiveWindow.Transactions second=new DamengArchiveWindow.Transactions(100,199,299);
|
||||
second.accept("a","START",110,null,null,false);
|
||||
second.accept("a","UPDATE",120,110L,250L,true);
|
||||
assertNull(second.earliestOpen());
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.apache.seatunnel.api.table.factory.*;
|
||||
import java.io.*;
|
||||
import java.sql.Types;
|
||||
import java.sql.*;
|
||||
import org.apache.seatunnel.api.table.catalog.*;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.*;
|
||||
import com.kingbase8.replication.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class NativeLogContractTest {
|
||||
@Test void damengFilesUseNamedAddOptionsRatherThanRemoveOption(){
|
||||
assertEquals("CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR.\"NEW\")",NativeLogReader.damengAddLogSql(true));
|
||||
assertEquals("CALL DBMS_LOGMNR.ADD_LOGFILE(?, DBMS_LOGMNR.ADDFILE)",NativeLogReader.damengAddLogSql(false));
|
||||
}
|
||||
@Test void damengCleanupIsIdempotentButDoesNotSwallowOtherErrors()throws Exception {
|
||||
int[] code={-2846};
|
||||
CallableStatement statement=(CallableStatement)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{CallableStatement.class},(proxy,m,args)->{
|
||||
if(m.getName().equals("execute"))throw new SQLException("private details","22000",code[0]);
|
||||
return null;
|
||||
});
|
||||
Connection connection=(Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},(proxy,m,args)->statement);
|
||||
assertDoesNotThrow(()->NativeLogReader.endDamengSession(connection));
|
||||
code[0]=-2000;
|
||||
assertEquals(-2000,assertThrows(SQLException.class,()->NativeLogReader.endDamengSession(connection)).getErrorCode());
|
||||
}
|
||||
@Test void snapshotPagesKeepLogWatermarkAndResumeCompositeKey()throws Exception {
|
||||
NativeLogSource source=new DamengSource();source.kind="DAMENG";source.schema="APP";source.table="T";
|
||||
source.names=Arrays.asList("TENANT","ID");source.types=Arrays.asList(Types.INTEGER,Types.INTEGER);source.primaryKeys=source.names;
|
||||
source.catalog=CatalogTable.of(TableIdentifier.of("test","db","APP","T"),TableSchema.builder()
|
||||
.column(PhysicalColumn.of("TENANT",NativeLogSource.dataType(Types.INTEGER,0,0),(Long)null,false,null,null))
|
||||
.column(PhysicalColumn.of("ID",NativeLogSource.dataType(Types.INTEGER,0,0),(Long)null,false,null,null)).build(),Collections.emptyMap(),Collections.emptyList(),"");
|
||||
NativeLogReader reader=new NativeLogReader(source);
|
||||
List<String> queries=new ArrayList<>();List<Object> params=new ArrayList<>();int[] page={0},row={0};
|
||||
ResultSet rs=(ResultSet)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{ResultSet.class},(proxy,m,args)->{
|
||||
if(m.getName().equals("next"))return page[0]==1&&++row[0]<=500;
|
||||
if(m.getName().equals("getString"))return "TENANT".equals(args[0])?"7":Integer.toString(row[0]);
|
||||
if(m.getName().equals("getObject"))return "TENANT".equals(args[0])?7:row[0];
|
||||
return null;
|
||||
});
|
||||
PreparedStatement ps=(PreparedStatement)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{PreparedStatement.class},(proxy,m,args)->{
|
||||
if(m.getName().equals("executeQuery"))return rs;
|
||||
if(m.getName().equals("setObject"))params.add(args[1]);return null;
|
||||
});
|
||||
Connection db=(Connection)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{Connection.class},(proxy,m,args)->{
|
||||
if(m.getName().equals("prepareStatement")){queries.add((String)args[0]);page[0]++;row[0]=0;return ps;}return null;
|
||||
});
|
||||
java.lang.reflect.Field field=NativeLogReader.class.getDeclaredField("db");field.setAccessible(true);field.set(reader,db);
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.cursor="12345";state.snapshotting=true;
|
||||
assertEquals(500,reader.snapshot(state).size());assertEquals("12345",state.cursor);assertTrue(state.snapshotting);
|
||||
NativeLogSource.Split restored=state.copy();state.snapshotKey[1]=-1;
|
||||
assertArrayEquals(new Object[]{7,500},restored.snapshotKey);
|
||||
assertEquals(0,reader.snapshot(restored).size());assertFalse(restored.snapshotting);assertEquals("12345",restored.cursor);
|
||||
assertEquals(Arrays.asList(7,7,500),params);
|
||||
assertTrue(queries.get(1).contains("(\"TENANT\">?) OR (\"TENANT\"=? AND \"ID\">?)"));
|
||||
assertTrue(queries.get(1).endsWith("ORDER BY \"TENANT\",\"ID\" FETCH FIRST 500 ROWS ONLY"));
|
||||
}
|
||||
@Test void insertNullQuotesAndUnicode(){
|
||||
KingbaseChangeDecoder.Change c=new KingbaseChangeDecoder().decode("table public.orders: INSERT: id[integer]:1 title[text]:'采购 ''订单'' : new-tuple: 中文' note[text]:null");
|
||||
assertEquals("采购 '订单' : new-tuple: 中文",c.after.get("title"));
|
||||
assertTrue(c.after.containsKey("note"));assertNull(c.after.get("note"));
|
||||
}
|
||||
@Test void updateCarriesOldAndNewPrimaryKey(){
|
||||
KingbaseChangeDecoder.Change c=new KingbaseChangeDecoder().decode("table \"APP\".\"ORDERS\": UPDATE: old-key: \"ID\"[integer]:1 \"NAME\"[text]:'旧' new-tuple: \"ID\"[integer]:2 \"NAME\"[text]:'新'");
|
||||
assertEquals("1",c.before.get("ID"));assertEquals("2",c.after.get("ID"));assertEquals("APP",c.schema);
|
||||
}
|
||||
@Test void deleteIncludesPreviousValues(){
|
||||
KingbaseChangeDecoder.Change c=new KingbaseChangeDecoder().decode("table public.orders: DELETE: id[integer]:1 name[text]:'删除'");
|
||||
assertEquals("删除",c.before.get("name"));assertTrue(c.after.isEmpty());
|
||||
}
|
||||
@Test void rejectIncompleteOrUnsupportedRows(){
|
||||
KingbaseChangeDecoder d=new KingbaseChangeDecoder();
|
||||
for(String s:new String[]{"table public.t: TRUNCATE: restart_seqs", "table public.t: UPDATE: id[int]:1", "table public.t: INSERT: name[text]:'unfinished", "table public.t: INSERT: name[text]:unchanged-toast-datum", "table public.t: INSERT: id[int]:1 id[int]:2"})
|
||||
assertThrows(IllegalArgumentException.class,()->d.decode(s));
|
||||
}
|
||||
@Test void positionAdvancesOnlyAtMatchingCommit(){
|
||||
CommittedBatch b=new CommittedBatch(10);
|
||||
assertNull(b.accept("0/10","BEGIN 42"));assertNull(b.accept("0/11","table public.t: INSERT: id[int]:1"));
|
||||
assertThrows(IllegalArgumentException.class,b::requireComplete);
|
||||
CommittedBatch.Transaction tx=b.accept("0/12","COMMIT 42");assertEquals("0/12",tx.lsn);assertEquals(1,tx.changes.size());b.requireComplete();
|
||||
}
|
||||
@Test void rejectsMismatchedCommitAndOversizedTransaction(){
|
||||
CommittedBatch b=new CommittedBatch(1);b.accept("0/1","BEGIN 1");b.accept("0/2","table public.t: INSERT: id[int]:1");
|
||||
assertThrows(IllegalArgumentException.class,()->b.accept("0/3","COMMIT 2"));
|
||||
assertThrows(IllegalArgumentException.class,()->b.accept("0/3","table public.t: INSERT: id[int]:2"));
|
||||
}
|
||||
@Test void unsignedLsnAcrossHighBitAndCarry(){
|
||||
assertTrue(LogPosition.lsn("80000000/0").compareTo(LogPosition.lsn("7FFFFFFF/FFFFFFFF"))>0);
|
||||
assertTrue(LogPosition.lsn("1/0").compareTo(LogPosition.lsn("0/FFFFFFFF"))>0);
|
||||
assertThrows(IllegalArgumentException.class,()->LogPosition.lsn("0/xyz"));
|
||||
}
|
||||
@Test void checkpointStateIsIndependentAndSerializable()throws Exception{
|
||||
NativeLogSource.Split s=new NativeLogSource.Split();s.cursor="0/FF";s.anchor="0/1";s.identity="db:slot";
|
||||
s.archives.add("archive1");s.schemaSignature="id:4";
|
||||
NativeLogSource.Split copy=s.copy();s.cursor="1/0";s.archives.add("archive2");
|
||||
ByteArrayOutputStream bytes=new ByteArrayOutputStream();new ObjectOutputStream(bytes).writeObject(copy);
|
||||
NativeLogSource.Split restored=(NativeLogSource.Split)new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray())).readObject();
|
||||
assertEquals("0/FF",restored.cursor);assertEquals("db:slot",restored.identity);
|
||||
assertEquals(Collections.singletonList("archive1"),restored.archives);assertEquals("id:4",restored.schemaSignature);
|
||||
}
|
||||
@Test void cannotCheckpointBeforeLogPositionIsEstablished(){
|
||||
NativeLogReader reader=new NativeLogReader(new DamengSource());
|
||||
reader.addSplits(Collections.singletonList(new NativeLogSource.Split()));
|
||||
assertThrows(IllegalStateException.class,()->reader.snapshotState(1));
|
||||
}
|
||||
@Test void rejectTypesThatCannotBeDecodedLosslessly(){
|
||||
assertThrows(IllegalArgumentException.class,()->NativeLogSource.dataType(Types.BLOB,0,0));
|
||||
assertThrows(IllegalArgumentException.class,()->NativeLogSource.dataType(Types.NUMERIC,40,0));
|
||||
assertThrows(IllegalArgumentException.class,()->NativeLogSource.convert("yes",Types.BOOLEAN));
|
||||
}
|
||||
@Test void bothFactoriesDiscoverWithoutConnecting(){
|
||||
ClassLoader loader=getClass().getClassLoader();
|
||||
assertEquals(DamengSource.class,FactoryUtil.discoverFactory(loader,TableSourceFactory.class,"Dameng-Native-CDC").getSourceClass());
|
||||
assertEquals(KingbaseSource.class,FactoryUtil.discoverFactory(loader,TableSourceFactory.class,"Kingbase-Native-CDC").getSourceClass());
|
||||
}
|
||||
@Test void walAcknowledgementOnlyAfterSuccessfulCheckpoint()throws Exception{
|
||||
NativeLogReader reader=new NativeLogReader(new KingbaseSource());
|
||||
NativeLogSource.Split state=new NativeLogSource.Split();state.cursor="0/20";state.anchor="0/10";state.identity="test";
|
||||
reader.addSplits(Collections.singletonList(state));
|
||||
List<String> acknowledged=new ArrayList<>();
|
||||
KBReplicationStream stream=(KBReplicationStream)Proxy.newProxyInstance(getClass().getClassLoader(),new Class[]{KBReplicationStream.class},(proxy,method,args)->{
|
||||
if(method.getName().equals("setFlushedLSN"))acknowledged.add(((LogSequenceNumber)args[0]).asString());
|
||||
return null;
|
||||
});
|
||||
java.lang.reflect.Field field=NativeLogReader.class.getDeclaredField("stream");field.setAccessible(true);field.set(reader,stream);
|
||||
reader.snapshotState(1);assertTrue(acknowledged.isEmpty());
|
||||
reader.notifyCheckpointAborted(1);reader.notifyCheckpointComplete(1);assertTrue(acknowledged.isEmpty());
|
||||
reader.snapshotState(2);reader.notifyCheckpointComplete(2);assertEquals(Collections.singletonList("0/20"),acknowledged);
|
||||
reader.notifyCheckpointComplete(1);assertEquals(1,acknowledged.size());
|
||||
}
|
||||
@Test void pendingTransactionIsNotPublishedAtPollBoundary(){
|
||||
CommittedBatch frames=new CommittedBatch(10);
|
||||
frames.accept("0/10","BEGIN 9");frames.accept("0/11","table public.t: INSERT: id[int]:7");
|
||||
// The next poll resumes the same transaction; the checkpoint still points to the previous commit.
|
||||
CommittedBatch.Transaction tx=frames.accept("0/12","COMMIT 9");
|
||||
assertEquals(1,tx.changes.size());assertEquals("0/12",tx.lsn);
|
||||
}
|
||||
}
|
||||
+549
@@ -0,0 +1,549 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile;
|
||||
import cn.aixunkeji.datagov.integration.m2.M2SecretReader;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.URLEncoder;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.security.Signature;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
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;
|
||||
|
||||
/** Bounded HTTPS pull and Doris write; source credentials remain inside Integration. */
|
||||
final class ApiPollExecutor {
|
||||
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]{0,127}");
|
||||
private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}");
|
||||
private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}");
|
||||
private static final int MAX_BODY = 2 * 1024 * 1024;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private final M2SecretReader secrets;
|
||||
private final HttpClient http;
|
||||
private final EndpointVerifier endpointVerifier;
|
||||
private final JdbcConnector jdbcConnector;
|
||||
private final Map<String, Token> tokenCache = new ConcurrentHashMap<>();
|
||||
|
||||
interface EndpointVerifier { M3HttpEndpointPolicy.Validation validate(String endpoint); }
|
||||
interface JdbcConnector { Connection open(String jdbc, String user, String password) throws SQLException; }
|
||||
private record Token(String value, Instant expiresAt) { }
|
||||
private record Page(int number, String cursor, URI link, String watermark, int size) { }
|
||||
private static final class PollFailure extends RuntimeException {
|
||||
final String code;
|
||||
PollFailure(String code) { super(code); this.code = code; }
|
||||
}
|
||||
|
||||
ApiPollExecutor(M2SecretReader secrets) {
|
||||
this(secrets, M3HttpEndpointPolicy::validate, DriverManager::getConnection,
|
||||
HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5))
|
||||
.followRedirects(HttpClient.Redirect.NEVER).build());
|
||||
}
|
||||
|
||||
ApiPollExecutor(M2SecretReader secrets, EndpointVerifier endpointVerifier,
|
||||
JdbcConnector jdbcConnector, HttpClient http) {
|
||||
this.secrets = secrets;
|
||||
this.endpointVerifier = endpointVerifier;
|
||||
this.jdbcConnector = jdbcConnector;
|
||||
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();
|
||||
var target = request.targetProfile();
|
||||
ApiPollProfile profile = request.profile() == null ? defaults() : request.profile();
|
||||
if (request.actorId() <= 0 || request.orgScopeId() <= 0 || request.intakeId() <= 0 ||
|
||||
source == null || target == null || !"API_SAAS".equals(source.sourceType()) ||
|
||||
!"GENERIC_HTTPS_JSON".equals(source.apiConnector()) || !"BEARER".equals(source.authMode()) ||
|
||||
!Set.of("PAGE_SIZE", "OFFSET_LIMIT", "CURSOR", "LINK_HEADER").contains(source.paginationMode()) ||
|
||||
!"DORIS".equals(target.resourceType()) ||
|
||||
source.targetStorageResourceId() == null || source.targetStorageResourceId() != target.resourceId() ||
|
||||
source.targetStorageSpaceId() == null || target.spaceId() == null ||
|
||||
!source.targetStorageSpaceId().equals(target.spaceId()) ||
|
||||
source.maxPages() == null || source.maxPages() < 1 || source.maxPages() > 100 ||
|
||||
source.rateLimitPerMinute() == null || source.rateLimitPerMinute() < 1 ||
|
||||
source.paginationField() == null || !valid(source.paginationField()) ||
|
||||
source.schema() == null || source.schema().isEmpty() || source.schema().size() > 200 ||
|
||||
source.secretRef() == null || target.secretRef() == null) return fail("API_POLL_CONTRACT_INVALID");
|
||||
if ("CURSOR".equals(source.paginationMode()) && !path(source.cursorResponseField()))
|
||||
return fail("API_POLL_CURSOR_INVALID");
|
||||
validateProfile(profile);
|
||||
String[] object = source.targetObject() == null ? new String[0] : source.targetObject().split("\\.");
|
||||
if (object.length != 2 || !valid(object[0]) || !valid(object[1]) ||
|
||||
!object[0].equals(target.externalSpaceId())) return fail("API_POLL_TARGET_INVALID");
|
||||
for (var field : source.schema()) if (field == null || !valid(field.sourceField()) ||
|
||||
!valid(field.targetField())) return fail("API_POLL_SCHEMA_INVALID");
|
||||
if (source.incrementalMarker() != null && !valid(source.incrementalMarker()))
|
||||
return fail("API_POLL_MARKER_INVALID");
|
||||
if (profile.queryParameters().containsKey(source.paginationField()) ||
|
||||
profile.queryParameters().containsKey("size") || profile.queryParameters().containsKey("limit"))
|
||||
return fail("API_POLL_QUERY_CONFLICT");
|
||||
if (request.watermark() != null) Instant.parse(request.watermark());
|
||||
URI endpoint = checked(source.endpoint());
|
||||
if (dynamic(profile)) checked(profile.tokenEndpoint());
|
||||
String authSecret = secrets.resolve(source.secretRef());
|
||||
String signingSecret = "NONE".equals(profile.signatureKind()) ? null :
|
||||
secrets.resolve(profile.signingSecretRef() == null ? source.secretRef() : profile.signingSecretRef());
|
||||
String password = secrets.resolve(target.secretRef());
|
||||
String jdbc = "jdbc:mysql://" + target.endpointHost() + ":" + target.endpointPort() + "/" + object[0] +
|
||||
"?useSSL=" + target.tlsEnabled() + "&serverTimezone=UTC";
|
||||
try (Connection connection = jdbcConnector.open(jdbc, target.serviceAccount(), password)) {
|
||||
connection.setAutoCommit(false);
|
||||
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 + ")";
|
||||
int written = 0;
|
||||
Instant watermark = request.watermark() == null ? null : Instant.parse(request.watermark());
|
||||
String queryWatermark = watermark == null ? null : watermark.minusSeconds(profile.lookbackSeconds()).toString();
|
||||
String cursor = null;
|
||||
URI link = null;
|
||||
for (int page = 1; page <= source.maxPages(); page++) {
|
||||
Page position = new Page(page, cursor, link, queryWatermark, profile.pageSize());
|
||||
URI uri = link != null ? checked(link.toASCIIString()) : pageUri(endpoint, source, profile, position);
|
||||
checked(uri.toASCIIString());
|
||||
String body = body(profile, position);
|
||||
HttpResponse<InputStream> response = sendData(request, profile, uri, body,
|
||||
authSecret, signingSecret);
|
||||
if (response.statusCode() != 200) {
|
||||
response.body().close(); return fail("API_POLL_HTTP_" + response.statusCode());
|
||||
}
|
||||
byte[] raw = read(response.body(), MAX_BODY);
|
||||
JsonNode root = JsonUtils.getObjectMapper().readTree(new String(raw, StandardCharsets.UTF_8));
|
||||
if (profile.successPath() != null) {
|
||||
JsonNode success = at(root, profile.successPath());
|
||||
if (success == null || !profile.successValue().equals(success.asText()))
|
||||
return fail("API_POLL_BUSINESS_ERROR");
|
||||
}
|
||||
JsonNode rows = rows(root, source.responseContentField());
|
||||
if (rows == null || !rows.isArray()) return fail("API_POLL_RESPONSE_SHAPE");
|
||||
if (!rows.isEmpty()) {
|
||||
try (PreparedStatement insert = connection.prepareStatement(sql)) {
|
||||
for (JsonNode row : rows) {
|
||||
if (!row.isObject()) return fail("API_POLL_ROW_SHAPE");
|
||||
for (int index = 0; index < source.schema().size(); index++) {
|
||||
var field = source.schema().get(index);
|
||||
JsonNode value = row.get(field.sourceField());
|
||||
if ((value == null || value.isNull()) && !field.nullable()) return fail("API_POLL_REQUIRED_FIELD");
|
||||
if (value == null || value.isNull()) insert.setObject(index + 1, null);
|
||||
else if (value.isObject() || value.isArray()) return fail("API_POLL_COMPLEX_FIELD");
|
||||
else insert.setString(index + 1, value.asText());
|
||||
}
|
||||
if (source.incrementalMarker() != null) {
|
||||
JsonNode marker = row.get(source.incrementalMarker());
|
||||
if (marker == null || !marker.isTextual()) return fail("API_POLL_MARKER_MISSING");
|
||||
Instant candidate = Instant.parse(marker.asText());
|
||||
if (watermark == null || candidate.isAfter(watermark)) watermark = candidate;
|
||||
}
|
||||
insert.addBatch();
|
||||
}
|
||||
insert.executeBatch();
|
||||
}
|
||||
connection.commit();
|
||||
written += rows.size();
|
||||
}
|
||||
boolean more = switch (source.paginationMode()) {
|
||||
case "CURSOR" -> {
|
||||
JsonNode next = at(root, source.cursorResponseField());
|
||||
cursor = next == null || next.isNull() ? null : next.asText();
|
||||
yield cursor != null && !cursor.isBlank();
|
||||
}
|
||||
case "LINK_HEADER" -> {
|
||||
link = nextLink(response.headers().firstValue("Link").orElse(null), endpoint);
|
||||
yield link != null;
|
||||
}
|
||||
default -> rows.size() >= profile.pageSize();
|
||||
};
|
||||
if (!more || rows.isEmpty()) break;
|
||||
if (page == source.maxPages()) return fail("API_POLL_PAGE_LIMIT");
|
||||
Thread.sleep(Math.max(1, 60_000L / source.rateLimitPerMinute()));
|
||||
}
|
||||
return new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", written,
|
||||
watermark == null ? request.watermark() : watermark.toString(), null);
|
||||
}
|
||||
} catch (PollFailure failure) {
|
||||
return fail(failure.code);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt(); return fail("API_POLL_INTERRUPTED");
|
||||
} catch (IllegalArgumentException exception) {
|
||||
return fail("API_POLL_TARGET_NOT_UNIQUE".equals(exception.getMessage()) ?
|
||||
"API_POLL_TARGET_NOT_UNIQUE" : "API_POLL_CONTRACT_INVALID");
|
||||
} catch (Exception exception) {
|
||||
return fail("API_POLL_EXECUTION_UNKNOWN");
|
||||
}
|
||||
}
|
||||
|
||||
private HttpResponse<InputStream> sendData(DataCollectionIntegrationService.ApiPollRequest request,
|
||||
ApiPollProfile profile, URI uri, String body,
|
||||
String authSecret, String signingSecret) throws Exception {
|
||||
String cacheKey = request.orgScopeId() + ":" + request.intakeId() + ":" + request.snapshot().secretRef() +
|
||||
":" + profile.authKind() + ":" + profile.tokenEndpoint() + ":" + profile.clientId() +
|
||||
":" + 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;
|
||||
String token = dynamic(profile) ? token(cacheKey, profile, authSecret, forceRefresh) : authSecret;
|
||||
refresh = false;
|
||||
URI signedUri = uri;
|
||||
String signature = null, timestamp = null, nonce = null;
|
||||
if (!"NONE".equals(profile.signatureKind())) {
|
||||
timestamp = Long.toString(Instant.now().getEpochSecond());
|
||||
byte[] random = new byte[16]; RANDOM.nextBytes(random);
|
||||
nonce = HexFormat.of().formatHex(random);
|
||||
URI unsignedUri = "QUERY".equals(profile.signaturePlacement())
|
||||
? append(append(uri, "timestamp", timestamp), "nonce", nonce) : uri;
|
||||
signature = sign(profile, signingSecret, unsignedUri, body, timestamp, nonce);
|
||||
if ("QUERY".equals(profile.signaturePlacement()))
|
||||
signedUri = append(unsignedUri, profile.signatureHeader(), signature);
|
||||
}
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(signedUri).timeout(Duration.ofSeconds(30))
|
||||
.header("Accept", "application/json");
|
||||
if ("API_KEY_HEADER".equals(profile.authKind())) builder.header("X-API-Key", token);
|
||||
else if (!"SIGN_ONLY".equals(profile.authKind())) builder.header("Authorization", "Bearer " + token);
|
||||
if (signature != null) {
|
||||
if ("HEADER".equals(profile.signaturePlacement())) {
|
||||
builder.header("X-Timestamp", timestamp).header("X-Nonce", nonce);
|
||||
builder.header(profile.signatureHeader(), signature);
|
||||
}
|
||||
}
|
||||
boolean hasContentType = false;
|
||||
for (var header : profile.headers().entrySet()) {
|
||||
builder.header(header.getKey(), header.getValue());
|
||||
if ("content-type".equalsIgnoreCase(header.getKey())) hasContentType = true;
|
||||
}
|
||||
if ("POST".equals(profile.requestMethod())) {
|
||||
if (!hasContentType) builder.header("Content-Type", "application/json");
|
||||
builder.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||
} else builder.GET();
|
||||
HttpResponse<InputStream> response = http.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream());
|
||||
int status = response.statusCode();
|
||||
if (status == 401 && dynamic(profile) && !forceRefresh) {
|
||||
response.body().close(); tokenCache.remove(cacheKey); refresh = true; continue;
|
||||
}
|
||||
if ((status == 429 || status >= 500 && status <= 599) && attempt < 2) {
|
||||
response.body().close();
|
||||
long delay = response.headers().firstValue("Retry-After").filter(v -> v.matches("[0-9]{1,2}"))
|
||||
.map(Long::parseLong).orElse(1L << attempt);
|
||||
Thread.sleep(Math.min(30_000L, delay * 1000L + RANDOM.nextInt(250)));
|
||||
continue;
|
||||
}
|
||||
return response;
|
||||
}
|
||||
throw new PollFailure("API_POLL_RETRY_EXHAUSTED");
|
||||
}
|
||||
|
||||
private String token(String key, ApiPollProfile profile, String authSecret, boolean refresh) throws Exception {
|
||||
Token cached = tokenCache.get(key);
|
||||
if (!refresh && cached != null && cached.expiresAt().isAfter(Instant.now().plusSeconds(30))) return cached.value();
|
||||
URI uri = checked(profile.tokenEndpoint());
|
||||
String payload;
|
||||
String contentType;
|
||||
String idField = profile.tokenClientField();
|
||||
String secretField = profile.tokenSecretField();
|
||||
boolean basic = "BASIC".equals(profile.tokenCredentialStyle());
|
||||
if ("JSON".equals(profile.tokenFormat())) {
|
||||
payload = (basic ? "{" : "{\"" + idField + "\":" +
|
||||
JsonUtils.getObjectMapper().writeValueAsString(profile.clientId()) + ",\"" + secretField + "\":" +
|
||||
JsonUtils.getObjectMapper().writeValueAsString(authSecret) +
|
||||
("CLIENT_CREDENTIALS".equals(profile.authKind()) ? "," : "")) +
|
||||
("CLIENT_CREDENTIALS".equals(profile.authKind()) ? "\"grant_type\":\"client_credentials\"" : "") + "}";
|
||||
contentType = "application/json";
|
||||
} else {
|
||||
payload = (basic ? "" : encode(idField) + "=" + encode(profile.clientId()) + "&" +
|
||||
encode(secretField) + "=" + encode(authSecret)) +
|
||||
("CLIENT_CREDENTIALS".equals(profile.authKind()) ? (basic ? "" : "&") + "grant_type=client_credentials" : "");
|
||||
contentType = "application/x-www-form-urlencoded";
|
||||
}
|
||||
HttpRequest.Builder authBuilder = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(15))
|
||||
.header("Content-Type", contentType).header("Accept", "application/json");
|
||||
if (basic) authBuilder.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(
|
||||
(profile.clientId() + ":" + authSecret).getBytes(StandardCharsets.UTF_8)));
|
||||
HttpRequest auth = authBuilder.POST(HttpRequest.BodyPublishers.ofString(payload)).build();
|
||||
HttpResponse<InputStream> response = http.send(auth, HttpResponse.BodyHandlers.ofInputStream());
|
||||
if (response.statusCode() != 200) {
|
||||
response.body().close(); throw new PollFailure("API_POLL_TOKEN_HTTP_" + response.statusCode());
|
||||
}
|
||||
JsonNode root = JsonUtils.getObjectMapper().readTree(new String(read(response.body(), 65536), StandardCharsets.UTF_8));
|
||||
JsonNode value = at(root, profile.tokenPath());
|
||||
if (value == null || !value.isTextual() || value.asText().isBlank() || value.asText().length() > 8192)
|
||||
throw new PollFailure("API_POLL_TOKEN_RESPONSE_INVALID");
|
||||
JsonNode expiry = profile.expiresPath() == null ? null : at(root, profile.expiresPath());
|
||||
long seconds = expiry == null ? 300 : Long.parseLong(expiry.asText());
|
||||
if (seconds < 1 || seconds > 86400) throw new PollFailure("API_POLL_TOKEN_EXPIRY_INVALID");
|
||||
tokenCache.put(key, new Token(value.asText(), Instant.now().plusSeconds(seconds)));
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
static String sign(ApiPollProfile profile, String secret, URI uri, String body,
|
||||
String timestamp, String nonce) throws Exception {
|
||||
String pathQuery = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
|
||||
String input = profile.signatureTemplate().replace("${method}", profile.requestMethod())
|
||||
.replace("${path}", uri.getRawPath()).replace("${query}", uri.getRawQuery() == null ? "" : uri.getRawQuery())
|
||||
.replace("${pathQuery}", pathQuery).replace("${bodySha256}", sha256(body))
|
||||
.replace("${body}", body).replace("${timestamp}", timestamp).replace("${nonce}", nonce);
|
||||
if (input.contains("${")) throw new PollFailure("API_POLL_SIGNATURE_TEMPLATE_INVALID");
|
||||
byte[] signed;
|
||||
if ("HMAC_SHA256".equals(profile.signatureKind())) {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
|
||||
signed = mac.doFinal(input.getBytes(StandardCharsets.UTF_8));
|
||||
} else {
|
||||
String pemBegin = "-----BEGIN " + "PRIVATE KEY-----";
|
||||
String pemEnd = "-----END " + "PRIVATE KEY-----";
|
||||
String pem = secret.replace(pemBegin, "").replace(pemEnd, "").replaceAll("\\s", "");
|
||||
Signature signer = Signature.getInstance("SHA256withRSA");
|
||||
signer.initSign(KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(Base64.getDecoder().decode(pem))));
|
||||
signer.update(input.getBytes(StandardCharsets.UTF_8));
|
||||
signed = signer.sign();
|
||||
}
|
||||
return "HEX".equals(profile.signatureEncoding()) ? HexFormat.of().formatHex(signed) :
|
||||
Base64.getEncoder().encodeToString(signed);
|
||||
}
|
||||
|
||||
private URI pageUri(URI base, DataCollectionIntegrationService.FileExecutionSnapshot source,
|
||||
ApiPollProfile profile, Page position) {
|
||||
URI uri = base;
|
||||
for (var item : profile.queryParameters().entrySet()) {
|
||||
if (position.watermark() == null && "${watermark}".equals(item.getValue())) continue;
|
||||
uri = append(uri, item.getKey(), expand(item.getValue(), position, "RAW"));
|
||||
}
|
||||
switch (source.paginationMode()) {
|
||||
case "PAGE_SIZE" -> { uri = append(uri, source.paginationField(), Integer.toString(position.number()));
|
||||
uri = append(uri, "size", Integer.toString(profile.pageSize())); }
|
||||
case "OFFSET_LIMIT" -> { uri = append(uri, source.paginationField(),
|
||||
Integer.toString((position.number() - 1) * profile.pageSize()));
|
||||
uri = append(uri, "limit", Integer.toString(profile.pageSize())); }
|
||||
case "CURSOR" -> { if (position.cursor() != null) uri = append(uri, source.paginationField(), position.cursor());
|
||||
uri = append(uri, "size", Integer.toString(profile.pageSize())); }
|
||||
default -> { }
|
||||
}
|
||||
boolean explicitWatermark = profile.queryParameters().values().stream().anyMatch(v -> v.contains("${watermark}")) ||
|
||||
profile.requestBody() != null && profile.requestBody().contains("${watermark}");
|
||||
if (source.incrementalMarker() != null && position.watermark() != null && !explicitWatermark)
|
||||
uri = append(uri, source.incrementalMarker(), position.watermark());
|
||||
return uri;
|
||||
}
|
||||
|
||||
private static String body(ApiPollProfile profile, Page page) {
|
||||
if (profile.requestBody() == null) return "";
|
||||
boolean form = profile.headers().entrySet().stream().anyMatch(e ->
|
||||
"content-type".equalsIgnoreCase(e.getKey()) && e.getValue().startsWith("application/x-www-form-urlencoded"));
|
||||
return expand(profile.requestBody(), page, form ? "FORM" : "JSON");
|
||||
}
|
||||
|
||||
private static String expand(String template, Page page, String mode) {
|
||||
String watermark = page.watermark() == null ? "" : page.watermark();
|
||||
String cursor = page.cursor() == null ? "" : page.cursor();
|
||||
if ("FORM".equals(mode)) { watermark = encode(watermark); cursor = encode(cursor); }
|
||||
else if ("JSON".equals(mode)) { watermark = jsonEscape(watermark); cursor = jsonEscape(cursor); }
|
||||
return template.replace("${page}", Integer.toString(page.number()))
|
||||
.replace("${size}", Integer.toString(page.size()))
|
||||
.replace("${offset}", Integer.toString((page.number() - 1) * page.size()))
|
||||
.replace("${watermark}", watermark).replace("${cursor}", cursor);
|
||||
}
|
||||
|
||||
private static String jsonEscape(String value) {
|
||||
return value.replace("\\", "\\\\").replace("\"", "\\\"")
|
||||
.replace("\n", "\\n").replace("\r", "\\r");
|
||||
}
|
||||
|
||||
private static URI append(URI base, String name, String value) {
|
||||
String raw = base.toASCIIString();
|
||||
String separator = base.getRawQuery() == null ? "?" : "&";
|
||||
return URI.create(raw + separator + encode(name) + "=" + encode(value));
|
||||
}
|
||||
|
||||
private URI checked(String value) {
|
||||
var checked = endpointVerifier.validate(value);
|
||||
if (!checked.accepted() || checked.redirects() != 0 || checked.finalUri() == null ||
|
||||
!checked.finalUri().equals(URI.create(value)))
|
||||
throw new PollFailure(checked.errorCode() == null ? "API_POLL_ENDPOINT_INVALID" : checked.errorCode());
|
||||
return checked.finalUri();
|
||||
}
|
||||
|
||||
private static URI nextLink(String header, URI origin) {
|
||||
if (header == null || header.length() > 2048) return null;
|
||||
for (String part : header.split(",")) {
|
||||
if (!part.contains("rel=\"next\"") && !part.contains("rel=next")) continue;
|
||||
int start = part.indexOf('<'), end = part.indexOf('>');
|
||||
if (start < 0 || end <= start) throw new PollFailure("API_POLL_NEXT_LINK_INVALID");
|
||||
URI next = origin.resolve(part.substring(start + 1, end));
|
||||
if (!origin.getScheme().equalsIgnoreCase(next.getScheme()) ||
|
||||
!origin.getHost().equalsIgnoreCase(next.getHost()) || origin.getPort() != next.getPort())
|
||||
throw new PollFailure("API_POLL_NEXT_LINK_ORIGIN_CHANGED");
|
||||
return next;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static byte[] read(InputStream body, int maximum) throws Exception {
|
||||
try (InputStream stream = body) {
|
||||
byte[] bytes = stream.readNBytes(maximum + 1);
|
||||
if (bytes.length > maximum) throw new PollFailure("API_POLL_RESPONSE_TOO_LARGE");
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonNode rows(JsonNode root, String path) {
|
||||
return path == null || path.isBlank() || "$".equals(path) ? root : at(root, path.replace("[*]", ""));
|
||||
}
|
||||
|
||||
private static JsonNode at(JsonNode root, String path) {
|
||||
if (!path(path)) return null;
|
||||
JsonNode current = root;
|
||||
if ("$".equals(path)) return current;
|
||||
for (String segment : path.substring(2).split("\\.")) {
|
||||
if (current == null) return null;
|
||||
current = current.get(segment);
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
private static void validateProfile(ApiPollProfile p) {
|
||||
if (!Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY").contains(p.authKind()) ||
|
||||
!Set.of("GET", "POST").contains(p.requestMethod()) || p.pageSize() == null ||
|
||||
p.pageSize() < 1 || p.pageSize() > 1000 || p.lookbackSeconds() == null ||
|
||||
p.lookbackSeconds() < 0 || p.lookbackSeconds() > 86400 ||
|
||||
!Set.of("NONE", "HMAC_SHA256", "RSA_SHA256").contains(p.signatureKind()) ||
|
||||
p.headers() == null || p.queryParameters() == null || p.headers().size() > 20 ||
|
||||
p.queryParameters().size() > 20 || (p.requestBody() != null && p.requestBody().length() > 8192))
|
||||
throw new PollFailure("API_POLL_PROFILE_INVALID");
|
||||
if (dynamic(p) && (p.tokenEndpoint() == null || p.clientId() == null ||
|
||||
!Set.of("FORM", "JSON").contains(p.tokenFormat()) || !path(p.tokenPath()) ||
|
||||
!IDENTIFIER.matcher(p.tokenClientField() == null ? "" : p.tokenClientField()).matches() ||
|
||||
!IDENTIFIER.matcher(p.tokenSecretField() == null ? "" : p.tokenSecretField()).matches() ||
|
||||
!Set.of("BODY", "BASIC").contains(p.tokenCredentialStyle())))
|
||||
throw new PollFailure("API_POLL_TOKEN_CONFIG_INVALID");
|
||||
if ("SIGN_ONLY".equals(p.authKind()) && "NONE".equals(p.signatureKind()))
|
||||
throw new PollFailure("API_POLL_SIGNATURE_CONFIG_INVALID");
|
||||
if (!"NONE".equals(p.signatureKind()) && (p.signingSecretRef() == null && !"SIGN_ONLY".equals(p.authKind()) ||
|
||||
p.signatureTemplate() == null || p.signatureTemplate().isBlank() ||
|
||||
!Set.of("HEADER", "QUERY").contains(p.signaturePlacement()) ||
|
||||
!("HEADER".equals(p.signaturePlacement()) ? HEADER : IDENTIFIER)
|
||||
.matcher(p.signatureHeader() == null ? "" : p.signatureHeader()).matches() ||
|
||||
!Set.of("BASE64", "HEX").contains(p.signatureEncoding())))
|
||||
throw new PollFailure("API_POLL_SIGNATURE_CONFIG_INVALID");
|
||||
for (var item : p.headers().entrySet()) if (item.getKey() == null || item.getValue() == null ||
|
||||
!HEADER.matcher(item.getKey()).matches() ||
|
||||
Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key")
|
||||
.contains(item.getKey().toLowerCase()) || item.getValue().contains("\r") ||
|
||||
item.getValue().contains("\n") || item.getValue().length() > 1024)
|
||||
throw new PollFailure("API_POLL_HEADER_INVALID");
|
||||
for (var item : p.queryParameters().entrySet()) if (item.getKey() == null || !valid(item.getKey()) ||
|
||||
Set.of("token", "access_token", "secret", "password", "api_key").contains(item.getKey().toLowerCase()) ||
|
||||
item.getValue() == null || item.getValue().length() > 1024)
|
||||
throw new PollFailure("API_POLL_QUERY_INVALID");
|
||||
}
|
||||
|
||||
private static ApiPollProfile defaults() {
|
||||
return new ApiPollProfile("STATIC_BEARER", null, "FORM", null,
|
||||
"client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"GET", Map.of(), Map.of(), null, 100, 0, null, null, "NONE", null,
|
||||
"HEADER", "X-Sign", "BASE64", null);
|
||||
}
|
||||
|
||||
private static boolean dynamic(ApiPollProfile p) {
|
||||
return "CLIENT_CREDENTIALS".equals(p.authKind()) || "PASSWORD_TOKEN".equals(p.authKind());
|
||||
}
|
||||
|
||||
private static String sha256(String body) throws Exception {
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(body.getBytes(StandardCharsets.UTF_8)));
|
||||
}
|
||||
private static String encode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); }
|
||||
private static boolean valid(String value) { return value != null && IDENTIFIER.matcher(value).matches(); }
|
||||
private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); }
|
||||
private static DataCollectionIntegrationService.ApiPollResult fail(String code) {
|
||||
return new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, code);
|
||||
}
|
||||
}
|
||||
+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).*");
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Operator-managed CDC endpoints. Public task requests cannot supply brokers or credentials. */
|
||||
@Data @Component @ConfigurationProperties(prefix="datagov.realtime-relays")
|
||||
public class CdcRelayProperties {
|
||||
private Map<String,Channel> channels=new LinkedHashMap<>();
|
||||
@Data public static class Channel {
|
||||
private boolean enabled;
|
||||
private String name;
|
||||
private long orgId;
|
||||
private long sourceId;
|
||||
private String schema;
|
||||
private String table;
|
||||
private String bootstrapServers;
|
||||
private String topic;
|
||||
private String format="ogg_json";
|
||||
private String securityProtocol="PLAINTEXT";
|
||||
private String mechanism="SCRAM-SHA-256";
|
||||
private String username;
|
||||
private String secretRef;
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.*;
|
||||
import cn.aixunkeji.datagov.integration.m2.M2SecretReader;
|
||||
import org.springframework.stereotype.Component;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
@Component
|
||||
public class CdcRelayRegistry {
|
||||
private final CdcRelayProperties properties;
|
||||
private final M2SecretReader secrets;
|
||||
public CdcRelayRegistry(CdcRelayProperties properties,M2SecretReader secrets){this.properties=properties;this.secrets=secrets;}
|
||||
public List<RelayOption> options(long org,long source){
|
||||
return properties.getChannels().entrySet().stream().filter(e->e.getValue().isEnabled() &&
|
||||
e.getValue().getOrgId()==org && e.getValue().getSourceId()==source).map(e->new RelayOption(e.getKey(),
|
||||
e.getValue().getName(),e.getValue().getSchema(),e.getValue().getTable(),e.getValue().getFormat())).toList();
|
||||
}
|
||||
CdcRelayProperties.Channel require(Command command){
|
||||
var p=command.spec();var c=properties.getChannels().get(p.cdcChannel());
|
||||
if(c==null || !c.isEnabled() || c.getOrgId()!=command.orgId() || c.getSourceId()!=p.sourceId() ||
|
||||
!Objects.equals(c.getSchema(),p.sourceSchema()) || !Objects.equals(c.getTable(),p.sourceTable()))
|
||||
throw new IllegalArgumentException("日志通道未登记、未启用或与当前组织、数据源、源表不匹配");
|
||||
validate(c);
|
||||
return c;
|
||||
}
|
||||
static void validate(CdcRelayProperties.Channel c){
|
||||
if(c.getBootstrapServers()==null || !c.getBootstrapServers().matches("[A-Za-z0-9._-]+:[0-9]{1,5}(,[A-Za-z0-9._-]+:[0-9]{1,5})*") ||
|
||||
c.getTopic()==null || !c.getTopic().matches("[A-Za-z0-9_-][A-Za-z0-9._-]{0,248}") ||
|
||||
!Set.of("ogg_json","debezium_json").contains(c.getFormat()))
|
||||
throw new IllegalArgumentException("日志通道服务器、主题或消息格式配置无效");
|
||||
if(!Set.of("PLAINTEXT","SASL_PLAINTEXT","SASL_SSL","SSL").contains(c.getSecurityProtocol()))
|
||||
throw new IllegalArgumentException("日志通道安全协议无效");
|
||||
if(c.getSecurityProtocol().startsWith("SASL") && (c.getUsername()==null || c.getUsername().isBlank() || c.getSecretRef()==null ||
|
||||
!Set.of("SCRAM-SHA-256","SCRAM-SHA-512","PLAIN").contains(c.getMechanism())))
|
||||
throw new IllegalArgumentException("日志通道缺少受管认证配置");
|
||||
}
|
||||
String fingerprint(Command c){
|
||||
var p=require(c);
|
||||
return List.of(p.getBootstrapServers(),p.getTopic(),p.getFormat(),p.getSecurityProtocol(),p.getMechanism(),
|
||||
Objects.toString(p.getUsername(),""),Objects.toString(p.getSecretRef(),"")).toString();
|
||||
}
|
||||
ObjectNode job(Command command,MysqlCdcJobFactory.Config common,ResultSetMetaData metadata) throws SQLException {
|
||||
var c=require(command);var root=MysqlCdcJobFactory.create(common);
|
||||
var source=(ObjectNode)root.putArray("source").addObject();
|
||||
source.put("plugin_name","Kafka");source.put("bootstrap.servers",c.getBootstrapServers());
|
||||
source.put("topic",c.getTopic());source.put("consumer.group","aixun_cdc_"+command.orgId()+"_"+command.taskId());
|
||||
source.put("format",c.getFormat());source.put("start_mode","initial".equals(command.spec().startupMode())?"earliest":"latest");
|
||||
source.put("commit_on_checkpoint",true);
|
||||
source.put("debezium-json.ignore-parse-errors",false);source.put("ogg_json.ignore-parse-errors",false);
|
||||
var fields=source.putObject("schema").putObject("fields");
|
||||
for(int i=1;i<=metadata.getColumnCount();i++)fields.put(metadata.getColumnName(i),type(metadata.getColumnType(i),metadata.getPrecision(i),metadata.getScale(i)));
|
||||
var config=source.putObject("kafka.config");config.put("security.protocol",c.getSecurityProtocol());
|
||||
config.put("isolation.level","read_committed");config.put("enable.auto.commit","false");
|
||||
config.put("auto.offset.reset","none");
|
||||
if(c.getSecurityProtocol().startsWith("SASL")){
|
||||
config.put("sasl.mechanism",c.getMechanism());
|
||||
String module="PLAIN".equals(c.getMechanism())?"org.apache.kafka.common.security.plain.PlainLoginModule":"org.apache.kafka.common.security.scram.ScramLoginModule";
|
||||
config.put("sasl.jaas.config",module+" required username=\""+escape(c.getUsername())+"\" password=\""+escape(secrets.resolve(c.getSecretRef()))+"\";");
|
||||
}
|
||||
return root;
|
||||
}
|
||||
static String type(int type,int precision,int scale){
|
||||
return switch(type){
|
||||
case Types.TINYINT -> "TINYINT";case Types.SMALLINT -> "SMALLINT";case Types.INTEGER -> "INT";case Types.BIGINT -> "BIGINT";
|
||||
case Types.FLOAT,Types.REAL -> "FLOAT";case Types.DOUBLE -> "DOUBLE";
|
||||
case Types.NUMERIC,Types.DECIMAL -> {if(precision<1||precision>38||scale<0||scale>precision)throw new IllegalArgumentException("日志通道暂不支持此精度的数值字段");yield "DECIMAL("+precision+","+scale+")";}
|
||||
case Types.BOOLEAN,Types.BIT -> "BOOLEAN";case Types.DATE -> "DATE";case Types.TIME -> "TIME";case Types.TIMESTAMP -> "TIMESTAMP";
|
||||
case Types.CHAR,Types.VARCHAR,Types.LONGVARCHAR,Types.NCHAR,Types.NVARCHAR,Types.LONGNVARCHAR,Types.CLOB,Types.NCLOB -> "STRING";
|
||||
default -> throw new IllegalArgumentException("日志通道存在暂不支持的字段类型,请先转换为标准JSON可表达字段");
|
||||
};
|
||||
}
|
||||
private static String escape(String value){return value.replace("\\","\\\\").replace("\"","\\\"");}
|
||||
}
|
||||
+3
-32
@@ -117,10 +117,6 @@ final class M3CollectionJobFactory {
|
||||
}
|
||||
MysqlTargetType mapped = normalizedType(field, target.resourceType());
|
||||
if (!mapped.supported()) return Capability.unsupported(mapped.errorCode(), mapped.errorSummary());
|
||||
var carrier = textCarrier(field, "field");
|
||||
if (carrier != null && carrier.binary() && (!"NONE".equals(field.transform()) ||
|
||||
field.filterOperator() != null && !Set.of("IS_NULL", "IS_NOT_NULL").contains(field.filterOperator())))
|
||||
return Capability.unsupported("BATCH_BINARY_TRANSFORM_UNSUPPORTED", "二进制大对象支持完整采集和空值过滤;文本转换及内容过滤请使用源视图");
|
||||
if (!sameDeclaration(mapped.targetType(), field.targetType()) || !validBatchTransform(field, mapped)) {
|
||||
return Capability.unsupported("MYSQL_TARGET_TYPE_MISMATCH",
|
||||
"字段“" + field.sourceField() + "”的目标类型与规范化" + target.resourceType() + "映射不一致");
|
||||
@@ -173,31 +169,15 @@ final class M3CollectionJobFactory {
|
||||
input.put("decimal_type_narrowing", false);
|
||||
input.put("query", selectSql(snapshot, sqlServer, oracle || dameng || kingbase, source.databaseName()));
|
||||
ObjectNode fields = input.putObject("schema").putObject("fields");
|
||||
boolean binaryEncoding = snapshot.mappings().stream().anyMatch(f -> textCarrier(f, "field") != null && textCarrier(f, "field").binary());
|
||||
for (BatchFieldExecution field : snapshot.mappings()) {
|
||||
MysqlTargetType mapped = normalizedType(field, target.resourceType());
|
||||
if (!mapped.supported() || !sameDeclaration(mapped.targetType(), field.targetType())) {
|
||||
throw new IllegalArgumentException("MYSQL_TARGET_TYPE_MISMATCH");
|
||||
}
|
||||
var carrier = textCarrier(field, "field");
|
||||
fields.put(field.targetField(), carrier != null && carrier.binary() ? "bytes" : mapped.seaTunnelType());
|
||||
}
|
||||
|
||||
if (binaryEncoding) {
|
||||
input.put("result_table_name", "batch_source");
|
||||
ObjectNode encoder = root.putArray("transform").addObject();
|
||||
encoder.put("plugin_name", "Sql");
|
||||
encoder.put("source_table_name", "batch_source");
|
||||
encoder.put("result_table_name", "batch_encoded");
|
||||
encoder.put("query", "SELECT " + snapshot.mappings().stream().map(f -> {
|
||||
String field = quoteIdentifier(f.targetField());
|
||||
var carrier = textCarrier(f, field);
|
||||
return carrier != null && carrier.binary() ? "RAWTOHEX(" + field + ") AS " + field : field;
|
||||
}).collect(java.util.stream.Collectors.joining(", ")) + " FROM batch_source");
|
||||
fields.put(field.targetField(), mapped.seaTunnelType());
|
||||
}
|
||||
|
||||
ObjectNode sink = root.putArray("sink").addObject();
|
||||
if (binaryEncoding) sink.put("source_table_name", "batch_encoded");
|
||||
String[] targetObject = objectParts(snapshot.targetObject(), target.externalSpaceId());
|
||||
// Hive writes through its native connector and metastore contract; Doris keeps the approved MySQL wire sink.
|
||||
boolean hive = "HIVE".equals(target.resourceType());
|
||||
@@ -214,7 +194,7 @@ final class M3CollectionJobFactory {
|
||||
} else {
|
||||
sink.put("plugin_name", "Jdbc");
|
||||
sink.put("url", mysqlUrl(target.endpointHost(), target.endpointPort(), targetObject[0], target.tlsEnabled()) +
|
||||
"&forceConnectionTimeZoneToSession=true&preserveInstants=false&sessionVariables=enable_insert_strict=true");
|
||||
"&forceConnectionTimeZoneToSession=true&preserveInstants=false");
|
||||
sink.put("driver", "com.mysql.cj.jdbc.Driver");
|
||||
sink.put("user", target.serviceAccount());
|
||||
sink.put("password", targetPassword);
|
||||
@@ -371,10 +351,7 @@ final class M3CollectionJobFactory {
|
||||
String source = sqlServer ? "[" + checkedIdentifier(field.sourceField()) + "]"
|
||||
: oracle ? oracleIdentifier(field.sourceField()) : quoteIdentifier(field.sourceField());
|
||||
String nativeType = field.sourceNativeType() == null ? "" : field.sourceNativeType().toUpperCase(Locale.ROOT).replaceAll("\\(.*\\)$", "").trim();
|
||||
var carrier = textCarrier(field, source);
|
||||
if (carrier != null) {
|
||||
source = carrier.expression();
|
||||
} else if (sqlServer) {
|
||||
if (sqlServer) {
|
||||
source = switch (nativeType) {
|
||||
case "SQLSERVER:BINARY", "SQLSERVER:VARBINARY", "SQLSERVER:TIMESTAMP", "SQLSERVER:ROWVERSION" -> "CONVERT(varchar(max)," + source + ",2)";
|
||||
case "SQLSERVER:UNIQUEIDENTIFIER" -> "CONVERT(varchar(36)," + source + ")";
|
||||
@@ -451,12 +428,6 @@ final class M3CollectionJobFactory {
|
||||
return DataSourceObjects.mysqlTargetType(source, TargetEngine.valueOf(targetType));
|
||||
}
|
||||
|
||||
private static cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.Carrier textCarrier(BatchFieldExecution field, String identifier) {
|
||||
return cn.aixunkeji.datagov.integration.api.datasource.BatchTextTypes.carrier(new Column(
|
||||
field.sourceField(), field.sourceType(), field.order(), null, false, field.sourceNativeType(),
|
||||
field.sourcePrecision(), field.sourceScale(), field.sourceOctetLength()), identifier);
|
||||
}
|
||||
|
||||
private static boolean validBatchTransform(BatchFieldExecution field, MysqlTargetType mapped) {
|
||||
if ("NONE".equals(field.transform()) || "DEFAULT_IF_NULL".equals(field.transform())) return true;
|
||||
return "string".equals(mapped.seaTunnelType()) && Set.of("TRIM", "UPPER", "LOWER").contains(field.transform());
|
||||
|
||||
+15
@@ -34,6 +34,7 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn
|
||||
private final DataSourceRegistry dataSourceRegistry;
|
||||
private final SeaTunnelAdapter seaTunnel;
|
||||
private final M2SecretReader secrets;
|
||||
private final ApiPollExecutor apiPoll;
|
||||
private final M3LakehouseDirectoryVerifier lakehouse;
|
||||
private final M3ControlledFileStore controlledFiles;
|
||||
private final VisualPreviewJdbcAdapter visualPreview;
|
||||
@@ -81,6 +82,7 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn
|
||||
this.dataSourceRegistry = dataSourceRegistry;
|
||||
this.seaTunnel = seaTunnel;
|
||||
this.secrets = secrets;
|
||||
this.apiPoll = secrets == null ? null : new ApiPollExecutor(secrets);
|
||||
this.lakehouse = new M3LakehouseDirectoryVerifier(secrets, hive);
|
||||
this.controlledFiles = controlledFiles;
|
||||
this.visualPreview = visualPreview;
|
||||
@@ -98,12 +100,25 @@ public class M3DataCollectionIntegrationDubboService implements DataCollectionIn
|
||||
this.dataSourceRegistry = dataSourceRegistry;
|
||||
this.seaTunnel = null;
|
||||
this.secrets = null;
|
||||
this.apiPoll = null;
|
||||
this.lakehouse = null;
|
||||
this.controlledFiles = null;
|
||||
this.visualPreview = visualPreview;
|
||||
this.batchTarget = new M3BatchTargetVerifier(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApiPollResult pollApi(ApiPollRequest request) {
|
||||
return apiPoll == null || request == null
|
||||
? new ApiPollResult("UNKNOWN", 0, null, "API_POLL_ADAPTER_UNAVAILABLE")
|
||||
: 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) {
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Generates the fixed single-table MySQL CDC to Doris execution shape. */
|
||||
final class MysqlCdcJobFactory {
|
||||
private static final Pattern IDENTIFIER = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}");
|
||||
private static final Pattern HOST = Pattern.compile("[A-Za-z0-9][A-Za-z0-9.-]{0,252}");
|
||||
private static final Pattern LABEL = Pattern.compile("[A-Za-z0-9_]{1,80}");
|
||||
|
||||
private MysqlCdcJobFactory() { }
|
||||
|
||||
record Config(String mysqlHost, int mysqlPort, String sourceDatabase, String sourceTable,
|
||||
String mysqlUser, String mysqlPassword, long serverId, String startupMode,
|
||||
String dorisHost, int dorisHttpPort, int dorisQueryPort, String targetDatabase,
|
||||
String targetTable, String dorisUser, String dorisPassword, String labelPrefix,
|
||||
int checkpointSeconds) {
|
||||
@Override public String toString() { return "MysqlCdcJobFactory.Config[credentials=REDACTED]"; }
|
||||
}
|
||||
|
||||
static ObjectNode create(Config c) {
|
||||
if (c == null || !host(c.mysqlHost()) || !host(c.dorisHost()) || !port(c.mysqlPort()) ||
|
||||
!port(c.dorisHttpPort()) || !port(c.dorisQueryPort()) || !identifier(c.sourceDatabase()) ||
|
||||
!identifier(c.sourceTable()) || !identifier(c.targetDatabase()) || !identifier(c.targetTable()) ||
|
||||
blank(c.mysqlUser()) || blank(c.mysqlPassword()) || blank(c.dorisUser()) || blank(c.dorisPassword()) ||
|
||||
c.serverId() < 1 || c.serverId() > 4_294_967_295L ||
|
||||
c.startupMode() == null || !Set.of("initial", "latest").contains(c.startupMode()) || c.labelPrefix() == null ||
|
||||
!LABEL.matcher(c.labelPrefix()).matches() || c.checkpointSeconds() < 10 || c.checkpointSeconds() > 86_400) {
|
||||
throw new IllegalArgumentException("CDC_EXECUTION_CONTRACT_INVALID");
|
||||
}
|
||||
ObjectNode root = JsonMapper.builder().build().createObjectNode();
|
||||
ObjectNode env = root.putObject("env");
|
||||
env.put("job.mode", "STREAMING");
|
||||
env.put("parallelism", 1);
|
||||
env.put("checkpoint.interval", c.checkpointSeconds() * 1000L);
|
||||
ObjectNode source = root.putArray("source").addObject();
|
||||
source.put("plugin_name", "MySQL-CDC");
|
||||
source.put("url", "jdbc:mysql://" + c.mysqlHost() + ':' + c.mysqlPort() + '/' + c.sourceDatabase());
|
||||
source.put("username", c.mysqlUser());
|
||||
source.put("password", c.mysqlPassword());
|
||||
source.put("server-id", Long.toString(c.serverId()));
|
||||
source.put("startup.mode", c.startupMode());
|
||||
source.put("schema-changes.enabled", false);
|
||||
source.putArray("table-names").add(c.sourceDatabase() + '.' + c.sourceTable());
|
||||
ObjectNode sink = root.putArray("sink").addObject();
|
||||
sink.put("plugin_name", "Doris");
|
||||
sink.put("fenodes", c.dorisHost() + ':' + c.dorisHttpPort());
|
||||
sink.put("query-port", c.dorisQueryPort());
|
||||
sink.put("database", c.targetDatabase());
|
||||
sink.put("table", c.targetTable());
|
||||
sink.put("username", c.dorisUser());
|
||||
sink.put("password", c.dorisPassword());
|
||||
sink.put("sink.label-prefix", c.labelPrefix());
|
||||
sink.put("sink.enable-delete", true);
|
||||
sink.put("sink.enable-2pc", true);
|
||||
sink.put("schema_save_mode", "ERROR_WHEN_SCHEMA_NOT_EXIST");
|
||||
sink.put("data_save_mode", "APPEND_DATA");
|
||||
sink.putObject("doris.config").put("format", "json").put("read_json_by_line", "true");
|
||||
return root;
|
||||
}
|
||||
|
||||
private static boolean identifier(String value) { return value != null && IDENTIFIER.matcher(value).matches(); }
|
||||
private static boolean host(String value) { return value != null && HOST.matcher(value).matches(); }
|
||||
private static boolean port(int value) { return value > 0 && value <= 65535; }
|
||||
private static boolean blank(String value) { return value == null || value.isBlank(); }
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.DataSourceView;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import cn.aixunkeji.datagov.integration.datasource.DataSourceOracleProfile;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
import java.sql.*;
|
||||
import java.util.Set;
|
||||
|
||||
/** Fixed native CDC profiles. JDBC connectivity alone is never advertised as CDC support. */
|
||||
final class NativeCdcSource {
|
||||
private NativeCdcSource() { }
|
||||
static void validate(DataSourceView s, Spec p) {
|
||||
if(p.oraclePdb()!=null || p.oracleCdbService()!=null) {
|
||||
if(!"ORACLE".equals(s.type()) || p.cdcChannel()!=null)
|
||||
throw new IllegalArgumentException("PDB参数只能用于Oracle原生CDC");
|
||||
identifier(p.oraclePdb());
|
||||
if(Set.of("CDB$ROOT","PDB$SEED").contains(p.oraclePdb()))throw new IllegalArgumentException("请选择业务PDB");
|
||||
if(p.oracleCdbService()==null || !p.oracleCdbService().matches("[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}"))
|
||||
throw new IllegalArgumentException("请填写CDB根容器服务名");
|
||||
}
|
||||
if(p.cdcChannel()!=null){
|
||||
if(!Set.of("DAMENG","KINGBASE","ORACLE").contains(s.type()) || !p.cdcChannel().matches("[A-Za-z0-9_-]{1,64}"))
|
||||
throw new IllegalArgumentException("此来源不支持所选日志通道");
|
||||
identifier(p.sourceSchema());return;
|
||||
}
|
||||
if (Set.of("DAMENG","KINGBASE").contains(s.type())) {
|
||||
identifier(p.sourceSchema());identifier(p.sourceDatabase());identifier(p.sourceTable());
|
||||
if(p.oracleDatabase()!=null)throw new IllegalArgumentException("此来源不使用Oracle数据库名");
|
||||
if(!Set.of("initial","latest").contains(p.startupMode()))throw new IllegalArgumentException("请选择首次全量或仅增量");
|
||||
return;
|
||||
}
|
||||
if (!Set.of("MYSQL", "ORACLE", "SQLSERVER").contains(s.type()))
|
||||
throw new IllegalArgumentException("此数据源尚未接入原生CDC");
|
||||
if ("MYSQL".equals(s.type())) {
|
||||
if (p.sourceSchema()!=null || p.oracleDatabase()!=null)
|
||||
throw new IllegalArgumentException("MySQL配置不能包含Oracle或架构参数");
|
||||
} else {
|
||||
identifier(p.sourceSchema());
|
||||
if ("ORACLE".equals(s.type())) {
|
||||
identifier(p.oracleDatabase());
|
||||
} else {
|
||||
identifier(p.sourceDatabase());
|
||||
if (p.oracleDatabase()!=null)
|
||||
throw new IllegalArgumentException("SQL Server配置不能包含Oracle参数");
|
||||
}
|
||||
}
|
||||
}
|
||||
static ObjectNode job(MysqlCdcJobFactory.Config common, DataSourceView s, Spec p) {
|
||||
validate(s,p);
|
||||
ObjectNode root=MysqlCdcJobFactory.create(common);
|
||||
if ("MYSQL".equals(s.type())) return root;
|
||||
ObjectNode source=(ObjectNode)root.path("source").get(0);
|
||||
if(Set.of("DAMENG","KINGBASE").contains(s.type())) {
|
||||
source.removeAll();
|
||||
boolean dm="DAMENG".equals(s.type());
|
||||
source.put("plugin_name",dm?"Dameng-Native-CDC":"Kingbase-Native-CDC");
|
||||
source.put("url",(dm?"jdbc:dm://":"jdbc:kingbase8://")+s.host()+":"+s.port()+"/"+p.sourceDatabase()+
|
||||
(dm?"?connectTimeout=30000&socketTimeout=90000":"?sslmode=disable&connectTimeout=30&socketTimeout=90"));
|
||||
source.put("username",common.mysqlUser());source.put("password",common.mysqlPassword());
|
||||
source.put("source_schema",p.sourceSchema());source.put("source_table",p.sourceTable());
|
||||
source.put("startup.mode",p.startupMode());
|
||||
if(!dm)source.put("slot_name",VendorCdcPrerequisites.slot(p));
|
||||
return root;
|
||||
}
|
||||
source.remove("server-id");
|
||||
String database="ORACLE".equals(s.type()) ? (p.oraclePdb()==null?p.oracleDatabase():p.oraclePdb()) : p.sourceDatabase();
|
||||
source.putArray("database-names").add(database);
|
||||
source.putArray("table-names").add(database+"."+p.sourceSchema()+"."+p.sourceTable());
|
||||
if ("ORACLE".equals(s.type())) {
|
||||
source.put("plugin_name","Oracle-CDC");
|
||||
source.put("url",DataSourceOracleProfile.url(s.host(),s.port(),s.databaseName(),s.userName(),s.connectionParameters()));
|
||||
source.putArray("schema-names").add(p.sourceSchema());
|
||||
source.put("skip_analyze",true);
|
||||
source.put("use_select_count",true);
|
||||
source.putObject("debezium").put("database.dbname",p.oracleDatabase());
|
||||
if(p.oraclePdb()!=null) {
|
||||
var debezium=(ObjectNode)source.path("debezium");
|
||||
debezium.put("database.pdb.name",p.oraclePdb());
|
||||
debezium.put("database.url",oracleRootUrl(s,p));
|
||||
}
|
||||
} else {
|
||||
source.put("plugin_name","SqlServer-CDC");
|
||||
boolean ssl=Boolean.parseBoolean(s.connectionParameters().getOrDefault("useSsl","false"));
|
||||
String trust=s.connectionParameters().getOrDefault("trustServerCertificate","false");
|
||||
source.put("url","jdbc:sqlserver://"+s.host()+":"+s.port()+";databaseName="+p.sourceDatabase()+
|
||||
";encrypt="+ssl+";trustServerCertificate="+trust+";integratedSecurity=false");
|
||||
// 2.3.13 must receive these explicitly for both snapshot and Debezium connections.
|
||||
source.putObject("debezium").put("database.encrypt",Boolean.toString(ssl)).put("database.trustServerCertificate",trust);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
static String oracleRootUrl(DataSourceView s,Spec p) {
|
||||
return "jdbc:oracle:thin:@//"+s.host()+":"+s.port()+"/"+p.oracleCdbService();
|
||||
}
|
||||
static String table(DataSourceView s,Spec p) {
|
||||
return switch(s.type()) {
|
||||
case "MYSQL" -> "`"+p.sourceDatabase()+"`.`"+p.sourceTable()+"`";
|
||||
case "SQLSERVER" -> "["+p.sourceDatabase()+"].["+p.sourceSchema()+"].["+p.sourceTable()+"]";
|
||||
case "ORACLE","DAMENG","KINGBASE" -> "\""+p.sourceSchema()+"\".\""+p.sourceTable()+"\"";
|
||||
default -> throw new IllegalArgumentException("不支持此CDC类型");
|
||||
};
|
||||
}
|
||||
static void prerequisites(Connection db,DataSourceView s,Spec p) throws SQLException {
|
||||
try(var st=db.createStatement()) {
|
||||
st.setQueryTimeout(15);
|
||||
switch(s.type()) {
|
||||
case "DAMENG","KINGBASE" -> VendorCdcPrerequisites.check(db,s.type(),p);
|
||||
case "MYSQL" -> {
|
||||
try(var rs=st.executeQuery("SELECT @@log_bin, @@binlog_format, @@binlog_row_image")) {
|
||||
if(!rs.next()||!rs.getBoolean(1)||!"ROW".equalsIgnoreCase(rs.getString(2))||!"FULL".equalsIgnoreCase(rs.getString(3)))
|
||||
throw new IllegalArgumentException("MySQL源库需要启用Binlog,并设置ROW与FULL");
|
||||
}
|
||||
}
|
||||
case "SQLSERVER" -> {
|
||||
try(var rs=st.executeQuery("SELECT is_cdc_enabled FROM sys.databases WHERE name=DB_NAME()")) {
|
||||
if(!rs.next()||!rs.getBoolean(1))throw new IllegalArgumentException("SQL Server源数据库未启用CDC,请由DBA启用数据库CDC及捕获作业");
|
||||
}
|
||||
try(var ps=db.prepareStatement("SELECT t.is_tracked_by_cdc FROM sys.tables t JOIN sys.schemas s ON s.schema_id=t.schema_id WHERE s.name=? AND t.name=?")) {
|
||||
ps.setQueryTimeout(15);ps.setString(1,p.sourceSchema());ps.setString(2,p.sourceTable());
|
||||
try(var rs=ps.executeQuery()) {
|
||||
if(!rs.next()||!rs.getBoolean(1))throw new IllegalArgumentException("SQL Server源表不存在、不可见或尚未启用CDC;请检查架构、表权限及表级CDC");
|
||||
}
|
||||
}
|
||||
// Checks capture-table visibility for this account; does not enable CDC or mutate grants.
|
||||
try(var rs=st.executeQuery("SELECT capture_instance FROM cdc.change_tables WHERE source_object_id=OBJECT_ID(N'"+p.sourceSchema()+"."+p.sourceTable()+"')")) {
|
||||
if(!rs.next())throw new IllegalArgumentException("当前账号不可读取SQL Server源表的CDC捕获实例");
|
||||
}
|
||||
}
|
||||
case "ORACLE" -> {
|
||||
try(var rs=st.executeQuery("SELECT NAME, LOG_MODE, SUPPLEMENTAL_LOG_DATA_MIN, SUPPLEMENTAL_LOG_DATA_ALL, CDB FROM V$DATABASE")) {
|
||||
if(!rs.next())throw new IllegalArgumentException("无法读取Oracle日志配置");
|
||||
if(!p.oracleDatabase().equals(rs.getString(1)))throw new IllegalArgumentException("Oracle数据库名与V$DATABASE.NAME不一致,不能填写服务名或PDB名代替");
|
||||
if(!"ARCHIVELOG".equals(rs.getString(2))||!Set.of("YES","IMPLICIT").contains(rs.getString(3)))
|
||||
throw new IllegalArgumentException("Oracle需要开启ARCHIVELOG和最小补充日志,请由DBA配置");
|
||||
if("YES".equals(rs.getString(5)) != (p.oraclePdb()!=null))
|
||||
throw new IllegalArgumentException("Oracle架构与配置不一致:多租户库请填写目标PDB和CDB根容器服务名;非CDB请留空");
|
||||
}
|
||||
if(p.oraclePdb()!=null)verifyContainer(db,p.oraclePdb());
|
||||
try(var ps=db.prepareStatement("SELECT COUNT(*) FROM ALL_LOG_GROUPS WHERE OWNER=? AND TABLE_NAME=? AND LOG_GROUP_TYPE='ALL COLUMN LOGGING'")) {
|
||||
ps.setQueryTimeout(15);ps.setString(1,p.sourceSchema());ps.setString(2,p.sourceTable());
|
||||
try(var rs=ps.executeQuery();var logs=db.createStatement()) {
|
||||
logs.setQueryTimeout(15);
|
||||
try(var all=logs.executeQuery("SELECT SUPPLEMENTAL_LOG_DATA_ALL FROM V$DATABASE")) {
|
||||
if(!rs.next()||!all.next()||rs.getLong(1)==0&&!"YES".equals(all.getString(1)))
|
||||
throw new IllegalArgumentException("Oracle源表缺少ALL COLUMNS补充日志,无法可靠同步更新和删除");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException("不支持此CDC类型");
|
||||
}
|
||||
}
|
||||
}
|
||||
static void verifyContainer(Connection db,String expected)throws SQLException {
|
||||
try(var st=db.createStatement()) {
|
||||
st.setQueryTimeout(15);
|
||||
try(var rs=st.executeQuery("SELECT SYS_CONTEXT('USERENV','CON_NAME') FROM DUAL")) {
|
||||
if(!rs.next() || !expected.equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Oracle连接容器不匹配,要求连接到 "+expected+";请检查数据源服务名和CDB服务名");
|
||||
}
|
||||
}
|
||||
}
|
||||
static void oracleRootPrerequisites(Connection db,Spec p)throws SQLException {
|
||||
verifyContainer(db,"CDB$ROOT");
|
||||
try(var st=db.createStatement()) {
|
||||
st.setQueryTimeout(15);
|
||||
try(var rs=st.executeQuery("SELECT NAME, LOG_MODE, SUPPLEMENTAL_LOG_DATA_MIN FROM V$DATABASE")) {
|
||||
if(!rs.next() || !p.oracleDatabase().equals(rs.getString(1)) || !"ARCHIVELOG".equals(rs.getString(2)) ||
|
||||
!Set.of("YES","IMPLICIT").contains(rs.getString(3)))
|
||||
throw new IllegalArgumentException("CDB数据库名、归档模式或根容器补充日志不满足CDC要求");
|
||||
}
|
||||
try(var rs=st.executeQuery("SELECT COMMON FROM USER_USERS")) {
|
||||
if(!rs.next() || !"YES".equals(rs.getString(1)))throw new IllegalArgumentException("CDB/PDB采集需要可访问根容器及目标PDB的公共用户");
|
||||
}
|
||||
try(var rs=st.executeQuery("SELECT PRIVILEGE FROM SESSION_PRIVS WHERE PRIVILEGE IN ('LOGMINING','SET CONTAINER')")) {
|
||||
var privileges=new java.util.HashSet<String>();while(rs.next())privileges.add(rs.getString(1));
|
||||
if(!privileges.containsAll(Set.of("LOGMINING","SET CONTAINER")))
|
||||
throw new IllegalArgumentException("Oracle公共用户缺少LOGMINING或SET CONTAINER权限,请由DBA配置");
|
||||
}
|
||||
// Verify the same connection can switch containers without changing persistent configuration.
|
||||
st.execute("ALTER SESSION SET CONTAINER = \""+p.oraclePdb()+"\"");
|
||||
verifyContainer(db,p.oraclePdb());
|
||||
}
|
||||
}
|
||||
private static void identifier(String value) {
|
||||
if(value==null||!value.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))
|
||||
throw new IllegalArgumentException("请填写正确的源架构、Oracle数据库名或PDB名");
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.*;
|
||||
import cn.aixunkeji.datagov.integration.datasource.DataSourceAccessScope;
|
||||
import cn.aixunkeji.datagov.integration.datasource.DataSourceObjectConnection;
|
||||
import cn.aixunkeji.datagov.integration.m2.*;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
@DubboService(timeout = 120000, retries = 0)
|
||||
public class RealtimeCollectionDubboService implements RealtimeCollectionService {
|
||||
private final DataSourceRegistry sources;
|
||||
private final M2SecretReader secrets;
|
||||
private final SeaTunnelAdapter engine;
|
||||
private final DataSourceObjectConnection connections;
|
||||
private final CdcRelayRegistry relays;
|
||||
public RealtimeCollectionDubboService(DataSourceRegistry sources, M2SecretReader secrets, SeaTunnelAdapter engine,
|
||||
DataSourceObjectConnection connections,CdcRelayRegistry relays) {
|
||||
this.sources = sources; this.secrets = secrets; this.engine = engine; this.connections = connections;this.relays=relays;
|
||||
}
|
||||
@Override public List<RelayOption> relays(long actor,long org,long source){
|
||||
if(actor<=0||org<=0||sources.find(new DataSourceAccessScope(actor,org),source)==null)return List.of();
|
||||
return relays.options(org,source);
|
||||
}
|
||||
@Override public SourceDefaults sourceDefaults(long actor,long org,long sourceId) {
|
||||
if(actor<=0 || org<=0)throw new IllegalArgumentException("无权访问数据源");
|
||||
var scope=new DataSourceAccessScope(actor,org);
|
||||
var s=sources.find(scope,sourceId);
|
||||
if(s==null)throw new IllegalArgumentException("数据源不存在或无权访问");
|
||||
String schema=null,database=null,pdb=null,rootService=null,warning=null;
|
||||
try(var db=connections.open(s,scope);var st=db.createStatement()) {
|
||||
st.setQueryTimeout(10);
|
||||
schema=db.getSchema();
|
||||
if("ORACLE".equals(s.type())) {
|
||||
try(var rs=st.executeQuery("SELECT NAME, CDB FROM V$DATABASE")) {
|
||||
if(rs.next()) {
|
||||
database=rs.getString(1);
|
||||
if("YES".equals(rs.getString(2))) {
|
||||
try(var ps=db.createStatement()) {
|
||||
ps.setQueryTimeout(10);
|
||||
try(var pr=ps.executeQuery("SELECT SYS_CONTEXT('USERENV','CON_NAME') FROM DUAL")) {
|
||||
if(pr.next() && !"CDB$ROOT".equals(pr.getString(1)))pdb=pr.getString(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(pdb!=null) {
|
||||
// Only advertise a service observed in the root container, never guess from the PDB name.
|
||||
try(var rs=st.executeQuery("SELECT DISTINCT NETWORK_NAME FROM V$SERVICES WHERE CON_ID=1 AND NETWORK_NAME IS NOT NULL AND NAME NOT LIKE 'SYS$%'")) {
|
||||
var services=new TreeSet<String>();while(rs.next())services.add(rs.getString(1));
|
||||
if(services.size()==1)rootService=services.first();
|
||||
} catch(SQLException ignored) { /* User can supply a root service if its catalog is not visible. */ }
|
||||
if(rootService==null)warning="未能唯一识别 CDB 根服务名,请由数据库管理员确认后填写。";
|
||||
}
|
||||
}
|
||||
} catch(SQLException | RuntimeException ex) {
|
||||
warning="部分连接参数无法自动读取,请确认数据源连接及元数据读取权限,或手动填写缺失项。";
|
||||
}
|
||||
return new SourceDefaults(s.version(),schema,database,pdb,rootService,warning);
|
||||
}
|
||||
private DataSourceView source(Command c) {
|
||||
if(c == null || c.actorId() <= 0 || c.orgId() <= 0 || c.spec() == null || c.target() == null)
|
||||
throw new IllegalArgumentException("实时采集配置不完整");
|
||||
var s = sources.find(new DataSourceAccessScope(c.actorId(), c.orgId()), c.spec().sourceId());
|
||||
if(s == null || s.version() != c.spec().sourceVersion() ||
|
||||
!Objects.equals(s.databaseName(), c.spec().sourceDatabase()))
|
||||
throw new IllegalArgumentException("源数据源已变化或不在授权范围,请重新创建配置");
|
||||
var t=c.target();
|
||||
if(!"DORIS".equals(t.resourceType()) || t.resourceId()!=c.spec().targetResourceId() ||
|
||||
!Objects.equals(t.spaceId(), c.spec().targetSpaceId()) || t.tlsEnabled() ||
|
||||
c.spec().cdcChannel()==null && !"SQLSERVER".equals(s.type()) && Boolean.parseBoolean(s.connectionParameters().getOrDefault("useSsl", "false")))
|
||||
throw new IllegalArgumentException("当前CDC要求Doris及MySQL/Oracle使用非TLS连接;SQL Server沿用登记的SSL设置");
|
||||
NativeCdcSource.validate(s,c.spec());
|
||||
if(c.spec().cdcChannel()!=null)relays.require(c);else NativeCdcSource.job(config(c,s),s,c.spec());
|
||||
return s;
|
||||
}
|
||||
private MysqlCdcJobFactory.Config config(Command c, DataSourceView s) {
|
||||
var p=c.spec(); var t=c.target();
|
||||
return new MysqlCdcJobFactory.Config(s.host(),s.port(),"MYSQL".equals(s.type())?p.sourceDatabase():"cdc",p.sourceTable(),s.userName(),
|
||||
secrets.resolve(s.secretRef()),p.serverId(),p.startupMode(),t.endpointHost(),p.httpPort(),t.endpointPort(),
|
||||
t.externalSpaceId(),p.targetTable(),t.serviceAccount(),secrets.resolve(t.secretRef()),
|
||||
"cdc_"+c.taskId()+"_"+c.attempt(),p.checkpointSeconds());
|
||||
}
|
||||
@Override public Check check(Command c) {return check(c,false);}
|
||||
@Override public Check prepare(Command c) {
|
||||
if(c==null || c.attempt()!=0)return rejected("仅未启动的任务可检查并准备目标表");
|
||||
return check(c,true);
|
||||
}
|
||||
private Check check(Command c,boolean prepare) {
|
||||
String stage="解析连接配置";
|
||||
try {
|
||||
var s=source(c); var p=c.spec(); var t=c.target();
|
||||
if(p.oraclePdb()!=null) {
|
||||
stage="检查Oracle CDB根容器连接和采集权限";
|
||||
var props=new Properties();props.setProperty("user",s.userName());
|
||||
props.setProperty("password",secrets.resolve(s.secretRef()));
|
||||
props.setProperty("oracle.net.CONNECT_TIMEOUT","15000");props.setProperty("oracle.jdbc.ReadTimeout","30000");
|
||||
try(var root=DriverManager.getConnection(NativeCdcSource.oracleRootUrl(s,p),props)) {
|
||||
NativeCdcSource.oracleRootPrerequisites(root,p);
|
||||
}
|
||||
}
|
||||
List<String> fields=new ArrayList<>(), keys=new ArrayList<>(), signatures=new ArrayList<>();
|
||||
List<RealtimeTargetTable.Field> targetFields;
|
||||
stage="连接"+s.type()+"源库";
|
||||
try(var db="MYSQL".equals(s.type()) ? connect(s.host(),s.port(),p.sourceDatabase(),s.userName(),secrets.resolve(s.secretRef())) :
|
||||
connections.open(s,new DataSourceAccessScope(c.actorId(),c.orgId()));
|
||||
var st=db.createStatement()) {
|
||||
st.setQueryTimeout(15);
|
||||
stage="检查"+s.type()+"日志和CDC配置";
|
||||
if(p.cdcChannel()==null)NativeCdcSource.prerequisites(db,s,p);
|
||||
stage="读取"+s.type()+"源表主键";
|
||||
try(var rs=db.getMetaData().getPrimaryKeys(Set.of("ORACLE","DAMENG").contains(s.type())?null:p.sourceDatabase(),p.sourceSchema(),p.sourceTable())) {
|
||||
Map<Short,String> ordered=new TreeMap<>();
|
||||
while(rs.next()) ordered.put(rs.getShort("KEY_SEQ"),rs.getString("COLUMN_NAME"));
|
||||
keys.addAll(ordered.values());
|
||||
}
|
||||
if(keys.isEmpty()) return rejected("源表必须有主键");
|
||||
stage="读取"+s.type()+"源表字段";
|
||||
try(var rs=st.executeQuery("SELECT * FROM "+NativeCdcSource.table(s,p)+" WHERE 1=0")) {
|
||||
var md=rs.getMetaData();
|
||||
if(md.getColumnCount()>200) return rejected("首期每表最多支持200个字段");
|
||||
targetFields=RealtimeTargetTable.fields(md,s.type());
|
||||
for(int i=1;i<=md.getColumnCount();i++) {
|
||||
fields.add(md.getColumnName(i));
|
||||
signatures.add(md.getColumnName(i)+":"+md.getColumnTypeName(i)+":"+md.getPrecision(i)+":"+md.getScale(i));
|
||||
if(p.cdcChannel()!=null)CdcRelayRegistry.type(md.getColumnType(i),md.getPrecision(i),md.getScale(i));
|
||||
else if(Set.of("DAMENG","KINGBASE").contains(s.type()))VendorCdcPrerequisites.field(md,i);
|
||||
}
|
||||
}
|
||||
}
|
||||
stage="连接Doris目标库";
|
||||
try(var db=connect(t.endpointHost(),t.endpointPort(),t.externalSpaceId(),t.serviceAccount(),secrets.resolve(t.secretRef()));
|
||||
var st=db.createStatement()) {
|
||||
st.setQueryTimeout(15);
|
||||
stage=prepare?"检查并准备Doris目标表":"读取Doris目标表定义";
|
||||
String ddl=RealtimeTargetTable.prepare(st,t.externalSpaceId(),p.targetTable(),targetFields,keys,prepare);
|
||||
{
|
||||
var matcher=java.util.regex.Pattern.compile("(?is)UNIQUE\\s+KEY\\s*\\(([^)]+)\\)").matcher(ddl);
|
||||
if(!matcher.find()) return rejected("Doris目标表必须为Unique Key模型");
|
||||
var targetKeys=Arrays.stream(matcher.group(1).replace("`", "").split(",")).map(String::trim).toList();
|
||||
if(!keys.equals(targetKeys)) return rejected("目标Unique Key须与源主键一致且顺序相同");
|
||||
signatures.add(ddl);
|
||||
}
|
||||
stage="读取Doris目标表字段";
|
||||
try(var rs=st.executeQuery("SELECT * FROM `"+t.externalSpaceId()+"`.`"+p.targetTable()+"` WHERE 1=0")) {
|
||||
RealtimeTargetTable.compatible(targetFields,rs.getMetaData());
|
||||
}
|
||||
if("initial".equals(p.startupMode()) && c.attempt()<=1 && c.recovery()==null) {
|
||||
stage="检查Doris目标表是否为空";
|
||||
try(var rs=st.executeQuery("SELECT 1 FROM `"+t.externalSpaceId()+"`.`"+p.targetTable()+"` LIMIT 1")) {
|
||||
if(rs.next()) return rejected("首次全量同步要求目标表为空;已有基线请使用仅增量模式");
|
||||
}
|
||||
}
|
||||
}
|
||||
if(p.cdcChannel()!=null)signatures.add(relays.fingerprint(c));
|
||||
String fingerprint=hash(p.fingerprintText()+"|"+s.version()+"|"+s.host()+"|"+s.port()+"|"+s.secretRef()+"|"+
|
||||
s.userName()+"|"+t.endpointHost()+"|"+t.endpointPort()+"|"+t.serviceAccount()+"|"+t.secretRef()+"|"+t.externalSpaceId()+"|"+signatures);
|
||||
return new Check(true,p.cdcChannel()==null?(prepare?"源库与目标表准备完成;缺失目标表已创建,已有表未修改,可以启动采集":"源库日志、主键与目标表结构检查通过;启动后核验同步结果"):
|
||||
"日志通道绑定、源表和目标表检查通过;需确认上游已输出全量及完整变更消息,Kafka连接与真实消息在启动后验证",fingerprint,fields,keys);
|
||||
} catch(IllegalArgumentException e) { return rejected(e.getMessage()); }
|
||||
catch(Exception e) { return rejected(checkFailure(stage,e)); }
|
||||
}
|
||||
static String checkFailure(String stage, Exception failure) {
|
||||
String reason="检查失败,请核对该步骤的连接配置和服务状态";
|
||||
if(failure instanceof SQLException sql) {
|
||||
String state=Objects.toString(sql.getSQLState(), "");
|
||||
int code=sql.getErrorCode();
|
||||
String message=Objects.toString(sql.getMessage(), "").toLowerCase(Locale.ROOT);
|
||||
boolean dorisMissingTable=code==1105 && (message.contains("unknown table") ||
|
||||
message.matches("(?s).*table[^\\n]*(does not exist|doesn't exist|not exist|not found).*"));
|
||||
if(code==1049 || code==4060 || code==12514 || code==1105 && message.contains("unknown database")) reason="数据库或连接服务不存在、未注册或无权访问,请核对所选数据库及服务名";
|
||||
else if(code==1146 || code==942 || code==208 || "42S02".equals(state) || dorisMissingTable) reason="表不存在或无权读取(也可能是系统视图),请核对模式、表名及大小写;目标表缺失时请检查并准备";
|
||||
else if(code==1105 && (message.contains("access denied") || message.contains("permission denied"))) reason="账号缺少此步骤需要的权限";
|
||||
else if(code==1045 || code==1017 || code==18456 || state.startsWith("28")) reason="账号认证失败,请检查此端的账号和托管密码";
|
||||
else if(Set.of(1044,1142,1143,1227,1031,229,297).contains(code) || "42501".equals(state)) reason="账号缺少此步骤需要的权限";
|
||||
else if(failure instanceof SQLTimeoutException || state.startsWith("HYT")) reason="访问超时,请检查Integration容器到数据库的网络";
|
||||
else if(state.startsWith("08")) reason="连接或通信失败,请检查Integration容器网络、数据库服务及连接参数";
|
||||
else reason="数据库拒绝此步骤,请核对表结构、权限及数据库兼容性";
|
||||
// Only structured codes are exposed; driver messages can contain credentials and SQL.
|
||||
return stage+"失败:"+reason+"(SQLState="+(state.matches("[A-Za-z0-9]{5}")?state:"UNKNOWN")+", code="+code+")";
|
||||
}
|
||||
return stage+"失败:"+reason;
|
||||
}
|
||||
@Override public Result execute(Command c, String action, String externalId, String restoreId) {
|
||||
String expected=RealtimeCollectionService.jobId(c.orgId(),c.taskId(),c.attempt());
|
||||
String name=RealtimeCollectionService.jobName(c.taskId(),c.attempt());
|
||||
try {
|
||||
if(c.actorId()<=0 || c.orgId()<=0 || c.spec()==null ||
|
||||
sources.find(new DataSourceAccessScope(c.actorId(),c.orgId()),c.spec().sourceId())==null)
|
||||
return unknown(expected,"源数据源不在当前授权范围");
|
||||
if(!expected.equals(externalId)) return unknown(expected,"外部作业身份不一致");
|
||||
if("RECREATE".equals(action)) {
|
||||
if(engine.absentFromEngine(expected))
|
||||
return new Result("ABSENT",expected,"已核实旧作业记录不存在,且旧作业不在运行或排队队列;历史执行结果不作推断",null,null,null);
|
||||
return unknown(expected,"未清理:旧作业仍在运行或排队、记录仍存在,或引擎查询失败,请核实后重试");
|
||||
}
|
||||
if("START".equals(action) || "RESUME".equals(action) || "RETRY".equals(action)) {
|
||||
if("RETRY".equals(action)) {
|
||||
String prior=RealtimeCollectionService.jobId(c.orgId(),c.taskId(),c.attempt()-1);
|
||||
var evidence=c.recovery();
|
||||
var old=engine.queryJob(prior);
|
||||
var checkpoint=engine.checkpoint(prior);
|
||||
if(c.attempt()<2 || evidence==null || !prior.equals(evidence.jobId()) || evidence.checkpointId()!=null ||
|
||||
!Set.of("FAILED","CANCELED").contains(evidence.status()) ||
|
||||
!prior.equals(old.jobId()) || !RealtimeCollectionService.jobName(c.taskId(),c.attempt()-1).equals(old.jobName()) ||
|
||||
!Set.of("FAILED","CANCELED").contains(old.status().name()) || checkpoint.completed() ||
|
||||
!"SEATUNNEL_CHECKPOINT_NOT_COMPLETED".equals(checkpoint.errorCode()))
|
||||
return new Result("REJECTED",expected,"未重试:需确认原作业已失败或停止且没有已完成检查点;请先同步状态,有检查点请使用检查并恢复",null,null,null);
|
||||
}
|
||||
DataSourceView s;
|
||||
try {s=source(c);} catch(RuntimeException ex) {
|
||||
return new Result("REJECTED",expected,"来源版本、目标配置或受管凭据已变化,请重新校验",null,null,null);
|
||||
}
|
||||
var check=check(c);
|
||||
if(!check.ready() || !Objects.equals(check.fingerprint(),c.fingerprint()))
|
||||
return new Result("REJECTED",expected,check.ready()?"配置或表结构已变化,禁止沿用原断点":check.summary(),null,null,null);
|
||||
if("RESUME".equals(action)) {
|
||||
String prior=expected;
|
||||
var old=engine.queryJob(prior);
|
||||
if(!validRecovery(c,restoreId) || !engine.recoverableStreamingIdentity(old,expected,name))
|
||||
return new Result("REJECTED",expected,"恢复证据不完整、作业仍在运行或引擎不可查询;未启动新采集",null,null,null);
|
||||
}
|
||||
var job=executionJob(c,s);
|
||||
if("RESUME".equals(action))job.withObject("env").put("aixun.restore.checkpoint",
|
||||
c.recovery().checkpointId()==null?0:Long.parseLong(c.recovery().checkpointId()));
|
||||
var result=engine.submitStreaming(RealtimeCollectionService.identity(c.orgId(),c.taskId(),c.attempt()),
|
||||
c.fingerprint(),name,job,restoreId);
|
||||
if("CDC_CHECKPOINT_UNAVAILABLE".equals(result.errorCode()))return new Result("REJECTED",expected,result.errorSummary(),null,null,null);
|
||||
return new Result(result.status().name(),expected,result.errorSummary(),null,null,null);
|
||||
}
|
||||
var info="STOP".equals(action)?engine.stopStreaming(expected,name):engine.queryJob(expected);
|
||||
if(!expected.equals(info.jobId()) || !name.equals(info.jobName())) return unknown(expected,statusQueryFailure(info,expected));
|
||||
var cp=engine.checkpoint(expected);
|
||||
return new Result(info.status().name(),expected,info.errorSummary(),cp.completed()?cp.checkpointId():null,
|
||||
info.sourceCount(),info.targetCount());
|
||||
} catch(Exception e) { return unknown(expected,"外部执行结果待确认,请刷新状态,勿重复启动"); }
|
||||
}
|
||||
static String statusQueryFailure(cn.aixunkeji.datagov.integration.m2.SeaTunnelAdapter.JobInfoResult info,String expected) {
|
||||
if(expected.equals(info.jobId()) && info.jobName()==null && info.errorSummary()!=null)
|
||||
return info.errorSummary();
|
||||
return "返回的作业身份与当前任务不一致,无法确认状态;请检查采集引擎配置,勿重复启动";
|
||||
}
|
||||
private static Connection connect(String host,int port,String database,String user,String password) throws SQLException {
|
||||
return DriverManager.getConnection("jdbc:mysql://"+host+":"+port+"/"+database+
|
||||
"?connectTimeout=5000&socketTimeout=15000&useSSL=false&allowPublicKeyRetrieval=true",user,password);
|
||||
}
|
||||
private tools.jackson.databind.node.ObjectNode executionJob(Command c,DataSourceView s) throws SQLException {
|
||||
if(c.spec().cdcChannel()==null)return NativeCdcSource.job(config(c,s),s,c.spec());
|
||||
try(var db=connections.open(s,new DataSourceAccessScope(c.actorId(),c.orgId()));var st=db.createStatement()){
|
||||
st.setQueryTimeout(15);
|
||||
try(var rs=st.executeQuery("SELECT * FROM "+NativeCdcSource.table(s,c.spec())+" WHERE 1=0")){
|
||||
return relays.job(c,config(c,s),rs.getMetaData());
|
||||
}
|
||||
}
|
||||
}
|
||||
static boolean validRecovery(Command c,String restoreId) {
|
||||
var p=c.recovery();String id=RealtimeCollectionService.jobId(c.orgId(),c.taskId(),c.attempt());
|
||||
return p!=null && id.equals(restoreId) && id.equals(p.jobId()) &&
|
||||
(Set.of("CANCELED","FAILED").contains(p.status()) && p.checkpointId()!=null || "UNKNOWN".equals(p.status())) &&
|
||||
(p.checkpointId()==null || p.checkpointId().matches("[0-9]{1,18}")) &&
|
||||
c.fingerprint()!=null && c.fingerprint().matches("[a-f0-9]{64}");
|
||||
}
|
||||
private static Check rejected(String text) { return new Check(false,text,null,List.of(),List.of()); }
|
||||
private static Result unknown(String id,String text) { return new Result("UNKNOWN",id,text,null,null,null); }
|
||||
private static String hash(String text) throws Exception {return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package cn.aixunkeji.datagov.integration.batchingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.*;
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.*;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Fixed CDC Unique Key DDL only. Never alters, drops or truncates an existing table. */
|
||||
final class RealtimeTargetTable {
|
||||
record Field(String name,String type,boolean nullable) { }
|
||||
private static final Pattern TYPE=Pattern.compile("([A-Z0-9]+)(?:\\((\\d+)(?:,(\\d+))?\\))?");
|
||||
private RealtimeTargetTable() { }
|
||||
|
||||
static List<Field> fields(ResultSetMetaData md,String vendor) throws SQLException {
|
||||
var fields=new ArrayList<Field>();
|
||||
for(int i=1;i<=md.getColumnCount();i++) {
|
||||
String name=md.getColumnName(i);quote(name);
|
||||
if(md.isNullable(i)==ResultSetMetaData.columnNullableUnknown)
|
||||
throw new IllegalArgumentException("字段“"+name+"”的可空性无法确认,不能准备目标表");
|
||||
int precision=md.getPrecision(i),scale=md.getScale(i);
|
||||
String nativeType=md.getColumnTypeName(i);
|
||||
String jdbc;try{jdbc=JDBCType.valueOf(md.getColumnType(i)).getName();}catch(IllegalArgumentException ex){jdbc="OTHER";}
|
||||
Long bytes=Set.of(Types.CHAR,Types.VARCHAR,Types.NCHAR,Types.NVARCHAR).contains(md.getColumnType(i))?precision*4L:null;
|
||||
var column=new Column(name,jdbc,i,md.isNullable(i)==ResultSetMetaData.columnNullable,false,nativeType,precision,scale,bytes);
|
||||
column=switch(vendor){case "ORACLE"->OracleBatchTypes.mark(column);case "DAMENG"->DamengBatchTypes.mark(column);
|
||||
case "KINGBASE"->KingbaseBatchTypes.mark(column);case "SQLSERVER"->SqlServerBatchTypes.mark(column);default->column;};
|
||||
var mapped=DataSourceObjects.mysqlTargetType(column,TargetEngine.DORIS);
|
||||
if(!mapped.supported())throw new IllegalArgumentException(mapped.errorSummary());
|
||||
fields.add(new Field(name,mapped.targetType(),column.nullable()));
|
||||
}
|
||||
if(fields.isEmpty() || fields.stream().map(f->f.name().toLowerCase(Locale.ROOT)).distinct().count()!=fields.size())
|
||||
throw new IllegalArgumentException("源字段为空或存在重名,无法准备目标表");
|
||||
return List.copyOf(fields);
|
||||
}
|
||||
|
||||
static String ddl(String database,String table,List<Field> fields,List<String> keys) {
|
||||
if(keys.isEmpty() || new HashSet<>(keys).size()!=keys.size())throw new IllegalArgumentException("源表必须有明确的主键");
|
||||
var byName=fields.stream().collect(Collectors.toMap(Field::name,f->f));
|
||||
var ordered=new ArrayList<Field>();
|
||||
for(String key:keys) {
|
||||
var field=byName.get(key);
|
||||
if(field==null || Set.of("FLOAT","DOUBLE","STRING","BOOLEAN").contains(base(field.type())))
|
||||
throw new IllegalArgumentException("主键字段“"+key+"”无法安全用作 Doris Unique Key");
|
||||
ordered.add(field);
|
||||
}
|
||||
fields.stream().filter(f->!keys.contains(f.name())).forEach(ordered::add);
|
||||
String columns=ordered.stream().map(f->quote(f.name())+" "+safeType(f.type())+
|
||||
(keys.contains(f.name()) || !f.nullable()?" NOT NULL":" NULL")).collect(Collectors.joining(", "));
|
||||
String keySql=keys.stream().map(RealtimeTargetTable::quote).collect(Collectors.joining(", "));
|
||||
return "CREATE TABLE "+quote(database)+"."+quote(table)+" ("+columns+") ENGINE=OLAP UNIQUE KEY ("+keySql+
|
||||
") DISTRIBUTED BY HASH ("+quote(keys.getFirst())+") BUCKETS 10 PROPERTIES (\"replication_num\"=\"1\", \"enable_unique_key_merge_on_write\"=\"true\")";
|
||||
}
|
||||
|
||||
static String definition(Statement st,String object) throws SQLException {
|
||||
try(var rs=st.executeQuery("SHOW CREATE TABLE "+object)) {
|
||||
if(!rs.next())throw new SQLException("Table definition unavailable","HY000");
|
||||
return rs.getString(2);
|
||||
} catch(SQLException ex) {if(missing(ex))return null;throw ex;}
|
||||
}
|
||||
static boolean missing(SQLException ex) {
|
||||
String message=Objects.toString(ex.getMessage(),"").toLowerCase(Locale.ROOT);
|
||||
return ex.getErrorCode()==1146 || "42S02".equals(ex.getSQLState()) || ex.getErrorCode()==1105 &&
|
||||
(message.contains("unknown table") || message.matches("(?s).*table[^\\n]*(does not exist|doesn't exist|not exist|not found).*"));
|
||||
}
|
||||
static String prepare(Statement st,String database,String table,List<Field> fields,List<String> keys,boolean create) throws SQLException {
|
||||
String object=quote(database)+"."+quote(table),definition=definition(st,object);
|
||||
if(definition!=null)return definition;
|
||||
if(!create)throw new IllegalArgumentException("目标表不存在,请先点击“检查并准备”;启动和恢复不会自动建表");
|
||||
String ddl=ddl(database,table,fields,keys);
|
||||
try{st.execute(ddl);}catch(SQLException ex) {
|
||||
// A timeout or concurrent creator can leave the table present. Read back once; never blindly repeat DDL.
|
||||
try{definition=definition(st,object);}catch(SQLException readback){throw ex;}
|
||||
if(definition==null)throw ex;
|
||||
return definition;
|
||||
}
|
||||
definition=definition(st,object);
|
||||
if(definition==null)throw new IllegalArgumentException("建表结果尚未确认,请再次检查并准备;不会重复覆盖目标表");
|
||||
return definition;
|
||||
}
|
||||
static void compatible(List<Field> expected,ResultSetMetaData actual) throws SQLException {
|
||||
if(actual.getColumnCount()!=expected.size())throw new IllegalArgumentException("目标表字段数量不一致:源表 "+expected.size()+",目标表 "+actual.getColumnCount()+";未修改已有表");
|
||||
Map<String,Integer> indexes=new HashMap<>();
|
||||
for(int i=1;i<=actual.getColumnCount();i++)if(indexes.put(actual.getColumnName(i),i)!=null)
|
||||
throw new IllegalArgumentException("目标表存在重名字段");
|
||||
for(var field:expected) {
|
||||
Integer i=indexes.get(field.name());
|
||||
if(i==null)throw new IllegalArgumentException("目标表缺少字段“"+field.name()+"”;未修改已有表");
|
||||
String observed=targetType(actual,i);
|
||||
if(!fits(field.type(),observed))throw new IllegalArgumentException("字段“"+field.name()+"”类型不兼容:需要 "+field.type()+",目标为 "+observed+";未修改已有表");
|
||||
if(actual.isNullable(i)==ResultSetMetaData.columnNullableUnknown || field.nullable() && actual.isNullable(i)!=ResultSetMetaData.columnNullable)
|
||||
throw new IllegalArgumentException("字段“"+field.name()+"”的可空性不兼容;未修改已有表");
|
||||
}
|
||||
}
|
||||
static boolean fits(String expected,String actual) {
|
||||
var a=TYPE.matcher(expected);var b=TYPE.matcher(actual);if(!a.matches()||!b.matches())return false;
|
||||
String x=a.group(1),y=b.group(1);int p=number(a.group(2)),s=number(a.group(3)),q=number(b.group(2)),t=number(b.group(3));
|
||||
var integers=List.of("TINYINT","SMALLINT","INT","BIGINT","LARGEINT");
|
||||
if(integers.contains(x)&&integers.contains(y))return integers.indexOf(y)>=integers.indexOf(x);
|
||||
if(Set.of("CHAR","VARCHAR").contains(x))return y.equals("STRING") || Set.of("CHAR","VARCHAR").contains(y)&&q>=p;
|
||||
if(x.equals("FLOAT")&&y.equals("DOUBLE"))return true;
|
||||
if(x.equals("DECIMAL")&&integers.contains(y))return s==0 && p<=List.of(2,4,9,18,38).get(integers.indexOf(y));
|
||||
if(!x.equals(y))return false;
|
||||
if(x.equals("DECIMAL"))return t>=s && q-t>=p-s;
|
||||
if(x.equals("DATETIME"))return q>=p;
|
||||
return true;
|
||||
}
|
||||
private static String targetType(ResultSetMetaData md,int i)throws SQLException {
|
||||
String raw=md.getColumnTypeName(i).toUpperCase(Locale.ROOT).replace(" ","");
|
||||
String base=raw.replaceAll("\\(.*","");
|
||||
base=switch(base){case "DECIMALV2","DECIMALV3","NUMERIC"->"DECIMAL";case "DATETIMEV2","TIMESTAMP"->"DATETIME";case "DATEV2"->"DATE";case "INTEGER"->"INT";case "BOOL","BIT"->"BOOLEAN";case "TEXT","LONGTEXT"->"STRING";default->base;};
|
||||
if(Set.of("CHAR","VARCHAR").contains(base))return base+"("+md.getPrecision(i)+")";
|
||||
if(base.equals("DECIMAL"))return base+"("+md.getPrecision(i)+","+md.getScale(i)+")";
|
||||
if(base.equals("DATETIME"))return base+"("+md.getScale(i)+")";
|
||||
return base;
|
||||
}
|
||||
private static int number(String value){return value==null?0:Integer.parseInt(value);}
|
||||
private static String base(String value){return value.replaceAll("\\(.*","");}
|
||||
private static String safeType(String value){if(!TYPE.matcher(value).matches())throw new IllegalArgumentException("不支持的目标字段类型");return value;}
|
||||
static String quote(String value){if(value==null||!value.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))throw new IllegalArgumentException("库表或字段名称格式不支持");return "`"+value+"`";}
|
||||
}
|
||||
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
在新工单中引用
屏蔽一个用户