比较提交
5
次代码提交
CDC-Collect
...
main
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
|
|
c6470aaf3c | ||
|
|
6c1febd22b | ||
|
|
32a3242a46 | ||
|
|
4d8c05e765 | ||
|
|
c5760c74eb |
+16
@@ -8,6 +8,22 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
# Generated packages and build outputs (existing tracked dependencies stay tracked).
|
||||
dist/
|
||||
node_modules/
|
||||
coverage/
|
||||
*.class
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
/deliverables/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
######################################################################
|
||||
# IDE
|
||||
|
||||
|
||||
+10
-1
@@ -28,10 +28,19 @@ 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) {
|
||||
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());
|
||||
}
|
||||
public DraftItem(long sourceId, long sourceVersion, String sourceName, String sourceDatabase,
|
||||
String sourceTable, String targetTable, String sourceFingerprint,
|
||||
List<ColumnDefinition> columns, List<BatchFieldMappingCommand> mappings, String errorSummary) {
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
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 { }
|
||||
}
|
||||
+6
-1
@@ -10,8 +10,13 @@ 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) implements Serializable {
|
||||
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);
|
||||
}
|
||||
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");
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
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,6 +10,9 @@ 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,6 +97,10 @@ 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);
|
||||
|
||||
+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").contains(businessOwner)) throw invalid();
|
||||
if (!java.util.Set.of("dataproduct", "governance", "dataops", "integration").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
@@ -0,0 +1,40 @@
|
||||
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");}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cn.aixunkeji.common.core.enums;
|
||||
|
||||
/** Platform storage only; external connector dialects are independent. */
|
||||
public enum PlatformDatabaseDialect {
|
||||
DAMENG, MYSQL;
|
||||
|
||||
public String sql(String dameng, String mysql) {
|
||||
return this == MYSQL ? mysql : dameng;
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,10 @@
|
||||
<description>DataGov internal maintenance scheduling and MySQL lease-lock foundation</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
||||
+15
-2
@@ -8,25 +8,38 @@ import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/** MySQL 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;
|
||||
|
||||
|
||||
private static final Instant INITIAL_LEASE_EXPIRY = Instant.parse("1970-01-01T00:00:01Z");
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public JdbcMaintenanceLeaseRepository(JdbcTemplate jdbcTemplate) {
|
||||
this(jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);
|
||||
}
|
||||
|
||||
public JdbcMaintenanceLeaseRepository(JdbcTemplate jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.databaseDialect = java.util.Objects.requireNonNull(databaseDialect);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean tryAcquire(MaintenanceLeaseRequest request) {
|
||||
jdbcTemplate.update(
|
||||
"""
|
||||
databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_maintenance_lease) */ INTO dg_maintenance_lease(
|
||||
lease_id, job_name, job_kind, lease_until, last_outcome,
|
||||
attempt_no, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, 'IDLE', 0, ?, ?, '0', 0)
|
||||
|
||||
""",
|
||||
""", """
|
||||
INSERT IGNORE INTO dg_maintenance_lease(
|
||||
lease_id, job_name, job_kind, lease_until, last_outcome,
|
||||
attempt_no, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, 'IDLE', 0, ?, ?, '0', 0)
|
||||
|
||||
"""),
|
||||
request.leaseId(), request.jobName(), request.jobKind().name(), timestamp(INITIAL_LEASE_EXPIRY),
|
||||
timestamp(request.acquiredAt()), timestamp(request.acquiredAt())
|
||||
);
|
||||
|
||||
@@ -49,8 +49,11 @@
|
||||
<version>${dynamic-ds.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Platform database. Reuse the pinned driver already used by Integration;
|
||||
target Pack89 compatibility must be verified against a real server. -->
|
||||
<!-- Both platform drivers ship in the same artifact; selection follows the JDBC URL. -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.dameng</groupId>
|
||||
<artifactId>DmJdbcDriver18</artifactId>
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package cn.aixunkeji.common.mybatis.config;
|
||||
|
||||
import cn.aixunkeji.common.core.enums.PlatformDatabaseDialect;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
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
|
||||
public PlatformDatabaseDialect platformDatabaseDialect(DataSource dataSource) throws SQLException {
|
||||
try (var connection = dataSource.getConnection()) {
|
||||
return PlatformDatabaseDialect.fromProduct(connection.getMetaData().getDatabaseProductName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -1 +1,2 @@
|
||||
cn.aixunkeji.common.mybatis.config.MybatisPlusConfiguration
|
||||
cn.aixunkeji.common.mybatis.config.PlatformDatabaseConfiguration
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package cn.aixunkeji.common.mybatis.config;
|
||||
|
||||
import cn.aixunkeji.common.core.enums.PlatformDatabaseDialect;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DatabaseMetaData;
|
||||
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 {
|
||||
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);
|
||||
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");
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -33,11 +33,11 @@ public final class AlertEventMaintenance implements AutoCloseable {
|
||||
Duration.ofMinutes(5)
|
||||
);
|
||||
|
||||
public AlertEventMaintenance(AlertEventService service, JdbcTemplate jdbcTemplate) {
|
||||
public AlertEventMaintenance(AlertEventService service, JdbcTemplate jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.service = service;
|
||||
this.runner = new MaintenanceJobRunner(
|
||||
"aixun-dataops-alert-event",
|
||||
new JdbcMaintenanceLeaseRepository(jdbcTemplate),
|
||||
new JdbcMaintenanceLeaseRepository(jdbcTemplate, databaseDialect),
|
||||
clock
|
||||
);
|
||||
}
|
||||
|
||||
+12
-2
@@ -32,6 +32,9 @@ import java.util.Objects;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class BatchIngestionRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String TASK_COLUMNS = """
|
||||
task_id, definition_id, current_snapshot_id, task_code, task_name, org_scope_id,
|
||||
@@ -1004,14 +1007,21 @@ public class BatchIngestionRepository {
|
||||
if (task.currentSnapshotId() != parent.snapshotId() || task.status() != BatchIngestionStatus.FAILED)
|
||||
throw BatchIngestionException.conflict("当前任务已有新运行或修订,不能续传旧运行");
|
||||
long checkpointRecordId = IdGeneratorUtil.nextLongId();
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(ops_batch_checkpoint) */ INTO ops_batch_checkpoint(
|
||||
checkpoint_record_id, task_id, run_id, request_record_id, external_job_id,
|
||||
checkpoint_id, checkpoint_sequence, checkpoint_status, evidence_at, evidence_ref,
|
||||
create_dept, create_by, create_time, update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, 'COMPLETED', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
|
||||
""", checkpointRecordId, parent.taskId(), parent.runId(),
|
||||
""", """
|
||||
INSERT IGNORE INTO ops_batch_checkpoint(
|
||||
checkpoint_record_id, task_id, run_id, request_record_id, external_job_id,
|
||||
checkpoint_id, checkpoint_sequence, checkpoint_status, evidence_at, evidence_ref,
|
||||
create_dept, create_by, create_time, update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, 'COMPLETED', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
|
||||
"""), checkpointRecordId, parent.taskId(), parent.runId(),
|
||||
reservation.record().requestRecordId(), parent.externalJobId(), evidence.checkpointId(),
|
||||
evidence.checkpointSequence(), timestamp(evidence.evidenceAt()), safeEvidenceRef(evidence.evidenceRef()),
|
||||
actor.orgScopeId(), actor.actorId(), actor.actorId());
|
||||
|
||||
+2
-2
@@ -28,9 +28,9 @@ public class UnifiedIngestionReconciliationMaintenance implements AutoCloseable
|
||||
1761500000000000111L, NAME, MaintenanceJobKind.STATUS_RECONCILIATION,
|
||||
Duration.ofMinutes(10), Duration.ofMinutes(11));
|
||||
|
||||
public UnifiedIngestionReconciliationMaintenance(UnifiedIngestionCommandWorker worker, JdbcTemplate jdbc) {
|
||||
public UnifiedIngestionReconciliationMaintenance(UnifiedIngestionCommandWorker worker, JdbcTemplate jdbc, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.worker = worker;
|
||||
runner = new MaintenanceJobRunner("aixun-dataops-ingestion", new JdbcMaintenanceLeaseRepository(jdbc), clock);
|
||||
runner = new MaintenanceJobRunner("aixun-dataops-ingestion", new JdbcMaintenanceLeaseRepository(jdbc, databaseDialect), clock);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${datagov.ingestion.observation-delay-ms:5000}")
|
||||
|
||||
+12
-3
@@ -211,9 +211,18 @@ 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<ColumnDefinition> columns = schema.columns().stream()
|
||||
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()
|
||||
.map(column -> BatchTargetTypePolicy.propose(column, targetEngine)).toList();
|
||||
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(schema.columns(),
|
||||
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(supported,
|
||||
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),
|
||||
@@ -222,7 +231,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()));
|
||||
schema.tableComment().value(), schema.tableComment().state().name(), List.copyOf(compatibility)));
|
||||
} 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(),
|
||||
|
||||
+5
-2
@@ -16,6 +16,9 @@ import static cn.aixunkeji.datagov.dataops.datasetpreparation.DatasetPreparation
|
||||
/** Only local database work inside these short transactions; callers do all RPC before/after. */
|
||||
@Repository
|
||||
public class DatasetPreparationJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper mapper;
|
||||
private final TransactionTemplate transaction;
|
||||
@@ -78,7 +81,7 @@ public class DatasetPreparationJdbcRepository {
|
||||
}
|
||||
View command(Actor a,String op,String object,Write w,String payload,Supplier<View> databaseWork) {
|
||||
return local(()->{
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_dataset_preparation_command) */ INTO dev_dataset_preparation_command (organization_id,department_id,actor_id,operation,object_id,idempotency_key,payload_sha,created_at) "
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_dataset_preparation_command) */ INTO dev_dataset_preparation_command (organization_id,department_id,actor_id,operation,object_id,idempotency_key,payload_sha,created_at) ", "INSERT IGNORE INTO dev_dataset_preparation_command (organization_id,department_id,actor_id,operation,object_id,idempotency_key,payload_sha,created_at) ")
|
||||
+"VALUES (?,?,?,?,?,?,UNHEX(?),CURRENT_TIMESTAMP(6)) ",
|
||||
a.organizationId(),a.departmentId(),a.id(),op,object,w.idempotencyKey(),payload);
|
||||
CommandRow row=commands(a,op,object,w.idempotencyKey(),true).getFirst();
|
||||
@@ -122,7 +125,7 @@ public class DatasetPreparationJdbcRepository {
|
||||
Artifact reserve(Actor a,Artifact f) {
|
||||
return local(()->{
|
||||
task(a,f.taskId(),true);
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_dataset_preparation_artifact) */ INTO dev_dataset_preparation_artifact (artifact_id,task_id,run_id,operation_key,row_version,artifact_json,updated_at) "
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_dataset_preparation_artifact) */ INTO dev_dataset_preparation_artifact (artifact_id,task_id,run_id,operation_key,row_version,artifact_json,updated_at) ", "INSERT IGNORE INTO dev_dataset_preparation_artifact (artifact_id,task_id,run_id,operation_key,row_version,artifact_json,updated_at) ")
|
||||
+"VALUES (?,?,?,?,?,?,CURRENT_TIMESTAMP(6)) ",f.id(),f.taskId(),f.runId(),f.operationKey(),f.rowVersion(),json(f));
|
||||
Artifact found=artifact(a,f.id());
|
||||
if(!found.target().equals(f.target()) || !found.operationKey().equals(f.operationKey()) || !found.runId().equals(f.runId())
|
||||
|
||||
+8
-2
@@ -8,6 +8,9 @@ import java.util.List;
|
||||
|
||||
@Repository
|
||||
public class OriginalFileRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
public OriginalFileRepository(JdbcTemplate jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; }
|
||||
@@ -22,10 +25,13 @@ public class OriginalFileRepository {
|
||||
Row reserve(FileIngestionActor a,String key,String name,long size,String sha,String mime) {
|
||||
String id=java.util.UUID.randomUUID().toString();
|
||||
String op=FileIngestionPolicy.sha256("original:"+a.orgScopeId()+":"+a.actorId()+":"+key);
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(ing_original_file) */ INTO ing_original_file(file_id,actor_id,org_scope_id,request_key,operation_key,original_name,byte_length,bytes_sha256,mime,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",id,a.actorId(),a.orgScopeId(),key,op,name,size,sha,mime,a.orgScopeId(),a.actorId(),a.actorId());
|
||||
""", """
|
||||
INSERT IGNORE INTO ing_original_file(file_id,actor_id,org_scope_id,request_key,operation_key,original_name,byte_length,bytes_sha256,mime,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
"""),id,a.actorId(),a.orgScopeId(),key,op,name,size,sha,mime,a.orgScopeId(),a.actorId(),a.actorId());
|
||||
Row row=jdbc.query("SELECT * FROM ing_original_file WHERE actor_id=? AND org_scope_id=? AND request_key=? AND del_flag='0'",
|
||||
(r,n)->map(r),a.actorId(),a.orgScopeId(),key).getFirst();
|
||||
if(!row.name().equals(name)||row.size()!=size||!row.sha().equals(sha)||!row.mime().equals(mime))
|
||||
|
||||
+2
-2
@@ -30,11 +30,11 @@ public class GoldenReconciliationMaintenance implements AutoCloseable {
|
||||
public GoldenReconciliationMaintenance(
|
||||
GoldenRunRepository repository,
|
||||
GoldenRunWorker worker,
|
||||
JdbcTemplate jdbcTemplate
|
||||
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), clock);
|
||||
this.runner = new MaintenanceJobRunner("aixun-dataops-m2", new JdbcMaintenanceLeaseRepository(jdbcTemplate, databaseDialect), clock);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${datagov.m2.reconciliation-delay-ms:15000}")
|
||||
|
||||
+6
-2
@@ -31,6 +31,9 @@ import java.util.function.Function;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class LakehouseLayerRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String LAYER_COLUMNS = """
|
||||
layer_id, layer_name, layer_type, org_scope_id, project_id, storage_resource_id, storage_space_id,
|
||||
@@ -380,14 +383,15 @@ public class LakehouseLayerRepository {
|
||||
WHERE layer_id=? AND del_flag='0'
|
||||
""", actor.actorId(), layerId);
|
||||
for (Long upstreamLayerId : upstreamLayerIds) {
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO store_layer_dependency t
|
||||
USING (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
|
||||
ON ((t.dependency_id=s.dependency_id) OR (t.layer_id=s.layer_id AND t.upstream_layer_id=s.upstream_layer_id))
|
||||
WHEN MATCHED THEN UPDATE SET t.del_flag='0', t.update_by=s.dg_update_arg_0, t.update_time=NOW(), t.version=t.version+1
|
||||
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)
|
||||
""", 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, false);
|
||||
return resolve(actorId, orgId, layerId, LoginHelper.isSuperAdmin(actorId));
|
||||
}
|
||||
|
||||
private Resolution resolve(long actorId, long orgId, long layerId, boolean unrestricted) {
|
||||
|
||||
+33
-7
@@ -36,6 +36,9 @@ import java.util.function.Supplier;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class SchedulingJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String DEFINITION_COLUMNS = """
|
||||
schedule_id, schedule_name, schedule_description, org_id, project_id,
|
||||
@@ -354,7 +357,7 @@ class SchedulingJdbcRepository {
|
||||
SchedulingPolicyReceipt.create(jdbcTemplate,policy,actor,definition,runId,businessDateFrom,businessDateTo);
|
||||
if (!selected) jdbcTemplate.update("UPDATE dev_schedule_run_request SET run_status='SKIPPED',source_status='CALENDAR_SKIPPED',error_code='CALENDAR_SKIPPED',error_summary='所选业务日期均不在发布日历内,未发起执行',last_sync_at=NOW(6) WHERE run_id=?",runId);
|
||||
else SchedulingSignalStore.enqueueWatch(jdbcTemplate, actor, runId,
|
||||
definition.summary().scheduleId(), definition.summary().currentSnapshotId());
|
||||
definition.summary().scheduleId(), definition.summary().currentSnapshotId(), databaseDialect);
|
||||
}
|
||||
return new RunReservation(requireRun(actor, runId), true);
|
||||
});
|
||||
@@ -592,7 +595,7 @@ class SchedulingJdbcRepository {
|
||||
actor.actorId(), runId, actor.orgId());
|
||||
requireChanged(changed);
|
||||
if (hasExternalEvidence(outcome)) {
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO dev_schedule_external_mapping t
|
||||
USING (SELECT ? AS mapping_id, schedule_id, snapshot_id, run_id,
|
||||
? AS external_project_code, ? AS external_definition_code,
|
||||
@@ -613,7 +616,21 @@ class SchedulingJdbcRepository {
|
||||
VALUES(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,
|
||||
s.org_id,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", IdGeneratorUtil.nextLongId(), outcome.externalProjectCode(), outcome.externalDefinitionCode(),
|
||||
""", """
|
||||
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,
|
||||
s.org_id,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS mapping_id, schedule_id, snapshot_id, run_id,
|
||||
? AS external_project_code, ? AS external_definition_code,
|
||||
? AS external_instance_id, ? AS source_status, ? AS last_sync_at,
|
||||
org_id, ? AS create_by, NOW() AS create_time, ? AS update_by,
|
||||
NOW() AS update_time, '0' AS del_flag, 0 AS version
|
||||
FROM dev_schedule_run_request WHERE run_id=? AND org_id=? AND del_flag='0') s WHERE TRUE ON DUPLICATE KEY UPDATE external_project_code=s.external_project_code,
|
||||
external_definition_code=s.external_definition_code,
|
||||
external_instance_id=s.external_instance_id, source_status=s.source_status,
|
||||
last_sync_at=s.last_sync_at, update_by=s.update_by,
|
||||
update_time=NOW(), version=dev_schedule_external_mapping.version+1"""), IdGeneratorUtil.nextLongId(), outcome.externalProjectCode(), outcome.externalDefinitionCode(),
|
||||
outcome.externalInstanceId(), sourceStatus, Timestamp.valueOf(observedAt), actor.actorId(),
|
||||
actor.actorId(), runId, actor.orgId());
|
||||
}
|
||||
@@ -637,7 +654,7 @@ class SchedulingJdbcRepository {
|
||||
? scope.defaultBusinessDate(observedAt.toLocalDate()) : instance.businessDate();
|
||||
RunStatus instanceStatus = stateStatus(instance.state());
|
||||
LocalDateTime instanceObservedAt = instance.observedAt() == null ? observedAt : instance.observedAt();
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO dev_schedule_external_instance_evidence t
|
||||
USING (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
|
||||
ON ((t.evidence_id=s.evidence_id) OR (t.run_id=s.run_id AND t.external_instance_id=s.external_instance_id AND t.del_flag=s.del_flag))
|
||||
@@ -647,7 +664,11 @@ class SchedulingJdbcRepository {
|
||||
t.update_by=s.update_by, t.update_time=NOW(), t.version=t.version+1
|
||||
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)
|
||||
""", IdGeneratorUtil.nextLongId(), runId, scope.scheduleId(), scope.snapshotId(),
|
||||
""", """
|
||||
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(),
|
||||
outcome.externalProjectCode(), outcome.externalDefinitionCode(), instance.externalInstanceId(),
|
||||
Date.valueOf(businessDate), truncate(instance.sourceStatus(), 64), instanceStatus.name(),
|
||||
truncate(instance.evidenceRef(), 512), Timestamp.valueOf(instanceObservedAt), actor.orgId(), actor.orgId(),
|
||||
@@ -663,7 +684,7 @@ class SchedulingJdbcRepository {
|
||||
LocalDate businessDate = item.businessDate() == null
|
||||
? scope.defaultBusinessDate(observedAt.toLocalDate()) : item.businessDate();
|
||||
LocalDateTime nodeObservedAt = item.observedAt() == null ? observedAt : item.observedAt();
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO dev_schedule_node_execution_evidence t
|
||||
USING (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
|
||||
ON ((t.evidence_id=s.evidence_id) OR (t.run_id=s.run_id AND t.node_key=s.node_key AND t.evidence_kind=s.evidence_kind AND t.external_instance_id=s.external_instance_id AND t.external_task_instance_id=s.external_task_instance_id AND t.business_date=s.business_date AND t.del_flag=s.del_flag))
|
||||
@@ -674,7 +695,12 @@ class SchedulingJdbcRepository {
|
||||
t.update_time=NOW(), t.version=t.version+1
|
||||
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)
|
||||
""", IdGeneratorUtil.nextLongId(), runId, scope.scheduleId(), scope.snapshotId(), item.nodeKey(),
|
||||
""", """
|
||||
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,
|
||||
update_time=NOW(), version=dev_schedule_node_execution_evidence.version+1"""), IdGeneratorUtil.nextLongId(), runId, scope.scheduleId(), scope.snapshotId(), item.nodeKey(),
|
||||
node.nodeType().name(), node.referenceId(), nullToEmpty(outcome.externalProjectCode()),
|
||||
nullToEmpty(outcome.externalDefinitionCode()), nullToEmpty(item.externalInstanceId()),
|
||||
nullToEmpty(item.externalTaskCode()), nullToEmpty(item.externalTaskInstanceId()),
|
||||
|
||||
+24
-5
@@ -18,6 +18,9 @@ import java.util.List;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class SchedulingSignalStore {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
|
||||
@@ -27,15 +30,23 @@ 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) {
|
||||
jdbc.update("""
|
||||
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 (
|
||||
SELECT 1 FROM dev_schedule_trigger_registration WHERE source_schedule_id=? AND source_snapshot_id=?
|
||||
AND org_id=? AND actor_id=? AND desired_enabled=1 AND current_slot=1
|
||||
AND registration_state='ONLINE' AND del_flag='0')
|
||||
|
||||
""", runId, scheduleId, snapshotId, actor.orgId(), actor.actorId(), actor.orgId(), actor.actorId(), actor.actorId(),
|
||||
""", """
|
||||
INSERT IGNORE 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 (
|
||||
SELECT 1 FROM dev_schedule_trigger_registration WHERE source_schedule_id=? AND source_snapshot_id=?
|
||||
AND org_id=? AND actor_id=? AND desired_enabled=1 AND current_slot=1
|
||||
AND registration_state='ONLINE' AND del_flag='0')
|
||||
|
||||
"""), runId, scheduleId, snapshotId, actor.orgId(), actor.actorId(), actor.orgId(), actor.actorId(), actor.actorId(),
|
||||
scheduleId, snapshotId, actor.orgId(), actor.actorId());
|
||||
}
|
||||
|
||||
@@ -73,7 +84,7 @@ class SchedulingSignalStore {
|
||||
if (!successfulSourceWithCalendar(watch,run)) throw SchedulingDomainException.conflict("缺少可信成功实例证据");
|
||||
transactions.executeWithoutResult(status -> {
|
||||
for (long registration : registrations) for (var instance : run.externalInstances()) {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_schedule_trigger_signal) */ INTO dev_schedule_trigger_signal(signal_id,registration_id,source_run_id,source_instance_id,business_date,
|
||||
org_id,actor_id,create_dept,create_by,update_by)
|
||||
SELECT ?,?,?,?,?,?,?, ?,?,? FROM dev_schedule_trigger_registration t
|
||||
@@ -81,7 +92,15 @@ class SchedulingSignalStore {
|
||||
WHERE t.registration_id=? AND t.current_slot=1 AND t.desired_enabled=1 AND t.registration_state='ONLINE'
|
||||
AND t.source_schedule_id=? AND t.source_snapshot_id=? AND t.org_id=? AND t.actor_id=? AND t.del_flag='0'
|
||||
|
||||
""", IdGeneratorUtil.nextLongId(), registration, run.runId(), instance.externalInstanceId(), Date.valueOf(instance.businessDate()),
|
||||
""", """
|
||||
INSERT IGNORE INTO dev_schedule_trigger_signal(signal_id,registration_id,source_run_id,source_instance_id,business_date,
|
||||
org_id,actor_id,create_dept,create_by,update_by)
|
||||
SELECT ?,?,?,?,?,?,?, ?,?,? FROM dev_schedule_trigger_registration t
|
||||
JOIN dev_schedule_trigger_watch w ON w.run_id=? AND w.create_time>=t.activated_at
|
||||
WHERE t.registration_id=? AND t.current_slot=1 AND t.desired_enabled=1 AND t.registration_state='ONLINE'
|
||||
AND t.source_schedule_id=? AND t.source_snapshot_id=? AND t.org_id=? AND t.actor_id=? AND t.del_flag='0'
|
||||
|
||||
"""), IdGeneratorUtil.nextLongId(), registration, run.runId(), instance.externalInstanceId(), Date.valueOf(instance.businessDate()),
|
||||
watch.orgId(), watch.actorId(), watch.orgId(), watch.actorId(), watch.actorId(), watch.runId(), registration,
|
||||
watch.scheduleId(), watch.snapshotId(), watch.orgId(), watch.actorId());
|
||||
}
|
||||
|
||||
+4
-1
@@ -19,6 +19,9 @@ import java.util.function.Consumer;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class SchedulingTriggerStore {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final TransactionTemplate transactions;
|
||||
private final SchedulingPolicy policy;
|
||||
@@ -94,7 +97,7 @@ class SchedulingTriggerStore {
|
||||
// Check the exact persisted window after replay/serialization and before any write, including rebind.
|
||||
if (enabled && "CRON".equals(snapshot.triggerType())) validateCron.accept(new CronSchedule(cron, zone, start, end));
|
||||
if (enabled) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_schedule_trigger_scope) */ INTO dev_schedule_trigger_scope(org_id,actor_id) VALUES(?,?) ", actor.orgId(), actor.actorId());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_schedule_trigger_scope) */ INTO dev_schedule_trigger_scope(org_id,actor_id) VALUES(?,?) ", "INSERT IGNORE INTO dev_schedule_trigger_scope(org_id,actor_id) VALUES(?,?) "), actor.orgId(), actor.actorId());
|
||||
jdbc.queryForObject("SELECT org_id FROM dev_schedule_trigger_scope WHERE org_id=? AND actor_id=? FOR UPDATE", Long.class, actor.orgId(), actor.actorId());
|
||||
validateGraph.run();
|
||||
}
|
||||
|
||||
+2
-2
@@ -33,11 +33,11 @@ public class StorageCapacityMaintenance implements AutoCloseable {
|
||||
Duration.ofMinutes(5)
|
||||
);
|
||||
|
||||
public StorageCapacityMaintenance(StorageResourceService service, JdbcTemplate jdbcTemplate) {
|
||||
public StorageCapacityMaintenance(StorageResourceService service, JdbcTemplate jdbcTemplate, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect) {
|
||||
this.service = service;
|
||||
this.runner = new MaintenanceJobRunner(
|
||||
"aixun-dataops-storage",
|
||||
new JdbcMaintenanceLeaseRepository(jdbcTemplate),
|
||||
new JdbcMaintenanceLeaseRepository(jdbcTemplate, databaseDialect),
|
||||
clock
|
||||
);
|
||||
}
|
||||
|
||||
+2
-2
@@ -83,10 +83,10 @@ public class StorageResourceService {
|
||||
return detail(currentActor(), resourceId);
|
||||
}
|
||||
|
||||
/** Server-derived identity only; ingestion never inherits the administrator scope bypass. */
|
||||
/** Server-derived identity only; use the same owner policy for viewing and ingestion. */
|
||||
public StorageResourceDetailView detailForIngestion(long actorId, long orgId, long resourceId) {
|
||||
if (actorId <= 0 || orgId <= 0) throw new StorageScopeException();
|
||||
return detail(new StorageActor(actorId, orgId, false), resourceId);
|
||||
return detail(new StorageActor(actorId, orgId, LoginHelper.isSuperAdmin(actorId)), 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, false);
|
||||
return resolve(actorId, orgId, resourceId, spaceId, LoginHelper.isSuperAdmin(actorId));
|
||||
}
|
||||
|
||||
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, false);
|
||||
return resolveObject(actorId, orgId, resourceId, externalObjectId, LoginHelper.isSuperAdmin(actorId));
|
||||
}
|
||||
|
||||
private ObjectResolution resolveObject(long actorId, long orgId, long resourceId, String externalObjectId,
|
||||
|
||||
+8
-2
@@ -33,6 +33,9 @@ import java.util.function.Supplier;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class TransformationCleaningJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String PLAN_COLUMNS = """
|
||||
p.plan_id, p.series_id, p.parent_plan_id, p.revision_no, p.plan_name, p.org_id,
|
||||
@@ -694,10 +697,13 @@ class TransformationCleaningJdbcRepository {
|
||||
TransformationCleaningExecutionFacts frozen = null;
|
||||
if (action != RequestAction.PREVIEW) {
|
||||
if (target == null || binding == null) throw TransformationCleaningDomainException.conflict("执行目标证据缺失");
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dev_transformation_target_guard) */ INTO dev_transformation_target_guard(target_identity_sha256, create_dept, create_by, update_by) VALUES (?, ?, ?, ?)
|
||||
|
||||
""", target, actor.orgId(), actor.actorId(), actor.actorId());
|
||||
""", """
|
||||
INSERT IGNORE INTO dev_transformation_target_guard(target_identity_sha256, create_dept, create_by, update_by) VALUES (?, ?, ?, ?)
|
||||
|
||||
"""), target, actor.orgId(), actor.actorId(), actor.actorId());
|
||||
TargetState guard = jdbcTemplate.queryForObject("""
|
||||
SELECT execution_generation, owner_request_id FROM dev_transformation_target_guard
|
||||
WHERE target_identity_sha256=? FOR UPDATE
|
||||
|
||||
+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);
|
||||
assertThatThrownBy(()->BatchTargetTypePolicy.propose(source("BIT",8,0,null,false))).isInstanceOf(BatchIngestionException.class);
|
||||
assertThat(BatchTargetTypePolicy.propose(source("BIT",8,0,null,false)).type()).isEqualTo(ColumnType.STRING);
|
||||
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精度未知");
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS))
|
||||
.hasMessageContaining("value").hasMessageContaining("JSON");
|
||||
assertThat(BatchTargetTypePolicy.propose(source("JSON",null,null,null,true), TargetEngine.DORIS).type()).isEqualTo(ColumnType.STRING);
|
||||
}
|
||||
@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,39,65)) assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source("DECIMAL",precision,0,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
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);
|
||||
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"))
|
||||
assertThatThrownBy(() -> BatchTargetTypePolicy.propose(source(type,100,0,null,true))).isInstanceOf(BatchIngestionException.class);
|
||||
assertThat(BatchTargetTypePolicy.propose(source(type,100,0,null,true)).type()).isEqualTo(ColumnType.STRING);
|
||||
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);
|
||||
|
||||
+1
-1
@@ -108,7 +108,7 @@ public final class UnifiedIngestionCommandProcessHarness {
|
||||
var worker=context.getBean(UnifiedIngestionCommandWorker.class);
|
||||
worker.start(); // SmartLifecycle already started it; this must be idempotent.
|
||||
if("observe".equals(mode)){
|
||||
try(var maintenance=new UnifiedIngestionReconciliationMaintenance(worker,f.jdbc)){maintenance.reconcile();}
|
||||
try(var maintenance=new UnifiedIngestionReconciliationMaintenance(worker,f.jdbc,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.MYSQL)){maintenance.reconcile();}
|
||||
check("DONE".equals(f.jdbc.queryForObject("SELECT processing_phase FROM ing_ingestion_collection_item WHERE collection_id=?",String.class,id)));
|
||||
worker.stop();System.out.println("TASK123_OBSERVE_PASS");
|
||||
}else if("hold".equals(mode)){
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
+20
-5
@@ -16,27 +16,40 @@ 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 ingestionAlwaysUsesStrictOrganizationEvenForAdministratorId() {
|
||||
@Test void ingestionUsesSameTrustedAdministratorPolicyAsViewing() {
|
||||
when(repository.requireResource(any(), org.mockito.ArgumentMatchers.eq(30L)))
|
||||
.thenThrow(new StorageScopeException());
|
||||
assertThat(directory.resolveForIngestion(1, 20, 30, 40).status())
|
||||
assertThat(directory.resolveForIngestion(ADMIN, 20, 30, 40).status())
|
||||
.isEqualTo(StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE);
|
||||
assertThat(directory.resolveObjectForIngestion(1, 20, 30, "sales").status())
|
||||
assertThat(directory.resolveObjectForIngestion(ADMIN, 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(1);
|
||||
assertThat(actor.actorId()).isEqualTo(ADMIN);
|
||||
assertThat(actor.departmentId()).isEqualTo(20);
|
||||
assertThat(actor.unrestricted()).isFalse();
|
||||
assertThat(actor.unrestricted()).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
@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(
|
||||
@@ -53,5 +66,7 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
+4
-1
@@ -13,6 +13,9 @@ import static cn.aixunkeji.datagov.dataproduct.apidevelopment.ApiProductionApi.*
|
||||
|
||||
@Repository
|
||||
class ApiProductionLedger {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
ApiProductionLedger(JdbcTemplate jdbc){this.jdbc=jdbc;}
|
||||
record Stored(Receipt receipt,String requestSha256) { }
|
||||
@@ -28,7 +31,7 @@ class ApiProductionLedger {
|
||||
String key,String hash) {
|
||||
Stored existing=find(actor,key);if(existing!=null)return replay(existing,api.apiId(),hash);
|
||||
var now=now();var policy=gateway.traffic();
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_api_runtime_budget) */ INTO svc_api_runtime_budget(organization_id,department_id,api_id,gateway_snapshot_id,tokens,refill_time,quota_day,daily_requests,circuit_until,create_dept,create_by,create_time,update_by,update_time) VALUES(?,?,?,?,?,?,?,0,NULL,?,?,?,?,?)",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_api_runtime_budget) */ INTO svc_api_runtime_budget(organization_id,department_id,api_id,gateway_snapshot_id,tokens,refill_time,quota_day,daily_requests,circuit_until,create_dept,create_by,create_time,update_by,update_time) VALUES(?,?,?,?,?,?,?,0,NULL,?,?,?,?,?)", "INSERT IGNORE INTO svc_api_runtime_budget(organization_id,department_id,api_id,gateway_snapshot_id,tokens,refill_time,quota_day,daily_requests,circuit_until,create_dept,create_by,create_time,update_by,update_time) VALUES(?,?,?,?,?,?,?,0,NULL,?,?,?,?,?)"),
|
||||
actor.organizationId(),actor.departmentId(),api.apiId(),gateway.snapshotId(),policy.burstCapacity(),now,now.toLocalDate(),actor.departmentId(),actor.actorId(),now,actor.actorId(),now);
|
||||
var state=lock(actor,api.apiId());
|
||||
existing=find(actor,key);if(existing!=null)return replay(existing,api.apiId(),hash);
|
||||
|
||||
+5
-2
@@ -14,6 +14,9 @@ import static cn.aixunkeji.datagov.dataproduct.bi.BiExportJob.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class BiExportJobRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final JsonMapper json;private final TransactionTemplate transactions;
|
||||
Row get(String id){return jdbc.query("SELECT * FROM svc_bi_export_job WHERE job_id=?",this::map,id).stream().findFirst().orElseThrow(BiException::forbidden);}
|
||||
Row owned(String id,BiActorProvider.Actor actor){var r=get(id);if(r.actor()!=actor.id()||r.department()!=actor.department())throw BiException.forbidden();return r;}
|
||||
@@ -21,7 +24,7 @@ class BiExportJobRepository {
|
||||
Row completed(BiActorProvider.Actor actor,String key,String hash){var rows=jdbc.query("SELECT * FROM svc_bi_export_job WHERE actor_id=? AND department_id=? AND request_key=?",this::map,actor.id(),actor.department(),key);if(rows.isEmpty())return null;var row=rows.getFirst();if(!hash.equals(row.requestSha()))throw BiException.conflict("幂等键已用于其他导出请求");return row;}
|
||||
Row create(BiActorProvider.Actor actor,String key,String hash,Snapshot snapshot,String snapshotSha,String encoded){
|
||||
return transactions.execute(status->{
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_export_admission) */ INTO svc_bi_export_admission(actor_id,department_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?)",actor.id(),actor.department(),actor.department(),actor.id(),actor.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_export_admission) */ INTO svc_bi_export_admission(actor_id,department_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?)", "INSERT IGNORE INTO svc_bi_export_admission(actor_id,department_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?)"),actor.id(),actor.department(),actor.department(),actor.id(),actor.id());
|
||||
jdbc.queryForObject("SELECT actor_id FROM svc_bi_export_admission WHERE actor_id=? AND department_id=? FOR UPDATE",Long.class,actor.id(),actor.department());
|
||||
var previous=completed(actor,key,hash);if(previous!=null)return previous;
|
||||
Long count=jdbc.queryForObject("SELECT COUNT(*) FROM svc_bi_export_job WHERE actor_id=? AND department_id=? AND state IN ('QUEUED','RUNNING','UNKNOWN') AND expires_at>NOW(6)",Long.class,actor.id(),actor.department());
|
||||
@@ -37,7 +40,7 @@ class BiExportJobRepository {
|
||||
jdbc.update("UPDATE svc_bi_export_job SET state='RUNNING',lease_nonce=?,lease_fence=lease_fence+1,lease_until=TIMESTAMPADD(MINUTE,5,NOW(6)),attempts=attempts+1,version=version+1,update_time=NOW(6),safe_code=NULL WHERE job_id=?",UUID.randomUUID().toString(),row.id());return get(row.id());
|
||||
});}
|
||||
Row mutate(BiActorProvider.Actor actor,String key,String hash,java.util.function.Supplier<Row> change){return transactions.execute(status->{
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_export_mutation) */ INTO svc_bi_export_mutation(actor_id,department_id,request_key,request_sha256,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?)",actor.id(),actor.department(),key,hash,actor.department(),actor.id(),actor.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_export_mutation) */ INTO svc_bi_export_mutation(actor_id,department_id,request_key,request_sha256,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?)", "INSERT IGNORE INTO svc_bi_export_mutation(actor_id,department_id,request_key,request_sha256,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?)"),actor.id(),actor.department(),key,hash,actor.department(),actor.id(),actor.id());
|
||||
var found=jdbc.query("SELECT request_sha256,job_id FROM svc_bi_export_mutation WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,i)->new String[]{r.getString(1),r.getString(2)},actor.id(),actor.department(),key);
|
||||
if(found.size()!=1||!hash.equals(found.getFirst()[0]))throw BiException.conflict("幂等键已用于其他导出操作");
|
||||
if(found.getFirst()[1]!=null)return owned(found.getFirst()[1],actor);
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ final class BiManagement {
|
||||
static void available(ObjectView object){available(object,Instant.now());}
|
||||
static void available(ObjectView object,Instant now){if(object==null)throw BiException.forbidden();if("ARCHIVED".equals(object.status()))throw BiException.conflict("对象已归档");if(expired(object,now))throw BiException.conflict("对象已到期,请由Owner修改有效期并重新发布所需版本");}
|
||||
/** Stored timestamps are normalized UTC milliseconds; old missing metadata has no expiry. */
|
||||
static String activeSql(String state){String expiry="JSON_UNQUOTE(JSON_EXTRACT("+state+",'$.management.expiresAt'))";return "("+expiry+" IS NULL OR "+expiry+" IN ('','null') OR CAST(REPLACE(REPLACE("+expiry+",'T',' '),'Z','') AS DATETIME(3))>CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)))";}
|
||||
static String activeSql(String state, cn.aixunkeji.common.core.enums.PlatformDatabaseDialect dialect){String expiry="JSON_UNQUOTE(JSON_EXTRACT("+state+",'$.management.expiresAt'))";return "("+expiry+" IS NULL OR "+expiry+" IN ('','null') OR CAST(REPLACE(REPLACE("+expiry+",'T',' '),'Z','') AS DATETIME(3))>"+dialect.sql("CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3))","UTC_TIMESTAMP(3)")+")";}
|
||||
static String folderSql(String state){return "COALESCE(NULLIF(JSON_UNQUOTE(JSON_EXTRACT("+state+",'$.management.folderPath')),'null'),'')";}
|
||||
private BiManagement(){ }
|
||||
}
|
||||
|
||||
+5
-2
@@ -13,6 +13,9 @@ import static cn.aixunkeji.datagov.dataproduct.bi.BiApi.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class BiRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper mapper;
|
||||
|
||||
@@ -70,7 +73,7 @@ class BiRepository {
|
||||
jdbc.update("INSERT INTO svc_bi_version(object_id,object_version,state_json,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,CAST(? AS JSON),?,?,?,0,'0')",v.id(),v.version(),encode(v),a.department(),a.id(),a.id());
|
||||
}
|
||||
ObjectView idempotent(BiActorProvider.Actor actor,String key,String hash,Supplier<ObjectView> action) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_request) */ INTO svc_bi_request(actor_id,department_id,request_key,request_hash,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,0,'0')",actor.id(),actor.department(),key,hash,actor.department(),actor.id(),actor.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_bi_request) */ INTO svc_bi_request(actor_id,department_id,request_key,request_hash,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,0,'0')", "INSERT IGNORE INTO svc_bi_request(actor_id,department_id,request_key,request_hash,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,0,'0')"),actor.id(),actor.department(),key,hash,actor.department(),actor.id(),actor.id());
|
||||
var rows=jdbc.query("SELECT request_hash,response_json FROM svc_bi_request WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,i)->new String[]{r.getString(1),r.getString(2)},actor.id(),actor.department(),key);
|
||||
if(rows.size()!=1 || !hash.equals(rows.getFirst()[0])) throw BiException.conflict("幂等键已用于其他请求");
|
||||
if(rows.getFirst()[1]!=null) return decode(rows.getFirst()[1]);
|
||||
@@ -96,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")+" 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")+") 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) {
|
||||
|
||||
+4
-1
@@ -17,6 +17,9 @@ import static cn.aixunkeji.datagov.dataproduct.datasetannotation.DatasetAnnotati
|
||||
/** SR07 SQL only; never creates tables. All callers lock the content row before sample/request rows. */
|
||||
@Repository
|
||||
public class DatasetAnnotationJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final TransactionTemplate transactions;
|
||||
@@ -276,7 +279,7 @@ public class DatasetAnnotationJdbcRepository {
|
||||
+ "ON i.content_version_id=c.content_version_id JOIN svc_dataset_content_history h ON h.content_version_id=c.content_version_id "
|
||||
+ "AND h.action='PREPARE_DRAFT' WHERE c.organization_id=? AND c.department_id=? AND c.dataset_id=? AND c.content_version_id=? "
|
||||
+ "AND c.state='DRAFT' AND c.canonical_sha=UNHEX(?) AND i.sample_id=? AND i.sample_sha=UNHEX(?) "
|
||||
+ "AND i.label_schema_version=? AND i.split='UNSPLIT' AND BINARY CAST(JSON_UNQUOTE(JSON_EXTRACT(h.evidence_json,'$.indexSha256')) AS VARCHAR(32767))=BINARY ?",
|
||||
+ databaseDialect.sql("AND i.label_schema_version=? AND i.split='UNSPLIT' AND BINARY CAST(JSON_UNQUOTE(JSON_EXTRACT(h.evidence_json,'$.indexSha256')) AS VARCHAR(32767))=BINARY ?", "AND i.label_schema_version=? AND i.split='UNSPLIT' AND BINARY CAST(JSON_UNQUOTE(JSON_EXTRACT(h.evidence_json,'$.indexSha256')) AS CHAR)=BINARY ?"),
|
||||
Long.class, scope.organizationId(), scope.departmentId(), datasetId, contentId, k.contentSha256(), k.sampleId(), k.sampleSha256(),
|
||||
k.labelSchemaVersion(), s.indexSha256());
|
||||
require(source != null && source == 1, "SOURCE_CONFLICT");
|
||||
|
||||
+4
-1
@@ -16,6 +16,9 @@ import static cn.aixunkeji.datagov.dataproduct.datasetcontent.DatasetContentMode
|
||||
/** Own-domain registration only. Each mutation commits before a Resource callback can read it. */
|
||||
@Repository
|
||||
public class DatasetContentInputRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
public record License(String grantor, String grantee, String sourceDescription, List<String> fields,
|
||||
String purpose, String recipient, Instant validFrom, Instant validUntil) {
|
||||
public License {
|
||||
@@ -49,7 +52,7 @@ public class DatasetContentInputRepository {
|
||||
var value = new Registration(UUID.randomUUID().toString(), actor.organizationId(), actor.departmentId(),
|
||||
definition.datasetId(), actor.id(), key, payloadSha, definition, format, license, Map.of(), null,
|
||||
"DECLARED", null, null, null, 0,List.of());
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_dataset_input_registration) */ INTO svc_dataset_input_registration (input_id,organization_id,department_id,dataset_id,"
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(svc_dataset_input_registration) */ INTO svc_dataset_input_registration (input_id,organization_id,department_id,dataset_id,", "INSERT IGNORE INTO svc_dataset_input_registration (input_id,organization_id,department_id,dataset_id,")
|
||||
+ "submitted_by,idempotency_key,payload_sha,state,row_version,registration_json,created_at,updated_at) "
|
||||
+ "VALUES (?,?,?,?,?,?,UNHEX(?),'DECLARED',0,?,CURRENT_TIMESTAMP(6),CURRENT_TIMESTAMP(6)) "
|
||||
+ "", value.id(), actor.organizationId(), actor.departmentId(),
|
||||
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
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()); }
|
||||
}
|
||||
+4
-1
@@ -10,10 +10,13 @@ import java.util.List;
|
||||
|
||||
@Repository
|
||||
class MetricFormulaStore {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final JsonMapper mapper;private final MetricFormulaPolicy policy;
|
||||
MetricFormulaStore(JdbcTemplate jdbc,JsonMapper mapper,MetricFormulaPolicy policy){this.jdbc=jdbc;this.mapper=mapper;this.policy=policy;}
|
||||
void graphLock(MetricSystemActorProvider.Actor actor){
|
||||
jdbc.update("MERGE INTO metric_formula_graph_guard t USING (SELECT ? AS organization_id, ? AS department_id, ? AS create_dept, ? AS create_by, ? AS update_by FROM DUAL) s ON ((t.organization_id=s.organization_id AND t.department_id=s.department_id)) WHEN MATCHED THEN UPDATE SET t.update_by=s.update_by,t.update_time=CURRENT_TIMESTAMP(6),t.version=t.version+1 WHEN NOT MATCHED THEN INSERT (organization_id,department_id,create_dept,create_by,update_by) VALUES (s.organization_id,s.department_id,s.create_dept,s.create_by,s.update_by)",
|
||||
jdbc.update(databaseDialect.sql("MERGE INTO metric_formula_graph_guard t USING (SELECT ? AS organization_id, ? AS department_id, ? AS create_dept, ? AS create_by, ? AS update_by FROM DUAL) s ON ((t.organization_id=s.organization_id AND t.department_id=s.department_id)) WHEN MATCHED THEN UPDATE SET t.update_by=s.update_by,t.update_time=CURRENT_TIMESTAMP(6),t.version=t.version+1 WHEN NOT MATCHED THEN INSERT (organization_id,department_id,create_dept,create_by,update_by) VALUES (s.organization_id,s.department_id,s.create_dept,s.create_by,s.update_by)", "INSERT INTO metric_formula_graph_guard(organization_id,department_id,create_dept,create_by,update_by) SELECT s.organization_id,s.department_id,s.create_dept,s.create_by,s.update_by FROM (SELECT ? AS organization_id, ? AS department_id, ? AS create_dept, ? AS create_by, ? AS update_by FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE update_by=s.update_by,update_time=CURRENT_TIMESTAMP(6),version=metric_formula_graph_guard.version+1"),
|
||||
actor.organizationId(),actor.departmentId(),actor.departmentId(),actor.actorId(),actor.actorId());
|
||||
var rows=jdbc.query("SELECT organization_id FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=? AND del_flag='0' FOR UPDATE",(r,n)->r.getLong(1),actor.organizationId(),actor.departmentId());
|
||||
if(rows.size()!=1)throw MetricFormulaPolicy.changed();
|
||||
|
||||
+41
-6
@@ -10,9 +10,12 @@ import static cn.aixunkeji.datagov.dataproduct.servicegateway.GatewayPolicyDiffA
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class GatewayPolicyDiffRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final JsonMapper mapper;private final GatewayPolicyDiffPolicy policy;
|
||||
private static final String SCOPE="g.gateway_id=? AND g.organization_id=? AND g.department_id=? AND g.del_flag='0'";
|
||||
private static final String CURRENT_SELECT="""
|
||||
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,
|
||||
@@ -28,8 +31,24 @@ class GatewayPolicyDiffRepository {
|
||||
ELSE LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(TRIM(scope_value) AS CLOB),DBMS_CRYPTO.HASH_SH256))) END),JSON_ARRAY())
|
||||
FROM JSON_TABLE(g.caller_scopes_json,'$[*]' COLUMNS(scope_value VARCHAR(128) PATH '$')) scopes) AS scope_hashes_json
|
||||
FROM svc_gateway_definition g WHERE
|
||||
"""+SCOPE;
|
||||
private static final String SNAPSHOT_SELECT="""
|
||||
""", """
|
||||
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,
|
||||
SHA2(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),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,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
FROM JSON_TABLE(g.caller_scopes_json,'$[*]' COLUMNS(scope_value VARCHAR(128) PATH '$')) scopes) AS scope_hashes_json
|
||||
FROM svc_gateway_definition g WHERE
|
||||
""")+SCOPE; }
|
||||
private String SNAPSHOT_SELECT() { return databaseDialect.sql("""
|
||||
SELECT g.gateway_id,g.version,s.snapshot_id,s.snapshot_version,s.create_time AS recorded_at,
|
||||
s.api_id,s.api_version,s.model_sha256,s.dataset_schema_sha256,s.http_method,s.relative_path,
|
||||
CONCAT(s.policy_payload_sha256,':',LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(s.policy_payload_json AS CLOB),DBMS_CRYPTO.HASH_SH256)))) AS stored_sha,
|
||||
@@ -45,9 +64,25 @@ class GatewayPolicyDiffRepository {
|
||||
FROM JSON_TABLE(s.policy_payload_json,'$.callerScopes[*]' COLUMNS(scope_value VARCHAR(128) PATH '$')) scopes) AS scope_hashes_json
|
||||
FROM svc_gateway_definition g JOIN svc_gateway_policy_snapshot s ON s.gateway_id=g.gateway_id AND s.del_flag='0'
|
||||
WHERE
|
||||
"""+SCOPE+" AND s.snapshot_id=?";
|
||||
Saved current(long id,ServiceGatewayActorProvider.Actor a){return jdbc.query(CURRENT_SELECT,this::saved,id,a.organizationId(),a.departmentId()).stream().findFirst().orElseThrow(ServiceGatewayDomainException::notFound);}
|
||||
Saved snapshot(long id,long snapshot,ServiceGatewayActorProvider.Actor a){return jdbc.query(SNAPSHOT_SELECT,this::saved,id,a.organizationId(),a.departmentId(),snapshot).stream().findFirst().orElseThrow(ServiceGatewayDomainException::notFound);}
|
||||
""", """
|
||||
SELECT g.gateway_id,g.version,s.snapshot_id,s.snapshot_version,s.create_time AS recorded_at,
|
||||
s.api_id,s.api_version,s.model_sha256,s.dataset_schema_sha256,s.http_method,s.relative_path,
|
||||
CONCAT(s.policy_payload_sha256,':',SHA2(s.policy_payload_json,256)) AS stored_sha,
|
||||
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,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
FROM JSON_TABLE(s.policy_payload_json,'$.callerScopes[*]' COLUMNS(scope_value VARCHAR(128) PATH '$')) scopes) AS scope_hashes_json
|
||||
FROM svc_gateway_definition g JOIN svc_gateway_policy_snapshot s ON s.gateway_id=g.gateway_id AND s.del_flag='0'
|
||||
WHERE
|
||||
""")+SCOPE+" AND s.snapshot_id=?"; }
|
||||
Saved current(long id,ServiceGatewayActorProvider.Actor a){return jdbc.query(CURRENT_SELECT(),this::saved,id,a.organizationId(),a.departmentId()).stream().findFirst().orElseThrow(ServiceGatewayDomainException::notFound);}
|
||||
Saved snapshot(long id,long snapshot,ServiceGatewayActorProvider.Actor a){return jdbc.query(SNAPSHOT_SELECT(),this::saved,id,a.organizationId(),a.departmentId(),snapshot).stream().findFirst().orElseThrow(ServiceGatewayDomainException::notFound);}
|
||||
SnapshotPage snapshots(long id,ServiceGatewayActorProvider.Actor a,int page,int size){
|
||||
if(page<1||page>10000||size<1||size>20)throw GatewayPolicyDiffPolicy.bad();
|
||||
String from=" FROM svc_gateway_definition g JOIN svc_gateway_policy_snapshot s ON s.gateway_id=g.gateway_id AND s.del_flag='0' WHERE "+SCOPE;
|
||||
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
+9
-2
@@ -15,6 +15,9 @@ import static cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionA
|
||||
/** Evidence can only be produced by rereading the original, physically bound profile runs. */
|
||||
@Service @RequiredArgsConstructor
|
||||
public class AnomalySourceEvidence {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
static final String PATH = "/api/governance/v1/anomaly-detections/assist/evaluations";
|
||||
public record Result(String resultId,String detectionId,long configVersion,String targetLogicalId,String targetFqn,
|
||||
String name,String configSha,String thresholdSha,String ownerSha,String verdict,long observedValue,
|
||||
@@ -51,11 +54,15 @@ public class AnomalySourceEvidence {
|
||||
requireResult(repository.result(resultId),observation,verified);
|
||||
var stored=new Stored(selection,verified.context().fingerprint(),configHash(verified),thresholdHash(verified),verified.series().ownerSha(),last.observedAt());
|
||||
var frozen=result(repository.result(resultId),stored,verified);
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_anomaly_source_evidence) */ INTO dq_anomaly_source_evidence(result_id,detection_id,organization_id,department_id,
|
||||
selection_json,frozen_result_json,context_sha256,config_sha256,threshold_sha256,owner_sha256,observed_at,create_dept,create_by,update_by)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",resultId,config.detectionId(),actor.organizationId(),actor.departmentId(),json.writeValueAsString(selection),
|
||||
""", """
|
||||
INSERT IGNORE INTO dq_anomaly_source_evidence(result_id,detection_id,organization_id,department_id,
|
||||
selection_json,frozen_result_json,context_sha256,config_sha256,threshold_sha256,owner_sha256,observed_at,create_dept,create_by,update_by)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
"""),resultId,config.detectionId(),actor.organizationId(),actor.departmentId(),json.writeValueAsString(selection),
|
||||
json.writeValueAsString(frozen),stored.contextSha(),stored.configSha(),stored.thresholdSha(),stored.ownerSha(),stored.observedAt(),actor.departmentId(),actor.actorId(),actor.actorId());
|
||||
if(!verified.equals(series.verified(selection,false)))throw invalid();authority.requireEvaluation(actor);
|
||||
repository.completeRequest(actor,"POST",PATH,key,AnomalyDetectionJdbcRepository.ObjectType.RESULT,resultId);
|
||||
|
||||
+6
-3
@@ -18,6 +18,9 @@ import static cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityModel.*
|
||||
/** Local SQL only. Tables are designed, not provisioned by this component. */
|
||||
@Repository
|
||||
class AssetIdentityJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
AssetIdentityJdbcRepository(JdbcTemplate jdbc, JsonMapper json) { this.jdbc = jdbc; this.json = json; }
|
||||
@@ -55,7 +58,7 @@ class AssetIdentityJdbcRepository {
|
||||
}
|
||||
void lockGraph(Actor actor) {
|
||||
transaction();
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(asset_composition_guard) */ INTO asset_composition_guard(organization_id,department_id,row_version) VALUES(?,?,0) "
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(asset_composition_guard) */ INTO asset_composition_guard(organization_id,department_id,row_version) VALUES(?,?,0) ", "INSERT IGNORE INTO asset_composition_guard(organization_id,department_id,row_version) VALUES(?,?,0) ")
|
||||
+ "", actor.scope().organizationId(), actor.scope().departmentId());
|
||||
one(jdbc.query("SELECT row_version FROM asset_composition_guard WHERE organization_id=? AND department_id=? FOR UPDATE",
|
||||
(rs, n) -> rs.getLong(1), actor.scope().organizationId(), actor.scope().departmentId()));
|
||||
@@ -272,14 +275,14 @@ class AssetIdentityJdbcRepository {
|
||||
void insertBinding(Actor actor, Binding b) {
|
||||
transaction();
|
||||
changed(jdbc.update("INSERT INTO asset_identity_source_binding(" + BIND_COLUMNS
|
||||
+ ",created_by,created_at,updated_by,updated_at) VALUES(?,?,?,?,?,?,?,?,'DRAFT',0,NULL,?,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),?,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))",
|
||||
+ databaseDialect.sql(",created_by,created_at,updated_by,updated_at) VALUES(?,?,?,?,?,?,?,?,'DRAFT',0,NULL,?,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),?,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))", ",created_by,created_at,updated_by,updated_at) VALUES(?,?,?,?,?,?,?,?,'DRAFT',0,NULL,?,UTC_TIMESTAMP(6),?,UTC_TIMESTAMP(6))"),
|
||||
b.bindingId(),actor.scope().organizationId(),actor.scope().departmentId(),b.detailId(),b.lifecycleId(),
|
||||
b.sourceOwner(),b.sourceType(),b.sourceStableId(),actor.actorId(),actor.actorId()));
|
||||
}
|
||||
void finishBinding(Actor actor, Binding before, Binding after, long observation, String reason, boolean inserted) {
|
||||
transaction();
|
||||
changed(jdbc.update("UPDATE asset_identity_source_binding SET lifecycle_id=?,source_stable_id=?,binding_state=?,row_version=?,"
|
||||
+ "latest_observation_id=?,updated_by=?,updated_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),revoked_by=?,revoked_at=?,revoke_reason=? "
|
||||
+ databaseDialect.sql("latest_observation_id=?,updated_by=?,updated_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),revoked_by=?,revoked_at=?,revoke_reason=? ", "latest_observation_id=?,updated_by=?,updated_at=UTC_TIMESTAMP(6),revoked_by=?,revoked_at=?,revoke_reason=? ")
|
||||
+ "WHERE organization_id=? AND department_id=? AND binding_id=? AND row_version=? AND binding_state=? "
|
||||
+ (inserted ? "AND latest_observation_id IS NULL" : "AND latest_observation_id <=> ?"),
|
||||
finishArguments(actor, before, after, observation, reason, inserted)));
|
||||
|
||||
+48
-2
@@ -33,6 +33,9 @@ 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;
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DatasetPublicationEvidenceDirectoryService.class);
|
||||
private static final int MAX_AGE_DAYS = 7;
|
||||
private static final tools.jackson.databind.json.JsonMapper SCHEMA_JSON = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||
@@ -217,7 +220,7 @@ public class DatasetPublicationEvidenceDirectoryService implements DatasetPublic
|
||||
var nativeTarget = command.sourceObjectRef().startsWith("table:") ? standardNativeTarget(command) : null;
|
||||
List<StandardRow> rows = new java.util.ArrayList<>();
|
||||
for (PublicationField field : command.fields()) {
|
||||
List<StandardRow> fieldRows = nativeTarget != null ? nativeStandardRows(command, field, nativeTarget) : jdbc.query("""
|
||||
List<StandardRow> fieldRows = nativeTarget != null ? nativeStandardRows(command, field, nativeTarget) : jdbc.query(databaseDialect.sql("""
|
||||
SELECT m.mapping_id,m.version,ps.snapshot_id physical_snapshot_id,
|
||||
ss.snapshot_id standard_snapshot_id,ps.observed_at physical_observed_at,
|
||||
ss.observed_at standard_observed_at,ps.payload_sha256 physical_sha,
|
||||
@@ -260,7 +263,50 @@ public class DatasetPublicationEvidenceDirectoryService implements DatasetPublic
|
||||
AND canonical_request.physical_source_version=CAST(SUBSTRING_INDEX(ps.external_ref,':',-1) AS BIGINT)
|
||||
AND CAST(ps.external_ref AS BINARY)=CAST(CONCAT('PROFILE:internal.',SUBSTRING_INDEX(source_asset.asset_fqn,'.default.',-1),':',canonical_request.physical_source_version) AS BINARY)))
|
||||
ORDER BY v.create_time DESC,v.validation_id DESC LIMIT 1
|
||||
""", DatasetPublicationEvidenceDirectoryService::standardRow,
|
||||
""", """
|
||||
SELECT m.mapping_id,m.version,ps.snapshot_id physical_snapshot_id,
|
||||
ss.snapshot_id standard_snapshot_id,ps.observed_at physical_observed_at,
|
||||
ss.observed_at standard_observed_at,ps.payload_sha256 physical_sha,
|
||||
ss.payload_sha256 standard_sha,v.validation_id,v.compliance_result,
|
||||
COALESCE(profile_request.physical_source_version,CAST(SUBSTRING_INDEX(ps.external_ref,':',-1) AS SIGNED)) physical_source_version,
|
||||
ps.field_name physical_field_name,
|
||||
ss.field_name standard_field_name
|
||||
FROM std_adoption_mapping m
|
||||
JOIN std_adoption_validation v ON v.mapping_id=m.mapping_id
|
||||
AND v.del_flag='0'
|
||||
JOIN std_adoption_snapshot ps ON ps.snapshot_id=v.physical_snapshot_id
|
||||
AND ps.mapping_id=m.mapping_id AND ps.snapshot_kind='PHYSICAL_FIELD'
|
||||
AND ps.reliable=1 AND ps.del_flag='0'
|
||||
JOIN std_adoption_snapshot ss ON ss.snapshot_id=v.standard_snapshot_id
|
||||
AND ss.mapping_id=m.mapping_id AND ss.snapshot_kind='STANDARD_EXPECTATION'
|
||||
AND ss.reliable=1 AND ss.del_flag='0'
|
||||
LEFT JOIN dq_data_profile_snapshot profile ON profile.snapshot_id=CAST(SUBSTRING(ps.external_ref,9) AS SIGNED)
|
||||
AND profile.del_flag='0'
|
||||
LEFT JOIN dq_data_profile_request profile_request ON profile_request.request_id=profile.request_id
|
||||
LEFT JOIN asset_detail_asset source_asset ON CAST(source_asset.asset_ref AS BINARY)=CAST(? AS BINARY)
|
||||
AND source_asset.organization_id=? AND source_asset.department_id=?
|
||||
AND source_asset.asset_status='ACTIVE' AND source_asset.del_flag='0'
|
||||
JOIN asset_detail_section_snapshot source_schema ON source_schema.asset_detail_id=source_asset.asset_detail_id
|
||||
AND source_schema.section_snapshot_id=? AND source_schema.section_type='SCHEMA'
|
||||
AND source_schema.reliable_flag='1' AND source_schema.evidence_state='KNOWN'
|
||||
WHERE m.organization_id=? AND m.department_id=? AND m.mapping_status='ACTIVE'
|
||||
AND m.del_flag='0' AND (CAST(m.physical_field_fqn AS BINARY)=CAST(? AS BINARY)
|
||||
OR CAST(m.physical_field_fqn AS BINARY)=CAST(CONCAT('internal.',SUBSTRING_INDEX(source_asset.asset_fqn,'.default.',-1),'.',?) AS BINARY))
|
||||
AND CAST(ps.field_name AS BINARY)=CAST(? AS BINARY)
|
||||
AND ((profile_request.del_flag='0' AND profile_request.profile_status='SUCCEEDED'
|
||||
AND (CAST(profile_request.physical_object_ref AS BINARY)=CAST(COALESCE(source_asset.asset_fqn,?) AS BINARY)
|
||||
OR CAST(profile_request.physical_object_ref AS BINARY)=CAST(CONCAT('internal.',SUBSTRING_INDEX(source_asset.asset_fqn,'.default.',-1)) AS BINARY))
|
||||
)
|
||||
OR EXISTS (SELECT 1 FROM dq_data_profile_request canonical_request
|
||||
WHERE canonical_request.organization_id=m.organization_id
|
||||
AND canonical_request.department_id=m.department_id
|
||||
AND canonical_request.del_flag='0' AND canonical_request.profile_status='SUCCEEDED'
|
||||
AND (CAST(canonical_request.physical_object_ref AS BINARY)=CAST(COALESCE(source_asset.asset_fqn,?) AS BINARY)
|
||||
OR CAST(canonical_request.physical_object_ref AS BINARY)=CAST(CONCAT('internal.',SUBSTRING_INDEX(source_asset.asset_fqn,'.default.',-1)) AS BINARY))
|
||||
AND canonical_request.physical_source_version=CAST(SUBSTRING_INDEX(ps.external_ref,':',-1) AS SIGNED)
|
||||
AND CAST(ps.external_ref AS BINARY)=CAST(CONCAT('PROFILE:internal.',SUBSTRING_INDEX(source_asset.asset_fqn,'.default.',-1),':',canonical_request.physical_source_version) AS BINARY)))
|
||||
ORDER BY v.create_time DESC,v.validation_id DESC LIMIT 1
|
||||
"""), DatasetPublicationEvidenceDirectoryService::standardRow,
|
||||
command.sourceObjectRef(), command.context().organizationId(), command.context().departmentId(), command.sourceVersion(),
|
||||
command.context().organizationId(), command.context().departmentId(),
|
||||
field.physicalFieldFqn(), field.fieldName(), field.fieldName(), command.sourceObjectRef(), command.sourceObjectRef());
|
||||
|
||||
+26
-4
@@ -23,7 +23,10 @@ import java.util.Map;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class NationalStandardCatalogJdbcRepository {
|
||||
private static final String VIEW_SELECT = """
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private String VIEW_SELECT() { return databaseDialect.sql("""
|
||||
SELECT s.catalog_standard_id,s.standard_code,s.standard_name,s.english_title,s.standard_kind,
|
||||
s.official_status,s.publication_date,s.effective_date,s.industry_code,s.industry_name,
|
||||
s.responsible_department,s.technical_committee,s.source_uri,s.source_observed_at,
|
||||
@@ -42,7 +45,26 @@ class NationalStandardCatalogJdbcRepository {
|
||||
AND CHAR_LENGTH(cx.classification_code)>CHAR_LENGTH(c.classification_code)
|
||||
AND cx.classification_code LIKE CONCAT(c.classification_code,'%') AND cx.del_flag='0')),'') AS ccs_codes
|
||||
FROM std_national_standard_catalog s
|
||||
""";
|
||||
""", """
|
||||
SELECT s.catalog_standard_id,s.standard_code,s.standard_name,s.english_title,s.standard_kind,
|
||||
s.official_status,s.publication_date,s.effective_date,s.industry_code,s.industry_name,
|
||||
s.responsible_department,s.technical_committee,s.source_uri,s.source_observed_at,
|
||||
s.review_status,s.usability_status,s.version,s.create_time,s.update_time,
|
||||
COALESCE((SELECT GROUP_CONCAT(DISTINCT c.classification_code ORDER BY c.classification_code SEPARATOR ',')
|
||||
FROM std_national_standard_classification c WHERE c.catalog_standard_id=s.catalog_standard_id
|
||||
AND c.classification_system='ICS' AND c.del_flag='0'
|
||||
AND NOT EXISTS(SELECT 1 FROM std_national_standard_classification cx
|
||||
WHERE cx.catalog_standard_id=c.catalog_standard_id AND cx.classification_system='ICS'
|
||||
AND cx.classification_code LIKE CONCAT(c.classification_code,'.%') AND cx.del_flag='0')),'') AS ics_codes,
|
||||
COALESCE((SELECT GROUP_CONCAT(DISTINCT c.classification_code ORDER BY c.classification_code SEPARATOR ',')
|
||||
FROM std_national_standard_classification c WHERE c.catalog_standard_id=s.catalog_standard_id
|
||||
AND c.classification_system='CCS' AND c.del_flag='0'
|
||||
AND NOT EXISTS(SELECT 1 FROM std_national_standard_classification cx
|
||||
WHERE cx.catalog_standard_id=c.catalog_standard_id AND cx.classification_system='CCS'
|
||||
AND CHAR_LENGTH(cx.classification_code)>CHAR_LENGTH(c.classification_code)
|
||||
AND cx.classification_code LIKE CONCAT(c.classification_code,'%') AND cx.del_flag='0')),'') AS ccs_codes
|
||||
FROM std_national_standard_catalog s
|
||||
"""); }
|
||||
private static final String BATCH_SELECT = """
|
||||
SELECT batch_id,request_id,source_kind,import_mode,query_keyword,page_num,page_size,next_page,total_pages,
|
||||
batch_status,reconciliation_status,expected_count,fetched_count,accepted_count,rejected_count,missing_count,
|
||||
@@ -81,7 +103,7 @@ class NationalStandardCatalogJdbcRepository {
|
||||
}
|
||||
paged.add(query.pageSize());
|
||||
paged.add((query.pageNum() - 1) * query.pageSize());
|
||||
var rows = jdbc.query(VIEW_SELECT + where
|
||||
var rows = jdbc.query(VIEW_SELECT() + where
|
||||
+ " ORDER BY " + priorityOrder + ",s.standard_code,s.catalog_standard_id LIMIT ? OFFSET ?",
|
||||
this::view, paged.toArray());
|
||||
return new CatalogPage(rows, total == null ? 0 : total);
|
||||
@@ -111,7 +133,7 @@ class NationalStandardCatalogJdbcRepository {
|
||||
}
|
||||
|
||||
CatalogDetailView detail(long id, ExternalStandardActorProvider.Actor actor) {
|
||||
CatalogView standard = jdbc.query(VIEW_SELECT + " WHERE s.catalog_standard_id=? AND s.organization_id=?"
|
||||
CatalogView standard = jdbc.query(VIEW_SELECT() + " WHERE s.catalog_standard_id=? AND s.organization_id=?"
|
||||
+ " AND s.department_id=? AND s.del_flag='0'", this::view, id, actor.organizationId(),
|
||||
actor.departmentId()).stream().findFirst().orElseThrow(ExternalStandardDomainException::notFound);
|
||||
var classifications = jdbc.query("""
|
||||
|
||||
+15
-4
@@ -17,6 +17,9 @@ import static cn.aixunkeji.datagov.governance.financialbatch.FinancialBatchPolic
|
||||
/** SR07 SQL only; never creates tables, executes cross-domain SQL or schedules work. */
|
||||
@Repository
|
||||
public class FinancialBatchJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final TransactionTemplate transactions;
|
||||
@@ -119,10 +122,13 @@ public class FinancialBatchJdbcRepository {
|
||||
|
||||
private void ledger(Actor a, String legalEntity, String ledger) {
|
||||
String digest = hash(legalEntity, ledger);
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(asset_financial_ledger_guard) */ INTO asset_financial_ledger_guard(organization_id,ledger_scope_sha,legal_entity,ledger,row_version)
|
||||
VALUES(?,UNHEX(?),?,?,0)
|
||||
""", a.organizationId(), digest, legalEntity, ledger);
|
||||
""", """
|
||||
INSERT IGNORE INTO asset_financial_ledger_guard(organization_id,ledger_scope_sha,legal_entity,ledger,row_version)
|
||||
VALUES(?,UNHEX(?),?,?,0)
|
||||
"""), a.organizationId(), digest, legalEntity, ledger);
|
||||
List<Boolean> match = jdbc.query("""
|
||||
SELECT legal_entity,ledger FROM asset_financial_ledger_guard
|
||||
WHERE organization_id=? AND ledger_scope_sha=UNHEX(?) FOR UPDATE
|
||||
@@ -133,12 +139,17 @@ public class FinancialBatchJdbcRepository {
|
||||
private Ticket begin(Actor a, String operation, String objectId, String key, String payload) {
|
||||
String scope = hash(a.organizationId(), a.actorId(), operation, objectId, key);
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(asset_financial_request) */ INTO asset_financial_request(request_id,organization_id,department_id,actor_id,operation,object_id,
|
||||
idempotency_key,scope_sha,payload_sha,state,response_ref,row_version,created_by,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,UNHEX(?),UNHEX(?),'PROCESSING',NULL,0,?,CURRENT_TIMESTAMP(6))
|
||||
|
||||
""", requestId, a.organizationId(), a.departmentId(), a.actorId(), operation, objectId, key, scope, payload, a.actorId());
|
||||
""", """
|
||||
INSERT IGNORE INTO asset_financial_request(request_id,organization_id,department_id,actor_id,operation,object_id,
|
||||
idempotency_key,scope_sha,payload_sha,state,response_ref,row_version,created_by,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,UNHEX(?),UNHEX(?),'PROCESSING',NULL,0,?,CURRENT_TIMESTAMP(6))
|
||||
|
||||
"""), requestId, a.organizationId(), a.departmentId(), a.actorId(), operation, objectId, key, scope, payload, a.actorId());
|
||||
return jdbc.query("SELECT *,LOWER(HEX(payload_sha)) AS payload_hex FROM asset_financial_request WHERE organization_id=? AND scope_sha=UNHEX(?) FOR UPDATE",
|
||||
(rs, n) -> {
|
||||
if (rs.getLong("actor_id") != a.actorId() || rs.getLong("department_id") != a.departmentId()
|
||||
|
||||
+5
-2
@@ -15,6 +15,9 @@ import java.util.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class MasterDataIdentityJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private static final String RULE_COLUMNS = "rule_id,rule_code,rule_name,rule_type,description,external_standard_ref,rule_status,sequence_start,sequence_step,sequence_max,organization_id,department_id,version,create_time,update_time";
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
@@ -83,7 +86,7 @@ class MasterDataIdentityJdbcRepository {
|
||||
}
|
||||
|
||||
long allocateSequence(MasterDataIdentityActorProvider.Actor actor, RuleView rule) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_identity_sequence) */ INTO mdm_identity_sequence(sequence_id,rule_id,organization_id,current_value,step_value,max_value,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_identity_sequence) */ INTO mdm_identity_sequence(sequence_id,rule_id,organization_id,current_value,step_value,max_value,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)", "INSERT IGNORE INTO mdm_identity_sequence(sequence_id,rule_id,organization_id,current_value,step_value,max_value,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)"),
|
||||
IdGeneratorUtil.nextLongId(), rule.ruleId(), actor.organizationId(),
|
||||
rule.sequenceStart() - rule.sequenceStep(), rule.sequenceStep(), rule.sequenceMax(),
|
||||
actor.departmentId(), actor.actorId(), actor.actorId());
|
||||
@@ -117,7 +120,7 @@ class MasterDataIdentityJdbcRepository {
|
||||
}
|
||||
|
||||
long createMapping(MasterDataIdentityActorProvider.Actor actor, MappingCommand command) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_identity_mapping_scope) */ INTO mdm_identity_mapping_scope(scope_id,organization_id,department_id,source_system,source_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_identity_mapping_scope) */ INTO mdm_identity_mapping_scope(scope_id,organization_id,department_id,source_system,source_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)", "INSERT IGNORE INTO mdm_identity_mapping_scope(scope_id,organization_id,department_id,source_system,source_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)"),
|
||||
IdGeneratorUtil.nextLongId(), actor.organizationId(), actor.departmentId(),
|
||||
command.sourceSystem(), command.sourceId(), actor.departmentId(), actor.actorId(), actor.actorId());
|
||||
required(jdbc.update("UPDATE mdm_identity_mapping_scope SET update_by=?,update_time=NOW(),version=version+1 WHERE organization_id=? AND department_id=? AND source_system=? AND source_id=? AND del_flag='0'",
|
||||
|
||||
+4
-1
@@ -15,6 +15,9 @@ import java.util.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class MasterDataSourceJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private static final String SOURCE_COLUMNS = "source_id,source_code,source_name,collection_method,owner_user_id,frequency_unit,frequency_interval,reliability_status,source_status,effective_from,effective_to,description,organization_id,department_id,version,create_time,update_time";
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
@@ -215,7 +218,7 @@ class MasterDataSourceJdbcRepository {
|
||||
|
||||
private void lockAuthorityScope(MasterDataSourceActorProvider.Actor actor,
|
||||
SaveAuthorityCommand command) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_source_authority_scope) */ INTO mdm_source_authority_scope(scope_id,organization_id,department_id,data_domain_ref,model_ref,attribute_code,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?, ?,NOW(),?,NOW(),'0',0)",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(mdm_source_authority_scope) */ INTO mdm_source_authority_scope(scope_id,organization_id,department_id,data_domain_ref,model_ref,attribute_code,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?, ?,NOW(),?,NOW(),'0',0)", "INSERT IGNORE INTO mdm_source_authority_scope(scope_id,organization_id,department_id,data_domain_ref,model_ref,attribute_code,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?, ?,NOW(),?,NOW(),'0',0)"),
|
||||
IdGeneratorUtil.nextLongId(), actor.organizationId(), actor.departmentId(),
|
||||
command.dataDomainRef(), command.modelRef(), command.attributeCode(), actor.departmentId(),
|
||||
actor.actorId(), actor.actorId());
|
||||
|
||||
+6
-2
@@ -11,6 +11,9 @@ import static cn.aixunkeji.datagov.governance.api.metadatacatalog.MetadataCatalo
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class MetadataCatalogRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
Ticket begin(MetadataCatalogActorProvider.Actor actor,String path,String key,String hash,String action){
|
||||
if(key==null||!key.matches("[A-Za-z0-9:_-]{16,128}"))throw MetadataCatalogDomainException.validation("Idempotency-Key无效");
|
||||
@@ -21,14 +24,15 @@ class MetadataCatalogRepository {
|
||||
}
|
||||
void complete(String requestId,CatalogDetail detail,MetadataCatalogActorProvider.Actor actor){ upsert(detail,actor); jdbc.update("UPDATE md_catalog_request SET request_status='COMPLETED',external_entity_id=?,update_time=NOW(),version=version+1 WHERE request_id=?",detail.item().externalId(),requestId); }
|
||||
void fail(String requestId,String code){jdbc.update("UPDATE md_catalog_request SET request_status='FAILED',error_code=?,update_time=NOW(),version=version+1 WHERE request_id=?",safe(code),requestId);}
|
||||
private void upsert(CatalogDetail d,MetadataCatalogActorProvider.Actor actor){jdbc.update("""
|
||||
private void upsert(CatalogDetail d,MetadataCatalogActorProvider.Actor actor){jdbc.update(databaseDialect.sql("""
|
||||
MERGE INTO md_catalog_projection t
|
||||
USING (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
|
||||
ON ((t.projection_id=s.projection_id) OR (t.org_id=s.org_id AND t.entity_type=s.entity_type AND t.external_entity_id=s.external_entity_id AND t.del_flag=s.del_flag))
|
||||
WHEN MATCHED THEN UPDATE SET t.fully_qualified_name=s.fully_qualified_name,t.entity_name=s.entity_name,t.description=s.description,t.owners_json=s.owners_json,t.glossary_terms_json=s.glossary_terms_json,t.domains_json=s.domains_json,t.life_cycle_json=s.life_cycle_json,t.security_tags_json=s.security_tags_json,t.external_version=s.external_version,t.external_updated_at=s.external_updated_at,t.update_by=s.update_by,t.update_time=NOW(),t.version=t.version+1
|
||||
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)
|
||||
""",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";}
|
||||
|
||||
+26
-2
@@ -11,6 +11,9 @@ import static cn.aixunkeji.datagov.governance.metadataingestion.MetadataIngestio
|
||||
/** Recorded run evidence only. Never calls status/reconcile, starts a scan or reads source rows. */
|
||||
@Repository
|
||||
class MetadataScanAssistEvidence {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
MetadataScanAssistEvidence(JdbcTemplate jdbc){this.jdbc=jdbc;}
|
||||
record Evidence(String snapshotSha,Long sourceVersion,Boolean incremental,
|
||||
@@ -20,7 +23,7 @@ class MetadataScanAssistEvidence {
|
||||
Evidence read(ConnectorView connector,RunView run){
|
||||
if(!Objects.equals(connector.connectorId(),run.connectorId())||connector.orgId()==null||connector.orgId()<=0
|
||||
||run.snapshotSha256()==null||!run.snapshotSha256().matches("[a-f0-9]{64}"))throw denied();
|
||||
var rows=jdbc.query("""
|
||||
var rows=jdbc.query(databaseDialect.sql("""
|
||||
SELECT r.snapshot_sha256,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.sourceDataSourceVersion')) AS source_version,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.incremental')) AS incremental,
|
||||
@@ -41,7 +44,28 @@ class MetadataScanAssistEvidence {
|
||||
AND CAST(j.source_version AS CHAR)=JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.sourceDataSourceVersion'))
|
||||
WHERE r.run_id=? AND r.connector_id=? AND r.org_id=? AND r.del_flag='0'
|
||||
AND r.snapshot_sha256=? AND LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(r.snapshot_json AS CLOB),DBMS_CRYPTO.HASH_SH256)))=r.snapshot_sha256
|
||||
""",(r,index)->new Evidence(r.getString("snapshot_sha256"),number(r,"source_version"),bool(r.getString("incremental")),
|
||||
""", """
|
||||
SELECT r.snapshot_sha256,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.sourceDataSourceVersion')) AS source_version,
|
||||
JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.incremental')) AS incremental,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.databaseIncludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.databaseIncludes')) AS JSON)) END AS database_includes,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.databaseExcludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.databaseExcludes')) AS JSON)) END AS database_excludes,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.schemaIncludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.schemaIncludes')) AS JSON)) END AS schema_includes,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.schemaExcludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.schemaExcludes')) AS JSON)) END AS schema_excludes,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.tableIncludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.tableIncludes')) AS JSON)) END AS table_includes,
|
||||
CASE WHEN JSON_TYPE(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.tableExcludes')) AS JSON))='ARRAY' THEN JSON_LENGTH(CAST(JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.tableExcludes')) AS JSON)) END AS table_excludes,
|
||||
j.state AS native_state,j.catalog_complete,j.asset_count,j.error_code,
|
||||
CASE WHEN j.job_id IS NULL THEN NULL ELSE
|
||||
(SELECT COUNT(*) FROM md_native_scan_stage s WHERE s.job_id=j.job_id AND s.del_flag='0') END AS staged_tables
|
||||
FROM md_ingestion_run r
|
||||
LEFT JOIN md_native_job j ON j.platform_run_id=r.run_id AND j.org_id=r.org_id AND j.del_flag='0'
|
||||
AND j.job_id=r.external_pipeline_id AND j.job_id=r.external_run_id
|
||||
AND j.pipeline_fqn=r.external_pipeline_fqn
|
||||
AND CAST(j.source_id AS CHAR)=JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.sourceDataSourceId'))
|
||||
AND CAST(j.source_version AS CHAR)=JSON_UNQUOTE(JSON_EXTRACT(r.snapshot_json,'$.sourceDataSourceVersion'))
|
||||
WHERE r.run_id=? AND r.connector_id=? AND r.org_id=? AND r.del_flag='0'
|
||||
AND r.snapshot_sha256=? AND SHA2(r.snapshot_json,256)=r.snapshot_sha256
|
||||
"""),(r,index)->new Evidence(r.getString("snapshot_sha256"),number(r,"source_version"),bool(r.getString("incremental")),
|
||||
number(r,"database_includes"),number(r,"database_excludes"),number(r,"schema_includes"),number(r,"schema_excludes"),
|
||||
number(r,"table_includes"),number(r,"table_excludes"),state(r.getString("native_state")),bool(r.getString("catalog_complete")),
|
||||
number(r,"staged_tables"),number(r,"asset_count"),error(r.getString("error_code"))),
|
||||
|
||||
+5
-2
@@ -12,6 +12,9 @@ import java.util.Map;
|
||||
/** Internal metadata maintenance only; execution keeps the existing policy/run/idempotency path. */
|
||||
@Component
|
||||
class NativeMetadataPolicyScheduler {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final TransactionTemplate tx;private final NativeMetadataMode mode;
|
||||
private final MetadataIngestionService ingestion;private final MetadataIngestionActorProvider actors;
|
||||
NativeMetadataPolicyScheduler(JdbcTemplate jdbc,TransactionTemplate tx,NativeMetadataMode mode,MetadataIngestionService ingestion,MetadataIngestionActorProvider actors){this.jdbc=jdbc;this.tx=tx;this.mode=mode;this.ingestion=ingestion;this.actors=actors;}
|
||||
@@ -35,9 +38,9 @@ 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("SELECT *,next_at<=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) 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("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_schedule) */ 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;
|
||||
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;
|
||||
}
|
||||
var r=rows.getFirst();
|
||||
if(number(r,"policy_version")!=version){jdbc.update("UPDATE md_native_schedule SET policy_version=?,next_at=?,pending_flag=FALSE,last_request_key=NULL,last_error_code=NULL,row_version=row_version+1 WHERE policy_id=?",version,next((String)p.get("schedule_interval"),(String)p.get("timezone"),Instant.now()),policy);return null;}
|
||||
|
||||
+11
-2
@@ -16,6 +16,9 @@ import static cn.aixunkeji.datagov.governance.metadataquality.MetadataQualityApi
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class MetadataQualityRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
Ticket begin(MetadataQualityActorProvider.Actor actor, String path, String key, String hash, String action,
|
||||
@@ -104,7 +107,7 @@ class MetadataQualityRepository {
|
||||
private void upsertBase(MetadataQualityActorProvider.Actor actor, CatalogDetail detail, String claimState,
|
||||
String ownerKind, String ownerId, String reason) {
|
||||
String state = claimState == null ? "UNCLAIMED" : claimState;
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
MERGE INTO md_quality_projection t
|
||||
USING (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
|
||||
ON ((t.projection_id=s.projection_id) OR (t.org_id=s.org_id AND t.entity_type=s.entity_type AND t.external_entity_id=s.external_entity_id AND t.del_flag=s.del_flag))
|
||||
@@ -116,7 +119,13 @@ class MetadataQualityRepository {
|
||||
t.external_updated_at=s.external_updated_at,t.update_by=s.update_by,t.update_time=NOW(),t.version=t.version+1
|
||||
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)
|
||||
""", IdGeneratorUtil.nextLongId(), detail.item().externalId(), detail.item().entityType().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),
|
||||
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_quality_projection.version+1"""), IdGeneratorUtil.nextLongId(), detail.item().externalId(), detail.item().entityType().name(),
|
||||
detail.item().fullyQualifiedName(), detail.item().name(), state, ownerKind, ownerId, reason, state,
|
||||
JsonUtils.toJsonString(detail.management().securityTags()), detail.item().externalVersion(),
|
||||
detail.item().updatedAt(), actor.orgId(), actor.orgId(), actor.actorId(), actor.actorId(),
|
||||
|
||||
+4
-1
@@ -13,6 +13,9 @@ import java.util.*;
|
||||
/** Persistent run identity replaces external DAG submission; old provider runs are never replayed. */
|
||||
@Component
|
||||
public class NativeMetadataIngestion implements MetadataIngestionAdapterService {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final NativeMetadataMode mode;
|
||||
private final TransactionTemplate tx;
|
||||
@@ -25,7 +28,7 @@ public class NativeMetadataIngestion implements MetadataIngestionAdapterService
|
||||
mode.requireWrite(epoch);
|
||||
Integer exists=jdbc.queryForObject("SELECT COUNT(*) FROM md_ingestion_run WHERE run_id=? AND org_id=? AND del_flag='0'",Integer.class,run,org);
|
||||
if(exists==null||exists!=1)throw new IllegalStateException("METADATA_RUN_NOT_FOUND");
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_job) */ INTO md_native_job(job_id,request_id,platform_run_id,actor_id,org_id,state) VALUES(?,?,?,?,?,'PREPARED') ",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_job) */ INTO md_native_job(job_id,request_id,platform_run_id,actor_id,org_id,state) VALUES(?,?,?,?,?,'PREPARED') ", "INSERT IGNORE INTO md_native_job(job_id,request_id,platform_run_id,actor_id,org_id,state) VALUES(?,?,?,?,?,'PREPARED') "),
|
||||
UUID.randomUUID().toString(),request,run,actor,org);
|
||||
});
|
||||
}
|
||||
|
||||
+5
-2
@@ -13,6 +13,9 @@ import java.util.*;
|
||||
|
||||
@DubboService(interfaceClass=NativeMetadataRegistrationService.class,version=NativeMetadataRegistrationService.VERSION,group=NativeMetadataRegistrationService.GROUP,register=false,timeout=15000,retries=0)
|
||||
public class NativeMetadataRegistration implements NativeMetadataRegistrationService {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final NativeMetadataMode mode;private final TransactionTemplate tx;private final MetadataProjectionService projection;private final NativeMetadataIngestion ingestion;
|
||||
public NativeMetadataRegistration(JdbcTemplate jdbc,NativeMetadataMode mode,TransactionTemplate tx,MetadataProjectionService projection,NativeMetadataIngestion ingestion){this.jdbc=jdbc;this.mode=mode;this.tx=tx;this.projection=projection;this.ingestion=ingestion;}
|
||||
@Override public boolean nativeActive(){return mode.nativeActive();}
|
||||
@@ -56,8 +59,8 @@ public class NativeMetadataRegistration implements NativeMetadataRegistrationSer
|
||||
var c=columns.addObject().put("name",column[0]).put("dataType",column[1]);if("record_id".equals(column[0]))c.put("constraint","PRIMARY_KEY");if("amount".equals(column[0]))c.put("dataLength",18);
|
||||
}
|
||||
}
|
||||
jdbc.update("INSERT INTO md_native_entity(entity_id,entity_kind,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))",id,kind,service==null?id:service.path("id").asText(),parent==null?null:parent.path("id").asText(),name,fqn,p.toString());return p;
|
||||
jdbc.update(databaseDialect.sql("INSERT INTO md_native_entity(entity_id,entity_kind,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))", "INSERT INTO md_native_entity(entity_id,entity_kind,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,0.1,UTC_TIMESTAMP(6))"),id,kind,service==null?id:service.path("id").asText(),parent==null?null:parent.path("id").asText(),name,fqn,p.toString());return p;
|
||||
}
|
||||
private void relation(String from,String to,long run,String request){String id=NativeMetadataCatalog.hash(List.of(from,to));jdbc.update("MERGE INTO md_native_relation t USING (SELECT ? AS relation_id, 'TABLE' AS from_kind, ? AS from_id, 'TABLE' AS to_kind, ? AS to_id, '[]' AS field_mappings, ? AS evidence_ref, CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) AS observed_at FROM DUAL) s ON ((t.relation_id=s.relation_id)) WHEN MATCHED THEN UPDATE SET t.evidence_ref=s.evidence_ref,t.observed_at=s.observed_at WHEN NOT MATCHED THEN INSERT (relation_id,from_kind,from_id,to_kind,to_id,field_mappings,evidence_ref,observed_at) VALUES (s.relation_id,s.from_kind,s.from_id,s.to_kind,s.to_id,s.field_mappings,s.evidence_ref,s.observed_at)",id,from,to,"DATAGOV_GOLDEN:"+run+":"+request);}
|
||||
private void relation(String from,String to,long run,String request){String id=NativeMetadataCatalog.hash(List.of(from,to));jdbc.update(databaseDialect.sql("MERGE INTO md_native_relation t USING (SELECT ? AS relation_id, 'TABLE' AS from_kind, ? AS from_id, 'TABLE' AS to_kind, ? AS to_id, '[]' AS field_mappings, ? AS evidence_ref, CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) AS observed_at FROM DUAL) s ON ((t.relation_id=s.relation_id)) WHEN MATCHED THEN UPDATE SET t.evidence_ref=s.evidence_ref,t.observed_at=s.observed_at WHEN NOT MATCHED THEN INSERT (relation_id,from_kind,from_id,to_kind,to_id,field_mappings,evidence_ref,observed_at) VALUES (s.relation_id,s.from_kind,s.from_id,s.to_kind,s.to_id,s.field_mappings,s.evidence_ref,s.observed_at)", "INSERT INTO md_native_relation(relation_id,from_kind,from_id,to_kind,to_id,field_mappings,evidence_ref,observed_at) SELECT s.relation_id,s.from_kind,s.from_id,s.to_kind,s.to_id,s.field_mappings,s.evidence_ref,s.observed_at FROM (SELECT ? AS relation_id, 'TABLE' AS from_kind, ? AS from_id, 'TABLE' AS to_kind, ? AS to_id, '[]' AS field_mappings, ? AS evidence_ref, UTC_TIMESTAMP(6) AS observed_at FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE evidence_ref=s.evidence_ref,observed_at=s.observed_at"),id,from,to,"DATAGOV_GOLDEN:"+run+":"+request);}
|
||||
private static ObjectNode reference(JsonNode e,String type){return JsonUtils.getObjectMapper().createObjectNode().put("id",e.path("id").asText()).put("type",type).put("name",e.path("name").asText()).put("fullyQualifiedName",e.path("fullyQualifiedName").asText());}
|
||||
}
|
||||
|
||||
+20
-17
@@ -18,6 +18,9 @@ import java.util.regex.Pattern;
|
||||
/** Durable, fenced technical scans. No data DAGs, business samples or destructive source operations. */
|
||||
@Component
|
||||
public class NativeMetadataWorker {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc; private final NativeMetadataMode mode; private final TransactionTemplate tx;
|
||||
@DubboReference(interfaceClass=MetadataScanService.class,version=MetadataScanService.VERSION,group=MetadataScanService.GROUP,url="dubbo://integration:20880",check=false,timeout=15000,retries=0)
|
||||
private MetadataScanService scan;
|
||||
@@ -25,20 +28,20 @@ public class NativeMetadataWorker {
|
||||
@Scheduled(fixedDelay=5000,scheduler="nativeMetadataScheduler")
|
||||
public void tick() {
|
||||
if(!mode.nativeActive())return;
|
||||
var ids=jdbc.queryForList("SELECT j.job_id FROM md_native_job j JOIN md_ingestion_request q ON q.org_id=j.org_id AND q.request_id=j.request_id AND q.action_type='RUN' AND q.request_status='COMPLETED' WHERE j.state='PENDING' OR (j.state='RUNNING' AND j.heartbeat_at<TIMESTAMPADD(SECOND,-45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))) ORDER BY j.created_at LIMIT 8",String.class);
|
||||
var ids=jdbc.queryForList(databaseDialect.sql("SELECT j.job_id FROM md_native_job j JOIN md_ingestion_request q ON q.org_id=j.org_id AND q.request_id=j.request_id AND q.action_type='RUN' AND q.request_status='COMPLETED' WHERE j.state='PENDING' OR (j.state='RUNNING' AND j.heartbeat_at<TIMESTAMPADD(SECOND,-45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))) ORDER BY j.created_at LIMIT 8", "SELECT j.job_id FROM md_native_job j JOIN md_ingestion_request q ON q.org_id=j.org_id AND q.request_id=j.request_id AND q.action_type='RUN' AND q.request_status='COMPLETED' WHERE j.state='PENDING' OR (j.state='RUNNING' AND j.heartbeat_at<TIMESTAMPADD(SECOND,-45,UTC_TIMESTAMP(6))) ORDER BY j.created_at LIMIT 8"),String.class);
|
||||
for(String id:ids){Job job=claim(id);if(job!=null){run(job);break;}}
|
||||
}
|
||||
private Job claim(String id) {
|
||||
long epoch=mode.state().epoch();return tx.execute(s->{
|
||||
mode.requireWrite(epoch);
|
||||
var rows=jdbc.queryForList("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)))))",id);
|
||||
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("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))))",org,source,id);
|
||||
var leases=jdbc.queryForList("SELECT fence_token,expires_at<CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) AS expired FROM md_native_source_lease WHERE org_id=? AND source_id=? FOR UPDATE",org,source);
|
||||
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);
|
||||
if(((Number)leases.getFirst().get("expired")).intValue()!=1)return null;
|
||||
long fence=num(leases.getFirst(),"fence_token")+1;
|
||||
jdbc.update("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=?",id,fence,org,source);
|
||||
int changed=jdbc.update("UPDATE md_native_job SET state='RUNNING',fence_token=?,heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),started_at=COALESCE(started_at,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))) WHERE job_id=? AND (state='PENDING' OR (state='RUNNING' AND heartbeat_at<TIMESTAMPADD(SECOND,-45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))))",fence,id);
|
||||
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);
|
||||
int changed=jdbc.update(databaseDialect.sql("UPDATE md_native_job SET state='RUNNING',fence_token=?,heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),started_at=COALESCE(started_at,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))) WHERE job_id=? AND (state='PENDING' OR (state='RUNNING' AND heartbeat_at<TIMESTAMPADD(SECOND,-45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))))", "UPDATE md_native_job SET state='RUNNING',fence_token=?,heartbeat_at=UTC_TIMESTAMP(6),started_at=COALESCE(started_at,UTC_TIMESTAMP(6)) WHERE job_id=? AND (state='PENDING' OR (state='RUNNING' AND heartbeat_at<TIMESTAMPADD(SECOND,-45,UTC_TIMESTAMP(6))))"),fence,id);
|
||||
if(changed!=1){s.setRollbackOnly();return null;}
|
||||
return new Job(id,org,num(r,"actor_id"),source,num(r,"source_version"),num(r,"platform_run_id"),fence,epoch,(String)r.get("request_id"),(String)r.get("service_id"),(String)r.get("service_fqn"),(String)r.get("pipeline_fqn"),(String)r.get("checkpoint"),JsonUtils.parseObject((String)r.get("config_json"),BoundSubmitCommand.class));
|
||||
});
|
||||
@@ -58,7 +61,7 @@ public class NativeMetadataWorker {
|
||||
var structure=scan.structure(new MetadataScanService.TableQuery(source(job),table.database(),table.name(),table.schema()));
|
||||
if(structure==null||!structure.complete()||structure.fields()==null||structure.fields().isEmpty()||structure.table()==null
|
||||
||!table.database().equals(structure.table().database())||!table.name().equals(structure.table().name())||!Objects.equals(table.schema(),structure.table().schema()))throw new IllegalStateException("METADATA_SCAN_INCOMPLETE");
|
||||
tx.executeWithoutResult(s->{guard(job);String value=JsonUtils.toJsonString(structure);jdbc.update("MERGE INTO md_native_scan_stage t USING (SELECT ? AS job_id, ? AS object_key, ? AS table_name, ? AS structure_json, ? AS structure_sha FROM DUAL) s ON ((t.job_id=s.job_id AND t.object_key=s.object_key)) WHEN MATCHED THEN UPDATE SET t.structure_json=s.structure_json,t.structure_sha=s.structure_sha WHEN NOT MATCHED THEN INSERT (job_id,object_key,table_name,structure_json,structure_sha) VALUES (s.job_id,s.object_key,s.table_name,s.structure_json,s.structure_sha)",job.id(),NativeMetadataIdentity.key(table),table.name(),value,NativeMetadataCatalog.hash(structure));heartbeat(job);});
|
||||
tx.executeWithoutResult(s->{guard(job);String value=JsonUtils.toJsonString(structure);jdbc.update(databaseDialect.sql("MERGE INTO md_native_scan_stage t USING (SELECT ? AS job_id, ? AS object_key, ? AS table_name, ? AS structure_json, ? AS structure_sha FROM DUAL) s ON ((t.job_id=s.job_id AND t.object_key=s.object_key)) WHEN MATCHED THEN UPDATE SET t.structure_json=s.structure_json,t.structure_sha=s.structure_sha WHEN NOT MATCHED THEN INSERT (job_id,object_key,table_name,structure_json,structure_sha) VALUES (s.job_id,s.object_key,s.table_name,s.structure_json,s.structure_sha)", "INSERT INTO md_native_scan_stage(job_id,object_key,table_name,structure_json,structure_sha) SELECT s.job_id,s.object_key,s.table_name,s.structure_json,s.structure_sha FROM (SELECT ? AS job_id, ? AS object_key, ? AS table_name, ? AS structure_json, ? AS structure_sha FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE structure_json=s.structure_json,structure_sha=s.structure_sha"),job.id(),NativeMetadataIdentity.key(table),table.name(),value,NativeMetadataCatalog.hash(structure));heartbeat(job);});
|
||||
}
|
||||
String next=batch.nextCursor();
|
||||
tx.executeWithoutResult(s->{guard(job);jdbc.update("UPDATE md_native_job SET checkpoint=?,catalog_complete=? WHERE job_id=? AND fence_token=?",next,batch.complete(),job.id(),job.fence());heartbeat(job);});
|
||||
@@ -67,7 +70,7 @@ public class NativeMetadataWorker {
|
||||
}
|
||||
throw new IllegalStateException("METADATA_SCAN_LIMIT");
|
||||
}catch(RuntimeException error){
|
||||
jdbc.update("UPDATE md_native_job SET state='UNKNOWN',error_code='METADATA_SCAN_UNCONFIRMED',heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE job_id=? AND fence_token=? AND state='RUNNING'",job.id(),job.fence());
|
||||
jdbc.update(databaseDialect.sql("UPDATE md_native_job SET state='UNKNOWN',error_code='METADATA_SCAN_UNCONFIRMED',heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE job_id=? AND fence_token=? AND state='RUNNING'", "UPDATE md_native_job SET state='UNKNOWN',error_code='METADATA_SCAN_UNCONFIRMED',heartbeat_at=UTC_TIMESTAMP(6) WHERE job_id=? AND fence_token=? AND state='RUNNING'"),job.id(),job.fence());
|
||||
jdbc.update("UPDATE md_ingestion_run r JOIN md_native_job j ON j.platform_run_id=r.run_id AND j.org_id=r.org_id SET r.run_status='UNKNOWN',r.external_error_code='METADATA_SCAN_UNCONFIRMED',r.error_summary='元数据扫描未取得完整结果,原目录已保留' WHERE j.job_id=? AND j.fence_token=? AND j.state='UNKNOWN' AND r.run_status IN ('SUBMITTED','RUNNING')",job.id(),job.fence());
|
||||
}
|
||||
}
|
||||
@@ -79,7 +82,7 @@ public class NativeMetadataWorker {
|
||||
guard(job);
|
||||
var servicePayload=ref(job.service(),"databaseService",job.serviceFqn(),job.serviceFqn());
|
||||
servicePayload.put("version",0.1).put("updatedAt",System.currentTimeMillis());
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_entity) */ INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,'SERVICE',?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))",job.service(),job.org(),job.source(),job.service(),job.serviceFqn(),job.serviceFqn(),servicePayload.toString());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(md_native_entity) */ INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,'SERVICE',?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))", "INSERT IGNORE INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,'SERVICE',?,?,?,?,?,?,0.1,UTC_TIMESTAMP(6))"),job.service(),job.org(),job.source(),job.service(),job.serviceFqn(),job.serviceFqn(),servicePayload.toString());
|
||||
List<String> values=jdbc.queryForList("SELECT structure_json FROM md_native_scan_stage WHERE job_id=? ORDER BY object_key",String.class,job.id());
|
||||
if(values.size()>20000)throw new IllegalStateException("METADATA_SCAN_LIMIT");
|
||||
for(String value:values){var table=JsonUtils.parseObject(value,MetadataScanService.TableStructure.class);NativeMetadataIdentity.validate(identity,table.table());if(!selected(job.config(),table.table()))throw new IllegalStateException("METADATA_STAGE_SCOPE_CHANGED");upsert(job,table);}
|
||||
@@ -90,11 +93,11 @@ public class NativeMetadataWorker {
|
||||
if(table!=null&&selected(job.config(),table))
|
||||
jdbc.update("UPDATE md_native_entity SET scan_status='UNCONFIRMED' WHERE entity_kind='TABLE' AND entity_id=? AND org_id=?",entity.get("entity_id"),job.org());
|
||||
}
|
||||
jdbc.update("MERGE INTO md_native_source_binding t USING (SELECT ? AS org_id, ? AS source_id, ? AS source_version, ? AS service_id, ? AS service_fqn, ? AS pipeline_id, ? AS pipeline_fqn, ? AS evidence_run_id, ? AS evidence_request_id FROM DUAL) s ON ((t.org_id=s.org_id AND t.source_id=s.source_id AND t.service_id=s.service_id)) WHEN MATCHED THEN UPDATE SET t.source_version=s.source_version,t.pipeline_id=s.pipeline_id,t.pipeline_fqn=s.pipeline_fqn,t.evidence_run_id=s.evidence_run_id,t.evidence_request_id=s.evidence_request_id WHEN NOT MATCHED THEN INSERT (org_id,source_id,source_version,service_id,service_fqn,pipeline_id,pipeline_fqn,evidence_run_id,evidence_request_id) VALUES (s.org_id,s.source_id,s.source_version,s.service_id,s.service_fqn,s.pipeline_id,s.pipeline_fqn,s.evidence_run_id,s.evidence_request_id)",
|
||||
jdbc.update(databaseDialect.sql("MERGE INTO md_native_source_binding t USING (SELECT ? AS org_id, ? AS source_id, ? AS source_version, ? AS service_id, ? AS service_fqn, ? AS pipeline_id, ? AS pipeline_fqn, ? AS evidence_run_id, ? AS evidence_request_id FROM DUAL) s ON ((t.org_id=s.org_id AND t.source_id=s.source_id AND t.service_id=s.service_id)) WHEN MATCHED THEN UPDATE SET t.source_version=s.source_version,t.pipeline_id=s.pipeline_id,t.pipeline_fqn=s.pipeline_fqn,t.evidence_run_id=s.evidence_run_id,t.evidence_request_id=s.evidence_request_id WHEN NOT MATCHED THEN INSERT (org_id,source_id,source_version,service_id,service_fqn,pipeline_id,pipeline_fqn,evidence_run_id,evidence_request_id) VALUES (s.org_id,s.source_id,s.source_version,s.service_id,s.service_fqn,s.pipeline_id,s.pipeline_fqn,s.evidence_run_id,s.evidence_request_id)", "INSERT INTO md_native_source_binding(org_id,source_id,source_version,service_id,service_fqn,pipeline_id,pipeline_fqn,evidence_run_id,evidence_request_id) SELECT s.org_id,s.source_id,s.source_version,s.service_id,s.service_fqn,s.pipeline_id,s.pipeline_fqn,s.evidence_run_id,s.evidence_request_id FROM (SELECT ? AS org_id, ? AS source_id, ? AS source_version, ? AS service_id, ? AS service_fqn, ? AS pipeline_id, ? AS pipeline_fqn, ? AS evidence_run_id, ? AS evidence_request_id FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE source_version=s.source_version,pipeline_id=s.pipeline_id,pipeline_fqn=s.pipeline_fqn,evidence_run_id=s.evidence_run_id,evidence_request_id=s.evidence_request_id"),
|
||||
job.org(),job.source(),job.sourceVersion(),job.service(),job.serviceFqn(),job.id(),job.pipelineFqn(),job.run(),job.request());
|
||||
jdbc.update("UPDATE md_native_job SET state='SUCCEEDED',completed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),asset_count=?,error_code=NULL WHERE job_id=? AND fence_token=?",values.size(),job.id(),job.fence());
|
||||
jdbc.update(databaseDialect.sql("UPDATE md_native_job SET state='SUCCEEDED',completed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),asset_count=?,error_code=NULL WHERE job_id=? AND fence_token=?", "UPDATE md_native_job SET state='SUCCEEDED',completed_at=UTC_TIMESTAMP(6),heartbeat_at=UTC_TIMESTAMP(6),asset_count=?,error_code=NULL WHERE job_id=? AND fence_token=?"),values.size(),job.id(),job.fence());
|
||||
jdbc.update("UPDATE md_ingestion_run SET run_status='SUCCEEDED',asset_count=?,external_error_code=NULL,error_summary=NULL,finished_at=NOW(),update_time=NOW(),version=version+1 WHERE run_id=? AND org_id=? AND run_status IN ('SUBMITTED','RUNNING','UNKNOWN')",values.size(),job.run(),job.org());
|
||||
jdbc.update("UPDATE md_native_source_lease SET expires_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?",job.org(),job.source(),job.id(),job.fence());
|
||||
jdbc.update(databaseDialect.sql("UPDATE md_native_source_lease SET expires_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?", "UPDATE md_native_source_lease SET expires_at=UTC_TIMESTAMP(6) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?"),job.org(),job.source(),job.id(),job.fence());
|
||||
});
|
||||
}
|
||||
private void upsert(Job job,MetadataScanService.TableStructure t) {
|
||||
@@ -128,10 +131,10 @@ public class NativeMetadataWorker {
|
||||
var constraints=p.putArray("tableConstraints");for(var c:t.constraints()){var v=constraints.addObject().put("constraintType",c.type());var fields=v.putArray("columns");c.columns().forEach(fields::add);if(c.referredTable()!=null){v.put("referredTable",c.referredTable());var refs=v.putArray("referredColumns");c.referredColumns().forEach(refs::add);}}
|
||||
if(t.location()!=null)p.put("locationPath",t.location());
|
||||
if(!t.partitions().isEmpty()){var partitions=p.putObject("tablePartition").putArray("columns");t.partitions().forEach(name->partitions.addObject().put("columnName",name));}
|
||||
if(p.equals(before)){jdbc.update("UPDATE md_native_entity SET observed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),scan_status='CURRENT',last_seen_job=? WHERE entity_kind='TABLE' AND entity_id=? AND org_id=?",job.id(),id,job.org());return;}
|
||||
if(p.equals(before)){jdbc.update(databaseDialect.sql("UPDATE md_native_entity SET observed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)),scan_status='CURRENT',last_seen_job=? WHERE entity_kind='TABLE' AND entity_id=? AND org_id=?", "UPDATE md_native_entity SET observed_at=UTC_TIMESTAMP(6),scan_status='CURRENT',last_seen_job=? WHERE entity_kind='TABLE' AND entity_id=? AND org_id=?"),job.id(),id,job.org());return;}
|
||||
BigDecimal version=existing.isEmpty()?new BigDecimal("0.1"):((BigDecimal)existing.getFirst().get("external_version")).add(new BigDecimal("0.1"));
|
||||
long revision=existing.isEmpty()?1:num(existing.getFirst(),"row_version")+1;p.put("version",version).put("updatedAt",System.currentTimeMillis());
|
||||
jdbc.update("MERGE INTO md_native_entity t USING (SELECT ? AS entity_id, 'TABLE' AS entity_kind, ? AS org_id, ? AS source_id, ? AS service_id, ? AS parent_id, ? AS entity_name, ? AS fqn, ? AS payload, ? AS external_version, ? AS row_version, CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) AS observed_at FROM DUAL) s ON ((t.entity_kind=s.entity_kind AND t.entity_id=s.entity_id)) WHEN MATCHED THEN UPDATE SET t.payload=s.payload,t.external_version=s.external_version,t.row_version=s.row_version,t.observed_at=s.observed_at WHEN NOT MATCHED THEN INSERT (entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,row_version,observed_at) VALUES (s.entity_id,s.entity_kind,s.org_id,s.source_id,s.service_id,s.parent_id,s.entity_name,s.fqn,s.payload,s.external_version,s.row_version,s.observed_at)",id,job.org(),job.source(),job.service(),p.path("databaseSchema").path("id").asText(),t.table().name(),p.path("fullyQualifiedName").asText(),p.toString(),version,revision);
|
||||
jdbc.update(databaseDialect.sql("MERGE INTO md_native_entity t USING (SELECT ? AS entity_id, 'TABLE' AS entity_kind, ? AS org_id, ? AS source_id, ? AS service_id, ? AS parent_id, ? AS entity_name, ? AS fqn, ? AS payload, ? AS external_version, ? AS row_version, CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) AS observed_at FROM DUAL) s ON ((t.entity_kind=s.entity_kind AND t.entity_id=s.entity_id)) WHEN MATCHED THEN UPDATE SET t.payload=s.payload,t.external_version=s.external_version,t.row_version=s.row_version,t.observed_at=s.observed_at WHEN NOT MATCHED THEN INSERT (entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,row_version,observed_at) VALUES (s.entity_id,s.entity_kind,s.org_id,s.source_id,s.service_id,s.parent_id,s.entity_name,s.fqn,s.payload,s.external_version,s.row_version,s.observed_at)", "INSERT INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,row_version,observed_at) SELECT s.entity_id,s.entity_kind,s.org_id,s.source_id,s.service_id,s.parent_id,s.entity_name,s.fqn,s.payload,s.external_version,s.row_version,s.observed_at FROM (SELECT ? AS entity_id, 'TABLE' AS entity_kind, ? AS org_id, ? AS source_id, ? AS service_id, ? AS parent_id, ? AS entity_name, ? AS fqn, ? AS payload, ? AS external_version, ? AS row_version, UTC_TIMESTAMP(6) AS observed_at FROM DUAL) s WHERE TRUE ON DUPLICATE KEY UPDATE payload=s.payload,external_version=s.external_version,row_version=s.row_version,observed_at=s.observed_at"),id,job.org(),job.source(),job.service(),p.path("databaseSchema").path("id").asText(),t.table().name(),p.path("fullyQualifiedName").asText(),p.toString(),version,revision);
|
||||
jdbc.update("INSERT INTO md_native_revision(entity_kind,entity_id,org_id,row_version,request_id,before_json,after_json,actor_id) VALUES('TABLE',?,?,?,?,?,?,?)",id,job.org(),revision,job.id()+":"+id,before.toString(),p.toString(),job.actor());
|
||||
jdbc.update("UPDATE md_native_entity SET scan_status='CURRENT',last_seen_job=? WHERE entity_kind='TABLE' AND entity_id=? AND org_id=?",job.id(),id,job.org());
|
||||
}
|
||||
@@ -150,14 +153,14 @@ public class NativeMetadataWorker {
|
||||
p.set("database",ref(parent,"database",(String)db.get("entity_name"),(String)db.get("fqn")));
|
||||
}
|
||||
p.put("version",0.1).put("updatedAt",System.currentTimeMillis());
|
||||
jdbc.update("INSERT INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))",id,kind,job.org(),job.source(),job.service(),parent,name,fqn,p.toString());return id;
|
||||
jdbc.update(databaseDialect.sql("INSERT INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,?,?,0.1,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)))", "INSERT INTO md_native_entity(entity_id,entity_kind,org_id,source_id,service_id,parent_id,entity_name,fqn,payload,external_version,observed_at) VALUES(?,?,?,?,?,?,?,?,?,0.1,UTC_TIMESTAMP(6))"),id,kind,job.org(),job.source(),job.service(),parent,name,fqn,p.toString());return id;
|
||||
}
|
||||
private void guard(Job job) {
|
||||
mode.requireWrite(job.epoch());
|
||||
var owned=jdbc.queryForList("SELECT job_id FROM md_native_source_lease WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=? AND expires_at>CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) FOR UPDATE",String.class,job.org(),job.source(),job.id(),job.fence());
|
||||
var owned=jdbc.queryForList(databaseDialect.sql("SELECT job_id FROM md_native_source_lease WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=? AND expires_at>CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) FOR UPDATE", "SELECT job_id FROM md_native_source_lease WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=? AND expires_at>UTC_TIMESTAMP(6) FOR UPDATE"),String.class,job.org(),job.source(),job.id(),job.fence());
|
||||
if(owned.size()!=1)throw new IllegalStateException("METADATA_WORKER_FENCED");
|
||||
}
|
||||
private void heartbeat(Job j){jdbc.update("UPDATE md_native_job SET heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE job_id=? AND fence_token=?",j.id(),j.fence());jdbc.update("UPDATE md_native_source_lease SET expires_at=TIMESTAMPADD(SECOND,45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?",j.org(),j.source(),j.id(),j.fence());}
|
||||
private void heartbeat(Job j){jdbc.update(databaseDialect.sql("UPDATE md_native_job SET heartbeat_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6)) WHERE job_id=? AND fence_token=?", "UPDATE md_native_job SET heartbeat_at=UTC_TIMESTAMP(6) WHERE job_id=? AND fence_token=?"),j.id(),j.fence());jdbc.update(databaseDialect.sql("UPDATE md_native_source_lease SET expires_at=TIMESTAMPADD(SECOND,45,CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(6))) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?", "UPDATE md_native_source_lease SET expires_at=TIMESTAMPADD(SECOND,45,UTC_TIMESTAMP(6)) WHERE org_id=? AND source_id=? AND job_id=? AND fence_token=?"),j.org(),j.source(),j.id(),j.fence());}
|
||||
static boolean accept(FilterPattern filter,String name){if(filter==null)return true;boolean included=filter.includes()==null||filter.includes().isEmpty()||filter.includes().stream().anyMatch(p->Pattern.matches(p,name));return included&&(filter.excludes()==null||filter.excludes().stream().noneMatch(p->Pattern.matches(p,name)));}
|
||||
static boolean selected(BoundSubmitCommand config,MetadataScanService.Table table){return accept(config.databaseFilter(),table.database())&&accept(config.schemaFilter(),NativeMetadataIdentity.schema(table))&&accept(config.tableFilter(),table.name());}
|
||||
private static MetadataScanService.Source source(Job j){return new MetadataScanService.Source(j.actor(),j.org(),j.source(),j.sourceVersion());}
|
||||
|
||||
+11
-2
@@ -23,6 +23,9 @@ import java.util.List;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class QualityModelJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String DIMENSION_SELECT = """
|
||||
SELECT dimension_id, dimension_code, dimension_name, description_text, dimension_status,
|
||||
@@ -50,13 +53,19 @@ class QualityModelJdbcRepository {
|
||||
""", (rs, rowNum) -> new DimensionSeed(rs.getString("dimension_code"),
|
||||
rs.getString("dimension_name"), rs.getString("description_text")));
|
||||
for (DimensionSeed seed : seeds) {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_quality_dimension) */ INTO dq_quality_dimension(
|
||||
dimension_id, dimension_code, dimension_name, description_text, dimension_status,
|
||||
normative_flag, organization_id, department_id, create_dept, create_by, create_time,
|
||||
update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, 'ENABLED', '1', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
""", IdGeneratorUtil.nextLongId(), seed.code(), seed.name(), seed.description(),
|
||||
""", """
|
||||
INSERT IGNORE INTO dq_quality_dimension(
|
||||
dimension_id, dimension_code, dimension_name, description_text, dimension_status,
|
||||
normative_flag, organization_id, department_id, create_dept, create_by, create_time,
|
||||
update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, 'ENABLED', '1', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
"""), IdGeneratorUtil.nextLongId(), seed.code(), seed.name(), seed.description(),
|
||||
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
|
||||
}
|
||||
}
|
||||
|
||||
+12
-2
@@ -17,6 +17,9 @@ import java.util.List;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class QualityRuleJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String TEMPLATE_SELECT = """
|
||||
SELECT template_id, template_code, template_name, template_type, description_text,
|
||||
@@ -49,14 +52,21 @@ class QualityRuleJdbcRepository {
|
||||
rs.getString("template_name"), TemplateType.valueOf(rs.getString("template_type")),
|
||||
rs.getString("description_text"), rs.getString("definition_json")));
|
||||
for (TemplateSeed seed : seeds) {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_quality_rule_template) */ INTO dq_quality_rule_template(
|
||||
template_id, template_code, template_name, template_type, description_text,
|
||||
definition_json, custom_sql_draft, sql_validation_status, template_status,
|
||||
system_template_flag, organization_id, department_id, create_dept, create_by,
|
||||
create_time, update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 'ENABLED', '1', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
""", IdGeneratorUtil.nextLongId(), seed.code(), seed.name(), seed.type().name(), seed.description(),
|
||||
""", """
|
||||
INSERT IGNORE INTO dq_quality_rule_template(
|
||||
template_id, template_code, template_name, template_type, description_text,
|
||||
definition_json, custom_sql_draft, sql_validation_status, template_status,
|
||||
system_template_flag, organization_id, department_id, create_dept, create_by,
|
||||
create_time, update_by, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 'ENABLED', '1', ?, ?, ?, ?, NOW(), ?, NOW(), '0', 0)
|
||||
"""), IdGeneratorUtil.nextLongId(), seed.code(), seed.name(), seed.type().name(), seed.description(),
|
||||
seed.definitionJson(), actor.organizationId(), actor.departmentId(), actor.departmentId(),
|
||||
actor.actorId(), actor.actorId());
|
||||
}
|
||||
|
||||
+4
-1
@@ -22,6 +22,9 @@ import java.util.Map;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class RootCauseAnalysisJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private static final String SELECT = "SELECT analysis_id,analysis_no,issue_logical_id,issue_display_snapshot,input_sha256,algorithm_version,analysis_status,evidence_state,organization_id,department_id,version,create_time,update_time FROM dq_root_cause_analysis";
|
||||
private static final String ROOT = "/api/governance/v1/root-cause-analyses";
|
||||
private final JdbcTemplate jdbc;
|
||||
@@ -235,7 +238,7 @@ class RootCauseAnalysisJdbcRepository {
|
||||
void saveImpacts(Actor actor, AnalysisView analysis, List<ImpactDraft> values, String requestId) {
|
||||
int changed = jdbc.update("UPDATE dq_root_cause_analysis SET update_by=?,version=version+1 WHERE analysis_id=? AND organization_id=? AND department_id=? AND version=? AND analysis_status<>'CLOSED'", actor.actorId(), analysis.analysisId(), actor.organizationId(), actor.departmentId(), analysis.version());
|
||||
if (changed != 1) throw RootCauseAnalysisDomainException.conflict("版本或状态已变化");
|
||||
for (ImpactDraft d : values) jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_root_cause_impact) */ INTO dq_root_cause_impact(impact_id,analysis_id,input_sha256,impact_type,object_id,display_name,graph_distance,path_object_ids_json,path_evidence_refs_json,evidence_sha256,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", IdGeneratorUtil.nextId(), analysis.analysisId(), analysis.inputSha(), d.impact().impactType().name(), d.impact().objectId(), d.impact().displayName(), d.path().distance(), json(d.path().objectIds()), json(d.path().evidenceRefs()), d.evidenceSha(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), LocalDateTime.now());
|
||||
for (ImpactDraft d : values) jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_root_cause_impact) */ INTO dq_root_cause_impact(impact_id,analysis_id,input_sha256,impact_type,object_id,display_name,graph_distance,path_object_ids_json,path_evidence_refs_json,evidence_sha256,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "INSERT IGNORE INTO dq_root_cause_impact(impact_id,analysis_id,input_sha256,impact_type,object_id,display_name,graph_distance,path_object_ids_json,path_evidence_refs_json,evidence_sha256,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"), IdGeneratorUtil.nextId(), analysis.analysisId(), analysis.inputSha(), d.impact().impactType().name(), d.impact().objectId(), d.impact().displayName(), d.path().distance(), json(d.path().objectIds()), json(d.path().evidenceRefs()), d.evidenceSha(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), LocalDateTime.now());
|
||||
timeline(actor, analysis.analysisId(), TimelineType.IMPACT_CALCULATED, analysis.status().name(), analysis.status().name(), values.isEmpty() ? "影响证据不足" : "影响范围已从快照计算", requestId);
|
||||
}
|
||||
long confirm(Actor actor, AnalysisView analysis, ConfirmCommand command, String requestId) {
|
||||
|
||||
+5
-4
@@ -8,13 +8,14 @@ import java.util.*;
|
||||
|
||||
/** Shared by every original rule confirmation and semantic confirmation. No external-engine claim. */
|
||||
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){
|
||||
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);
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(sec_classification_resource_guard) */ INTO sec_classification_resource_guard(guard_id,resource_sha256,resource_ref,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(6),?,NOW(6),'0',0) ",
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(sec_classification_resource_guard) */ INTO sec_classification_resource_guard(guard_id,resource_sha256,resource_ref,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(6),?,NOW(6),'0',0) ", "INSERT IGNORE INTO sec_classification_resource_guard(guard_id,resource_sha256,resource_ref,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,NOW(6),?,NOW(6),'0',0) "),
|
||||
IdGeneratorUtil.nextLongId(),sha,ref,a.organizationId(),a.departmentId(),a.departmentId(),a.actorId(),a.actorId());
|
||||
var rows=jdbc.query("SELECT resource_ref FROM sec_classification_resource_guard WHERE organization_id=? AND department_id=? AND resource_sha256=? AND del_flag='0' AND version=0 FOR UPDATE",(r,n)->r.getString(1),a.organizationId(),a.departmentId(),sha);
|
||||
if(rows.size()!=1||!ref.equals(rows.getFirst()))throw SecurityClassificationDomainException.conflict("资源锁标识冲突");
|
||||
@@ -25,8 +26,8 @@ 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){
|
||||
lock(jdbc,a,List.of(c.resourceRef()));var existing=labels(jdbc,a,c.resourceRef(),true);
|
||||
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("资源已有标签,与本次确认冲突;不能覆盖或降密");
|
||||
}
|
||||
|
||||
+4
-1
@@ -17,6 +17,9 @@ import static cn.aixunkeji.datagov.governance.securityclassification.SecurityCla
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class SecurityClassificationJdbcRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String RULE_SELECT = """
|
||||
SELECT rule_id,rule_code,rule_name,classification_code,level_code,resource_type,condition_field,
|
||||
@@ -432,7 +435,7 @@ class SecurityClassificationJdbcRepository {
|
||||
if (command.decision() == ReviewDecision.CONFIRMED) {
|
||||
requireVocabulary(actor, command.classificationCode(), command.levelCode());
|
||||
lockNativeVocabulary(actor,List.of(command.classificationCode()),List.of(command.levelCode()));
|
||||
ClassificationResourceGuard.confirm(jdbc,actor,candidate,command);
|
||||
ClassificationResourceGuard.confirm(jdbc,actor,candidate,command,databaseDialect);
|
||||
}
|
||||
CandidateStatus target = CandidateStatus.valueOf(command.decision().name());
|
||||
int updated = jdbc.update("""
|
||||
|
||||
+4
-1
@@ -10,6 +10,9 @@ import static cn.aixunkeji.datagov.governance.securityclassification.SecurityCla
|
||||
|
||||
@Repository
|
||||
class SemanticClassificationRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;private final SemanticClassificationPolicy policy;
|
||||
SemanticClassificationRepository(JdbcTemplate jdbc,SemanticClassificationPolicy policy){this.jdbc=jdbc;this.policy=policy;}
|
||||
List<Vocabulary> vocabulary(SecurityClassificationActorProvider.Actor a,boolean levels,boolean lock){
|
||||
@@ -18,7 +21,7 @@ class SemanticClassificationRepository {
|
||||
(r,n)->new Vocabulary((levels?"L":"C")+(n+1),r.getLong(1),r.getLong(2),r.getString(3),r.getString(4)),a.organizationId(),a.departmentId());
|
||||
if(rows.size()>limit)throw SecurityClassificationDomainException.conflict("词表超过有界范围,请先维护词表");return List.copyOf(rows);
|
||||
}
|
||||
void lock(SecurityClassificationActorProvider.Actor a,List<String> refs){ClassificationResourceGuard.lock(jdbc,a,refs);}
|
||||
void lock(SecurityClassificationActorProvider.Actor a,List<String> refs){ClassificationResourceGuard.lock(jdbc,a,refs,databaseDialect);}
|
||||
Map<String,List<ClassificationResourceGuard.Label>> labels(SecurityClassificationActorProvider.Actor a,List<String> refs,boolean lock){var result=new LinkedHashMap<String,List<ClassificationResourceGuard.Label>>();for(String ref:refs.stream().distinct().sorted().toList())result.put(ref,ClassificationResourceGuard.labels(jdbc,a,ref,lock));return Collections.unmodifiableMap(result);}
|
||||
long run(SecurityClassificationActorProvider.Actor a,long snapshot){long id=IdGeneratorUtil.nextLongId();jdbc.update("INSERT INTO sec_identification_run(run_id,rule_id,rule_version,snapshot_id,run_status,reason_code,candidate_count,basis_kind,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,NULL,NULL,?,'RELIABLE',NULL,0,'SEMANTIC_METADATA',?,?,?,?,NOW(),?,NOW(),'0',0)",id,snapshot,a.organizationId(),a.departmentId(),a.departmentId(),a.actorId(),a.actorId());return id;}
|
||||
long candidate(SecurityClassificationActorProvider.Actor a,long run,Binding b){
|
||||
|
||||
+11
-2
@@ -34,6 +34,14 @@ 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());}
|
||||
@@ -41,8 +49,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()>1000
|
||||
||completed.returnedColumns()==null||completed.returnedColumns().size()>200
|
||||
||completed.returnedRows()<0||completed.returnedRows()>(work.request().completeRead()?100000:1000)
|
||||
||completed.returnedColumns()==null||completed.returnedColumns().size()>(work.request().completeRead()?500:200)
|
||||
||completed.returnedColumns().stream().anyMatch(Objects::isNull)
|
||||
||new java.util.HashSet<>(completed.returnedColumns()).size()!=completed.returnedColumns().size()
|
||||
||!work.decision().columns().containsAll(completed.returnedColumns())
|
||||
@@ -67,6 +75,7 @@ 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();
|
||||
|
||||
+4
-1
@@ -11,12 +11,15 @@ import static cn.aixunkeji.datagov.governance.workbenchknowledge.KnowledgeAttach
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class KnowledgeAttachmentRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper mapper;
|
||||
PageResult<View> page(KnowledgeActor.Actor actor,int page,int size) { var count=jdbc.queryForObject("SELECT COUNT(*) FROM wb_knowledge_attachment WHERE owner_id=? AND department_id=? AND file_state<>\'DELETED\' AND (session_id IS NULL OR retained=1)",Long.class,actor.id(),actor.department());var rows=jdbc.query("SELECT state_json FROM wb_knowledge_attachment WHERE owner_id=? AND department_id=? AND file_state<>\'DELETED\' AND (session_id IS NULL OR retained=1) ORDER BY update_time DESC,attachment_id LIMIT ? OFFSET ?",(r,i)->decode(r.getString(1)).view(),actor.id(),actor.department(),size,(page-1)*size);return PageResult.build(rows,count==null?0:count); }
|
||||
Row read(String id,KnowledgeActor.Actor actor,boolean lock) { return jdbc.query("SELECT state_json FROM wb_knowledge_attachment WHERE attachment_id=? AND owner_id=? AND department_id=?"+(lock?" FOR UPDATE":""),(r,i)->decode(r.getString(1)),id,actor.id(),actor.department()).stream().findFirst().orElseThrow(KnowledgeException::forbidden); }
|
||||
Row reserve(Row row) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_attachment) */ INTO wb_knowledge_attachment(attachment_id,owner_id,department_id,file_state,parser_state,state_json,create_dept,create_by,update_by,version,del_flag,session_id,expires_at,retained) VALUES(?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0',?,?,?)",row.id(),row.owner(),row.department(),row.state(),row.parserStatus(),mapper.writeValueAsString(row),row.department(),row.owner(),row.owner(),row.session()==null?null:row.session().sessionId(),row.session()==null?null:java.sql.Timestamp.from(row.session().expiresAt()),row.session()!=null&&row.session().retained()?1:0);
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_attachment) */ INTO wb_knowledge_attachment(attachment_id,owner_id,department_id,file_state,parser_state,state_json,create_dept,create_by,update_by,version,del_flag,session_id,expires_at,retained) VALUES(?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0',?,?,?)", "INSERT IGNORE INTO wb_knowledge_attachment(attachment_id,owner_id,department_id,file_state,parser_state,state_json,create_dept,create_by,update_by,version,del_flag,session_id,expires_at,retained) VALUES(?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0',?,?,?)"),row.id(),row.owner(),row.department(),row.state(),row.parserStatus(),mapper.writeValueAsString(row),row.department(),row.owner(),row.owner(),row.session()==null?null:row.session().sessionId(),row.session()==null?null:java.sql.Timestamp.from(row.session().expiresAt()),row.session()!=null&&row.session().retained()?1:0);
|
||||
return read(row.id(),new KnowledgeActor.Actor(row.owner(),row.department(),java.util.Set.of()),true);
|
||||
}
|
||||
void update(Row before,Row next) {
|
||||
|
||||
+4
-1
@@ -9,6 +9,9 @@ import static cn.aixunkeji.datagov.governance.workbenchknowledge.KnowledgeDraftA
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class KnowledgeDraftRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
Candidate find(String id,KnowledgeActor.Actor actor) {
|
||||
@@ -18,7 +21,7 @@ class KnowledgeDraftRepository {
|
||||
return jdbc.query("SELECT state_json FROM wb_knowledge_candidate WHERE owner_id=? AND department_id=? AND del_flag='0' AND (? IS NULL OR source_id=?) ORDER BY create_time DESC,candidate_id LIMIT 30",(rs,row)->json.readValue(rs.getString(1),Candidate.class),actor.id(),actor.department(),sourceId,sourceId);
|
||||
}
|
||||
boolean reserve(Candidate value,KnowledgeActor.Actor actor) {
|
||||
int inserted=jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_candidate) */ INTO wb_knowledge_candidate(candidate_id,owner_id,department_id,source_id,request_hash,candidate_state,state_json,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0')",value.id(),actor.id(),actor.department(),value.sourceId(),value.requestHash(),value.state(),json.writeValueAsString(value),actor.department(),actor.id(),actor.id());
|
||||
int inserted=jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_candidate) */ INTO wb_knowledge_candidate(candidate_id,owner_id,department_id,source_id,request_hash,candidate_state,state_json,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0')", "INSERT IGNORE INTO wb_knowledge_candidate(candidate_id,owner_id,department_id,source_id,request_hash,candidate_state,state_json,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,CAST(? AS JSON),?,?,?,0,'0')"),value.id(),actor.id(),actor.department(),value.sourceId(),value.requestHash(),value.state(),json.writeValueAsString(value),actor.department(),actor.id(),actor.id());
|
||||
var stored=find(value.id(),actor);if(stored==null)throw KnowledgeException.forbidden();if(!stored.requestHash().equals(value.requestHash()))throw KnowledgeException.conflict("候选标识已用于其他请求");return inserted==1;
|
||||
}
|
||||
void complete(Candidate value,KnowledgeActor.Actor actor) {
|
||||
|
||||
+4
-1
@@ -13,6 +13,9 @@ import static cn.aixunkeji.datagov.governance.workbenchknowledge.KnowledgeApi.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class KnowledgeRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper mapper;
|
||||
PageResult<View> page(KnowledgeActor.Actor a,Kind kind,String keyword,int page,int size) { return page(a,kind,keyword,null,page,size); }
|
||||
@@ -75,7 +78,7 @@ class KnowledgeRepository {
|
||||
if(row.erased) throw KnowledgeException.forbidden(); return row.response==null?null:decode(row.response);
|
||||
}
|
||||
View idempotent(KnowledgeActor.Actor a,String key,String hash,String documentId,Supplier<View> action) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_request) */ INTO wb_knowledge_request(actor_id,department_id,request_key,request_hash,document_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')",a.id(),a.department(),key,hash,documentId,a.department(),a.id(),a.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(wb_knowledge_request) */ INTO wb_knowledge_request(actor_id,department_id,request_key,request_hash,document_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')", "INSERT IGNORE INTO wb_knowledge_request(actor_id,department_id,request_key,request_hash,document_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')"),a.id(),a.department(),key,hash,documentId,a.department(),a.id(),a.id());
|
||||
var rows=jdbc.query("SELECT request_hash,response_json,erased FROM wb_knowledge_request WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,i)->new Receipt(r.getString(1),r.getString(2),r.getBoolean(3)),a.id(),a.department(),key);
|
||||
if(rows.size()!=1||!hash.equals(rows.getFirst().hash)) throw KnowledgeException.conflict("幂等键已用于其他请求");
|
||||
if(rows.getFirst().erased) throw KnowledgeException.forbidden();
|
||||
|
||||
+7
-7
@@ -15,13 +15,13 @@ class ClassificationResourceGuardTest {
|
||||
@AfterEach void end(){TransactionSynchronizationManager.setActualTransactionActive(false);}
|
||||
CandidateView candidate(boolean semantic){return new CandidateView(1,2,semantic?null:3L,ref,"C","L",CandidateStatus.PENDING_REVIEW,0,null,null,semantic?BasisKind.SEMANTIC_METADATA:BasisKind.RULE_MATCH);}
|
||||
final ReviewCommand command=new ReviewCommand(ReviewDecision.CONFIRMED,"C","L","人工确认",0L);
|
||||
@Test void differentRuleLabelCannotBeConfirmed(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"OTHER","L"));assertThatThrownBy(()->ClassificationResourceGuard.confirm(jdbc,actor,candidate(false),command)).hasMessageContaining("冲突");}
|
||||
@Test void identicalRulePairRetainsExistingBehavior(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"C","L"));ClassificationResourceGuard.confirm(jdbc,actor,candidate(false),command);assertThat(jdbc.sql.getFirst()).contains("IGNORE_ROW_ON_DUPKEY_INDEX(sec_classification_resource_guard)");assertThat(jdbc.sql.getLast()).contains("FOR UPDATE","BINARY resource_ref=BINARY ?");}
|
||||
@Test void semanticCannotAppendEvenIdenticalExistingLabel(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"C","L"));assertThatThrownBy(()->ClassificationResourceGuard.confirm(jdbc,actor,candidate(true),command)).hasMessageContaining("不能覆盖");}
|
||||
@Test void emptyCurrentLabelsPermitOriginalReviewToProceed(){ClassificationResourceGuard.confirm(jdbc,actor,candidate(true),command);assertThat(jdbc.sql).hasSize(3);assertThat(jdbc.sql.get(1)).contains("FOR UPDATE","organization_id=?","department_id=?");}
|
||||
@Test void exactFullResourceMustMatchGuardEvenWithSameHash(){jdbc.collision=true;assertThatThrownBy(()->ClassificationResourceGuard.lock(jdbc,actor,List.of(ref))).hasMessageContaining("标识冲突");}
|
||||
@Test void resourcesAreLockedInStableShaOrder(){String other="table:"+SemanticClassificationPolicyTest.ID+"/field/code";ClassificationResourceGuard.lock(jdbc,actor,List.of(ref,other,ref));assertThat(jdbc.inserted).containsExactlyElementsOf(List.of(ref,other).stream().sorted(Comparator.comparing(ClassificationResourceGuard::sha)).toList());}
|
||||
@Test void noAutocommitLockCanPretendToSerializeConfirmations(){TransactionSynchronizationManager.setActualTransactionActive(false);assertThatThrownBy(()->ClassificationResourceGuard.lock(jdbc,actor,List.of(ref))).hasMessageContaining("事务");assertThat(jdbc.sql).isEmpty();}
|
||||
@Test void differentRuleLabelCannotBeConfirmed(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"OTHER","L"));assertThatThrownBy(()->ClassificationResourceGuard.confirm(jdbc,actor,candidate(false),command,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG)).hasMessageContaining("冲突");}
|
||||
@Test void identicalRulePairRetainsExistingBehavior(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"C","L"));ClassificationResourceGuard.confirm(jdbc,actor,candidate(false),command,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);assertThat(jdbc.sql.getFirst()).contains("IGNORE_ROW_ON_DUPKEY_INDEX(sec_classification_resource_guard)");assertThat(jdbc.sql.getLast()).contains("FOR UPDATE","BINARY resource_ref=BINARY ?");}
|
||||
@Test void semanticCannotAppendEvenIdenticalExistingLabel(){jdbc.labels=List.of(new ClassificationResourceGuard.Label(5,0,"C","L"));assertThatThrownBy(()->ClassificationResourceGuard.confirm(jdbc,actor,candidate(true),command,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG)).hasMessageContaining("不能覆盖");}
|
||||
@Test void emptyCurrentLabelsPermitOriginalReviewToProceed(){ClassificationResourceGuard.confirm(jdbc,actor,candidate(true),command,cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);assertThat(jdbc.sql).hasSize(3);assertThat(jdbc.sql.get(1)).contains("FOR UPDATE","organization_id=?","department_id=?");}
|
||||
@Test void exactFullResourceMustMatchGuardEvenWithSameHash(){jdbc.collision=true;assertThatThrownBy(()->ClassificationResourceGuard.lock(jdbc,actor,List.of(ref),cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG)).hasMessageContaining("标识冲突");}
|
||||
@Test void resourcesAreLockedInStableShaOrder(){String other="table:"+SemanticClassificationPolicyTest.ID+"/field/code";ClassificationResourceGuard.lock(jdbc,actor,List.of(ref,other,ref),cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);assertThat(jdbc.inserted).containsExactlyElementsOf(List.of(ref,other).stream().sorted(Comparator.comparing(ClassificationResourceGuard::sha)).toList());}
|
||||
@Test void noAutocommitLockCanPretendToSerializeConfirmations(){TransactionSynchronizationManager.setActualTransactionActive(false);assertThatThrownBy(()->ClassificationResourceGuard.lock(jdbc,actor,List.of(ref),cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG)).hasMessageContaining("事务");assertThat(jdbc.sql).isEmpty();}
|
||||
static class RecordingJdbc extends JdbcTemplate {
|
||||
final List<String> sql=new ArrayList<>(),inserted=new ArrayList<>();List<ClassificationResourceGuard.Label> labels=List.of();String last;boolean collision;
|
||||
@Override public int update(String value,Object...args){sql.add(value);last=(String)args[2];inserted.add(last);return 1;}
|
||||
|
||||
+8
@@ -48,6 +48,14 @@ 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,6 +11,12 @@
|
||||
<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>
|
||||
|
||||
+4
-1
@@ -10,10 +10,13 @@ import static cn.aixunkeji.datagov.integration.aiassistant.AiWorkbenchDomain.Act
|
||||
|
||||
@Repository @RequiredArgsConstructor
|
||||
class WorkbenchMemoryRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
record Settings(boolean enabled,long version) { }
|
||||
Settings settings(Actor actor,boolean lock) {
|
||||
if(lock)jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_workbench_memory_settings) */ INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)",actor.userId(),actor.departmentId());
|
||||
if(lock)jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_ai_workbench_memory_settings) */ INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)", "INSERT IGNORE INTO dg_ai_workbench_memory_settings(actor_id,department_id) VALUES(?,?)"),actor.userId(),actor.departmentId());
|
||||
return jdbc.query("SELECT enabled,version FROM dg_ai_workbench_memory_settings WHERE actor_id=? AND department_id=?"+(lock?" FOR UPDATE":""),
|
||||
(r,n)->new Settings(r.getBoolean(1),r.getLong(2)),actor.userId(),actor.departmentId()).stream().findFirst().orElse(new Settings(false,0));
|
||||
}
|
||||
|
||||
+4
-1
@@ -17,6 +17,9 @@ import static cn.aixunkeji.datagov.integration.aischedule.ScheduleApi.*;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
class ScheduleRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private static final String PLAN_COLUMNS="plan_json,status,next_run_at,reserved_tokens,run_count,pause_reason,version,update_time";
|
||||
@@ -39,7 +42,7 @@ class ScheduleRepository {
|
||||
return rows.getFirst()[1]==null?null:json.readValue(rows.getFirst()[1],Plan.class);
|
||||
}
|
||||
Plan receipt(ScheduleActor.Actor a,String key,String hash,String id,Supplier<Plan> action) {
|
||||
jdbc.update("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_assistant_schedule_request) */ INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')",a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
jdbc.update(databaseDialect.sql("INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_assistant_schedule_request) */ INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')", "INSERT IGNORE INTO dg_assistant_schedule_request(actor_id,department_id,request_key,request_hash,schedule_id,create_dept,create_by,update_by,version,del_flag) VALUES(?,?,?,?,?,?,?,?,0,'0')"),a.id(),a.department(),key,hash,id,a.department(),a.id(),a.id());
|
||||
var rows=jdbc.query("SELECT request_hash,response_json FROM dg_assistant_schedule_request WHERE actor_id=? AND department_id=? AND request_key=? FOR UPDATE",(r,i)->new String[]{r.getString(1),r.getString(2)},a.id(),a.department(),key);
|
||||
if(rows.size()!=1||!hash.equals(rows.getFirst()[0])) throw ScheduleException.conflict("幂等键已用于其他请求");
|
||||
if(rows.getFirst()[1]!=null) return json.readValue(rows.getFirst()[1],Plan.class);
|
||||
|
||||
+32
-3
@@ -117,6 +117,10 @@ 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() + "映射不一致");
|
||||
@@ -169,15 +173,31 @@ 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");
|
||||
}
|
||||
fields.put(field.targetField(), mapped.seaTunnelType());
|
||||
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");
|
||||
}
|
||||
|
||||
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());
|
||||
@@ -194,7 +214,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");
|
||||
"&forceConnectionTimeZoneToSession=true&preserveInstants=false&sessionVariables=enable_insert_strict=true");
|
||||
sink.put("driver", "com.mysql.cj.jdbc.Driver");
|
||||
sink.put("user", target.serviceAccount());
|
||||
sink.put("password", targetPassword);
|
||||
@@ -351,7 +371,10 @@ 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();
|
||||
if (sqlServer) {
|
||||
var carrier = textCarrier(field, source);
|
||||
if (carrier != null) {
|
||||
source = carrier.expression();
|
||||
} else 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 + ")";
|
||||
@@ -428,6 +451,12 @@ 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());
|
||||
|
||||
+13
-4
@@ -30,6 +30,10 @@ final class DataSourceBiQueryJdbc {
|
||||
}
|
||||
static AnalyticsQuery.Result read(Connection connection,DataSourceView source,NativeMetadataBiDirectory.Target target,
|
||||
List<String> allowed,AnalyticsQuery.Plan plan,NativeQueryPolicyApi.Decision policy,AnalyticsExecution execution) throws SQLException {
|
||||
return read(connection,source,target,allowed,plan,policy,execution,false);
|
||||
}
|
||||
static AnalyticsQuery.Result read(Connection connection,DataSourceView source,NativeMetadataBiDirectory.Target target,
|
||||
List<String> allowed,AnalyticsQuery.Plan plan,NativeQueryPolicyApi.Decision policy,AnalyticsExecution execution,boolean complete) throws SQLException {
|
||||
String schema=Set.of("MYSQL","MARIADB","DORIS").contains(source.type())?null:target.schema();
|
||||
List<Field> before=fields(connection,source,target,schema);
|
||||
List<String> permitted=permitted(target,before,allowed,plan);
|
||||
@@ -38,16 +42,18 @@ final class DataSourceBiQueryJdbc {
|
||||
if(policy.columns()==null||!allowed.containsAll(policy.columns()))throw new IllegalArgumentException();
|
||||
var projected=permitted.stream().filter(policy.columns()::contains).toList();
|
||||
// Authorize every user-supplied projection and analysis before adding owner-only row conditions.
|
||||
AnalyticsSqlCompiler.compileForSource(plan,projected,source.type(),target.database(),schema,target.table());
|
||||
compile(plan,projected,source.type(),target.database(),schema,target.table(),complete);
|
||||
protectedPlan=DataSourceBiQueryPolicy.guarded(plan,policy);
|
||||
var needed=new LinkedHashSet<>(projected);policy.filters().forEach(f->needed.add(f.field()));
|
||||
permitted=permitted(target,before,List.copyOf(needed),protectedPlan);
|
||||
}
|
||||
var sql=AnalyticsSqlCompiler.compileForSource(protectedPlan,permitted,source.type(),target.database(),schema,target.table());
|
||||
AnalyticsQuery.Result result=rows(connection,sql,policy==null?List.of():policy.masks(),execution);
|
||||
var sql=compile(protectedPlan,permitted,source.type(),target.database(),schema,target.table(),complete);
|
||||
AnalyticsQuery.Result result=rows(connection,sql,policy==null?List.of():policy.masks(),execution,System::nanoTime,complete);
|
||||
if(complete&&result.truncated())throw new SQLException("COMPLETE_READ_LIMIT_EXCEEDED");
|
||||
if (!before.equals(fields(connection,source,target,schema))) throw new SQLException("NATIVE_BI_STRUCTURE_CHANGED");
|
||||
return result;
|
||||
}
|
||||
private static AnalyticsSqlCompiler.Compiled compile(AnalyticsQuery.Plan p,List<String> allowed,String source,String database,String schema,String table,boolean complete){return complete?AnalyticsSqlCompiler.compileForSnapshot(p,allowed,source,database,schema,table):AnalyticsSqlCompiler.compileForSource(p,allowed,source,database,schema,table);}
|
||||
|
||||
static List<String> permitted(NativeMetadataBiDirectory.Target target,List<Field> actual,List<String> allowed,
|
||||
AnalyticsQuery.Plan plan) {
|
||||
@@ -166,6 +172,9 @@ final class DataSourceBiQueryJdbc {
|
||||
return rows(connection,sql,masks,execution,System::nanoTime);
|
||||
}
|
||||
static AnalyticsQuery.Result rows(Connection connection,AnalyticsSqlCompiler.Compiled sql,List<NativeQueryPolicyApi.Mask> masks,AnalyticsExecution execution,java.util.function.LongSupplier nanoClock)throws SQLException{
|
||||
return rows(connection,sql,masks,execution,nanoClock,false);
|
||||
}
|
||||
static AnalyticsQuery.Result rows(Connection connection,AnalyticsSqlCompiler.Compiled sql,List<NativeQueryPolicyApi.Mask> masks,AnalyticsExecution execution,java.util.function.LongSupplier nanoClock,boolean complete)throws SQLException{
|
||||
Map<String,NativeQueryPolicyApi.Mask> outputMasks=new HashMap<>();masks.forEach(mask->{DataSourceBiQueryPolicy.validate(mask);if(outputMasks.put(mask.field(),mask)!=null)throw new IllegalArgumentException();});
|
||||
try(PreparedStatement statement=connection.prepareStatement(sql.sql());var cancellation=NativeQueryCancellation.watch(execution,statement)){
|
||||
int seconds=SqlExecutionBudget.seconds(sql.maxExecutionSeconds());
|
||||
@@ -187,7 +196,7 @@ final class DataSourceBiQueryJdbc {
|
||||
deadline.check();
|
||||
String value=result.getString(i+1);
|
||||
if(value!=null){if(value.length()>1_000_000)throw new SQLException();bytes+=value.getBytes(StandardCharsets.UTF_8).length;}
|
||||
if(bytes>2_000_000){statement.cancel();throw new SQLException();}
|
||||
if(bytes>(complete?8_000_000:2_000_000)){statement.cancel();throw new SQLException(complete?"COMPLETE_READ_LIMIT_EXCEEDED":"QUERY_SIZE_EXCEEDED");}
|
||||
row.put(sql.columns().get(i),value);
|
||||
}
|
||||
rows.add(Collections.unmodifiableMap(row));
|
||||
|
||||
+41
-5
@@ -35,6 +35,22 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
this.registry=registry;this.credentials=credentials;this.connections=connections;this.access=access;
|
||||
}
|
||||
@Override public AnalyticsQuery.Result query(Query query){
|
||||
return execute(query,false);
|
||||
}
|
||||
@Override public AnalyticsQuery.Result complete(Query query){
|
||||
if(query==null||!"EXPORT".equals(query.action())||query.plan()==null||query.plan().limit()!=100000)return failure("COMPLETE_READ_INVALID");
|
||||
return execute(query,true);
|
||||
}
|
||||
private AnalyticsQuery.Result execute(Query query,boolean complete){
|
||||
return execute(query,complete,false);
|
||||
}
|
||||
@Override public String authorizeComplete(Query query){
|
||||
if(query==null||!"EXPORT".equals(query.action())||query.plan()==null||query.plan().limit()!=100000)throw new IllegalArgumentException();
|
||||
var result=execute(query,true,true);
|
||||
if(result==null||!"SUCCEEDED".equals(result.state())||result.authorizationSha256()==null)throw DataSourceOperationException.forbidden();
|
||||
return result.authorizationSha256();
|
||||
}
|
||||
private AnalyticsQuery.Result execute(Query query,boolean complete,boolean authorizationOnly){
|
||||
Future<AnalyticsQuery.Result> work=null;
|
||||
try{
|
||||
if(query==null||query.tableId()==null||!query.tableId().matches("[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}")
|
||||
@@ -49,22 +65,35 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
var scope=new DataSourceAccessScope(query.actorId(),query.departmentId());
|
||||
DataSourceView before=source(scope,target);
|
||||
String queryHash=hash(JsonMapper.builder().build().writeValueAsString(query.plan()));
|
||||
var decision=policies.prepare(new NativeQueryPolicyApi.Request(query.actorId(),query.departmentId(),query.tableId(),
|
||||
target.sourceVersion(),target.revision(),before.type(),"EXPORT".equals(query.action())?"EXPORT":"SELECT",query.allowedColumns(),queryHash,purpose));
|
||||
var policyRequest=new NativeQueryPolicyApi.Request(query.actorId(),query.departmentId(),query.tableId(),
|
||||
target.sourceVersion(),target.revision(),before.type(),"EXPORT".equals(query.action())?"EXPORT":"SELECT",query.allowedColumns(),queryHash,purpose,complete);
|
||||
var decision=authorizationOnly?policies.authorize(policyRequest):policies.prepare(policyRequest);
|
||||
if(decision==null||decision.queryId()==null||decision.fingerprint()==null||!decision.fingerprint().matches("[0-9a-f]{64}"))throw new IllegalArgumentException();
|
||||
work=workers.submit(()->connections.read(before,scope,c->DataSourceBiQueryJdbc.read(c,before,target,query.allowedColumns(),query.plan(),decision,query.execution())));
|
||||
var result=work.get(10,TimeUnit.SECONDS);
|
||||
AnalyticsQuery.Result result;
|
||||
if(authorizationOnly){
|
||||
cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler.compileForSnapshot(query.plan(),decision.columns(),before.type(),target.database(),target.schema(),target.table());
|
||||
var needed=new LinkedHashSet<>(decision.columns());decision.filters().forEach(f->needed.add(f.field()));
|
||||
cn.aixunkeji.datagov.integration.tablefile.AnalyticsSqlCompiler.compileForSnapshot(DataSourceBiQueryPolicy.guarded(query.plan(),decision),List.copyOf(needed),before.type(),target.database(),target.schema(),target.table());
|
||||
result=new AnalyticsQuery.Result("SUCCEEDED",query.plan().columns(),List.of(),false,LocalDateTime.now(),null);
|
||||
}else{
|
||||
work=workers.submit(()->connections.read(before,scope,c->DataSourceBiQueryJdbc.read(c,before,target,query.allowedColumns(),query.plan(),decision,query.execution(),complete)));
|
||||
result=work.get(10,TimeUnit.SECONDS);
|
||||
}
|
||||
authorize(query,purpose);
|
||||
if("EXPORT".equals(query.action()))access.requireExport(query.actorId(),query.departmentId());
|
||||
DataSourceView after=source(scope,target);
|
||||
if(!Objects.equals(before.secretRef(),after.secretRef())||!Objects.equals(before.lastTestId(),after.lastTestId())
|
||||
||!target.equals(directory.resolve(reference)))return failure("SOURCE_CHANGED");
|
||||
if(result==null||!"SUCCEEDED".equals(result.state()))return result==null?failure("QUERY_NOT_AUTHORIZED_OR_UNAVAILABLE"):result;
|
||||
if(authorizationOnly){
|
||||
if(!decision.fingerprint().equals(policies.authorize(policyRequest).fingerprint()))return failure("POLICY_CHANGED_OR_REVOKED");
|
||||
return DataSourceQueryProof.attach(result,completeProof(query,decision));
|
||||
}
|
||||
var receipt=policies.complete(new NativeQueryPolicyApi.Completion(query.actorId(),query.departmentId(),decision.queryId(),
|
||||
decision.fingerprint(),queryHash,result.rows().size(),outputSources(query.plan(),result.columns()),result.observedAt()));
|
||||
if(receipt==null||!receipt.accepted())return failure("POLICY_CHANGED_OR_REVOKED");
|
||||
NativeQueryCancellation.requireRunning(query.execution(),query.actorId(),query.departmentId());
|
||||
return DataSourceQueryProof.attach(result,decision.fingerprint());
|
||||
return DataSourceQueryProof.attach(result,complete?completeProof(query,decision):decision.fingerprint());
|
||||
}catch(InterruptedException exception){Thread.currentThread().interrupt();return failure("QUERY_INTERRUPTED");}
|
||||
catch(TimeoutException exception){return failure("QUERY_TIMEOUT");}
|
||||
catch(RejectedExecutionException exception){return failure("QUERY_BUSY");}
|
||||
@@ -78,8 +107,15 @@ public class DataSourceBiQueryService implements DataSourceBiQueryApi {
|
||||
var frames=Arrays.stream(error.getStackTrace()).filter(f->f.getClassName().startsWith("cn.aixunkeji.datagov.")).limit(5).map(StackTraceElement::toString).toList();
|
||||
LOG.warn("Native query rejected: type={}, frames={}",error.getClass().getSimpleName(),frames);
|
||||
}
|
||||
/** A reporting reader must independently obtain exactly the same effective data scope.
|
||||
* The real actor remains in the policy ticket/receipt; matching scope is not an authorization grant.
|
||||
*/
|
||||
static String completeProof(Query query,NativeQueryPolicyApi.Decision decision){
|
||||
return hash(JsonMapper.builder().build().writeValueAsString(List.of("reporting-complete-scope-v1",query.departmentId(),query.tableId(),query.allowedColumns(),query.plan(),decision.resourceRef(),decision.columns(),decision.filters(),decision.masks(),decision.policies())));
|
||||
}
|
||||
static String executionFailure(ExecutionException exception){
|
||||
Throwable cause=exception.getCause();
|
||||
if(cause instanceof java.sql.SQLException&&"COMPLETE_READ_LIMIT_EXCEEDED".equals(cause.getMessage()))return "COMPLETE_READ_LIMIT_EXCEEDED";
|
||||
return cause instanceof cn.aixunkeji.datagov.integration.tablefile.SqlExecutionTimeoutException?"QUERY_EXECUTION_TIMEOUT":cause instanceof java.sql.SQLException&&"QUERY_EXECUTION_WATCH_BUSY".equals(cause.getMessage())?"QUERY_BUSY":"QUERY_NOT_AUTHORIZED_OR_UNAVAILABLE";
|
||||
}
|
||||
private void authorize(Query query,String purpose){
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.aixunkeji.datagov.integration.datasource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
|
||||
/** Reporting-owned source selection, never a published/governed dataset identity. */
|
||||
public final class ReportingSourceRead {
|
||||
private ReportingSourceRead() { }
|
||||
public record Table(String alias,String catalog,String schema,String table) { }
|
||||
public record Join(String leftTable,String leftField,String rightTable,String rightField) { }
|
||||
public record Field(String name,String tableAlias,String column) { }
|
||||
public record Parameter(String name,String type,String value) { }
|
||||
public record Definition(long sourceId,List<Table> tables,List<Join> joins,List<Field> fields,
|
||||
String mode,String sql,String catalog,String schema,List<Parameter> parameters,String readinessAgreement) {
|
||||
public Definition { parameters=parameters==null?List.of():List.copyOf(parameters); }
|
||||
public Definition(long sourceId,List<Table> tables,List<Join> joins,List<Field> fields){this(sourceId,tables,joins,fields,null,null,null,null,List.of(),null);}
|
||||
public boolean sqlSource(){return "SQL".equals(mode);}
|
||||
}
|
||||
public record Fixed(Definition definition,long sourceVersion,String schemaSha256,List<ReportingDatasetDirectory.Field> fields) { }
|
||||
public record Query(Fixed source,List<String> columns,List<ReportingDatasetDirectory.Filter> filters,Map<String,String> parameters) {
|
||||
public Query { parameters=parameters==null?Map.of():Map.copyOf(parameters); }
|
||||
public Query(Fixed source,List<String> columns,List<ReportingDatasetDirectory.Filter> filters){this(source,columns,filters,Map.of());}
|
||||
}
|
||||
public record Rows(List<Map<String,String>> rows,String authorizationSha256,String observedAt,boolean complete) { }
|
||||
}
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
package cn.aixunkeji.datagov.integration.datasource;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.aixunkeji.datagov.integration.api.DataSourceView;
|
||||
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects;
|
||||
import cn.aixunkeji.datagov.integration.m2.DataSourceRegistry;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.sql.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import static cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.*;
|
||||
|
||||
/** Reuses registered source credentials and browse scope. Generates only bound SELECTs. */
|
||||
@Service
|
||||
public class ReportingSourceService {
|
||||
private final DataSourceRegistry registry;
|
||||
private final DataSourceObjectConnection credentials;
|
||||
private final DataSourceBiQueryConnection connections;
|
||||
private final ExecutorService workers=new ThreadPoolExecutor(0,4,30,TimeUnit.SECONDS,new SynchronousQueue<>(),Thread.ofPlatform().daemon().name("reporting-source-",0).factory(),new ThreadPoolExecutor.AbortPolicy());
|
||||
private static final JsonMapper JSON=JsonMapper.builder().build();
|
||||
public ReportingSourceService(DataSourceRegistry registry,DataSourceObjectConnection credentials,DataSourceBiQueryConnection connections){this.registry=registry;this.credentials=credentials;this.connections=connections;}
|
||||
private DataSourceAccessScope actor(){
|
||||
StpUtil.checkPermission("aixun:integration:regulatory-reporting:view");
|
||||
StpUtil.checkPermission("aixun:integration:data-source:browse");
|
||||
StpUtil.checkPermission("aixun:integration:data-source:preview");
|
||||
Long user=LoginHelper.getUserId(),dept=LoginHelper.getDeptId();
|
||||
if(user==null||dept==null||user<=0||dept<=0)throw DataSourceOperationException.forbidden();
|
||||
return new DataSourceAccessScope(user,dept);
|
||||
}
|
||||
private DataSourceView source(DataSourceAccessScope scope,long id){
|
||||
var s=registry.find(scope,id);
|
||||
if(s==null||s.orgScopeId()!=scope.orgScopeId())throw DataSourceOperationException.forbidden();
|
||||
DataSourceObjectService.requireReady(s);credentials.requireActive(s);
|
||||
if("HIVE".equals(s.type()))throw invalid("直连报送暂不支持Hive;可使用原授权数据集路径");
|
||||
return s;
|
||||
}
|
||||
public Fixed describe(Definition d){
|
||||
validate(d);var a=actor();var before=source(a,d.sourceId());
|
||||
Fixed fixed=work(()->connections.read(before,a,c->inspect(c,before,d)));
|
||||
same(before,source(a,d.sourceId()));return fixed;
|
||||
}
|
||||
public void require(Fixed fixed){if(fixed==null||!fixed.equals(describe(fixed.definition())))throw invalid("来源连接或表字段结构已变化,请重新绑定");}
|
||||
public Rows read(Query q,boolean preview){
|
||||
if(q==null||q.source()==null)throw invalid("请选择直连来源");
|
||||
validate(q.source().definition());var a=actor();var before=source(a,q.source().definition().sourceId());
|
||||
var result=work(()->connections.read(before,a,c->{
|
||||
if(!q.source().equals(inspect(c,before,q.source().definition())))throw invalid("来源版本或结构已变化");
|
||||
var sql=compile(q,before.type(),c.getMetaData().getIdentifierQuoteString());
|
||||
List<Map<String,String>> rows=new ArrayList<>();int bytes=0,limit=preview?5:100000;
|
||||
try(var statement=c.prepareStatement(sql.sql(),ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY)){
|
||||
statement.setQueryTimeout(10);statement.setMaxRows(limit+1);statement.setFetchSize(100);
|
||||
for(int i=0;i<sql.arguments().size();i++)statement.setObject(i+1,ReportingSqlPolicy.value(new Parameter("p"+i,sql.types().get(i),sql.arguments().get(i))));
|
||||
try(var data=statement.executeQuery()){
|
||||
if(data.getMetaData().getColumnCount()!=q.columns().size())throw invalid("取数结果结构变化");
|
||||
if(q.source().definition().sqlSource()){
|
||||
var actual=resultFields(data.getMetaData());
|
||||
var expected=q.columns().stream().map(name->q.source().fields().stream().filter(f->f.name().equals(name)).findFirst().orElseThrow()).toList();
|
||||
if(!actual.equals(expected))throw invalid("本批SQL参数使结果结构发生变化,请重新绑定来源");
|
||||
}
|
||||
while(data.next()){
|
||||
if(rows.size()==limit){if(preview)break;throw invalid("完整取数超过100000条,请缩小过滤范围;未保存截断快照");}
|
||||
var row=new LinkedHashMap<String,String>();
|
||||
for(int i=0;i<q.columns().size();i++){
|
||||
String value=readCell(data,i+1);
|
||||
bytes+=value==null?4:value.getBytes(StandardCharsets.UTF_8).length;
|
||||
if(bytes>8_000_000)throw invalid("完整取数超过8 MB,请缩小范围");
|
||||
row.put(q.columns().get(i),value);
|
||||
}
|
||||
rows.add(Collections.unmodifiableMap(row));
|
||||
}
|
||||
requireUntruncated(data.getWarnings());requireUntruncated(statement.getWarnings());
|
||||
}
|
||||
}
|
||||
return List.copyOf(rows);
|
||||
}));
|
||||
same(before,source(a,q.source().definition().sourceId()));require(q.source());
|
||||
return new Rows(result,proof(a,before,q),java.time.LocalDateTime.now().toString(),!preview);
|
||||
}
|
||||
public void authorize(Query q,String expected){
|
||||
var a=actor();require(q.source());var s=source(a,q.source().definition().sourceId());
|
||||
compile(q,s.type(),"MYSQL".equals(s.type())||"DORIS".equals(s.type())?"`":"\"");
|
||||
if(expected==null||!expected.equals(proof(a,s,q)))throw DataSourceOperationException.forbidden();
|
||||
}
|
||||
static String readCell(ResultSet data,int index)throws SQLException{
|
||||
int type=data.getMetaData().getColumnType(index);
|
||||
if(!Set.of(Types.CHAR,Types.VARCHAR,Types.LONGVARCHAR,Types.NCHAR,Types.NVARCHAR,Types.LONGNVARCHAR,Types.CLOB,Types.NCLOB).contains(type))return data.getString(index);
|
||||
// Bounded character streaming preserves the complete value; no preview-length truncation.
|
||||
try(var reader=data.getCharacterStream(index)){
|
||||
if(reader==null)return null;var out=new StringBuilder();char[] buffer=new char[4096];int n;
|
||||
while((n=reader.read(buffer))!=-1){if(out.length()+n>1_000_000)throw invalid("单字段超过100万字符,请整改或缩小范围");out.append(buffer,0,n);}
|
||||
return out.toString();
|
||||
}catch(java.io.IOException e){throw new SQLException("REPORTING_CELL_READ_FAILED");}
|
||||
}
|
||||
static void requireUntruncated(SQLWarning warning){
|
||||
int seen=0;for(var current=warning;current!=null;current=current.getNextWarning()){
|
||||
if(++seen>100||Set.of("01004","22001").contains(Objects.toString(current.getSQLState(),""))||Set.of(1260,1265).contains(current.getErrorCode()))throw invalid("源SQL返回数据截断警告,请修正查询或来源设置;未保存不完整快照");
|
||||
}
|
||||
}
|
||||
private Fixed inspect(Connection c,DataSourceView s,Definition d)throws SQLException{
|
||||
if(d.sqlSource())return inspectSql(c,s,d);
|
||||
Map<String,Map<String,DataSourceObjects.Column>> tables=new LinkedHashMap<>();
|
||||
for(var table:d.tables()){
|
||||
var request=new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,1,100,100);
|
||||
var first=(DataSourceObjects.Page<?>)DataSourceObjectJdbc.browse(c,s.type(),s.databaseName(),request);
|
||||
Map<String,DataSourceObjects.Column> fields=new LinkedHashMap<>();
|
||||
for(var f:first.rows()){var column=(DataSourceObjects.Column)f;fields.put(column.name(),column);}
|
||||
if(first.total()>100){var rest=(DataSourceObjects.Page<?>)DataSourceObjectJdbc.browse(c,s.type(),s.databaseName(),new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,2,100,100));for(var f:rest.rows()){var column=(DataSourceObjects.Column)f;fields.put(column.name(),column);}}
|
||||
if(fields.size()!=first.total())throw invalid("来源字段读取不完整");tables.put(table.alias(),fields);
|
||||
}
|
||||
List<ReportingDatasetDirectory.Field> projected=new ArrayList<>();
|
||||
for(var f:d.fields()){
|
||||
var field=allowed(tables,f.tableAlias(),f.column());
|
||||
projected.add(new ReportingDatasetDirectory.Field(f.name(),Objects.toString(field.comment(),f.name()),field.type(),Boolean.TRUE.equals(field.nullable())||!d.tables().getFirst().alias().equals(f.tableAlias())));
|
||||
}
|
||||
for(var j:d.joins()){
|
||||
allowed(tables,j.leftTable(),j.leftField());allowed(tables,j.rightTable(),j.rightField());
|
||||
var right=d.tables().stream().filter(t->t.alias().equals(j.rightTable())).findFirst().orElseThrow();
|
||||
requireUniqueJoin(c.getMetaData(),s.type(),right,j.rightField());
|
||||
}
|
||||
return new Fixed(d,s.version(),hash(JSON.writeValueAsString(List.of(fingerprintDefinition(d),tables))),List.copyOf(projected));
|
||||
}
|
||||
private Fixed inspectSql(Connection connection,DataSourceView source,Definition d)throws SQLException{
|
||||
var query=ReportingSqlPolicy.prepare(d,source.type(),Map.of());var evidence=new LinkedHashMap<String,Object>();
|
||||
for(var table:query.tables()){
|
||||
var page=(DataSourceObjects.Page<?>)DataSourceObjectJdbc.browse(connection,source.type(),source.databaseName(),new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,1,100,100));
|
||||
var fields=new ArrayList<DataSourceObjects.Column>();for(var raw:page.rows())fields.add((DataSourceObjects.Column)raw);
|
||||
if(page.total()>100){var second=(DataSourceObjects.Page<?>)DataSourceObjectJdbc.browse(connection,source.type(),source.databaseName(),new DataSourceObjectRequest("COLUMN",table.catalog(),table.schema(),table.table(),null,2,100,100));for(var raw:second.rows())fields.add((DataSourceObjects.Column)raw);}
|
||||
if(fields.size()!=page.total())throw invalid("SQL来源字段目录不完整");
|
||||
for(var field:fields)if(field.masked()&&(query.wildcard()||query.columns().contains(field.name().toLowerCase(Locale.ROOT))))throw invalid("SQL引用受保护字段,不能通过别名或计算绕过:"+field.name());
|
||||
evidence.put(table.alias(),fields);
|
||||
}
|
||||
List<ReportingDatasetDirectory.Field> fields;
|
||||
try(var statement=connection.prepareStatement("SELECT * FROM ("+query.sql()+") reporting_result WHERE 1=0")){
|
||||
statement.setQueryTimeout(5);statement.setMaxRows(1);ReportingSqlPolicy.bind(statement,query.arguments());
|
||||
try(var result=statement.executeQuery()){fields=resultFields(result.getMetaData());}
|
||||
}
|
||||
return new Fixed(d,source.version(),hash(JSON.writeValueAsString(List.of(d,evidence,fields))),fields);
|
||||
}
|
||||
static List<ReportingDatasetDirectory.Field> resultFields(ResultSetMetaData metadata)throws SQLException{
|
||||
if(metadata.getColumnCount()<1||metadata.getColumnCount()>200)throw invalid("SQL结果须有1至200列");
|
||||
var fields=new ArrayList<ReportingDatasetDirectory.Field>();var names=new HashSet<String>();
|
||||
for(int i=1;i<=metadata.getColumnCount();i++){
|
||||
String name=outputId(metadata.getColumnLabel(i));
|
||||
if(!names.add(name.toLowerCase(Locale.ROOT)))throw invalid("SQL结果列名重复或大小写歧义,请使用唯一别名:"+name);
|
||||
if(DataSourceObjectJdbc.masked(name,metadata.getColumnType(i)))throw invalid("SQL输出包含受保护或非标量字段:"+name);
|
||||
String type=metadata.getColumnTypeName(i);int precision=metadata.getPrecision(i),scale=metadata.getScale(i);
|
||||
if(Set.of(Types.VARCHAR,Types.CHAR,Types.NVARCHAR,Types.NCHAR).contains(metadata.getColumnType(i)))type="VARCHAR("+precision+")";
|
||||
if(Set.of(Types.DECIMAL,Types.NUMERIC).contains(metadata.getColumnType(i)))type="DECIMAL("+precision+","+scale+")";
|
||||
fields.add(new ReportingDatasetDirectory.Field(name,name,type,metadata.isNullable(i)!=ResultSetMetaData.columnNoNulls));
|
||||
}return List.copyOf(fields);
|
||||
}
|
||||
static void requireUniqueJoin(DatabaseMetaData md,String type,Table table,String field)throws SQLException{
|
||||
Map<String,List<String>> indexes=new HashMap<>();
|
||||
String catalog=Set.of("ORACLE","DAMENG","KINGBASE").contains(type)?null:table.catalog();
|
||||
try(var rows=md.getIndexInfo(catalog,table.schema(),table.table(),true,false)){
|
||||
while(rows.next()){
|
||||
if(!table.table().equals(rows.getString("TABLE_NAME"))||rows.getBoolean("NON_UNIQUE"))continue;
|
||||
String name=rows.getString("INDEX_NAME"),column=rows.getString("COLUMN_NAME");
|
||||
if(name!=null)indexes.computeIfAbsent(name,k->new ArrayList<>()).add(column);
|
||||
}
|
||||
}
|
||||
if(indexes.values().stream().noneMatch(columns->columns.size()==1&&field.equals(columns.getFirst())))throw invalid("关联字段缺少可确认的单列唯一约束:"+table.alias()+"."+field+";请使用唯一关联表或标准中间库");
|
||||
}
|
||||
private static DataSourceObjects.Column allowed(Map<String,Map<String,DataSourceObjects.Column>> tables,String alias,String name){
|
||||
var field=tables.getOrDefault(alias,Map.of()).get(name);
|
||||
if(field==null||field.masked()||field.type()==null||field.type().toUpperCase(Locale.ROOT).matches(".*(BINARY|BLOB|RAW|GEOMETRY|ARRAY|STRUCT|OBJECT).*"))throw invalid("字段不存在、受保护或不是可报送标量:"+alias+"."+name);
|
||||
return field;
|
||||
}
|
||||
public static void validate(Definition d){
|
||||
if(d!=null&&d.sqlSource()){
|
||||
if(d.sourceId()<=0||d.tables()!=null&&!d.tables().isEmpty()||d.joins()!=null&&!d.joins().isEmpty()||d.fields()!=null&&!d.fields().isEmpty())throw invalid("SQL来源不能同时携带表关联定义");
|
||||
if(d.catalog()!=null)id(d.catalog());if(d.schema()!=null)id(d.schema());
|
||||
ReportingSqlPolicy.prepare(d,d.schema()==null?"MYSQL":"ORACLE",Map.of());return;
|
||||
}
|
||||
if(d==null||d.sourceId()<=0||d.tables()==null||d.tables().isEmpty()||d.tables().size()>5||d.joins()==null||d.joins().size()!=d.tables().size()-1||d.fields()==null||d.fields().isEmpty()||d.fields().size()>200)throw invalid("直连来源定义无效(最多5表、200字段)");
|
||||
if(d.mode()!=null&&!Set.of("TABLE","INTERMEDIATE_TABLE").contains(d.mode()))throw invalid("来源模式无效");
|
||||
if("INTERMEDIATE_TABLE".equals(d.mode())&&(d.readinessAgreement()==null||d.readinessAgreement().isBlank()||d.readinessAgreement().length()>1000))throw invalid("请保存中间库推送完成及范围确认约定");
|
||||
if(d.sql()!=null&&!d.sql().isBlank()||!d.parameters().isEmpty())throw invalid("表来源不能携带SQL参数");
|
||||
Set<String> aliases=new HashSet<>(),names=new HashSet<>();
|
||||
for(var t:d.tables()){if(t==null||!aliases.add(id(t.alias())))throw invalid("表别名重复");id(t.table());if(t.catalog()!=null)id(t.catalog());if(t.schema()!=null)id(t.schema());}
|
||||
Set<String> linked=new HashSet<>();linked.add(d.tables().getFirst().alias());
|
||||
for(var j:d.joins()){
|
||||
if(j==null||!linked.contains(j.leftTable())||!aliases.contains(j.rightTable())||!linked.add(j.rightTable()))throw invalid("关联须从主表依次连接各来源表,不能循环");
|
||||
id(j.leftField());id(j.rightField());
|
||||
}
|
||||
for(var f:d.fields())if(f==null||!names.add(id(f.name()))||!aliases.contains(f.tableAlias()))throw invalid("输出别名重复或来源表无效");else id(f.column());
|
||||
}
|
||||
record Sql(String sql,List<String> arguments,List<String> types) {
|
||||
Sql(String sql,List<String> arguments){this(sql,arguments,Collections.nCopies(arguments.size(),"STRING"));}
|
||||
}
|
||||
static Sql compile(Query q,String type,String quote){
|
||||
if(!Set.of("`","\"").contains(quote))throw invalid("数据库标识引用方式不支持");
|
||||
var d=q.source().definition();validate(d);
|
||||
Map<String,Field> fields=new HashMap<>();
|
||||
ReportingSqlPolicy.Prepared raw=null;
|
||||
if(d.sqlSource()){raw=ReportingSqlPolicy.prepare(d,type,q.parameters());q.source().fields().forEach(f->fields.put(f.name(),new Field(f.name(),"reporting_result",f.name())));}
|
||||
else {if(!q.parameters().isEmpty())throw invalid("表来源不接受SQL参数");d.fields().forEach(f->fields.put(f.name(),f));}
|
||||
if(q.columns()==null||q.columns().isEmpty()||new HashSet<>(q.columns()).size()!=q.columns().size()||!fields.keySet().containsAll(q.columns())||q.filters()==null||q.filters().size()>20)throw invalid("取数列或过滤无效");
|
||||
String sql="SELECT "+String.join(",",q.columns().stream().map(name->column(fields.get(name).tableAlias(),fields.get(name).column(),quote)+" AS "+quoted(name,quote)).toList())+" FROM "+(raw==null?table(d.tables().getFirst(),type,quote):"("+raw.sql()+") "+quoted("reporting_result",quote));
|
||||
if(raw==null)for(var j:d.joins())sql+=" LEFT JOIN "+table(d.tables().stream().filter(t->t.alias().equals(j.rightTable())).findFirst().orElseThrow(),type,quote)+" ON "+column(j.leftTable(),j.leftField(),quote)+"="+column(j.rightTable(),j.rightField(),quote);
|
||||
List<String> values=new ArrayList<>(),conditions=new ArrayList<>(),types=new ArrayList<>();
|
||||
if(raw!=null)for(var parameter:raw.arguments()){values.add(parameter.value());types.add(parameter.type());}
|
||||
for(var f:q.filters()){
|
||||
if(f==null||!fields.containsKey(f.field())||f.values()==null||f.values().size()>100||f.values().stream().anyMatch(v->v==null||v.length()>1000))throw invalid("过滤字段或值无效");
|
||||
var field=fields.get(f.field());String col=column(field.tableAlias(),field.column(),quote);
|
||||
String op=Objects.toString(f.operator(),"");
|
||||
if(Set.of("IS_NULL","IS_NOT_NULL").contains(op)){if(!f.values().isEmpty())throw invalid("空值过滤不接受值");conditions.add(col+(op.equals("IS_NULL")?" IS NULL":" IS NOT NULL"));}
|
||||
else if(Set.of("IN","NOT_IN").contains(op)){if(f.values().isEmpty())throw invalid("集合过滤不能为空");conditions.add(col+(op.equals("IN")?" IN (":" NOT IN (")+String.join(",",Collections.nCopies(f.values().size(),"?"))+")");values.addAll(f.values());}
|
||||
else {String symbol=Map.of("EQ","=","NE","<>","GT",">","GTE",">=","LT","<","LTE","<=").get(op);if(symbol==null||f.values().size()!=1)throw invalid("过滤操作或参数数量无效");conditions.add(col+symbol+"?");values.addAll(f.values());}
|
||||
}
|
||||
if(!conditions.isEmpty())sql+=" WHERE "+String.join(" AND ",conditions);
|
||||
while(types.size()<values.size())types.add("STRING");return new Sql(sql,List.copyOf(values),List.copyOf(types));
|
||||
}
|
||||
private static String table(Table t,String type,String q){
|
||||
String namespace=Set.of("MYSQL","DORIS").contains(type)?t.catalog():t.schema();
|
||||
if(namespace==null)throw invalid("请选择数据库或Schema");
|
||||
return ("DORIS".equals(type)?quoted("internal",q)+".":"")+quoted(namespace,q)+"."+quoted(t.table(),q)+" "+quoted(t.alias(),q);
|
||||
}
|
||||
private static String column(String table,String name,String q){return quoted(table,q)+"."+quoted(name,q);}
|
||||
private static String quoted(String value,String q){return q+outputId(value)+q;}
|
||||
private static String outputId(String value){if(value==null||!value.matches("[\\p{L}_][\\p{L}\\p{N}_ .-]{0,127}"))throw invalid("输出字段名称无效,请使用明确的字段别名");return value;}
|
||||
private static String id(String value){if(value==null||!value.matches("[A-Za-z_][A-Za-z0-9_]{0,127}"))throw invalid("表、字段或别名格式无效");return value;}
|
||||
private static Object fingerprintDefinition(Definition definition){
|
||||
if(definition.mode()!=null)return definition;
|
||||
var legacy=new LinkedHashMap<String,Object>();legacy.put("sourceId",definition.sourceId());legacy.put("tables",definition.tables());legacy.put("joins",definition.joins());legacy.put("fields",definition.fields());return legacy;
|
||||
}
|
||||
private static String proof(DataSourceAccessScope a,DataSourceView s,Query q){
|
||||
Object value=q;
|
||||
if(q.source().definition().mode()==null&&q.parameters().isEmpty()){
|
||||
var legacySource=new LinkedHashMap<String,Object>();legacySource.put("definition",fingerprintDefinition(q.source().definition()));legacySource.put("sourceVersion",q.source().sourceVersion());legacySource.put("schemaSha256",q.source().schemaSha256());legacySource.put("fields",q.source().fields());
|
||||
var legacy=new LinkedHashMap<String,Object>();legacy.put("source",legacySource);legacy.put("columns",q.columns());legacy.put("filters",q.filters());value=legacy;
|
||||
}
|
||||
return hash(JSON.writeValueAsString(List.of(a.orgScopeId(),s.version(),s.secretRef(),value)));
|
||||
}
|
||||
private static String hash(String s){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
private static void same(DataSourceView a,DataSourceView b){if(a.version()!=b.version()||!Objects.equals(a.secretRef(),b.secretRef())||!Objects.equals(a.lastTestId(),b.lastTestId()))throw invalid("来源配置或凭据已变化");}
|
||||
private <T>T work(Callable<T> action){Future<T> f=null;try{f=workers.submit(action);return f.get(15,TimeUnit.SECONDS);}catch(InterruptedException e){Thread.currentThread().interrupt();throw invalid("直连读取已中断");}catch(ExecutionException e){if(e.getCause() instanceof DataSourceOperationException safe)throw safe;throw invalid("直连读取失败,请核对来源权限、结构及数据类型");}catch(TimeoutException|RejectedExecutionException e){throw invalid("直连读取超时或繁忙,请缩小范围后重试");}finally{if(f!=null&&!f.isDone())f.cancel(true);}}
|
||||
private static DataSourceOperationException invalid(String message){return DataSourceOperationException.validation(message);}
|
||||
@PreDestroy public void close(){workers.shutdownNow();}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package cn.aixunkeji.datagov.integration.datasource;
|
||||
|
||||
import java.util.*;
|
||||
import java.sql.*;
|
||||
import java.math.BigDecimal;
|
||||
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
|
||||
import net.sf.jsqlparser.statement.select.*;
|
||||
import net.sf.jsqlparser.schema.Column;
|
||||
import net.sf.jsqlparser.expression.Function;
|
||||
import net.sf.jsqlparser.expression.*;
|
||||
import net.sf.jsqlparser.util.TablesNamesFinder;
|
||||
import org.springframework.jdbc.core.namedparam.*;
|
||||
import static cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.*;
|
||||
|
||||
/** AST-checked single SELECT, scoped physical objects and typed named parameters. */
|
||||
final class ReportingSqlPolicy extends TablesNamesFinder<Void> {
|
||||
private static final Set<String> FUNCTIONS=Set.of("COUNT","SUM","AVG","MIN","MAX","COALESCE","IFNULL","NULLIF","NVL","ISNULL","IF","CONCAT","CONCAT_WS","SUBSTRING","SUBSTR","LEFT","RIGHT","TRIM","LTRIM","RTRIM","UPPER","LOWER","REPLACE","LENGTH","CHAR_LENGTH","CHARACTER_LENGTH","ROUND","TRUNC","TRUNCATE","ABS","CEIL","CEILING","FLOOR","DATE","DATE_FORMAT","STR_TO_DATE","TO_CHAR","TO_DATE","TO_NUMBER","YEAR","MONTH","DAY","DAYOFMONTH","EXTRACT","FIND_IN_SET","GROUP_CONCAT","STRING_AGG","LISTAGG","ROW_NUMBER","RANK","DENSE_RANK");
|
||||
private final Definition definition;
|
||||
private final String engine;
|
||||
private final List<Table> tables=new ArrayList<>();
|
||||
private final Set<String> columns=new HashSet<>();
|
||||
private final Deque<Set<String>> scopes=new ArrayDeque<>();
|
||||
private boolean wildcard;
|
||||
private ReportingSqlPolicy(Definition definition,String engine){this.definition=definition;this.engine=engine;}
|
||||
record Prepared(String sql,List<Parameter> arguments,List<Table> tables,Set<String> columns,boolean wildcard) { }
|
||||
static Prepared prepare(Definition definition,String engine,Map<String,String> overrides){
|
||||
if(definition.sql()==null||definition.sql().isBlank()||definition.sql().length()>100000||definition.parameters().size()>50)throw invalid("SQL为空或超过100000字符,参数最多50项");
|
||||
var supplied=new MapSqlParameterSource();var parameters=new LinkedHashMap<String,Parameter>();
|
||||
for(var p:definition.parameters()){
|
||||
if(p==null||p.name()==null||!p.name().matches("[A-Za-z][A-Za-z0-9_]{0,63}")||parameters.containsKey(p.name()))throw invalid("SQL参数名称无效或重复");
|
||||
var actual=new Parameter(p.name(),p.type(),overrides.getOrDefault(p.name(),p.value()));value(actual);
|
||||
parameters.put(p.name(),actual);supplied.addValue(p.name(),actual);
|
||||
}
|
||||
if(!parameters.keySet().containsAll(overrides.keySet()))throw invalid("本批参数包含未定义项");
|
||||
try{
|
||||
var parsed=NamedParameterUtils.parseSqlStatement(definition.sql());
|
||||
var names=NamedParameterUtils.buildSqlParameterList(parsed,supplied);var used=new HashSet<String>();var args=new ArrayList<Parameter>();
|
||||
if(NamedParameterUtils.buildValueArray(parsed,supplied,null).length!=names.size())throw invalid("SQL参数只允许命名占位符,不接受问号位置参数");
|
||||
for(var name:names){var parameter=parameters.get(name.getName());if(parameter==null)throw invalid("SQL缺少参数定义:"+name.getName());used.add(name.getName());args.add(parameter);}
|
||||
if(!used.equals(parameters.keySet()))throw invalid("存在SQL未使用的参数");
|
||||
String bound=NamedParameterUtils.substituteNamedParameters(parsed,supplied);
|
||||
var statements=CCJSqlParserUtil.parseStatements(bound,parser->parser.withSquareBracketQuotation(true));
|
||||
if(statements.size()!=1||!(statements.get(0) instanceof Select select))throw invalid("每个资源只允许一条只读SELECT,关联和子查询可在该SELECT内编写");
|
||||
var policy=new ReportingSqlPolicy(definition,engine);policy.getTables((net.sf.jsqlparser.statement.Statement)select);
|
||||
if(policy.tables.isEmpty())throw invalid("SQL须读取当前数据源的业务表或视图");
|
||||
// Re-serialization removes executable comment/hint text instead of sending original SQL to JDBC.
|
||||
return new Prepared(select.toString(),List.copyOf(args),List.copyOf(policy.tables),Set.copyOf(policy.columns),policy.wildcard);
|
||||
}catch(DataSourceOperationException e){throw e;}catch(Exception e){throw invalid("SQL解析失败或包含不支持的只读语法,请分别保存每个资源的查询");}
|
||||
}
|
||||
static Object value(Parameter parameter){
|
||||
if(parameter.type()==null||parameter.value()==null||parameter.value().length()>4000)throw invalid("SQL参数必须有类型和值(最长4000字符)");
|
||||
try{return switch(parameter.type()){
|
||||
case "STRING"->parameter.value();case "INTEGER"->Long.valueOf(parameter.value());case "DECIMAL"->new BigDecimal(parameter.value());
|
||||
case "DATE"->java.sql.Date.valueOf(java.time.LocalDate.parse(parameter.value()));case "DATETIME"->Timestamp.valueOf(java.time.LocalDateTime.parse(parameter.value()));
|
||||
case "BOOLEAN"->{if(!Set.of("true","false").contains(parameter.value()))throw new IllegalArgumentException();yield Boolean.valueOf(parameter.value());}
|
||||
default->throw new IllegalArgumentException();};}catch(RuntimeException e){throw invalid("SQL参数值不符合类型:"+parameter.name());}
|
||||
}
|
||||
static void bind(PreparedStatement statement,List<Parameter> values)throws SQLException{for(int i=0;i<values.size();i++)statement.setObject(i+1,value(values.get(i)));}
|
||||
private Void scope(Select select,Runnable visitor){
|
||||
scopes.push(new HashSet<>());
|
||||
try{
|
||||
if(select.getForMode()!=null||select.getForUpdateTable()!=null||select.getIsolation()!=null)throw invalid("SQL不能加锁或改变隔离方式");
|
||||
if(select.getPivot()!=null||select.getUnPivot()!=null)throw invalid("SQL暂不支持PIVOT,请使用普通SELECT表达式");
|
||||
visitor.run();if(select.getOrderByElements()!=null)select.getOrderByElements().forEach(item->expression(item.getExpression()));
|
||||
limit(select.getLimit());limit(select.getLimitBy());if(select.getOffset()!=null)expression(select.getOffset().getOffset());if(select.getFetch()!=null)expression(select.getFetch().getExpression());return null;
|
||||
}finally{scopes.pop();}
|
||||
}
|
||||
@Override public <S> Void visit(Select select,S context){return select.accept((SelectVisitor<Void>)this,context);}
|
||||
@Override public <S> Void visit(PlainSelect select,S context){
|
||||
if(select.getIntoTables()!=null&&!select.getIntoTables().isEmpty()||select.getIntoTempTable()!=null)throw invalid("禁止SELECT INTO或写出文件");
|
||||
if(select.getOracleHint()!=null)throw invalid("SQL不允许执行提示");
|
||||
return scope(select,()->{
|
||||
super.visit(select,context);
|
||||
if(select.getGroupBy()!=null){expression(select.getGroupBy().getGroupByExpressionList());if(select.getGroupBy().getGroupingSets()!=null)select.getGroupBy().getGroupingSets().forEach(this::expression);}
|
||||
expression(select.getQualify());
|
||||
if(select.getTop()!=null)expression(select.getTop().getExpression());
|
||||
if(select.getWindowDefinitions()!=null)select.getWindowDefinitions().forEach(this::window);
|
||||
});
|
||||
}
|
||||
@Override public <S> Void visit(ParenthesedSelect select,S context){return scope(select,()->super.visit(select,context));}
|
||||
@Override public <S> Void visit(SetOperationList select,S context){return scope(select,()->super.visit(select,context));}
|
||||
@Override public <S> Void visit(WithItem<?> item,S context){
|
||||
if(item.getSelect()==null||item.getAlias()==null||item.isRecursive())throw invalid("只支持非递归只读CTE");
|
||||
item.getSelect().accept((SelectVisitor<Void>)this,context);scopes.peek().add(identifier(item.getAlias().getName()).toLowerCase(Locale.ROOT));return null;
|
||||
}
|
||||
@Override public <S> Void visit(net.sf.jsqlparser.schema.Table table,S context){
|
||||
if(table.getSqlServerHints()!=null||table.getIndexHint()!=null||table.getPivot()!=null||table.getUnPivot()!=null||table.getSampleClause()!=null)throw invalid("SQL来源不允许表提示、采样或PIVOT");
|
||||
String name=identifier(table.getName());
|
||||
if(table.getSchemaName()==null&&table.getDatabaseName()==null&&scopes.stream().anyMatch(s->s.contains(name.toLowerCase(Locale.ROOT))))return null;
|
||||
if(table.getNameParts().size()>2)throw invalid("SQL不支持跨服务器或三段式来源,请在所选库内查询");
|
||||
boolean catalogEngine=Set.of("MYSQL","DORIS").contains(engine);
|
||||
String namespace=table.getSchemaName()==null?(catalogEngine?definition.catalog():definition.schema()):identifier(table.getSchemaName());
|
||||
namespace=identifier(namespace);String quote=catalogEngine?"`":"\"";
|
||||
table.setSchemaName(quote+namespace+quote);table.setName(quote+name+quote);
|
||||
var physical=new Table("q"+tables.size(),catalogEngine?namespace:definition.catalog(),catalogEngine?null:namespace,name);
|
||||
if(tables.stream().anyMatch(existing->Objects.equals(existing.catalog(),physical.catalog())&&Objects.equals(existing.schema(),physical.schema())&&existing.table().equals(physical.table())))return null;
|
||||
if(tables.size()>=32)throw invalid("SQL最多引用32个来源表");tables.add(physical);return null;
|
||||
}
|
||||
@Override public <S> Void visit(Column column,S context){String name=identifier(column.getColumnName());if(Set.of("NEXTVAL","CURRVAL").contains(name.toUpperCase(Locale.ROOT)))throw invalid("SQL不能访问序列状态");columns.add(name.toLowerCase(Locale.ROOT));return null;}
|
||||
@Override public <S> Void visit(Function function,S context){
|
||||
if(!FUNCTIONS.contains(function.getName().toUpperCase(Locale.ROOT)))throw invalid("SQL函数不在只读函数范围内:"+function.getName());
|
||||
boolean countAll="COUNT".equalsIgnoreCase(function.getName())&&function.getParameters()!=null&&function.getParameters().size()==1&&function.getParameters().getFirst() instanceof AllColumns;
|
||||
if(!countAll)expression(function.getParameters());expression(function.getNamedParameters());expression(function.getKeep());expression(function.getAttributeColumn());
|
||||
if(function.getAttribute() instanceof Expression attribute)expression(attribute);
|
||||
if(function.getHavingClause()!=null)expression(function.getHavingClause().getExpression());
|
||||
if(function.getOrderByElements()!=null)function.getOrderByElements().forEach(item->expression(item.getExpression()));limit(function.getLimit());return null;
|
||||
}
|
||||
@Override public <S> Void visit(KeepExpression value,S context){if(value.getOrderByElements()!=null)value.getOrderByElements().forEach(item->expression(item.getExpression()));return null;}
|
||||
@Override public <S> Void visit(MySQLGroupConcat value,S context){expression(value.getExpressionList());if(value.getOrderByElements()!=null)value.getOrderByElements().forEach(item->expression(item.getExpression()));return null;}
|
||||
@Override public <S> Void visit(AnalyticExpression value,S context){
|
||||
if(value.getName()!=null&&!FUNCTIONS.contains(value.getName().toUpperCase(Locale.ROOT)))throw invalid("窗口函数不在只读范围内");
|
||||
expression(value.getExpression());expression(value.getOffset());expression(value.getDefaultValue());expression(value.getFilterExpression());expression(value.getKeep());expression(value.getPartitionExpressionList());
|
||||
if(value.getOrderByElements()!=null)value.getOrderByElements().forEach(item->expression(item.getExpression()));
|
||||
if(value.getFuncOrderBy()!=null)value.getFuncOrderBy().forEach(item->expression(item.getExpression()));
|
||||
if(value.getHavingClause()!=null)expression(value.getHavingClause().getExpression());limit(value.getLimit());
|
||||
window(value.getWindowDefinition());frame(value.getWindowElement());return null;
|
||||
}
|
||||
private void expression(Expression value){if(value!=null)value.accept(this,null);}
|
||||
private void limit(Limit value){if(value==null)return;expression(value.getOffset());expression(value.getRowCount());expression(value.getByExpressions());}
|
||||
private void window(WindowDefinition value){if(value==null)return;expression(value.getPartitionExpressionList());if(value.getOrderByElements()!=null)value.getOrderByElements().forEach(item->expression(item.getExpression()));frame(value.getWindowElement());}
|
||||
private void frame(WindowElement value){if(value==null)return;if(value.getOffset()!=null)expression(value.getOffset().getExpression());if(value.getRange()!=null){if(value.getRange().getStart()!=null)expression(value.getRange().getStart().getExpression());if(value.getRange().getEnd()!=null)expression(value.getRange().getEnd().getExpression());}}
|
||||
@Override public <S> Void visit(TableFunction function,S context){throw invalid("SQL不允许外部表函数");}
|
||||
@Override public <S> Void visit(AllColumns expression,S context){wildcard=true;return super.visit(expression,context);}
|
||||
@Override public <S> Void visit(AllTableColumns expression,S context){wildcard=true;return super.visit(expression,context);}
|
||||
@Override public <S> Void visit(net.sf.jsqlparser.expression.UserVariable expression,S context){throw invalid("SQL不允许会话变量或赋值");}
|
||||
@Override public <S> Void visit(net.sf.jsqlparser.expression.VariableAssignment expression,S context){throw invalid("SQL不允许变量赋值");}
|
||||
@Override public <S> Void visit(net.sf.jsqlparser.expression.NextValExpression expression,S context){throw invalid("SQL不允许改变序列");}
|
||||
private static String identifier(String value){if(value!=null&&value.length()>1&&(value.startsWith("`")&&value.endsWith("`")||value.startsWith("\"")&&value.endsWith("\"")||value.startsWith("[")&&value.endsWith("]")))value=value.substring(1,value.length()-1);if(value==null||!value.matches("[\\p{L}_][\\p{L}\\p{N}_ $]{0,127}"))throw invalid("SQL表或字段名称无效");return value;}
|
||||
private static DataSourceOperationException invalid(String message){return DataSourceOperationException.validation(message);}
|
||||
}
|
||||
+8
-2
@@ -31,6 +31,9 @@ import java.util.Optional;
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DataSourceRegistry {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final String SELECT_SOURCE = """
|
||||
SELECT data_source_id, data_source_name, source_type, host_name, port_no,
|
||||
@@ -340,7 +343,7 @@ public class DataSourceRegistry {
|
||||
private void upsertBinding(long dataSourceId, String reference, DataSourceAccessScope scope) {
|
||||
cn.aixunkeji.datagov.integration.secret.SecretRef secretRef =
|
||||
new cn.aixunkeji.datagov.integration.secret.SecretRef(reference);
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
MERGE INTO dg_secret_binding t
|
||||
USING (SELECT ? AS binding_id, 'data-source' AS owner_object_type, ? AS owner_object_id, ? AS secret_ref, ? AS secret_ref_fingerprint, ? AS secret_version, 'ACTIVE' AS binding_status, ? 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
|
||||
ON ((t.binding_id=s.binding_id) OR (t.owner_object_type=s.owner_object_type AND t.owner_object_id=s.owner_object_id AND t.del_flag=s.del_flag))
|
||||
@@ -349,7 +352,10 @@ public class DataSourceRegistry {
|
||||
t.binding_status='ACTIVE', t.update_by=s.update_by, t.update_time=NOW(), t.version=t.version+1
|
||||
WHEN NOT MATCHED THEN INSERT (binding_id,owner_object_type,owner_object_id,secret_ref,secret_ref_fingerprint,secret_version,binding_status,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
|
||||
VALUES (s.binding_id,s.owner_object_type,s.owner_object_id,s.secret_ref,s.secret_ref_fingerprint,s.secret_version,s.binding_status,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version)
|
||||
""", IdGeneratorUtil.nextLongId(), dataSourceId, secretRef.value(), secretRef.fingerprint(),
|
||||
""", """
|
||||
INSERT INTO dg_secret_binding(binding_id,owner_object_type,owner_object_id,secret_ref,secret_ref_fingerprint,secret_version,binding_status,create_dept,create_by,create_time,update_by,update_time,del_flag,version) SELECT s.binding_id,s.owner_object_type,s.owner_object_id,s.secret_ref,s.secret_ref_fingerprint,s.secret_version,s.binding_status,s.create_dept,s.create_by,s.create_time,s.update_by,s.update_time,s.del_flag,s.version FROM (SELECT ? AS binding_id, 'data-source' AS owner_object_type, ? AS owner_object_id, ? AS secret_ref, ? AS secret_ref_fingerprint, ? AS secret_version, 'ACTIVE' AS binding_status, ? 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 secret_ref=s.secret_ref,
|
||||
secret_ref_fingerprint=s.secret_ref_fingerprint, secret_version=s.secret_version,
|
||||
binding_status='ACTIVE', update_by=s.update_by, update_time=NOW(), version=dg_secret_binding.version+1"""), IdGeneratorUtil.nextLongId(), dataSourceId, secretRef.value(), secretRef.fingerprint(),
|
||||
secretRef.version(), scope.orgScopeId(), scope.actorId(), scope.actorId());
|
||||
}
|
||||
|
||||
|
||||
+10
-2
@@ -14,6 +14,9 @@ import java.util.List;
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class GoldenStageRepository {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
|
||||
private static final List<String> STAGES = List.of("SEATUNNEL", "HIVE", "DORIS", "OPENMETADATA", "FINALIZE");
|
||||
|
||||
@@ -25,12 +28,17 @@ public class GoldenStageRepository {
|
||||
STAGES.forEach(stage -> {
|
||||
boolean reused = "RETRY".equals(command.runType()) && command.parentRunId() != null &&
|
||||
parentStageSucceeded(command.parentRunId(), stage);
|
||||
jdbcTemplate.update("""
|
||||
jdbcTemplate.update(databaseDialect.sql("""
|
||||
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dg_golden_stage) */ INTO dg_golden_stage(
|
||||
stage_id, run_id, batch_no, stage_name, stage_status, attempt_no, fail_once,
|
||||
request_id, payload_sha256, completed_at, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW(), NOW(), '0', 0)
|
||||
""", IdGeneratorUtil.nextLongId(), command.runId(), command.batchNo(), stage,
|
||||
""", """
|
||||
INSERT IGNORE INTO dg_golden_stage(
|
||||
stage_id, run_id, batch_no, stage_name, stage_status, attempt_no, fail_once,
|
||||
request_id, payload_sha256, completed_at, create_time, update_time, del_flag, version
|
||||
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?, NOW(), NOW(), '0', 0)
|
||||
"""), IdGeneratorUtil.nextLongId(), command.runId(), command.batchNo(), stage,
|
||||
reused ? "SUCCEEDED" : "PENDING",
|
||||
command.failHiveOnce() && "HIVE".equals(stage) ? "1" : "0", command.requestId(),
|
||||
command.payloadSha256(), reused ? new java.sql.Timestamp(System.currentTimeMillis()) : null);
|
||||
|
||||
+23
-6
@@ -14,6 +14,9 @@ import java.util.List;
|
||||
|
||||
@Repository
|
||||
class AlertDeliveryStore {
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
AlertDeliveryStore(JdbcTemplate jdbc) { this.jdbc = jdbc; }
|
||||
record Stored(String hash, Receipt receipt) { }
|
||||
@@ -26,23 +29,32 @@ class AlertDeliveryStore {
|
||||
public boolean reserve(Command command, String hash, AlertDeliveryProperties.Channel channel, String targetLabel) {
|
||||
// This committed reservation precedes network I/O. A lost process is UNKNOWN, never a new send.
|
||||
try {
|
||||
return jdbc.update("""
|
||||
return jdbc.update(databaseDialect.sql("""
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,'UNKNOWN','AWAITING_RECEIPT',CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),?,?,?)
|
||||
""", command.scope().orgId(), command.scope().actorId(), command.requestKey(), command.eventId(),
|
||||
""", """
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,'UNKNOWN','AWAITING_RECEIPT',UTC_TIMESTAMP(3),?,?,?)
|
||||
"""), command.scope().orgId(), command.scope().actorId(), command.requestKey(), command.eventId(),
|
||||
command.eventVersion(), hash, channel.getId(), channel.getLabel(), command.targetKey(), targetLabel,
|
||||
command.scope().orgId(), command.scope().actorId(), command.scope().actorId()) == 1;
|
||||
} catch (DuplicateKeyException existing) { return false; }
|
||||
}
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void finish(Command command, AlertDeliveryTransport.Result result) {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
UPDATE dg_alert_external_delivery SET delivery_state=?,safe_code=?,completed_at=CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),
|
||||
update_time=CURRENT_TIMESTAMP(3),version=version+1
|
||||
WHERE org_id=? AND actor_id=? AND request_key=? AND command_sha256=? AND safe_code='AWAITING_RECEIPT' AND del_flag='0'
|
||||
""", result.state(), result.code(), command.scope().orgId(), command.scope().actorId(),
|
||||
""", """
|
||||
UPDATE dg_alert_external_delivery SET delivery_state=?,safe_code=?,completed_at=UTC_TIMESTAMP(3),
|
||||
update_time=CURRENT_TIMESTAMP(3),version=version+1
|
||||
WHERE org_id=? AND actor_id=? AND request_key=? AND command_sha256=? AND safe_code='AWAITING_RECEIPT' AND del_flag='0'
|
||||
"""), result.state(), result.code(), command.scope().orgId(), command.scope().actorId(),
|
||||
command.requestKey(), AlertDeliveryService.hash(command));
|
||||
}
|
||||
List<Receipt> history(Scope scope, long eventId) {
|
||||
@@ -52,12 +64,17 @@ class AlertDeliveryStore {
|
||||
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||
public void cancelUnsubmitted(Scope scope, long eventId, String key) {
|
||||
try {
|
||||
jdbc.update("""
|
||||
jdbc.update(databaseDialect.sql("""
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,completed_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,0,?,'-','未开始','-','未开始','CANCELLED','REQUEST_CANCELLED',CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS TIMESTAMP(3)),?,?,?)
|
||||
""", scope.orgId(), scope.actorId(), key, eventId, "0".repeat(64), scope.orgId(), scope.actorId(), scope.actorId());
|
||||
""", """
|
||||
INSERT INTO dg_alert_external_delivery
|
||||
(org_id,actor_id,request_key,event_id,event_version,command_sha256,channel_id,channel_label,
|
||||
target_key,target_label,delivery_state,safe_code,started_at,completed_at,create_dept,create_by,update_by)
|
||||
VALUES (?,?,?,?,0,?,'-','未开始','-','未开始','CANCELLED','REQUEST_CANCELLED',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3),?,?,?)
|
||||
"""), scope.orgId(), scope.actorId(), key, eventId, "0".repeat(64), scope.orgId(), scope.actorId(), scope.actorId());
|
||||
} catch (DuplicateKeyException alreadySubmitted) { /* A claimed send cannot be cancelled or retried. */ }
|
||||
}
|
||||
private static Receipt receipt(ResultSet rs) throws SQLException {
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
class ReportingActor {
|
||||
static final String PREFIX = "aixun:integration:regulatory-reporting:";
|
||||
Scope current(String action) {
|
||||
Long user = LoginHelper.getUserId(), organization = LoginHelper.getDeptId();
|
||||
if (user == null || organization == null || user <= 0 || organization <= 0
|
||||
|| !StpUtil.hasPermission(PREFIX + action)) throw ReportingException.forbidden();
|
||||
return new Scope(user, organization);
|
||||
}
|
||||
void credentials() {
|
||||
if (!StpUtil.hasPermission(PREFIX + "credential")) throw ReportingException.forbidden();
|
||||
}
|
||||
record Scope(long user, long organization) { }
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public final class ReportingApi {
|
||||
private ReportingApi() { }
|
||||
public enum Kind { DEPARTMENT, SYSTEM, TOPIC }
|
||||
public record Department(String shortName, String level, String supervisor, String role) {
|
||||
public Department(String shortName, String level, String supervisor) { this(shortName, level, supervisor, "UNCLASSIFIED"); }
|
||||
}
|
||||
public record TargetSystem(String endpoint, String environment, String transport, String authentication,
|
||||
int timeoutSeconds, int maxRetries, String defaultVersion, String fileNameRule,
|
||||
boolean attachments, boolean batchSupport, boolean receiptQuery,
|
||||
String reporterCode,String interfaceCode) {
|
||||
public TargetSystem(String endpoint,String environment,String transport,String authentication,int timeoutSeconds,int maxRetries,String defaultVersion,String fileNameRule,boolean attachments,boolean batchSupport,boolean receiptQuery){this(endpoint,environment,transport,authentication,timeoutSeconds,maxRetries,defaultVersion,fileNameRule,attachments,batchSupport,receiptQuery,null,null);}
|
||||
}
|
||||
public record Topic(String responsibleDepartment, String period) { }
|
||||
/** A null credential reference retains the current binding; an empty one removes it. */
|
||||
public record Command(long version, Kind kind, String code, String name, String parentId, String description,
|
||||
boolean enabled, Department department, TargetSystem system, Topic topic,
|
||||
String credentialReference) { }
|
||||
public record View(String id, long version, Kind kind, String code, String name, String parentId,
|
||||
String parentName, String description, boolean enabled, Department department,
|
||||
TargetSystem system, Topic topic, boolean credentialConfigured, String organizationId,
|
||||
String updatedAt) { }
|
||||
public record Page<T>(List<T> rows, long total) { }
|
||||
public record Overview(long departments, long systems, long topics, long enabledTopics, long regulators, long internalDepartments, long unclassifiedDepartments) { }
|
||||
public record Audit(String id, String action, String actorId, long version, String reason, String occurredAt) { }
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
/** Derives associations from immutable mapped rows; no client-supplied business keys or arbitrary file IDs. */
|
||||
final class ReportingAttachments {
|
||||
private ReportingAttachments() { }
|
||||
static boolean configured(Frozen fixed){return fixed.selections().stream().anyMatch(s->!s.attachmentFields().isEmpty());}
|
||||
static LinkedHashMap<String,List<AttachmentUse>> expected(Frozen fixed,Snapshot snapshot){
|
||||
var result=new LinkedHashMap<String,List<AttachmentUse>>();var folded=new HashSet<String>();
|
||||
for(var selection:fixed.selections()){
|
||||
if(selection.attachmentFields().isEmpty())continue;
|
||||
var data=snapshot.resources().stream().filter(r->r.resource().equals(selection.resourceCode())).toList();
|
||||
if(data.size()!=1)throw ReportingException.conflict("附件资源不属于当前快照");
|
||||
int row=0;
|
||||
for(var record:data.getFirst().rows()){
|
||||
row++;
|
||||
for(String field:selection.attachmentFields()){
|
||||
if(!record.containsKey(field))throw ReportingException.conflict("附件字段不属于当前快照");
|
||||
String reference=record.get(field);if(reference==null||reference.isBlank())continue;
|
||||
String name=name(reference);
|
||||
if(!result.containsKey(name)){
|
||||
if(!folded.add(name.toLowerCase(Locale.ROOT)))throw ReportingException.invalid("附件名称存在大小写冲突");
|
||||
if(result.size()>=ReportingAttachmentPolicy.MAX_FILES)throw ReportingException.invalid("每批次最多50份不同附件");
|
||||
result.put(name,new ArrayList<>());
|
||||
}
|
||||
if(result.get(name).size()>=2000)throw ReportingException.invalid("单个附件最多关联2000条字段记录,请拆分期间");
|
||||
result.get(name).add(new AttachmentUse(selection.resourceCode(),row,field));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static String name(String reference){
|
||||
String name=reference.startsWith("unStruct/")?reference.substring(9):reference;
|
||||
try{ReportingAttachmentPolicy.originalName(name);return name;}
|
||||
catch(IllegalArgumentException e){throw ReportingException.invalid("附件引用须为32位大写MD5_原文件名,可带unStruct/前缀;请核对附件类型和文件名");}
|
||||
}
|
||||
static void validateUpload(String name,String original,byte[] bytes){
|
||||
try{if(!ReportingAttachmentPolicy.originalName(name).equals(original))throw new IllegalArgumentException();ReportingAttachmentPolicy.verify(name,bytes);}
|
||||
catch(IllegalArgumentException e){throw ReportingException.invalid("附件名称、内容MD5或大小与快照引用不一致;单批次附件总量最多8 MiB");}
|
||||
}
|
||||
static List<Attachment> describe(Frozen fixed,Snapshot snapshot,List<Artifact> artifacts,boolean requireComplete){
|
||||
var expected=expected(fixed,snapshot);var stored=new HashMap<String,Artifact>();long total=0;
|
||||
for(var file:artifacts)if("ATTACHMENT".equals(file.kind())){
|
||||
if(!expected.containsKey(file.name())||stored.put(file.name(),file)!=null)throw ReportingException.conflict("附件关联重复或不属于当前快照");
|
||||
total+=file.length();
|
||||
}
|
||||
if(total>ReportingAttachmentPolicy.MAX_BYTES)throw ReportingException.invalid("批次附件总量超过8 MiB");
|
||||
var result=new ArrayList<Attachment>();
|
||||
expected.forEach((name,uses)->{
|
||||
var file=stored.get(name);String state=file==null?"MISSING":file.state();
|
||||
if(requireComplete&&!"BOUND".equals(state))throw ReportingException.conflict("附件未完整保存,不能审核或生成文件:"+name);
|
||||
result.add(new Attachment(name,name.substring(0,32),file==null?null:file.id(),state,file==null?0:file.length(),List.copyOf(uses)));
|
||||
});
|
||||
return List.copyOf(result);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
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 static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingApi.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting")
|
||||
class ReportingController {
|
||||
private final ReportingService service;
|
||||
@GetMapping("/overview") @SaCheckPermission(ReportingActor.PREFIX + "view")
|
||||
public R<Overview> overview() { return R.ok(service.overview()); }
|
||||
@GetMapping("/configs") @SaCheckPermission(ReportingActor.PREFIX + "view")
|
||||
public R<Page<View>> list(@RequestParam Kind kind, @RequestParam(defaultValue = "") String keyword,
|
||||
@RequestParam(required = false) String parentId, @RequestParam(required = false) Boolean enabled,
|
||||
@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
|
||||
return R.ok(service.list(kind, keyword, parentId, enabled, pageNum, pageSize));
|
||||
}
|
||||
@GetMapping("/configs/{id}") @SaCheckPermission(ReportingActor.PREFIX + "view")
|
||||
public R<View> get(@PathVariable String id) { return R.ok(service.get(id)); }
|
||||
@GetMapping("/configs/{id}/audit") @SaCheckPermission(ReportingActor.PREFIX + "view")
|
||||
public R<Page<Audit>> history(@PathVariable String id, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
|
||||
return R.ok(service.history(id, pageNum, pageSize));
|
||||
}
|
||||
@PutMapping("/configs/{id}") @SaCheckPermission(ReportingActor.PREFIX + "edit")
|
||||
@Log(title = "监管报送配置", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
|
||||
public R<View> save(@PathVariable String id, @RequestBody Command command) { return R.ok(service.save(id, command)); }
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.apache.pdfbox.Loader;
|
||||
import org.apache.pdfbox.text.PDFTextStripper;
|
||||
|
||||
/** Supplementary text only: never silently infer field constraints from prose. */
|
||||
final class ReportingDocumentNotes {
|
||||
record Note(String file,String location,String text,boolean confirmationRequired) { }
|
||||
static List<Note> extract(String name,byte[] bytes) throws IOException {
|
||||
List<Note> notes=new ArrayList<>();
|
||||
if(name.toLowerCase(Locale.ROOT).endsWith(".pdf")){
|
||||
try(var pdf=Loader.loadPDF(bytes)){
|
||||
if(pdf.isEncrypted()||pdf.getNumberOfPages()>200)throw ReportingException.invalid("PDF已加密或超过200页");
|
||||
var reader=new PDFTextStripper();int total=0;
|
||||
for(int page=1;page<=pdf.getNumberOfPages();page++){
|
||||
reader.setStartPage(page);reader.setEndPage(page);String text=reader.getText(pdf).strip();
|
||||
total+=text.length();if(total>200000)throw ReportingException.invalid("规范文本超过20万字符,请拆分文件");
|
||||
notes.add(new Note(name,"第"+page+"页",text.isBlank()?"未提取到文本;扫描页需人工识别和核对":text,true));
|
||||
}
|
||||
}
|
||||
}else{
|
||||
byte[] document=null;int count=0,total=0;Set<String> entries=new HashSet<>();
|
||||
try(var zip=new ZipInputStream(new ByteArrayInputStream(bytes))){
|
||||
for(var entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry()){
|
||||
if(++count>500||!entries.add(entry.getName())||entry.getName().contains("..")||entry.getName().startsWith("/"))throw ReportingException.invalid("DOCX压缩结构无效");
|
||||
var content=zip.readNBytes(2_000_001);total+=content.length;
|
||||
if(content.length>2_000_000||total>10_000_000)throw ReportingException.invalid("DOCX解压内容过大");
|
||||
if(entry.getName().equals("word/document.xml"))document=content;
|
||||
}
|
||||
}
|
||||
if(document==null)throw ReportingException.invalid("不是有效的DOCX文档");
|
||||
try{
|
||||
var f=DocumentBuilderFactory.newInstance();f.setNamespaceAware(true);f.setXIncludeAware(false);f.setExpandEntityReferences(false);
|
||||
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);f.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
|
||||
f.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD,"");f.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA,"");
|
||||
var doc=f.newDocumentBuilder().parse(new ByteArrayInputStream(document));
|
||||
var paragraphs=doc.getElementsByTagNameNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main","p");int totalText=0;
|
||||
for(int i=0;i<paragraphs.getLength();i++){
|
||||
var text=new StringBuilder();var nodes=((org.w3c.dom.Element)paragraphs.item(i)).getElementsByTagNameNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main","t");
|
||||
for(int j=0;j<nodes.getLength();j++)text.append(nodes.item(j).getTextContent());
|
||||
if(text.isEmpty())continue;totalText+=text.length();if(totalText>200000||notes.size()>=2000)throw ReportingException.invalid("DOCX文本过多,请拆分文件");
|
||||
notes.add(new Note(name,"段落"+(i+1),text.toString(),true));
|
||||
}
|
||||
}catch(ReportingException e){throw e;}catch(Exception e){throw ReportingException.invalid("DOCX正文XML无效");}
|
||||
}
|
||||
if(notes.isEmpty())notes.add(new Note(name,"正文","未提取到可识别文本,请人工核对",true));
|
||||
return List.copyOf(notes);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
final class ReportingException extends RuntimeException {
|
||||
final int status;
|
||||
ReportingException(int status, String message) { super(message); this.status = status; }
|
||||
static ReportingException invalid(String message) { return new ReportingException(400, message); }
|
||||
static ReportingException conflict(String message) { return new ReportingException(409, message); }
|
||||
static ReportingException forbidden() { return new ReportingException(403, "报送对象不存在或当前无访问权限"); }
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestControllerAdvice(assignableTypes = { ReportingController.class, ReportingStandardController.class, ReportingImportController.class, ReportingPlanController.class, ReportingExecutionController.class })
|
||||
class ReportingExceptionHandler {
|
||||
@ExceptionHandler(ReportingException.class)
|
||||
ResponseEntity<R<Void>> handle(ReportingException error) {
|
||||
return ResponseEntity.status(error.status).body(R.fail(error.status, error.getMessage()));
|
||||
}
|
||||
@ExceptionHandler(DuplicateKeyException.class)
|
||||
ResponseEntity<R<Void>> duplicate() {
|
||||
return ResponseEntity.status(409).body(R.fail(409, "当前组织中该类型的编码或对象标识已存在,请刷新核对"));
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
|
||||
public final class ReportingExecutionApi {
|
||||
private ReportingExecutionApi() { }
|
||||
public record Selection(String resourceCode,String periodField,List<String> keyFields,List<ReportingDatasetDirectory.Filter> filters,List<String> attachmentFields,Map<String,String> parameters) {
|
||||
public Selection { attachmentFields=attachmentFields==null?List.of():List.copyOf(attachmentFields);parameters=parameters==null?Map.of():Map.copyOf(parameters); }
|
||||
public Selection(String resourceCode,String periodField,List<String> keyFields,List<ReportingDatasetDirectory.Filter> filters,List<String> attachmentFields){this(resourceCode,periodField,keyFields,filters,attachmentFields,Map.of());}
|
||||
public Selection(String resourceCode,String periodField,List<String> keyFields,List<ReportingDatasetDirectory.Filter> filters){this(resourceCode,periodField,keyFields,filters,List.of());}
|
||||
}
|
||||
public record TaskDefinition(String name,String planId,long planVersion,String periodType,List<Selection> selections) { }
|
||||
public record TaskSave(long version,TaskDefinition definition) { }
|
||||
public record Task(String id,long version,boolean enabled,TaskDefinition definition,String updatedAt) { }
|
||||
public record CreateBatch(String taskId,long taskVersion,String startDate,String endDate,Map<String,Map<String,String>> parameters,Map<String,String> readinessEvidence) {
|
||||
public CreateBatch {parameters=parameters==null?Map.of():Map.copyOf(parameters);readinessEvidence=readinessEvidence==null?Map.of():Map.copyOf(readinessEvidence);}
|
||||
public CreateBatch(String taskId,long taskVersion,String startDate,String endDate){this(taskId,taskVersion,startDate,endDate,Map.of(),Map.of());}
|
||||
}
|
||||
public record Action(long version,String reason) { }
|
||||
public record Envelope(String reporterCode,String interfaceCode,String version,String timestamp,String packageCode) { }
|
||||
public record Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> selections,Envelope envelope,Map<String,String> readinessEvidence) {
|
||||
public Frozen {readinessEvidence=readinessEvidence==null?Map.of():Map.copyOf(readinessEvidence);}
|
||||
public Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> selections,Envelope envelope){this(plan,standard,templates,selections,envelope,Map.of());}
|
||||
public Frozen(ReportingPlanApi.View plan,ReportingStandardApi.Definition standard,List<ReportingStandardApi.Template> templates,List<Selection> selections){this(plan,standard,templates,selections,null);}
|
||||
}
|
||||
public record Issue(String resource,int row,String key,String field,String rule,String severity,String message) { }
|
||||
public record Batch(String id,String taskId,long taskVersion,long version,String state,String startDate,String endDate,
|
||||
int rowCount,int blockingCount,int warningCount,List<Issue> issues,String snapshotId,String packageId,String message,String updatedAt) { }
|
||||
public record SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt,cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Query directQuery) {
|
||||
public SourceProof(String resource,ReportingDatasetDirectory.Read query,String authorizationSha256,String observedAt){this(resource,query,authorizationSha256,observedAt,null);}
|
||||
}
|
||||
public record ResourceRows(String resource,List<Map<String,String>> rows,List<Map<String,String>> sourceKeys) {
|
||||
public ResourceRows(String resource,List<Map<String,String>> rows){this(resource,rows,List.of());}
|
||||
}
|
||||
public record QualityEvidence(long ruleId,long snapshotId,String configSha256,String operationKey,String state,Long validationId,String evidenceRef) { }
|
||||
public record Snapshot(String batchId,String startDate,String endDate,String definitionSha256,List<ResourceRows> resources,List<QualityEvidence> sourceQualityEvidence) {
|
||||
public Snapshot(String batchId,String startDate,String endDate,String definitionSha256,List<ResourceRows> resources){this(batchId,startDate,endDate,definitionSha256,resources,List.of());}
|
||||
}
|
||||
public record Artifact(String id,String batchId,String kind,String name,String sha256,long length,String state,String createdAt) { }
|
||||
public record AttachmentUse(String resource,int row,String field) { }
|
||||
public record Attachment(String name,String md5,String artifactId,String state,long length,List<AttachmentUse> uses) { }
|
||||
public record Precheck(boolean fileReady,boolean submissionReady,List<String> blockers) { }
|
||||
public record SnapshotRow(String resource,int row,Map<String,String> values) { }
|
||||
public record SnapshotView(int readCount,int selectedCount,int passedCount,int failedCount,boolean batchBlocked,Integer submittedCount,List<SnapshotRow> rows,Map<String,Map<String,String>> parameters,Map<String,String> readinessEvidence) { }
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.http.*;
|
||||
import java.util.List;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting/execution")
|
||||
@SaCheckPermission(ReportingActor.PREFIX+"view")
|
||||
class ReportingExecutionController {
|
||||
private final ReportingExecutionService service;
|
||||
private final ReportingSubmissionService submissions;
|
||||
@GetMapping("/daily/tasks") public R<ReportingApi.Page<Task>> dailyTasks(@RequestParam String topicId,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.dailyTasks(topicId,pageNum,pageSize));}
|
||||
@PostMapping("/daily/batches/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> start(@PathVariable String id,@RequestBody CreateBatch request){return R.ok(service.start(id,request));}
|
||||
@PostMapping("/batches/{id}/approve-and-generate") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> approveAndGenerate(@PathVariable String id,@RequestBody Action action){return R.ok(service.approveAndGenerate(id,action));}
|
||||
@PostMapping("/batches/{id}/submit") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> submit(@PathVariable String id,@RequestBody Action action){return R.ok(submissions.submit(id,action));}
|
||||
@PostMapping("/batches/{id}/submission-reconcile") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> reconcileSubmission(@PathVariable String id){return R.ok(submissions.reconcile(id));}
|
||||
@GetMapping("/batches/{id}/submissions") public R<List<ReportingSubmissionService.Attempt>> submissions(@PathVariable String id){return R.ok(submissions.attempts(id));}
|
||||
@GetMapping("/batches/{id}/verifications") public R<List<ReportingSubmissionService.Verification>> verifications(@PathVariable String id){return R.ok(submissions.verifications(id));}
|
||||
@PutMapping("/batches/{id}/verifications/{verificationId}") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> verify(@PathVariable String id,@PathVariable String verificationId,@RequestBody ReportingSubmissionService.VerificationCommand command){return R.ok(submissions.verify(id,verificationId,command));}
|
||||
@GetMapping("/quality-rules/{ruleId}/reference") @SaCheckPermission(ReportingActor.PREFIX+"standard")
|
||||
public R<String> qualityReference(@PathVariable long ruleId){return R.ok(service.qualityReference(ruleId));}
|
||||
@GetMapping("/tasks") public R<ReportingApi.Page<Task>> tasks(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.tasks(pageNum,pageSize));}
|
||||
@PutMapping("/tasks/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Task> save(@PathVariable String id,@RequestBody TaskSave request){return R.ok(service.saveTask(id,request));}
|
||||
@PostMapping("/tasks/{id}/{operation:enable|disable}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Task> enable(@PathVariable String id,@PathVariable String operation,@RequestBody Action action){return R.ok(service.enable(id,action,"enable".equals(operation)));}
|
||||
@GetMapping("/batches") public R<ReportingApi.Page<Batch>> batches(@RequestParam String taskId,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.batches(taskId,pageNum,pageSize));}
|
||||
@GetMapping("/batches/{id}") public R<Batch> get(@PathVariable String id){return R.ok(service.get(id));}
|
||||
@PutMapping("/batches/{id}") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> create(@PathVariable String id,@RequestBody CreateBatch request){return R.ok(service.create(id,request));}
|
||||
@PostMapping("/batches/{id}/{operation:prepare|approve|reject|generate|cancel}") @SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> action(@PathVariable String id,@PathVariable String operation,@RequestBody Action action){return R.ok(switch(operation){case "prepare"->service.prepare(id,action);case "approve"->service.review(id,action,true);case "reject"->service.review(id,action,false);case "generate"->service.generate(id,action);case "cancel"->service.cancel(id,action);default->throw ReportingException.invalid("操作无效");});}
|
||||
@PostMapping("/batches/{id}/reconcile") @SaCheckPermission(ReportingActor.PREFIX+"edit") public R<Batch> reconcile(@PathVariable String id,@RequestBody Action action){return R.ok(service.reconcile(id,action));}
|
||||
@GetMapping("/batches/{id}/precheck") public R<Precheck> precheck(@PathVariable String id){return R.ok(service.precheck(id));}
|
||||
@GetMapping("/batches/{id}/files") public R<List<Artifact>> files(@PathVariable String id){return R.ok(service.artifacts(id));}
|
||||
@GetMapping("/batches/{id}/data") public R<SnapshotView> data(@PathVariable String id,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.snapshotRows(id,pageNum,pageSize));}
|
||||
@GetMapping("/batches/{id}/attachments") public R<List<Attachment>> attachments(@PathVariable String id){return R.ok(service.attachments(id));}
|
||||
@PostMapping(value="/batches/{id}/attachments",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
@SaCheckPermission(ReportingActor.PREFIX+"edit")
|
||||
public R<Batch> attach(@PathVariable String id,@RequestParam long version,@RequestParam String name,@RequestPart("file") org.springframework.web.multipart.MultipartFile file) throws java.io.IOException {
|
||||
if(file.isEmpty()||file.getSize()>cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.MAX_BYTES)throw ReportingException.invalid("附件为空或超过8 MiB");
|
||||
return R.ok(service.attach(id,version,name,file.getOriginalFilename(),file.getBytes()));
|
||||
}
|
||||
@GetMapping("/batches/{id}/files/{fileId}") public ResponseEntity<byte[]> download(@PathVariable String id,@PathVariable String fileId){return ResponseEntity.ok().header(HttpHeaders.CACHE_CONTROL,"no-store").header(HttpHeaders.CONTENT_DISPOSITION,"attachment; filename=reporting-"+ReportingPolicy.id(fileId)+".bin").contentType(MediaType.APPLICATION_OCTET_STREAM).body(service.download(id,fileId));}
|
||||
@GetMapping("/batches/{id}/audit") public R<ReportingApi.Page<ReportingApi.Audit>> audit(@PathVariable String id,@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.history(id,pageNum,pageSize));}
|
||||
}
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingException.*;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingExecutionService {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final ReportingActor actors;
|
||||
private final ReportingPlanService plans;
|
||||
private final ReportingStandardService standards;
|
||||
private final ReportingRepository audit;
|
||||
private final ReportingFiles files;
|
||||
private final ReportingQuality quality;
|
||||
private final org.springframework.transaction.support.TransactionTemplate transactions;
|
||||
@DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=30000)
|
||||
private ReportingDatasetDirectory datasets;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.datagov.integration.datasource.ReportingSourceService directSources;
|
||||
|
||||
String qualityReference(long ruleId){return quality.resolveReference(actors.current("standard"),ruleId);}
|
||||
ReportingApi.Page<Task> dailyTasks(String topicId,int page,int size){
|
||||
var a=actors.current("view");ReportingPolicy.id(topicId);ReportingService.paging(page,size);
|
||||
audit.required(a,topicId,false);
|
||||
String from=" FROM dg_reporting_task t JOIN dg_reporting_plan p ON p.organization_id=t.organization_id AND p.plan_id=t.plan_id AND p.version=t.plan_version WHERE t.organization_id=? AND p.topic_id=? AND t.enabled=1 AND p.plan_state='FROZEN'";
|
||||
var ids=jdbc.query("SELECT t.task_id"+from+" ORDER BY t.update_time DESC,t.task_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),topicId,size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->task(a,id,false)).toList(),jdbc.queryForObject("SELECT COUNT(*)"+from,Long.class,a.organization(),topicId));
|
||||
}
|
||||
Batch start(String id,CreateBatch request){var b=Objects.requireNonNull(transactions.execute(tx->create(id,request)));return "DRAFT".equals(b.state())?prepare(id,new Action(b.version(),"日常报送:按已保存配置和本批范围取数校验")):b;}
|
||||
Batch approveAndGenerate(String id,Action action){var b=Objects.requireNonNull(transactions.execute(tx->review(id,action,true)));return "FROZEN".equals(b.state())?generate(id,new Action(b.version(),"审核后生成同一快照的正式文件")):b;}
|
||||
|
||||
ReportingApi.Page<Task> tasks(int page,int size){var a=actors.current("view");ReportingService.paging(page,size);
|
||||
var ids=jdbc.query("SELECT task_id FROM dg_reporting_task WHERE organization_id=? ORDER BY update_time DESC,task_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->task(a,id,false)).toList(),jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_task WHERE organization_id=?",Long.class,a.organization()));}
|
||||
Task task(ReportingActor.Scope a,String id,boolean lock){ReportingPolicy.id(id);return jdbc.query("SELECT * FROM dg_reporting_task WHERE organization_id=? AND task_id=?"+(lock?" FOR UPDATE":""),(r,n)->new Task(id,r.getLong("version"),r.getInt("enabled")==1,json.readValue(r.getString("definition_json"),TaskDefinition.class),r.getTimestamp("update_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);}
|
||||
@Transactional public Task saveTask(String id,TaskSave request){
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);if(request==null||request.version() < -1||request.version()==Long.MAX_VALUE)throw invalid("任务版本无效");
|
||||
var d=normalizeTask(request.definition());String hash=ReportingService.hash(json.writeValueAsString(new TaskSave(request.version(),d)));
|
||||
var count=jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_task WHERE organization_id=? AND task_id=?",Integer.class,a.organization(),id);
|
||||
if(count>0){var before=task(a,id,true);if(hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_task WHERE organization_id=? AND task_id=?",String.class,a.organization(),id)))return before;
|
||||
if(before.version()!=request.version())throw conflict("任务已变化,请刷新");
|
||||
}else if(request.version()!=-1)throw forbidden();
|
||||
var plan=plans.read(a,d.planId(),false);if(plan==null)throw forbidden();
|
||||
if(!"FROZEN".equals(plan.state())||plan.version()!=d.planVersion()||!plans.check(plan.definition()).configurationValid())throw conflict("请选择当前可用的冻结方案版本");
|
||||
validateSelections(d,plan);
|
||||
if(count==0)jdbc.update("INSERT INTO dg_reporting_task(organization_id,task_id,task_name,plan_id,plan_version,definition_json,command_sha256,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?)",a.organization(),id,d.name(),d.planId(),d.planVersion(),json.writeValueAsString(d),hash,a.user(),a.user());
|
||||
else if(jdbc.update("UPDATE dg_reporting_task SET task_name=?,plan_id=?,plan_version=?,definition_json=?,command_sha256=?,version=version+1,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND task_id=? AND version=?",d.name(),d.planId(),d.planVersion(),json.writeValueAsString(d),hash,a.user(),a.organization(),id,request.version())!=1)throw conflict("任务版本已变化");
|
||||
audit.audit(a,id,count==0?"TASK_CREATE":"TASK_UPDATE",request.version()+1);return task(a,id,false);
|
||||
}
|
||||
@Transactional public Task enable(String id,Action action,boolean enabled){
|
||||
var a=actors.current("edit");validate(action);var before=task(a,id,true);String hash=command("TASK_ENABLED_"+enabled,action);
|
||||
if(hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_task WHERE organization_id=? AND task_id=?",String.class,a.organization(),id)))return before;
|
||||
if(before.version()!=action.version())throw conflict("任务版本已变化");
|
||||
jdbc.update("UPDATE dg_reporting_task SET enabled=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND task_id=?",enabled?1:0,hash,a.user(),a.organization(),id);
|
||||
audit.audit(a,id,enabled?"TASK_ENABLE":"TASK_DISABLE",action.version()+1,action.reason());return task(a,id,false);
|
||||
}
|
||||
ReportingApi.Page<Batch> batches(String taskId,int page,int size){var a=actors.current("view");ReportingService.paging(page,size);task(a,taskId,false);
|
||||
var ids=jdbc.query("SELECT batch_id FROM dg_reporting_batch WHERE organization_id=? AND task_id=? ORDER BY create_time DESC,batch_id LIMIT ? OFFSET ?",(r,n)->r.getString(1),a.organization(),taskId,size,(page-1)*size);
|
||||
return new ReportingApi.Page<>(ids.stream().map(id->batch(a,id)).toList(),jdbc.queryForObject("SELECT COUNT(*) FROM dg_reporting_batch WHERE organization_id=? AND task_id=?",Long.class,a.organization(),taskId));}
|
||||
Batch get(String id){return batch(actors.current("view"),id);}
|
||||
Batch batch(ReportingActor.Scope a,String id){ReportingPolicy.id(id);return jdbc.query("SELECT * FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",(r,n)->new Batch(id,r.getString("task_id"),r.getLong("task_version"),r.getLong("version"),r.getString("batch_state"),r.getString("start_date"),r.getString("end_date"),r.getInt("row_count"),r.getInt("blocking_count"),r.getInt("warning_count"),Arrays.asList(json.readValue(r.getString("issue_json"),Issue[].class)),r.getString("snapshot_id"),r.getString("package_id"),r.getString("message"),r.getTimestamp("update_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);}
|
||||
Frozen frozen(ReportingActor.Scope a,String id){batch(a,id);return json.readValue(jdbc.queryForObject("SELECT frozen_json FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id),Frozen.class);}
|
||||
@Transactional public Batch create(String id,CreateBatch request){
|
||||
var a=actors.current("edit");ReportingPolicy.id(id);if(request==null)throw invalid("请选择任务和期间");
|
||||
Object command=request;
|
||||
if(request.parameters().isEmpty()&&request.readinessEvidence().isEmpty()){
|
||||
var legacy=new LinkedHashMap<String,Object>();legacy.put("taskId",request.taskId());legacy.put("taskVersion",request.taskVersion());legacy.put("startDate",request.startDate());legacy.put("endDate",request.endDate());command=legacy;
|
||||
}
|
||||
String hash=ReportingService.hash(json.writeValueAsString(command));
|
||||
var old=jdbc.query("SELECT create_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",(r,n)->r.getString(1),a.organization(),id);
|
||||
if(!old.isEmpty()){if(!hash.equals(old.getFirst()))throw conflict("批次标识已用于其他请求");return batch(a,id);}
|
||||
var task=task(a,request.taskId(),true);if(!task.enabled()||task.version()!=request.taskVersion())throw conflict("任务已停用或版本变化");
|
||||
period(task.definition().periodType(),request.startDate(),request.endDate());
|
||||
var plan=plans.read(a,task.definition().planId(),false);
|
||||
if(plan==null||!"FROZEN".equals(plan.state())||plan.version()!=task.definition().planVersion()||!plans.check(plan.definition()).configurationValid())throw conflict("方案或其基础引用已变化,请修订任务");
|
||||
var standard=standards.read(a,plan.definition().standardId(),false);
|
||||
if(standard==null||!"PUBLISHED".equals(standard.status())||standard.version()!=plan.definition().standardVersion())throw conflict("标准固定版本不可用");
|
||||
var templates=standard.definition().resources().stream().filter(r->r.templateId()!=null&&!r.templateId().isBlank()).map(r->standards.template(a,r.templateId())).toList();
|
||||
var target=audit.required(a,plan.definition().systemId(),false).command().system();
|
||||
var envelope=ReportingPackage.envelope(target,id,LocalDateTime.now(java.time.ZoneId.of("Asia/Shanghai")));
|
||||
var selections=batchSelections(task.definition(),plan,request);
|
||||
var captured=new Frozen(plan,standard.definition(),templates,selections,envelope,request.readinessEvidence());String value=json.writeValueAsString(captured);
|
||||
jdbc.update("INSERT INTO dg_reporting_batch(organization_id,batch_id,task_id,task_version,batch_state,start_date,end_date,frozen_json,frozen_sha256,issue_json,create_sha256,command_sha256,create_by,update_by) VALUES(?,?,?,?,'DRAFT',?,?,?,?, '[]',?,?,?,?)",a.organization(),id,task.id(),task.version(),request.startDate(),request.endDate(),value,ReportingService.hash(value),hash,hash,a.user(),a.user());
|
||||
audit.audit(a,id,"BATCH_CREATE",0);return batch(a,id);
|
||||
}
|
||||
Batch prepare(String id,Action action){
|
||||
var a=actors.current("edit");var before=batch(a,id);if(!claim(a,before,action,"PREPARE",Set.of("DRAFT"),"READING"))return batch(a,id);
|
||||
try{
|
||||
var fixed=frozen(a,id);requireActive(a,before,fixed);
|
||||
List<ResourceRows> rows=new ArrayList<>();List<Issue> issues=new ArrayList<>();List<SourceProof> proofs=new ArrayList<>();int count=0,totalBytes=0;
|
||||
ReportingRows.rules(fixed.standard(),issues);
|
||||
var qualityEvidence=quality.execute(a,id,before.startDate(),fixed.standard(),issues);
|
||||
for(var resource:fixed.standard().resources()){
|
||||
var binding=fixed.plan().definition().bindings().stream().filter(b->b.resourceCode().equals(resource.code())).findFirst().orElseThrow();
|
||||
var selection=fixed.selections().stream().filter(s->s.resourceCode().equals(resource.code())).findFirst().orElseThrow();
|
||||
if(binding.directSource()!=null)plans.sourceFields(binding);
|
||||
var columns=new LinkedHashSet<String>();binding.mappings().forEach(m->columns.addAll(ReportingMapping.sources(m)));columns.addAll(selection.keyFields());
|
||||
var filters=new ArrayList<>(selection.filters());
|
||||
if(!selection.periodField().isBlank()){filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"GTE",List.of(before.startDate())));filters.add(new ReportingDatasetDirectory.Filter(selection.periodField(),"LT",List.of(before.endDate())));}
|
||||
List<Map<String,String>> sourceRows;
|
||||
if(binding.directSource()!=null){
|
||||
var query=new cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Query(binding.directSource(),List.copyOf(columns),List.copyOf(filters),selection.parameters());var data=directSources.read(query,false);
|
||||
if(data==null||!data.complete()||data.authorizationSha256()==null)throw conflict("直连数据未完整读取");sourceRows=data.rows();
|
||||
proofs.add(new SourceProof(resource.code(),null,data.authorizationSha256(),data.observedAt(),query));
|
||||
}else{
|
||||
var dataset=datasets.resolve(binding.datasetId());requireVersion(binding,dataset);
|
||||
var query=new ReportingDatasetDirectory.Read(dataset,List.copyOf(columns),List.copyOf(filters));var data=datasets.read(query);
|
||||
if(data==null||!data.complete()||!dataset.equals(data.dataset())||!query.columns().equals(data.columns())||data.authorizationSha256()==null||data.rows().size()>100000)throw conflict("数据未完整读取,不能生成快照");sourceRows=data.rows();
|
||||
proofs.add(new SourceProof(resource.code(),query,data.authorizationSha256(),data.observedAt()));
|
||||
}
|
||||
totalBytes+=json.writeValueAsBytes(sourceRows).length;if(totalBytes>8_000_000)throw invalid("批次数据总量超过8 MB,请缩小期间或过滤范围");
|
||||
var result=ReportingRows.map(resource,binding,selection,sourceRows,fixed.envelope()==null?null:fixed.envelope().reporterCode());rows.add(result.data());issues.addAll(result.issues());if(issues.size()>2000)throw invalid("校验问题超过2000项");count+=sourceRows.size();
|
||||
}
|
||||
for(var proof:proofs)if(proof.directQuery()!=null)directSources.authorize(proof.directQuery(),proof.authorizationSha256());else datasets.authorize(proof.query(),proof.authorizationSha256());requireActive(a,before,fixed);
|
||||
int blocking=(int)issues.stream().filter(i->"BLOCKING".equals(i.severity())).count(),warnings=issues.size()-blocking;
|
||||
jdbc.update("UPDATE dg_reporting_batch SET issue_json=?,row_count=?,blocking_count=?,warning_count=? WHERE organization_id=? AND batch_id=? AND batch_state='READING'",json.writeValueAsString(issues),count,blocking,warnings,a.organization(),id);
|
||||
var snapshot=new Snapshot(id,before.startDate(),before.endDate(),definitionHash(a,id),List.copyOf(rows),qualityEvidence);
|
||||
ReportingAttachments.expected(fixed,snapshot);
|
||||
String artifact=files.write(a,id,"SNAPSHOT","snapshot.json","application/json",json.writeValueAsBytes(snapshot),List.copyOf(proofs));
|
||||
finish(a,id,"READING",blocking>0?"VALIDATION_FAILED":"REVIEW_PENDING",artifact,null,blocking>0?"存在阻断问题,请整改后创建新批次":"候选数据已完整保存,等待审核;不表示已报送");
|
||||
}catch(RuntimeException e){failure(a,id,"READING",e instanceof ReportingException||e instanceof cn.aixunkeji.datagov.integration.datasource.DataSourceOperationException?e.getMessage():"数据读取、校验或文件保存未完成;请核对数据访问权限、范围和文件操作");}
|
||||
return batch(a,id);
|
||||
}
|
||||
@Transactional public Batch review(String id,Action action,boolean approve){
|
||||
var a=actors.current("edit");var b=batch(a,id);String hash=command(approve?"APPROVE":"REJECT",action);
|
||||
if(same(a,id,hash))return b;validate(action);
|
||||
if(!"REVIEW_PENDING".equals(b.state())||b.version()!=action.version()||b.blockingCount()>0||b.snapshotId()==null)throw conflict("批次未通过校验或状态已变化");
|
||||
if(approve)quality.validateCurrent(a,frozen(a,id).standard());
|
||||
// Physical bytes are immutable before review; freezing fixes the approved reference, not a fresh source read.
|
||||
if(!"BOUND".equals(files.required(a,b.snapshotId()).state()))throw conflict("候选快照尚未完成绑定");
|
||||
var fixed=frozen(a,id);
|
||||
if(approve&&ReportingAttachments.configured(fixed))attachmentBytes(a,b,fixed,readSnapshot(a,b));
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,version=version+1,command_sha256=?,message=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND version=?",approve?"FROZEN":"REJECTED",hash,approve?"已审核并冻结快照":"审核驳回;整改后创建新批次",a.user(),a.organization(),id,b.version())!=1)throw conflict("批次已变化");
|
||||
audit.audit(a,id,approve?"BATCH_APPROVE_AND_FREEZE":"BATCH_REJECT",b.version()+1,action.reason());return batch(a,id);
|
||||
}
|
||||
Batch generate(String id,Action action){
|
||||
var a=actors.current("edit");var before=batch(a,id);if(!claim(a,before,action,"GENERATE",Set.of("FROZEN"),"GENERATING"))return batch(a,id);
|
||||
try{
|
||||
var snapshot=json.readValue(files.read(a,before.snapshotId()),Snapshot.class);var fixed=frozen(a,id);verifySnapshot(a,before,snapshot);
|
||||
byte[] bytes=ReportingPackage.generate(fixed,snapshot,attachmentBytes(a,before,fixed,snapshot));
|
||||
String artifact=files.write(a,id,"PACKAGE",fixed.envelope()==null?"reporting_"+id+".zip":ReportingPackage.fileName(fixed.envelope(),fixed.envelope().interfaceCode(),"zip"),"application/zip",bytes,files.required(a,before.snapshotId()).proofs());
|
||||
finish(a,id,"GENERATING","FILE_READY",null,artifact,"文件已生成;尚未提交监管系统");
|
||||
}catch(RuntimeException e){failure(a,id,"GENERATING",e instanceof ReportingException?e.getMessage():"文件生成或保存未完成,请核对原文件操作");}
|
||||
return batch(a,id);
|
||||
}
|
||||
Batch reconcile(String id,Action action){
|
||||
var a=actors.current("edit");validate(action);var b=batch(a,id);
|
||||
if(b.version()!=action.version())throw conflict("批次版本已变化,请刷新后核对");
|
||||
audit.audit(a,id,"BATCH_RECONCILE_REQUEST",b.version(),action.reason());
|
||||
try{return reconcile(id);}
|
||||
catch(ReportingException failure){audit.audit(a,id,"BATCH_RECONCILE_UNRESOLVED",b.version(),failure.getMessage());throw failure;}
|
||||
}
|
||||
Batch reconcile(String id){
|
||||
var a=actors.current("edit");var b=batch(a,id);
|
||||
if(Set.of("ATTACHING","ATTACHMENT_UNKNOWN").contains(b.state()))return reconcileAttachments(a,b);
|
||||
if(!Set.of("READING","GENERATING","UNKNOWN").contains(b.state()))throw conflict("此状态不需要核对");
|
||||
if(!"UNKNOWN".equals(b.state())&&LocalDateTime.parse(b.updatedAt()).isAfter(LocalDateTime.now().minusMinutes(5)))throw conflict("操作仍在执行,请稍后刷新;超过5分钟后可以核对");
|
||||
boolean generating=b.snapshotId()!=null;
|
||||
String artifact=files.reconcile(a,id,generating?"PACKAGE":"SNAPSHOT");
|
||||
if(!generating){var snapshot=json.readValue(files.read(a,artifact),Snapshot.class);verifySnapshot(a,b,snapshot);}
|
||||
finish(a,id,b.state(),generating?"FILE_READY":b.blockingCount()>0?"VALIDATION_FAILED":"REVIEW_PENDING",generating?null:artifact,generating?artifact:null,"已核对同一私有文件操作,未重复读取源数据");return batch(a,id);
|
||||
}
|
||||
@Transactional public Batch cancel(String id,Action action){var a=actors.current("edit");var b=batch(a,id);claim(a,b,action,"CANCEL",Set.of("DRAFT","VALIDATION_FAILED","REJECTED","FAILED","FROZEN","REVIEW_PENDING","FILE_READY"),"CANCELED");return batch(a,id);}
|
||||
List<Artifact> artifacts(String id){var a=actors.current("view");var b=batch(a,id);if(b.snapshotId()!=null)files.authorizeMetadata(a,b.snapshotId());return files.list(a,id);}
|
||||
SnapshotView snapshotRows(String id,int page,int size){
|
||||
var a=actors.current("view");ReportingService.paging(page,size);var b=batch(a,id);var snapshot=readSnapshot(a,b);var fixed=frozen(a,id);
|
||||
var rows=new ArrayList<SnapshotRow>();int count=0,offset=(page-1)*size;
|
||||
for(var resource:snapshot.resources())for(int i=0;i<resource.rows().size();i++){if(count>=offset&&rows.size()<size)rows.add(new SnapshotRow(resource.resource(),i+1,resource.rows().get(i)));count++;}
|
||||
int failed=(int)b.issues().stream().filter(i->"BLOCKING".equals(i.severity())&&i.row()>0).map(i->i.resource()+":"+i.row()).distinct().count();
|
||||
var parameters=new LinkedHashMap<String,Map<String,String>>();
|
||||
for(var selection:fixed.selections()){
|
||||
var values=new LinkedHashMap<String,String>();
|
||||
fixed.plan().definition().bindings().stream().filter(binding->binding.resourceCode().equals(selection.resourceCode())&&binding.directSource()!=null).findFirst().ifPresent(binding->binding.directSource().definition().parameters().forEach(p->values.put(p.name(),p.value())));
|
||||
values.putAll(selection.parameters());if(!values.isEmpty())parameters.put(selection.resourceCode(),Map.copyOf(values));
|
||||
}
|
||||
Integer submitted=Set.of("SUBMITTING","SUBMISSION_UNKNOWN").contains(b.state())?null:Integer.valueOf("ACCEPTED".equals(b.state())?count:0);
|
||||
return new SnapshotView(count,count,Math.max(0,count-failed),failed,b.issues().stream().anyMatch(i->"BLOCKING".equals(i.severity())&&i.row()==0),submitted,List.copyOf(rows),Map.copyOf(parameters),fixed.readinessEvidence());
|
||||
}
|
||||
List<Attachment> attachments(String id){var a=actors.current("view");var b=batch(a,id);if(b.snapshotId()==null)return List.of();return ReportingAttachments.describe(frozen(a,id),readSnapshot(a,b),files.list(a,id),false);}
|
||||
Batch attach(String id,long version,String name,String original,byte[] bytes){
|
||||
var a=actors.current("edit");var b=batch(a,id);
|
||||
ReportingAttachments.validateUpload(name,original,bytes);
|
||||
var action=new Action(version,"附件:"+name+":"+ReportingFiles.sha(bytes));
|
||||
if(same(a,id,command("ATTACH",action)))return b;
|
||||
if(!"REVIEW_PENDING".equals(b.state())||b.version()!=version)throw conflict("仅待审核批次可上传附件,请刷新状态");
|
||||
var fixed=frozen(a,id);var snapshot=readSnapshot(a,b);var manifest=ReportingAttachments.describe(fixed,snapshot,files.list(a,id),false);
|
||||
var expected=manifest.stream().filter(f->f.name().equals(name)).findFirst().orElseThrow(()->invalid("附件不属于当前快照中的业务记录"));
|
||||
if(expected.artifactId()!=null)throw conflict("该附件已登记,待核对时请核对原文件操作");
|
||||
if(manifest.stream().mapToLong(Attachment::length).sum()+bytes.length>cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.MAX_BYTES)throw invalid("批次附件总量超过8 MiB");
|
||||
if(!claim(a,b,action,"ATTACH",Set.of("REVIEW_PENDING"),"ATTACHING"))return batch(a,id);
|
||||
try{
|
||||
files.write(a,id,"ATTACHMENT:"+(version+1),name,cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.mime(original),bytes,files.required(a,b.snapshotId()).proofs());
|
||||
finish(a,id,"ATTACHING","REVIEW_PENDING",null,null,"附件已关联快照记录;全部附件齐备后可以审核");
|
||||
}catch(RuntimeException e){finish(a,id,"ATTACHING","ATTACHMENT_UNKNOWN",null,null,e instanceof ReportingException?e.getMessage():"附件写入未确认;请核对原操作,不能重复上传或审核");}
|
||||
return batch(a,id);
|
||||
}
|
||||
private Batch reconcileAttachments(ReportingActor.Scope a,Batch b){
|
||||
if("ATTACHING".equals(b.state())&&LocalDateTime.parse(b.updatedAt()).isAfter(LocalDateTime.now().minusMinutes(5)))throw conflict("附件正在保存,请稍后刷新;超过5分钟后可以核对");
|
||||
// The claimed version identifies exactly this upload, including a BOUND write whose batch update was lost.
|
||||
// Absence of its persisted operation is not proof of completion; never unlock another upload on that basis.
|
||||
String kind="ATTACHMENT:"+("ATTACHING".equals(b.state())?b.version():b.version()-1);
|
||||
files.reconcile(a,b.id(),kind);
|
||||
var fixed=frozen(a,b.id());var snapshot=readSnapshot(a,b);
|
||||
var manifest=ReportingAttachments.describe(fixed,snapshot,files.list(a,b.id()),false);
|
||||
for(var attachment:manifest)if(attachment.artifactId()!=null)verifyAttachment(a,attachment);
|
||||
finish(a,b.id(),b.state(),"REVIEW_PENDING",null,null,"已核对原附件操作;请检查附件清单,缺失文件仍须补齐后审核");return batch(a,b.id());
|
||||
}
|
||||
private Snapshot readSnapshot(ReportingActor.Scope a,Batch b){
|
||||
if(b.snapshotId()==null)throw conflict("批次尚无候选快照");
|
||||
var snapshot=json.readValue(files.read(a,b.snapshotId()),Snapshot.class);verifySnapshot(a,b,snapshot);return snapshot;
|
||||
}
|
||||
private Map<String,byte[]> attachmentBytes(ReportingActor.Scope a,Batch b,Frozen fixed,Snapshot snapshot){
|
||||
var result=new LinkedHashMap<String,byte[]>();
|
||||
for(var attachment:ReportingAttachments.describe(fixed,snapshot,files.list(a,b.id()),true))result.put(attachment.name(),verifyAttachment(a,attachment));
|
||||
return result;
|
||||
}
|
||||
private byte[] verifyAttachment(ReportingActor.Scope a,Attachment attachment){
|
||||
byte[] bytes=files.read(a,attachment.artifactId());
|
||||
ReportingAttachments.validateUpload(attachment.name(),cn.aixunkeji.resource.api.assetupgrade.ReportingAttachmentPolicy.originalName(attachment.name()),bytes);return bytes;
|
||||
}
|
||||
byte[] download(String batchId,String artifactId){var a=actors.current("view");batch(a,batchId);var f=files.required(a,artifactId);if(!batchId.equals(f.batchId()))throw forbidden();return files.read(a,artifactId);}
|
||||
ReportingApi.Page<ReportingApi.Audit> history(String id,int page,int size){var a=actors.current("view");batch(a,id);ReportingService.paging(page,size);return audit.objectHistory(a,id,page,size);}
|
||||
@org.springframework.beans.factory.annotation.Autowired private ReportingTransport transport;
|
||||
Precheck precheck(String id){return precheck(id,false);}
|
||||
Precheck precheck(String id,boolean claimed){
|
||||
var a=actors.current("view");var b=batch(a,id);var blockers=new ArrayList<String>();boolean ready=false;
|
||||
if(!("FILE_READY".equals(b.state())||claimed&&"SUBMITTING".equals(b.state()))||b.packageId()==null||b.snapshotId()==null)blockers.add("仅已审核并生成正式文件、尚未提交的批次可提交");
|
||||
else try{
|
||||
actors.current("edit");var fixed=frozen(a,id);requireActive(a,b,fixed);readSnapshot(a,b);
|
||||
var file=files.required(a,b.packageId());
|
||||
if(!id.equals(file.batchId())||!"PACKAGE".equals(file.kind())||!"BOUND".equals(file.state()))throw conflict("正式文件引用与批次不一致或尚未绑定");
|
||||
files.authorizeMetadata(a,b.packageId());ready=true;
|
||||
var system=audit.required(a,fixed.plan().definition().systemId(),false);
|
||||
var envelope=fixed.envelope();var target=system.command().system();
|
||||
if(envelope==null||!Objects.equals(envelope.reporterCode(),target.reporterCode())||!Objects.equals(envelope.interfaceCode(),target.interfaceCode())||!Objects.equals(envelope.version(),target.defaultVersion()))blockers.add("文件冻结的上报单位、接口代号或版本与当前系统配置不一致,请重新生成批次");
|
||||
blockers.addAll(transport==null?List.of("传输适配器不可用"):transport.blockers(a,system,fixed.plan().definition().adapterProfile()));
|
||||
}catch(ReportingException e){blockers.add(e.getMessage());}catch(RuntimeException e){blockers.add("批次、来源权限或文件检查暂不可用,请核对服务状态");}
|
||||
return new Precheck(ready,ready&&blockers.isEmpty(),List.copyOf(blockers));
|
||||
}
|
||||
private void requireActive(ReportingActor.Scope a,Batch b,Frozen frozen){var task=task(a,b.taskId(),false);var plan=plans.read(a,frozen.plan().id(),false);if(!task.enabled()||plan==null||!"FROZEN".equals(plan.state())||plan.version()!=frozen.plan().version()||!plans.check(plan.definition()).configurationValid())throw conflict("任务、方案或引用已停用或变化");}
|
||||
private String definitionHash(ReportingActor.Scope a,String id){return jdbc.queryForObject("SELECT frozen_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id);}
|
||||
private void verifySnapshot(ReportingActor.Scope a,Batch b,Snapshot s){if(!b.id().equals(s.batchId())||!b.startDate().equals(s.startDate())||!b.endDate().equals(s.endDate())||!definitionHash(a,b.id()).equals(s.definitionSha256()))throw conflict("快照不属于当前固定批次");}
|
||||
private boolean claim(ReportingActor.Scope a,Batch b,Action action,String operation,Set<String> allowed,String state){
|
||||
return Boolean.TRUE.equals(transactions.execute(status->claimInTransaction(a,b,action,operation,allowed,state)));
|
||||
}
|
||||
private boolean claimInTransaction(ReportingActor.Scope a,Batch b,Action action,String operation,Set<String> allowed,String state){
|
||||
validate(action);String hash=command(operation,action);if(same(a,b.id(),hash))return false;
|
||||
if(!allowed.contains(b.state())||b.version()!=action.version())throw conflict("批次状态或版本已变化,请刷新");
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,version=version+1,command_sha256=?,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND version=?",state,hash,a.user(),a.organization(),b.id(),b.version())!=1)throw conflict("批次操作已被其他请求接管");
|
||||
audit.audit(a,b.id(),"BATCH_"+operation,b.version()+1,action.reason());return true;
|
||||
}
|
||||
private boolean same(ReportingActor.Scope a,String id,String hash){return hash.equals(jdbc.queryForObject("SELECT command_sha256 FROM dg_reporting_batch WHERE organization_id=? AND batch_id=?",String.class,a.organization(),id));}
|
||||
private String command(String operation,Action action){validate(action);return ReportingService.hash(json.writeValueAsString(List.of(operation,action.version(),action.reason())));}
|
||||
private static void validate(Action a){if(a==null||a.version()<0||a.version()==Long.MAX_VALUE)throw invalid("操作版本无效");if(a.reason()==null||a.reason().length()>1000)throw invalid("操作意见必须为1至1000字");ReportingPolicy.text(a.reason(),1000,true,"操作原因/审核意见");}
|
||||
private void finish(ReportingActor.Scope a,String id,String old,String state,String snapshot,String file,String message){
|
||||
transactions.executeWithoutResult(status->finishInTransaction(a,id,old,state,snapshot,file,message));
|
||||
}
|
||||
private void finishInTransaction(ReportingActor.Scope a,String id,String old,String state,String snapshot,String file,String message){
|
||||
if(jdbc.update("UPDATE dg_reporting_batch SET batch_state=?,snapshot_id=COALESCE(?,snapshot_id),package_id=COALESCE(?,package_id),message=?,version=version+1,update_by=?,update_time=CURRENT_TIMESTAMP WHERE organization_id=? AND batch_id=? AND batch_state=?",state,snapshot,file,message,a.user(),a.organization(),id,old)!=1)throw conflict("批次已变化,请刷新核对");
|
||||
audit.audit(a,id,"BATCH_"+state,batch(a,id).version(),message);
|
||||
}
|
||||
private void failure(ReportingActor.Scope a,String id,String old,String message){boolean uncertain=files.list(a,id).stream().anyMatch(f->("READING".equals(old)?"SNAPSHOT":"PACKAGE").equals(f.kind()));finish(a,id,old,uncertain?"UNKNOWN":"FAILED",null,null,message);}
|
||||
private void validateSelections(TaskDefinition d,ReportingPlanApi.View plan){
|
||||
var expected=plan.definition().bindings().stream().map(ReportingPlanApi.Binding::resourceCode).collect(java.util.stream.Collectors.toSet());
|
||||
if(!expected.equals(d.selections().stream().map(Selection::resourceCode).collect(java.util.stream.Collectors.toSet())))throw invalid("任务必须为每张方案资源指定主键及期间过滤");
|
||||
for(var s:d.selections()){
|
||||
var b=plan.definition().bindings().stream().filter(v->v.resourceCode().equals(s.resourceCode())).findFirst().orElseThrow();
|
||||
List<ReportingDatasetDirectory.Field> sourceFields;
|
||||
if(b.directSource()!=null)sourceFields=plans.sourceFields(b);else {var dataset=datasets.resolve(b.datasetId());requireVersion(b,dataset);sourceFields=dataset.fields();}
|
||||
var fields=sourceFields.stream().map(ReportingDatasetDirectory.Field::name).toList();
|
||||
if(!fields.containsAll(s.keyFields())||!s.periodField().isBlank()&&!fields.contains(s.periodField())||s.filters().stream().anyMatch(f->!fields.contains(f.field())))throw invalid("任务主键或过滤字段不属于取数来源");
|
||||
var targets=b.mappings().stream().map(ReportingPlanApi.Mapping::target).toList();
|
||||
if(!targets.containsAll(s.attachmentFields()))throw invalid("附件引用字段必须是方案中已映射的目标字段");
|
||||
validateParameters(b,s.parameters());
|
||||
}
|
||||
}
|
||||
static List<Selection> batchSelections(TaskDefinition task,ReportingPlanApi.View plan,CreateBatch request){
|
||||
var codes=task.selections().stream().map(Selection::resourceCode).collect(java.util.stream.Collectors.toSet());
|
||||
if(!codes.containsAll(request.parameters().keySet())||!codes.containsAll(request.readinessEvidence().keySet()))throw invalid("本批参数或完成确认包含未绑定资源");
|
||||
request.readinessEvidence().values().forEach(value->ReportingPolicy.text(value,1000,true,"本批完成确认"));
|
||||
var selections=new ArrayList<Selection>();
|
||||
for(var selection:task.selections()){
|
||||
var binding=plan.definition().bindings().stream().filter(b->b.resourceCode().equals(selection.resourceCode())).findFirst().orElseThrow();
|
||||
var values=new LinkedHashMap<>(selection.parameters());values.putAll(request.parameters().getOrDefault(selection.resourceCode(),Map.of()));validateParameters(binding,values);
|
||||
if(binding.directSource()!=null&&"INTERMEDIATE_TABLE".equals(binding.directSource().definition().mode()))ReportingPolicy.text(request.readinessEvidence().get(selection.resourceCode()),1000,true,"中间库本批已推送完成的范围及确认依据");
|
||||
selections.add(new Selection(selection.resourceCode(),selection.periodField(),selection.keyFields(),selection.filters(),selection.attachmentFields(),Map.copyOf(values)));
|
||||
}return List.copyOf(selections);
|
||||
}
|
||||
private static void validateParameters(ReportingPlanApi.Binding binding,Map<String,String> values){
|
||||
if(values.size()>50||values.entrySet().stream().anyMatch(e->e.getKey()==null||e.getValue()==null||e.getKey().length()>64||e.getValue().length()>4000))throw invalid("本批SQL参数无效");
|
||||
if(values.isEmpty())return;
|
||||
if(binding.directSource()==null||!binding.directSource().definition().sqlSource())throw invalid("只有SQL来源可以设置查询参数");
|
||||
var declared=binding.directSource().definition().parameters().stream().map(cn.aixunkeji.datagov.integration.datasource.ReportingSourceRead.Parameter::name).collect(java.util.stream.Collectors.toSet());
|
||||
if(!declared.containsAll(values.keySet()))throw invalid("本批参数包含SQL未定义名称");
|
||||
}
|
||||
static TaskDefinition normalizeTask(TaskDefinition d){
|
||||
if(d==null||d.planVersion()<0||d.selections()==null||d.selections().isEmpty()||d.selections().size()>50||!Set.of("MONTH","QUARTER","YEAR","CUSTOM").contains(Objects.toString(d.periodType(),"")))throw invalid("任务定义无效");ReportingPolicy.id(d.planId());Set<String> codes=new HashSet<>();
|
||||
for(var s:d.selections()){
|
||||
if(s==null||s.resourceCode()==null||!codes.add(s.resourceCode())||s.periodField()==null||s.keyFields()==null||s.keyFields().isEmpty()||s.keyFields().size()>10||new HashSet<>(s.keyFields()).size()!=s.keyFields().size()||s.filters()==null||s.filters().size()>18)throw invalid("资源、业务主键或过滤设置无效");
|
||||
if(s.attachmentFields().size()>20||new HashSet<>(s.attachmentFields()).size()!=s.attachmentFields().size()||s.attachmentFields().stream().anyMatch(f->f==null||f.isBlank()||f.length()>128))throw invalid("附件引用字段无效");
|
||||
for(var f:s.filters())if(f==null||f.field()==null||!Set.of("EQ","NE","GT","GTE","LT","LTE","IN","NOT_IN","IS_NULL","IS_NOT_NULL").contains(Objects.toString(f.operator(),""))||f.values()==null||f.values().size()>100||f.values().stream().anyMatch(v->v==null||v.length()>1000))throw invalid("过滤条件无效");
|
||||
}
|
||||
return new TaskDefinition(ReportingPolicy.text(d.name(),160,true,"任务名称"),d.planId(),d.planVersion(),d.periodType(),List.copyOf(d.selections()));
|
||||
}
|
||||
static void period(String type,String start,String end){try{
|
||||
LocalDate a=LocalDate.parse(start),b=LocalDate.parse(end);if(!a.isBefore(b)||a.getYear()<1900||b.getYear()>2200||java.time.temporal.ChronoUnit.DAYS.between(a,b)>366)throw new IllegalArgumentException();
|
||||
boolean valid=switch(type){case "MONTH"->a.getDayOfMonth()==1&&b.equals(a.plusMonths(1));case "QUARTER"->a.getDayOfMonth()==1&&(a.getMonthValue()-1)%3==0&&b.equals(a.plusMonths(3));case "YEAR"->a.getDayOfYear()==1&&b.equals(a.plusYears(1));case "CUSTOM"->true;default->false;};if(!valid)throw new IllegalArgumentException();
|
||||
}catch(Exception e){throw invalid("期间须匹配任务周期,采用起日包含、止日不包含,最多366天");}}
|
||||
private static void requireVersion(ReportingPlanApi.Binding b,ReportingDatasetDirectory.Dataset d){if(d.version()!=b.datasetVersion()||!d.releaseId().equals(b.releaseId())||!d.schemaVersionId().equals(b.schemaVersionId())||!d.schemaSha256().equals(b.schemaSha256()))throw conflict("数据集发布或结构版本已变化");}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import org.apache.dubbo.config.annotation.DubboService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@DubboService(group="aixun-datagov-private-file-integration",version="1.0.0",retries=0)
|
||||
@RequiredArgsConstructor
|
||||
public class ReportingFileAuthorization implements AuthorizationOwner {
|
||||
private final ReportingFiles files;
|
||||
@Override public AuthorizationDecision authorize(AuthorizationQuery query){
|
||||
try{return files.authorize(query);}catch(RuntimeException e){return new AuthorizationDecision(query,State.DENIED,null,0,null,null,null,false,"REPORTING_FILE_FORBIDDEN");}
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.Instant;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.function.Supplier;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner;
|
||||
import cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.*;
|
||||
import cn.aixunkeji.datagov.dataproduct.api.reporting.ReportingDatasetDirectory;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingExecutionApi.*;
|
||||
import static cn.aixunkeji.resource.api.assetupgrade.PrivateBusinessFileOwner.MAX_CHUNK_BYTES;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingFiles {
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final ReportingActor actors;
|
||||
@DubboReference(version=PrivateBusinessFileOwner.VERSION,group=PrivateBusinessFileOwner.GROUP,check=false,retries=0,timeout=15000)
|
||||
private PrivateBusinessFileOwner files;
|
||||
@DubboReference(version=ReportingDatasetDirectory.VERSION,group=ReportingDatasetDirectory.GROUP,check=false,retries=0,timeout=10000)
|
||||
private ReportingDatasetDirectory datasets;
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.datagov.integration.datasource.ReportingSourceService directSources;
|
||||
record Stored(String id,String batchId,String kind,Target target,Binding binding,List<SourceProof> proofs,String operation,String state,long creator,String createdAt) { }
|
||||
String write(ReportingActor.Scope a,String batch,String kind,String name,String mime,byte[] bytes,List<SourceProof> proofs){
|
||||
if(bytes.length==0||bytes.length>10*1024*1024)throw ReportingException.invalid("批次文件为空或超过10 MiB;请缩小任务期间或过滤范围");
|
||||
String id=UUID.randomUUID().toString(),operation=ReportingService.hash("reporting:"+a.organization()+":"+id);
|
||||
var target=new Target("integration","REGULATORY_REPORTING_ARTIFACT",id,1,"PACKAGE".equals(kind)?FileUse.DELIVERY_PACKAGE:FileUse.EVIDENCE,
|
||||
"REGULATORY_REPORTING",batch,name,sha(bytes),bytes.length,mime,null,null);
|
||||
jdbc.update("INSERT INTO dg_reporting_artifact(organization_id,artifact_id,batch_id,artifact_kind,target_json,proof_json,operation_key,artifact_state,create_by) VALUES(?,?,?,?,?,?,?,'PENDING',?)",
|
||||
a.organization(),id,batch,kind,json.writeValueAsString(target),json.writeValueAsString(proofs),operation,a.user());
|
||||
var context=context(a,id);var query=new WriteQuery(context,operation);
|
||||
var status=remote("创建文件操作",()->files.stage(new StageRequest(context,target,operation,target.bytesSha256())));
|
||||
verifyBinding(target,status.binding());
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET binding_json=? WHERE organization_id=? AND artifact_id=? AND artifact_state='PENDING'",json.writeValueAsString(status.binding()),a.organization(),id);
|
||||
if(status.state()!=WriteState.PREPARING)throw ReportingException.conflict("私有文件写入状态异常,需核对后继续");
|
||||
for(long offset=status.nextOffset();offset<bytes.length;){
|
||||
byte[] chunk=Arrays.copyOfRange(bytes,(int)offset,(int)Math.min(bytes.length,offset+MAX_CHUNK_BYTES));
|
||||
var append=new AppendRequest(query,offset,chunk,sha(chunk));
|
||||
status=remote("写入文件",()->files.append(append));
|
||||
if(status.nextOffset()!=offset+chunk.length)throw ReportingException.conflict("文件写入偏移不一致");offset=status.nextOffset();
|
||||
}
|
||||
status=remote("完成暂存",()->files.finish(query));verifyBinding(target,status.binding());
|
||||
if(status.state()!=WriteState.STAGED)throw ReportingException.conflict("文件未完成暂存");
|
||||
Stored stored=required(a,id);readBytes(a,stored,true);
|
||||
commit(a,stored);return id;
|
||||
}
|
||||
private void commit(ReportingActor.Scope a,Stored stored){
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='COMMITTED' WHERE organization_id=? AND artifact_id=? AND artifact_state='PENDING'",a.organization(),stored.id());
|
||||
var status=remote("绑定文件",()->files.complete(new WriteQuery(context(a,stored.id()),stored.operation())));verifyBinding(stored.target(),status.binding());
|
||||
if(status.state()!=WriteState.BOUND)throw ReportingException.conflict("文件绑定结果未知,请核对后继续");
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='BOUND' WHERE organization_id=? AND artifact_id=? AND artifact_state='COMMITTED'",a.organization(),stored.id());
|
||||
}
|
||||
/** Reconcile the SAME immutable operation; never regenerate source data on an uncertain write. */
|
||||
String reconcile(ReportingActor.Scope a,String batch,String kind){
|
||||
var found=jdbc.query("SELECT artifact_id FROM dg_reporting_artifact WHERE organization_id=? AND batch_id=? AND artifact_kind=?",(r,n)->r.getString(1),a.organization(),batch,kind);
|
||||
if(found.size()!=1)throw ReportingException.conflict("未发现唯一文件操作;请保留原批次并新建批次");
|
||||
return reconcileArtifact(a,found.getFirst());
|
||||
}
|
||||
String reconcileArtifact(ReportingActor.Scope a,String id){
|
||||
var stored=required(a,id);
|
||||
if(stored.creator()!=a.user())throw ReportingException.forbidden();
|
||||
authorizeMetadata(a,id);
|
||||
// Check the same immutable operation only. No source reread or replacement artifact is allowed.
|
||||
var query=new WriteQuery(context(a,stored.id()),stored.operation());
|
||||
var status=remote("核对文件",()->files.status(query));verifyBinding(stored.target(),status.binding());
|
||||
if(stored.binding()!=null&&!stored.binding().equals(status.binding()))throw ReportingException.forbidden();
|
||||
if(!stored.operation().equals(status.operationKey())||status.nextOffset()<0||status.nextOffset()>stored.target().byteLength())
|
||||
throw ReportingException.conflict("私有文件操作或写入偏移不一致,请核对原操作");
|
||||
if(stored.binding()==null){jdbc.update("UPDATE dg_reporting_artifact SET binding_json=? WHERE organization_id=? AND artifact_id=?",json.writeValueAsString(status.binding()),a.organization(),stored.id());stored=required(a,stored.id());}
|
||||
if(status.state()==WriteState.PREPARING){
|
||||
if(status.nextOffset()!=stored.target().byteLength())throw ReportingException.conflict("私有文件仅确认写入 "+status.nextOffset()+" / "+stored.target().byteLength()+" 字节,尚无完整快照。请先核实原写入是否结束并修复存储;无法续写时保留原批次,另建批次重新取数校验");
|
||||
status=remote("完成原文件暂存",()->files.finish(query));verifyBinding(stored.target(),status.binding());
|
||||
}
|
||||
if(status.state()==WriteState.STAGED){readBytes(a,stored,true);commit(a,stored);}
|
||||
else if(status.state()==WriteState.BOUND&&Set.of("COMMITTED","BOUND").contains(stored.state())){
|
||||
jdbc.update("UPDATE dg_reporting_artifact SET artifact_state='BOUND' WHERE organization_id=? AND artifact_id=?",a.organization(),stored.id());read(a,stored.id());
|
||||
}else throw ReportingException.conflict("原文件状态与批次不一致,不能认定成功;请核对原操作,保留原批次");
|
||||
return stored.id();
|
||||
}
|
||||
Stored required(ReportingActor.Scope a,String id){
|
||||
ReportingPolicy.id(id);
|
||||
return jdbc.query("SELECT * FROM dg_reporting_artifact WHERE organization_id=? AND artifact_id=?",(r,n)->new Stored(id,r.getString("batch_id"),r.getString("artifact_kind"),json.readValue(r.getString("target_json"),Target.class),r.getString("binding_json")==null?null:json.readValue(r.getString("binding_json"),Binding.class),Arrays.asList(json.readValue(r.getString("proof_json"),SourceProof[].class)),r.getString("operation_key"),r.getString("artifact_state"),r.getLong("create_by"),r.getTimestamp("create_time").toLocalDateTime().toString()),a.organization(),id).stream().findFirst().orElseThrow(ReportingException::forbidden);
|
||||
}
|
||||
List<Artifact> list(ReportingActor.Scope a,String batch){
|
||||
return jdbc.query("SELECT artifact_id FROM dg_reporting_artifact WHERE organization_id=? AND batch_id=? ORDER BY create_time,artifact_id",(r,n)->r.getString(1),a.organization(),batch).stream().map(id->{var s=required(a,id);return new Artifact(id,batch,s.kind().startsWith("ATTACHMENT:")?"ATTACHMENT":s.kind(),s.target().originalName(),s.target().bytesSha256(),s.target().byteLength(),s.state(),s.createdAt());}).toList();
|
||||
}
|
||||
byte[] read(ReportingActor.Scope a,String id){var s=required(a,id);if(!"BOUND".equals(s.state()))throw ReportingException.conflict("文件未完成绑定");return readBytes(a,s,false);}
|
||||
void authorizeMetadata(ReportingActor.Scope a,String id){
|
||||
var stored=required(a,id);if(stored.proofs().isEmpty())throw ReportingException.forbidden();
|
||||
for(var proof:stored.proofs())authorizeProof(proof);
|
||||
}
|
||||
private byte[] readBytes(ReportingActor.Scope a,Stored s,boolean staged){
|
||||
if(staged&&s.creator()!=a.user()||s.binding()==null)throw ReportingException.forbidden();
|
||||
var out=new ByteArrayOutputStream();var context=context(a,s.id());long offset=0;
|
||||
while(offset<s.target().byteLength()){
|
||||
long position=offset;
|
||||
var chunk=remote("读取文件",()->staged?files.readStaged(new StagedRead(new WriteQuery(context,s.operation()),position,MAX_CHUNK_BYTES)):
|
||||
files.readChunk(new ChunkQuery(new FileQuery(context,s.binding(),s.target().purpose(),s.batchId()),position,MAX_CHUNK_BYTES)));
|
||||
if(chunk.binding().offset()!=offset||!chunk.binding().file().context().equals(context)||!chunk.binding().file().binding().equals(s.binding())||chunk.bytes().length!=Math.min(MAX_CHUNK_BYTES,s.target().byteLength()-offset)||chunk.nextOffset()!=offset+chunk.bytes().length||chunk.endOfFile()!=(chunk.nextOffset()==s.target().byteLength())||!sha(chunk.bytes()).equals(chunk.chunkSha256()))throw ReportingException.conflict("私有文件分块完整性校验失败");
|
||||
out.writeBytes(chunk.bytes());offset=chunk.nextOffset();
|
||||
}
|
||||
byte[] bytes=out.toByteArray();if(bytes.length!=s.target().byteLength()||!sha(bytes).equals(s.target().bytesSha256()))throw ReportingException.conflict("私有文件内容完整性校验失败");return bytes;
|
||||
}
|
||||
AuthorizationDecision authorize(AuthorizationQuery query){
|
||||
var a=actors.current(query.action()==PrivateBusinessFileOwner.Action.READ?"view":"edit");
|
||||
var c=query.context();var t=query.target();
|
||||
if(c.actorId()!=a.user()||c.organizationId()!=a.organization()||c.departmentId()!=a.organization()||!"integration".equals(c.callerService())||!c.delegationRef().equals("reporting:"+t.objectId()))throw ReportingException.forbidden();
|
||||
var stored=required(a,t.objectId());
|
||||
if(query.action()!=PrivateBusinessFileOwner.Action.READ&&stored.creator()!=a.user()||!stored.target().equals(t)||!stored.operation().equals(query.operationKey()))throw ReportingException.forbidden();
|
||||
if(query.binding()!=null){verifyBinding(t,query.binding());if(stored.binding()!=null&&!stored.binding().equals(query.binding()))throw ReportingException.forbidden();}
|
||||
if(query.action()==PrivateBusinessFileOwner.Action.READ&&(!"BOUND".equals(stored.state())||query.binding()==null))throw ReportingException.forbidden();
|
||||
if(query.action()==PrivateBusinessFileOwner.Action.CANCEL||query.action()==PrivateBusinessFileOwner.Action.ERASE_KNOWLEDGE)throw ReportingException.forbidden();
|
||||
if(stored.proofs().isEmpty())throw ReportingException.forbidden();
|
||||
for(var proof:stored.proofs())authorizeProof(proof);
|
||||
Instant now=Instant.now();return new AuthorizationDecision(query,State.AVAILABLE,"reporting:"+stored.id(),1,"reporting-current-policy:"+stored.id(),now,now.plusSeconds(5),Set.of("COMMITTED","BOUND").contains(stored.state()),null);
|
||||
}
|
||||
private void authorizeProof(SourceProof proof){
|
||||
if(proof.directQuery()!=null){if(proof.query()!=null)throw ReportingException.forbidden();directSources.authorize(proof.directQuery(),proof.authorizationSha256());}
|
||||
else {if(proof.query()==null)throw ReportingException.forbidden();datasets.authorize(proof.query(),proof.authorizationSha256());}
|
||||
}
|
||||
private static Context context(ReportingActor.Scope a,String id){return new Context(1,a.user(),a.organization(),a.organization(),"integration","reporting:"+id,UUID.randomUUID().toString());}
|
||||
private static <T> T remote(String phase,Supplier<T> call){
|
||||
try{return call.get();}
|
||||
catch(ReportingException failure){throw failure;}
|
||||
catch(RuntimeException failure){
|
||||
String code="PRIVATE_FILE_UNAVAILABLE";
|
||||
// Do not match fragments of arbitrary RPC messages, which may include SQL, paths or secrets.
|
||||
Throwable cause=failure;
|
||||
for(int depth=0;cause!=null&&depth<12;depth++,cause=cause.getCause()){
|
||||
if(cause.getMessage()!=null&&cause.getMessage().matches("PRIVATE_FILE_[A-Z_]{1,64}")){code=cause.getMessage();break;}
|
||||
if(cause.getCause()==cause)break;
|
||||
}
|
||||
String detail=switch(code){
|
||||
case "PRIVATE_FILE_NOT_FOUND" -> "文件服务当前未找到原操作,尚无可恢复的完整快照。请核实原写入是否结束及服务数据库是否一致;确认未创建后修复存储,保留原批次并新建批次重新取数校验";
|
||||
case "PRIVATE_FILE_STORAGE_DISABLED" -> "私有文件存储未启用,请检查 Resource 的 local-file 配置";
|
||||
case "PRIVATE_FILE_DATABASE" -> "私有文件操作数据库访问失败,请按 Resource 日志中的 SQLState 和数据库错误码检查表、权限与连接";
|
||||
case "PRIVATE_FILE_WRITE_UNCONFIRMED" -> "文件写入未确认,请检查私有存储目录、权限及多节点共享挂载,再核对原操作";
|
||||
case "PRIVATE_FILE_INTEGRITY" -> "文件读取或完整性校验失败,请检查原文件、权限及多节点共享挂载;不能以其他文件替代";
|
||||
case "PRIVATE_FILE_SIZE" -> "文件长度超出 Resource 私有存储容量限制,请核对 max-bytes 配置和本批范围";
|
||||
default -> "私有文件操作未确认,请按 Resource 日志核查存储、业务授权及服务连接,再核对原操作";
|
||||
};
|
||||
throw ReportingException.conflict(phase+"失败:"+detail+"("+code+")。未自动重读数据或对外发送");
|
||||
}
|
||||
}
|
||||
private static void verifyBinding(Target t,Binding b){if(b==null||!t.businessOwner().equals(b.businessOwner())||!t.objectType().equals(b.objectType())||!t.objectId().equals(b.objectId())||t.artifactVersion()!=b.objectVersion()||!t.bytesSha256().equals(b.bytesSha256())||t.byteLength()!=b.byteLength()||!t.mime().equals(b.mime())||t.use()!=b.use())throw ReportingException.forbidden();}
|
||||
static String sha(byte[] bytes){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes));}catch(Exception e){throw new IllegalStateException(e);}}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
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 org.springframework.web.multipart.MultipartFile;
|
||||
import java.util.List;
|
||||
|
||||
@RestController @RequiredArgsConstructor
|
||||
@RequestMapping("/api/integration/v1/regulatory-reporting/standard-imports")
|
||||
class ReportingImportController {
|
||||
private final ReportingImportService service;
|
||||
@PostMapping(value = "/preview", consumes = "multipart/form-data")
|
||||
@SaCheckPermission(ReportingActor.PREFIX + "standard")
|
||||
public R<ReportingImportService.Preview> preview(@RequestParam("files") List<MultipartFile> files) { return R.ok(service.preview(files)); }
|
||||
@PostMapping(value = "/confirm", consumes = "multipart/form-data")
|
||||
@SaCheckPermission(ReportingActor.PREFIX + "standard")
|
||||
@Log(title = "确认导入监管标准", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
|
||||
public R<ReportingImportService.Preview> confirm(@RequestParam("files") List<MultipartFile> files) { return R.ok(service.confirm(files)); }
|
||||
}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.io.*;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
|
||||
|
||||
/** Bounded, side-effect-free parsing. No sample record values become standard defaults. */
|
||||
final class ReportingImportParser {
|
||||
static final int MAX_BYTES = 10 * 1024 * 1024;
|
||||
record Input(String name, byte[] bytes) { }
|
||||
record Issue(String file, String location, String severity, String message) { }
|
||||
record Parsed(Resource resource, String xml) { }
|
||||
record Result(List<Parsed> resources, List<Issue> issues, int fields, int required, int nullable, List<ReportingDocumentNotes.Note> notes) { }
|
||||
private final List<ReportingDocumentNotes.Note> notes = new ArrayList<>();
|
||||
private final JsonMapper json;
|
||||
private final List<Parsed> resources = new ArrayList<>();
|
||||
private final List<Issue> issues = new ArrayList<>();
|
||||
private final Set<String> digests = new HashSet<>();
|
||||
private final Set<String> codes = new HashSet<>();
|
||||
private int expanded, entries;
|
||||
ReportingImportParser(JsonMapper json) { this.json = json; }
|
||||
|
||||
Result parse(List<Input> inputs) {
|
||||
if (inputs == null || inputs.isEmpty() || inputs.size() > 50) throw ReportingException.invalid("请选择1至50个文件");
|
||||
for (var input : inputs) parseFile(input, false);
|
||||
int total = resources.stream().mapToInt(p -> p.resource().fields().size()).sum();
|
||||
if (total > 2000 || resources.size() > 50) throw ReportingException.invalid("单次最多50张资源表、2000个字段");
|
||||
int required = (int) resources.stream().flatMap(p -> p.resource().fields().stream()).filter(Field::required).count();
|
||||
int nullable = (int) resources.stream().flatMap(p -> p.resource().fields().stream()).filter(f -> f.details() != null && Boolean.TRUE.equals(f.details().nullable())).count();
|
||||
return new Result(List.copyOf(resources), List.copyOf(issues), total, required, nullable, List.copyOf(notes));
|
||||
}
|
||||
private void parseFile(Input input, boolean zipped) {
|
||||
String name = input.name();
|
||||
if (name == null || name.length() > 255 || input.bytes() == null || input.bytes().length == 0 || input.bytes().length > MAX_BYTES) throw ReportingException.invalid("文件为空、名称过长或超过10 MiB");
|
||||
expanded += input.bytes().length;
|
||||
if (++entries > 100 || expanded > 30 * 1024 * 1024) throw ReportingException.invalid("批量文件解压后超过30 MiB或条目过多");
|
||||
String digest = hash(input.bytes());
|
||||
if (!digests.add(digest)) { issue(name, "文件", "WARNING", "重复文件,未重复导入"); return; }
|
||||
try {
|
||||
String extension = name.substring(name.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);
|
||||
switch (extension) {
|
||||
case "xml" -> xml(name, utf8(input.bytes()));
|
||||
case "json" -> json(name, utf8(input.bytes()));
|
||||
case "xlsx", "xls" -> excel(name, input.bytes());
|
||||
case "pdf", "docx" -> {
|
||||
notes.addAll(ReportingDocumentNotes.extract(name,input.bytes()));
|
||||
if(notes.size()>4000||notes.stream().mapToInt(n->n.text().length()).sum()>400000)throw ReportingException.invalid("辅助说明过多,请分批导入");
|
||||
issue(name,"辅助说明","WARNING","辅助文本须人工核对并回填字段说明和规则,不自动生成约束或发布标准");
|
||||
}
|
||||
case "zip" -> {
|
||||
if (zipped) throw ReportingException.invalid("不支持嵌套ZIP");
|
||||
try (var zip = new ZipInputStream(new ByteArrayInputStream(input.bytes()), StandardCharsets.UTF_8)) {
|
||||
for (var e = zip.getNextEntry(); e != null; e = zip.getNextEntry()) {
|
||||
if (e.isDirectory()) { if (++entries > 100) throw ReportingException.invalid("ZIP条目过多"); continue; }
|
||||
if (!e.getName().toLowerCase(Locale.ROOT).endsWith(".xml") || e.getName().contains("..") || e.getName().startsWith("/")) {
|
||||
issue(name, e.getName(), "BLOCKING", "ZIP只接受XML模板,存在非法路径或非XML文件");
|
||||
break;
|
||||
}
|
||||
byte[] bytes = zip.readNBytes(MAX_BYTES + 1);
|
||||
parseFile(new Input(name + "/" + e.getName(), bytes), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> issue(name, "文件", "BLOCKING", "请选择XML、XML ZIP、JSON、Excel、PDF或DOCX");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
issue(name, "文件", "BLOCKING", ex instanceof ReportingException ? ex.getMessage() : "解析失败,请检查文件格式、编码及字段结构");
|
||||
}
|
||||
}
|
||||
private static String utf8(byte[] bytes) throws Exception {
|
||||
String value = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes)).toString();
|
||||
return value.startsWith("\uFEFF") ? value.substring(1) : value;
|
||||
}
|
||||
private static String hash(byte[] bytes) {
|
||||
try { return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (Exception e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
private void issue(String file, String location, String severity, String message) {
|
||||
if (issues.size() >= 2000) throw ReportingException.invalid("导入错误过多,请分批修正");
|
||||
issues.add(new Issue(file, location, severity, message));
|
||||
}
|
||||
private void add(String file, Resource resource, String xml) {
|
||||
try {
|
||||
ReportingStandardService.normalize(new Definition("IMPORT", "导入预览", "1", "", "", List.of(resource)));
|
||||
if (!codes.add(resource.code())) {
|
||||
int index = java.util.stream.IntStream.range(0, resources.size()).filter(i -> resources.get(i).resource().code().equals(resource.code())).findFirst().orElseThrow();
|
||||
Parsed old = resources.get(index);
|
||||
if ((old.xml() == null) == (xml == null)) { issue(file, resource.code(), "BLOCKING", "资源编码重复;不能自动覆盖或拼接定义"); return; }
|
||||
Resource definition = xml == null ? resource : old.resource();
|
||||
String template = xml == null ? old.xml() : xml;
|
||||
var shape = ReportingTemplateParser.parse(template, "Record");
|
||||
if (!TemplateConsistency.compare(definition.fields().stream().map(Field::name).toList(), shape.fields()).consistent())
|
||||
issue(file, resource.code(), "BLOCKING", "规范与XML字段或顺序不一致,须修正后导入");
|
||||
resources.set(index, new Parsed(definition, template));
|
||||
return;
|
||||
}
|
||||
resources.add(new Parsed(resource, xml));
|
||||
} catch (ReportingException e) { issue(file, resource.code(), "BLOCKING", e.getMessage()); }
|
||||
}
|
||||
private void xml(String file, String xml) {
|
||||
var shape = ReportingTemplateParser.parse(xml, "Record");
|
||||
var s = shape.structure();
|
||||
String code = s.resourceCode();
|
||||
if (code.isBlank()) { issue(file, "/Head/resCode", "BLOCKING", "模板缺少资源编码,不能从文件名猜测监管资源代号"); return; }
|
||||
var fields = new ArrayList<Field>();
|
||||
for (String name : shape.fields()) fields.add(new Field(name, name, "STRING", false, null, null, null,
|
||||
new FieldDetails("", null, null, List.of(), "", "", "", "BLOCKING",
|
||||
new Source(file, s.recordPath() + "/" + name, name, "REVIEW_REQUIRED", false))));
|
||||
issue(file, s.recordPath(), "WARNING", "XML仅声明字段和顺序,无法确定类型、长度和必填;请根据正式规范逐字段核对");
|
||||
add(file, new Resource(code, s.resourceName().isBlank() ? code : s.resourceName(), fields, null), xml);
|
||||
}
|
||||
private void json(String file, String text) {
|
||||
JsonNode root = JsonMapper.builder().enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION).build().readTree(text);
|
||||
if (!root.isObject() || !root.path("resources").isArray()) { issue(file, "$.resources", "BLOCKING", "需要对象根节点及resources数组;请按导入格式示例提供,不自动猜测表归属"); return; }
|
||||
unknown(file, "$", root, Set.of("resources", "code", "name", "versionLabel", "publisher", "description"));
|
||||
if (root.path("resources").size() > 50) throw ReportingException.invalid("资源表超过50张");
|
||||
int ri = 0;
|
||||
for (var resource : root.path("resources")) {
|
||||
String path = "$.resources[" + ri++ + "]";
|
||||
if (!resource.isObject()) { issue(file, path, "BLOCKING", "资源必须为对象"); continue; }
|
||||
unknown(file, path, resource, Set.of("code", "name", "fields"));
|
||||
if (!resource.path("fields").isArray() || resource.path("fields").size() > 500) { issue(file, path + ".fields", "BLOCKING", "字段必须为数组且不超过500个"); continue; }
|
||||
List<Field> fields = new ArrayList<>(); int fi = 0;
|
||||
for (var field : resource.path("fields")) {
|
||||
String fp = path + ".fields[" + fi++ + "]";
|
||||
try {
|
||||
if (!field.isObject()) throw ReportingException.invalid("字段必须为对象");
|
||||
unknown(file, fp, field, Set.of("name", "label", "type", "required", "nullable", "maxLength", "precision", "scale", "description", "defaultValue", "enumeration", "dictionary", "fillingRule", "validationRule", "severity"));
|
||||
if (!field.path("required").isBoolean()) throw ReportingException.invalid("required必须是布尔值");
|
||||
if (field.hasNonNull("nullable") && !field.path("nullable").isBoolean()) throw ReportingException.invalid("nullable必须是布尔值");
|
||||
var values = new ArrayList<String>();
|
||||
if (field.hasNonNull("enumeration")) {
|
||||
if (!field.path("enumeration").isArray()) throw ReportingException.invalid("enumeration必须为字符串数组");
|
||||
for (var v : field.path("enumeration")) { if (!v.isString()) throw ReportingException.invalid("枚举必须为字符串"); values.add(v.asString()); }
|
||||
}
|
||||
TypeSpec type = type(requiredText(field, "type"), integer(field, "maxLength"), integer(field, "precision"), integer(field, "scale"));
|
||||
var parsed = new Field(requiredText(field, "name"), optionalText(field, "label"), type.name(), field.path("required").asBoolean(), type.length(), type.precision(), type.scale(),
|
||||
new FieldDetails(optionalText(field, "description"), field.hasNonNull("nullable") ? field.path("nullable").asBoolean() : !field.path("required").asBoolean(),
|
||||
optionalText(field, "defaultValue"), values, optionalText(field, "dictionary"), optionalText(field, "fillingRule"), optionalText(field, "validationRule"),
|
||||
field.hasNonNull("severity") ? requiredText(field, "severity") : "BLOCKING", new Source(file, fp, field.toString(), "EXACT", false)));
|
||||
validateField(parsed); fields.add(parsed);
|
||||
} catch (Exception e) { issue(file, fp, "BLOCKING", e instanceof ReportingException ? e.getMessage() : "字段格式无效"); }
|
||||
}
|
||||
try { add(file, new Resource(requiredText(resource, "code"), requiredText(resource, "name"), fields, null), null); }
|
||||
catch (ReportingException e) { issue(file, path, "BLOCKING", e.getMessage()); }
|
||||
}
|
||||
}
|
||||
private void unknown(String file, String path, JsonNode node, Set<String> allowed) {
|
||||
for (String key : node.propertyNames()) if (!allowed.contains(key)) issue(file, path + "." + key, "BLOCKING", "未知属性,不能静默忽略,请确认字段映射");
|
||||
}
|
||||
private static String requiredText(JsonNode node, String name) { String v = optionalText(node, name); if (v.isBlank()) throw ReportingException.invalid(name + "不能为空"); return v; }
|
||||
private static String optionalText(JsonNode node, String name) {
|
||||
if (!node.hasNonNull(name)) return "";
|
||||
if (!node.path(name).isString()) throw ReportingException.invalid(name + "必须为字符串");
|
||||
return node.path(name).asString();
|
||||
}
|
||||
private static Integer integer(JsonNode node, String name) {
|
||||
if (!node.hasNonNull(name)) return null;
|
||||
if (!node.path(name).isIntegralNumber() || !node.path(name).canConvertToInt()) throw ReportingException.invalid(name + "必须为整数");
|
||||
return node.path(name).asInt();
|
||||
}
|
||||
private static final Map<String, String> HEADERS = Map.ofEntries(
|
||||
Map.entry("资源编码", "resourceCode"), Map.entry("表编码", "resourceCode"), Map.entry("resourcecode", "resourceCode"),
|
||||
Map.entry("资源名称", "resourceName"), Map.entry("表名称", "resourceName"), Map.entry("resourcename", "resourceName"),
|
||||
Map.entry("字段编码", "name"), Map.entry("字段名", "name"), Map.entry("name", "name"),
|
||||
Map.entry("字段名称", "label"), Map.entry("中文名称", "label"), Map.entry("label", "label"),
|
||||
Map.entry("类型", "type"), Map.entry("数据类型", "type"), Map.entry("type", "type"),
|
||||
Map.entry("必填", "required"), Map.entry("是否必填", "required"), Map.entry("required", "required"),
|
||||
Map.entry("允许空值", "nullable"), Map.entry("nullable", "nullable"),
|
||||
Map.entry("长度", "maxLength"), Map.entry("maxlength", "maxLength"), Map.entry("精度", "precision"), Map.entry("precision", "precision"),
|
||||
Map.entry("小数位", "scale"), Map.entry("scale", "scale"), Map.entry("说明", "description"), Map.entry("备注", "description"), Map.entry("description", "description"),
|
||||
Map.entry("填写规则", "fillingRule"), Map.entry("fillingrule", "fillingRule"), Map.entry("校验规则", "validationRule"), Map.entry("validationrule", "validationRule"),
|
||||
Map.entry("校验级别", "severity"), Map.entry("severity", "severity"), Map.entry("字典", "dictionary"), Map.entry("dictionary", "dictionary"),
|
||||
Map.entry("默认值", "defaultValue"), Map.entry("defaultvalue", "defaultValue"), Map.entry("枚举", "enumeration"), Map.entry("enumeration", "enumeration"));
|
||||
private void excel(String file, byte[] bytes) throws IOException {
|
||||
try (Workbook book = WorkbookFactory.create(new ByteArrayInputStream(bytes))) {
|
||||
if (book.getNumberOfSheets() > 50) throw ReportingException.invalid("工作表数量超过50");
|
||||
Map<String, List<Field>> groups = new LinkedHashMap<>(); Map<String, String> names = new HashMap<>();
|
||||
for (Sheet sheet : book) {
|
||||
if (sheet.getLastRowNum() > 10000 || sheet.getNumMergedRegions() > 2000) throw ReportingException.invalid("工作表行数或合并单元格过多");
|
||||
int header = -1; Map<String, Integer> columns = new LinkedHashMap<>();
|
||||
for (int r = 0; r <= Math.min(50, sheet.getLastRowNum()); r++) {
|
||||
var row = sheet.getRow(r); if (row == null) continue;
|
||||
Map<String, Integer> found = new LinkedHashMap<>();
|
||||
for (Cell cell : row) {
|
||||
String key = HEADERS.get(new DataFormatter(Locale.ROOT).formatCellValue(cell).strip().replace(" ", "").toLowerCase(Locale.ROOT));
|
||||
if (key != null && found.put(key, cell.getColumnIndex()) != null) issue(file, sheet.getSheetName() + "!" + cell.getAddress(), "BLOCKING", "重复语义列");
|
||||
}
|
||||
if (found.keySet().containsAll(Set.of("resourceCode", "resourceName", "name", "type")) && (found.containsKey("required") || found.containsKey("nullable"))) { header = r; columns = found; break; }
|
||||
}
|
||||
if (header < 0) { issue(file, sheet.getSheetName(), "BLOCKING", "未识别表头,需要资源编码、资源名称、字段编码、类型和必填/允许空值列"); continue; }
|
||||
Row headerRow = sheet.getRow(header);
|
||||
for (Cell cell : headerRow) if (!new DataFormatter().formatCellValue(cell).isBlank() && !columns.containsValue(cell.getColumnIndex()))
|
||||
issue(file, sheet.getSheetName() + "!" + cell.getAddress(), "BLOCKING", "未识别表头,须显式调整,不能丢弃规范列");
|
||||
for (int r = header + 1; r <= sheet.getLastRowNum(); r++) {
|
||||
Row row = sheet.getRow(r); if (row == null) continue;
|
||||
String location = sheet.getSheetName() + "!" + (r + 1);
|
||||
final int sourceRow = r;
|
||||
try {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (var col : columns.entrySet()) values.put(col.getKey(), cell(sheet, r, col.getValue()));
|
||||
// Only skip genuinely empty rows, not malformed field rows.
|
||||
boolean hasOwnValue = false;
|
||||
for (Cell c : row) if (!new DataFormatter().formatCellValue(c).isBlank()) { hasOwnValue = true; break; }
|
||||
if (!hasOwnValue) continue;
|
||||
String code = value(values, "resourceCode"), resourceName = value(values, "resourceName");
|
||||
if (code.isBlank() || resourceName.isBlank() || value(values, "name").isBlank()) throw ReportingException.invalid("资源编码、资源名称或字段编码为空");
|
||||
if (names.containsKey(code) && !names.get(code).equals(resourceName)) throw ReportingException.invalid("同一资源编码有不同名称");
|
||||
boolean required = values.containsKey("required") ? bool(value(values, "required")) : !bool(value(values, "nullable"));
|
||||
Boolean nullable = values.containsKey("nullable") ? bool(value(values, "nullable")) : !required;
|
||||
TypeSpec type = type(value(values, "type"), number(values, "maxLength"), number(values, "precision"), number(values, "scale"));
|
||||
var f = new Field(value(values, "name"), value(values, "label"), type.name(), required, type.length(), type.precision(), type.scale(),
|
||||
new FieldDetails(value(values, "description"), nullable, value(values, "defaultValue"),
|
||||
value(values, "enumeration").isBlank() ? List.of() : Arrays.asList(value(values, "enumeration").split("\\|", -1)),
|
||||
value(values, "dictionary"), value(values, "fillingRule"), value(values, "validationRule"), value(values, "severity").isBlank() ? "BLOCKING" : value(values, "severity"),
|
||||
new Source(file, location + " " + columns.entrySet().stream().map(e -> e.getKey() + "=" + new org.apache.poi.ss.util.CellReference(sourceRow, e.getValue()).formatAsString()).toList(), json.writeValueAsString(values), "EXACT", false)));
|
||||
validateField(f); names.put(code, resourceName); groups.computeIfAbsent(code, k -> new ArrayList<>()).add(f);
|
||||
} catch (Exception e) { issue(file, location, "BLOCKING", e instanceof ReportingException ? e.getMessage() : "单元格数值或格式无效"); }
|
||||
}
|
||||
}
|
||||
groups.forEach((code, fields) -> add(file, new Resource(code, names.get(code), fields, null), null));
|
||||
}
|
||||
}
|
||||
private static String cell(Sheet sheet, int r, int c) {
|
||||
for (var range : sheet.getMergedRegions()) if (range.isInRange(r, c)) { r = range.getFirstRow(); c = range.getFirstColumn(); break; }
|
||||
Row row = sheet.getRow(r); Cell cell = row == null ? null : row.getCell(c);
|
||||
if (cell == null) return "";
|
||||
if (cell.getCellType() == CellType.FORMULA) throw ReportingException.invalid("规范单元格包含公式,请确认并转换为明确值");
|
||||
return new DataFormatter(Locale.ROOT).formatCellValue(cell).strip();
|
||||
}
|
||||
private static String value(Map<String, String> values, String key) { return values.getOrDefault(key, ""); }
|
||||
private static void validateField(Field f) { ReportingStandardService.normalize(new Definition("IMPORT", "预览", "1", "", "", List.of(new Resource("ROW", "资源", List.of(f), null)))); }
|
||||
private record TypeSpec(String name, Integer length, Integer precision, Integer scale) { }
|
||||
private static TypeSpec type(String value, Integer length, Integer precision, Integer scale) {
|
||||
var m = java.util.regex.Pattern.compile("([A-Z][A-Z0-9]*)(?:\\((\\d+)(?:,(\\d+))?\\))?").matcher(value.toUpperCase(Locale.ROOT).replace(" ", ""));
|
||||
if (!m.matches()) throw ReportingException.invalid("字段类型无法识别:" + value);
|
||||
String name = switch (m.group(1)) {
|
||||
case "STRING", "CHAR", "VARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2", "TEXT", "CLOB" -> "STRING";
|
||||
case "INTEGER", "INT", "BIGINT", "SMALLINT", "TINYINT" -> "INTEGER";
|
||||
case "DECIMAL", "NUMERIC", "NUMBER" -> "DECIMAL";
|
||||
case "DATE" -> "DATE";
|
||||
case "DATETIME", "TIMESTAMP" -> "DATETIME";
|
||||
case "BOOLEAN", "BOOL" -> "BOOLEAN";
|
||||
default -> throw ReportingException.invalid("不支持的标准类型:" + value);
|
||||
};
|
||||
if (m.group(2) != null) {
|
||||
int a = Integer.parseInt(m.group(2)); Integer b = m.group(3) == null ? null : Integer.parseInt(m.group(3));
|
||||
if ("STRING".equals(name) && b == null) { if (length != null && length != a) throw ReportingException.invalid("类型内长度与长度列冲突"); length = a; }
|
||||
else if ("DECIMAL".equals(name)) {
|
||||
if (precision != null && precision != a || scale != null && b != null && !scale.equals(b)) throw ReportingException.invalid("类型内精度与精度列冲突");
|
||||
precision = a; if (b != null) scale = b;
|
||||
} else throw ReportingException.invalid("该类型的参数需要人工确认,不能忽略:" + value);
|
||||
}
|
||||
return new TypeSpec(name, length, precision, scale);
|
||||
}
|
||||
private static Integer number(Map<String, String> values, String key) { return value(values, key).isBlank() ? null : Integer.valueOf(value(values, key)); }
|
||||
private static boolean bool(String value) {
|
||||
if (Set.of("true", "1", "是", "Y", "YES").contains(value)) return true;
|
||||
if (Set.of("false", "0", "否", "N", "NO").contains(value)) return false;
|
||||
throw ReportingException.invalid("布尔标识须明确填写是/否或true/false");
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingStandardApi.*;
|
||||
|
||||
@Service @RequiredArgsConstructor
|
||||
class ReportingImportService {
|
||||
private final ReportingActor actors;
|
||||
private final ReportingStandardService standards;
|
||||
private final JsonMapper json;
|
||||
record Preview(List<Resource> resources, List<ReportingImportParser.Issue> issues, int fields, int required, int nullable, List<ReportingDocumentNotes.Note> notes) { }
|
||||
Preview preview(List<MultipartFile> files) { actors.current("standard"); return response(parse(files)); }
|
||||
@Transactional
|
||||
public Preview confirm(List<MultipartFile> files) {
|
||||
actors.current("standard");
|
||||
var result = parse(files);
|
||||
if (result.resources().isEmpty() || result.issues().stream().anyMatch(i -> "BLOCKING".equals(i.severity())))
|
||||
throw ReportingException.invalid("导入存在阻断错误,请先修正;未写入任何模板或标准");
|
||||
var resources = new ArrayList<Resource>();
|
||||
for (var p : result.resources()) {
|
||||
var r = p.resource();
|
||||
String templateId = p.xml() == null ? null : standards.importTemplate(new TemplateImport(p.xml(), "Record")).id();
|
||||
resources.add(new Resource(r.code(), r.name(), r.fields(), templateId));
|
||||
}
|
||||
return new Preview(resources, result.issues(), result.fields(), result.required(), result.nullable(), result.notes());
|
||||
}
|
||||
private Preview response(ReportingImportParser.Result r) {
|
||||
// XML sample values are neither returned nor persisted by preview.
|
||||
return new Preview(r.resources().stream().map(ReportingImportParser.Parsed::resource).toList(), r.issues(), r.fields(), r.required(), r.nullable(), r.notes());
|
||||
}
|
||||
private ReportingImportParser.Result parse(List<MultipartFile> files) {
|
||||
if (files == null || files.isEmpty() || files.size() > 50) throw ReportingException.invalid("请选择1至50个文件");
|
||||
var inputs = new ArrayList<ReportingImportParser.Input>(); long total = 0;
|
||||
for (var file : files) {
|
||||
if (file.isEmpty() || file.getSize() > ReportingImportParser.MAX_BYTES || (total += file.getSize()) > 30 * 1024 * 1024) throw ReportingException.invalid("单文件不能超过10 MiB,总计不能超过30 MiB");
|
||||
try { inputs.add(new ReportingImportParser.Input(file.getOriginalFilename(), file.getBytes())); }
|
||||
catch (java.io.IOException e) { throw ReportingException.invalid("文件读取失败"); }
|
||||
}
|
||||
return new ReportingImportParser(json).parse(inputs);
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package cn.aixunkeji.datagov.integration.regulatoryreporting;
|
||||
|
||||
import java.util.*;
|
||||
import java.math.*;
|
||||
import java.time.*;
|
||||
import java.time.format.*;
|
||||
import static cn.aixunkeji.datagov.integration.regulatoryreporting.ReportingPlanApi.*;
|
||||
|
||||
/** Closed operations, no script, SQL, reflection or expression interpreter. */
|
||||
final class ReportingMapping {
|
||||
static void validate(Mapping m){
|
||||
var t=m.transform();if(t==null)return;
|
||||
if(!Set.of("DIRECT","CONSTANT","REPORTER_CODE","STABLE_GUID","DEFAULT","TRIM","UPPER","LOWER","DICTIONARY","DATE","DATETIME","DECIMAL","DECIMAL_PLAIN","CONCAT").contains(Objects.toString(t.kind(),"")))throw ReportingException.invalid("不支持的转换类型");
|
||||
if("STABLE_GUID".equals(t.kind())&&(t.argument()==null||t.argument().isBlank()))throw ReportingException.invalid("稳定GUID须指定长期不变的业务命名空间");
|
||||
if(t.argument()!=null&&t.argument().length()>2000||t.outputFormat()!=null&&t.outputFormat().length()>100||t.values()!=null&&t.values().size()>1000||t.sources()!=null&&t.sources().size()>20)throw ReportingException.invalid("转换配置超过范围");
|
||||
if(t.values()!=null)for(var entry:t.values().entrySet())if(entry.getKey()==null||entry.getValue()==null||entry.getKey().length()>2000||entry.getValue().length()>2000)throw ReportingException.invalid("字典项无效");
|
||||
if(t.sources()!=null&&t.sources().stream().anyMatch(s->s==null||!s.matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}")))throw ReportingException.invalid("表达式来源字段无效");
|
||||
if("CONSTANT".equals(t.kind())&&t.argument()==null||"DEFAULT".equals(t.kind())&&t.argument()==null||"DICTIONARY".equals(t.kind())&&(t.values()==null||t.values().isEmpty())||"CONCAT".equals(t.kind())&&(t.sources()==null||t.sources().isEmpty()))throw ReportingException.invalid("转换参数不完整");
|
||||
try{
|
||||
if(Set.of("DATE","DATETIME").contains(t.kind())){formatter(t.argument());formatter(t.outputFormat());}
|
||||
if("DECIMAL".equals(t.kind())&&(Integer.parseInt(t.argument())<0||Integer.parseInt(t.argument())>30))throw new IllegalArgumentException();
|
||||
}catch(Exception e){throw ReportingException.invalid("日期格式或小数位配置无效");}
|
||||
}
|
||||
static List<String> sources(Mapping m){
|
||||
if(m.transform()!=null&&Set.of("CONSTANT","REPORTER_CODE").contains(m.transform().kind()))return List.of();
|
||||
if(m.transform()!=null&&"CONCAT".equals(m.transform().kind()))return m.transform().sources();
|
||||
return m.source()==null||m.source().isBlank()?List.of():List.of(m.source());
|
||||
}
|
||||
static String apply(Mapping m,Map<String,String> row){
|
||||
return apply(m,row,null);
|
||||
}
|
||||
static String apply(Mapping m,Map<String,String> row,String reporterCode){
|
||||
String v=row.get(m.source());var t=m.transform();if(t==null||"DIRECT".equals(t.kind()))return v;
|
||||
if("REPORTER_CODE".equals(t.kind())){if(reporterCode==null||!reporterCode.matches("[0-9A-HJ-NPQRTUWXY]{18}"))throw ReportingException.invalid("上报系统尚未配置单位信用代码");return reporterCode;}
|
||||
if("STABLE_GUID".equals(t.kind())){if(v==null||v.isBlank())throw ReportingException.invalid("稳定GUID的业务主键为空");return UUID.nameUUIDFromBytes(tools.jackson.databind.json.JsonMapper.builder().build().writeValueAsBytes(List.of(t.argument(),v))).toString();}
|
||||
if("CONSTANT".equals(t.kind()))return t.argument();
|
||||
if("DEFAULT".equals(t.kind()))return v==null||v.isBlank()?t.argument():v;
|
||||
if("CONCAT".equals(t.kind())){
|
||||
if(t.sources().stream().anyMatch(s->row.get(s)==null))return null;
|
||||
return String.join(Objects.toString(t.argument(),""),t.sources().stream().map(row::get).toList());
|
||||
}
|
||||
if(v==null)return null;
|
||||
return switch(t.kind()){
|
||||
case "TRIM"->v.strip();case "UPPER"->v.toUpperCase(Locale.ROOT);case "LOWER"->v.toLowerCase(Locale.ROOT);
|
||||
case "DICTIONARY"->{if(!t.values().containsKey(v))throw new IllegalArgumentException("字典未命中");yield t.values().get(v);}
|
||||
case "DATE"->LocalDate.parse(v,formatter(t.argument())).format(formatter(t.outputFormat()));
|
||||
case "DATETIME"->LocalDateTime.parse(v,formatter(t.argument())).format(formatter(t.outputFormat()));
|
||||
case "DECIMAL"->new BigDecimal(v).setScale(Integer.parseInt(t.argument()),RoundingMode.UNNECESSARY).toPlainString();
|
||||
case "DECIMAL_PLAIN"->new BigDecimal(v).stripTrailingZeros().toPlainString();
|
||||
default->throw new IllegalArgumentException("转换类型无效");
|
||||
};
|
||||
}
|
||||
private static DateTimeFormatter formatter(String pattern){
|
||||
if(pattern==null||pattern.isBlank()||pattern.length()>100||pattern.contains("yy")&&!pattern.contains("uuuu"))throw new IllegalArgumentException();
|
||||
return DateTimeFormatter.ofPattern(pattern,Locale.ROOT).withResolverStyle(ResolverStyle.STRICT);
|
||||
}
|
||||
}
|
||||
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
在新工单中引用
屏蔽一个用户