比较提交
6
次代码提交
main
...
CDC-Collect
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
|
|
b49578022b | ||
|
|
bd87d49778 | ||
|
|
17e80cef9c | ||
|
|
1146b30509 | ||
|
|
2e2910ce2e | ||
|
|
c252f40172 |
@@ -10,6 +10,9 @@ docs
|
||||
outputs
|
||||
tmp
|
||||
.cache
|
||||
/runtime/dev-private
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/node_modules
|
||||
**/.venv
|
||||
**/__pycache__
|
||||
|
||||
+16
@@ -8,6 +8,22 @@
|
||||
target/
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
|
||||
# Local delivery bundles and generated build output
|
||||
/deliverables/
|
||||
dist/
|
||||
node_modules/
|
||||
coverage/
|
||||
*.class
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
!.mvn/wrapper/maven-wrapper.jar
|
||||
!gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
######################################################################
|
||||
# IDE
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
- 使用aixun-datagov-local、归属明确的aixun-datagov-*容器及专属网络、卷、端口、schema、Redis/Nacos、账号与浏览器存储。拒绝其他项目引用和latest镜像。
|
||||
- 不打印或写入证据密码、token、私钥、连接串和真实.env。保留MIT LICENSE及第三方署名。
|
||||
- 四业务服务保持integration、dataops、governance、dataproduct;适配器位于integration。复用RCP6鉴权、组织、角色、菜单、文件、日志和公共UI;新业务包cn.aixunkeji.datagov.<context>。
|
||||
- DolphinScheduler负责数据DAG,Spring/达梦锁负责内部维护。平台自身数据库全新部署仅支持达梦;外部数据源适配器的MySQL等类型保留。使用批准的外部API/适配器,不直读写产品库;未知观测如实UNKNOWN。
|
||||
- DolphinScheduler负责数据DAG,Spring/平台数据库锁负责内部维护。按用户本次授权,平台自身数据库支持达梦与MySQL通过配置切换;切换需目标库完成初始化并重启服务,不自动迁移业务数据。外部数据源适配器类型保留。使用批准的外部API/适配器,不直读写产品库;未知观测如实UNKNOWN。
|
||||
- 采集节点V1只登记/授权/监控SeaTunnel,不安装或远程运维节点,不执行任意Shell/SSH,不新增DataGov Agent。保留Dubbo,Seata仍关闭。
|
||||
- start-docs下四份原始输入只读。产品、架构和安全结论未明确修订时保持;旧开发过程限制由本规则和ADR-0033替代。
|
||||
- 源码完成、本地部署、人工功能验收分别报告。结果使用PASS / PASS_WITH_LIMITATION / BLOCKED,未运行写NOT_RUN;不推导生产批准。
|
||||
|
||||
@@ -37,4 +37,4 @@ D-020保持:只操作aixun-datagov-local与本项目专属对象,禁止复
|
||||
|
||||
源码完成、本地部署和功能验收分别报告;M0~M6历史结果及其限制保持,不等于当前所有功能已通过或生产批准。四业务单元、RCP6公共能力、DolphinScheduler数据调度、内部维护数据库锁及外部适配器边界保持。
|
||||
|
||||
平台自身数据库的全新部署现适配达梦;连接、初始化和验证边界见[达梦全新部署记录](docs/runbook/达梦全新部署适配-20261118.md)。外部数据源类型不受此切换限制。
|
||||
平台自身数据库支持达梦与MySQL通过连接配置切换,同一套后端制品包含两种驱动;切换后重启服务,数据迁移须单独执行。连接、初始化和验证边界见[达梦与MySQL配置切换](docs/runbook/达梦与MySQL配置切换.md)。外部数据源类型不受此切换限制。
|
||||
|
||||
+12
-1
@@ -484,8 +484,19 @@ public final class TableFileApi {
|
||||
PartitionPolicy partitionPolicy,
|
||||
ViewDefinition viewDefinition,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
|
||||
String physicalTableComment
|
||||
String physicalTableComment,
|
||||
@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_EMPTY)
|
||||
List<String> uniqueKeyColumns
|
||||
) {
|
||||
public CreateCommand(String name, ObjectType objectType, Long layerId, Long storageResourceId,
|
||||
Long storageSpaceId, EngineType engineType, StorageFormat storageFormat,
|
||||
String catalogName, String namespaceName, String externalLocation, String comment,
|
||||
List<ColumnDefinition> columns, PartitionPolicy partitionPolicy, ViewDefinition viewDefinition,
|
||||
String physicalTableComment) {
|
||||
this(name, objectType, layerId, storageResourceId, storageSpaceId, engineType, storageFormat,
|
||||
catalogName, namespaceName, externalLocation, comment, columns, partitionPolicy, viewDefinition,
|
||||
physicalTableComment, null);
|
||||
}
|
||||
public CreateCommand(String name, ObjectType objectType, Long layerId, Long storageResourceId,
|
||||
Long storageSpaceId, EngineType engineType, StorageFormat storageFormat,
|
||||
String catalogName, String namespaceName, String externalLocation, String comment,
|
||||
|
||||
+40
@@ -46,6 +46,46 @@ public interface DataCollectionIntegrationService {
|
||||
|
||||
FileSubmissionResult submitFile(FileSubmissionRequest request);
|
||||
|
||||
/** API polling is executed inside Integration so source credentials never enter a SeaTunnel job. */
|
||||
default ApiPollResult pollApi(ApiPollRequest request) {
|
||||
return new ApiPollResult("UNKNOWN", 0, null, "API_POLL_ADAPTER_UNAVAILABLE");
|
||||
}
|
||||
|
||||
default ApiPreviewResult previewApi(ApiPreviewRequest request) {
|
||||
return new ApiPreviewResult("UNKNOWN", "API_PREVIEW_UNAVAILABLE", List.of());
|
||||
}
|
||||
|
||||
record ApiPreviewRequest(long actorId, long orgScopeId, String endpoint, String secretRef,
|
||||
String paginationMode, String paginationField, String responsePath,
|
||||
ApiPollProfile profile) implements Serializable { }
|
||||
record ApiPreviewField(String name, String fieldType, boolean nullable, boolean supported,
|
||||
String warning) implements Serializable { }
|
||||
record ApiPreviewDataset(String path, int sampledRows, List<ApiPreviewField> fields,
|
||||
List<Map<String, String>> rows) implements Serializable { }
|
||||
record ApiPreviewResult(String status, String errorCode, List<ApiPreviewDataset> datasets) implements Serializable { }
|
||||
|
||||
record ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark,
|
||||
FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile,
|
||||
ApiPollProfile profile) implements Serializable {
|
||||
public ApiPollRequest(long actorId, long orgScopeId, long intakeId, String watermark,
|
||||
FileExecutionSnapshot snapshot, StorageExecutionProfile targetProfile) {
|
||||
this(actorId, orgScopeId, intakeId, watermark, snapshot, targetProfile, null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Only references to managed secrets cross the service boundary. */
|
||||
record ApiPollProfile(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
String signingSecretRef) implements Serializable { }
|
||||
|
||||
record ApiPollResult(String status, int writtenRows, String watermark, String errorCode)
|
||||
implements Serializable { }
|
||||
|
||||
FileBatchResult observeFileBatches(FileBatchRequest request);
|
||||
|
||||
FileActionResult quarantineFile(FileActionRequest request);
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package cn.aixunkeji.datagov.integration.api;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
/** Internal owner-authorized CDC execution contract; never exposed as a public request. */
|
||||
public interface RealtimeCollectionService {
|
||||
Check check(Command command);
|
||||
Check prepare(Command command);
|
||||
Result execute(Command command, String action, String externalId, String restoreId);
|
||||
List<RelayOption> relays(long actorId,long orgId,long sourceId);
|
||||
SourceDefaults sourceDefaults(long actorId,long orgId,long sourceId);
|
||||
record SourceDefaults(long sourceVersion,String sourceSchema,String oracleDatabase,String oraclePdb,
|
||||
String oracleCdbService,String warning) implements Serializable { }
|
||||
record RelayOption(String id,String name,String schema,String table,String format) implements Serializable { }
|
||||
record Spec(String name, long sourceId, long sourceVersion, String sourceDatabase, String sourceTable,
|
||||
long targetResourceId, long targetSpaceId, String targetTable, int httpPort,
|
||||
String startupMode, int checkpointSeconds, long serverId, String sourceSchema,
|
||||
String oracleDatabase,String cdcChannel,String oraclePdb,String oracleCdbService) implements Serializable {
|
||||
public Spec(String name,long sourceId,long sourceVersion,String sourceDatabase,String sourceTable,
|
||||
long targetResourceId,long targetSpaceId,String targetTable,int httpPort,String startupMode,
|
||||
int checkpointSeconds,long serverId,String sourceSchema,String oracleDatabase,String cdcChannel) {
|
||||
this(name,sourceId,sourceVersion,sourceDatabase,sourceTable,targetResourceId,targetSpaceId,targetTable,
|
||||
httpPort,startupMode,checkpointSeconds,serverId,sourceSchema,oracleDatabase,cdcChannel,null,null);
|
||||
}
|
||||
public Spec(String name,long sourceId,long sourceVersion,String sourceDatabase,String sourceTable,
|
||||
long targetResourceId,long targetSpaceId,String targetTable,int httpPort,String startupMode,
|
||||
int checkpointSeconds,long serverId,String sourceSchema,String oracleDatabase) {
|
||||
this(name,sourceId,sourceVersion,sourceDatabase,sourceTable,targetResourceId,targetSpaceId,targetTable,
|
||||
httpPort,startupMode,checkpointSeconds,serverId,sourceSchema,oracleDatabase,null);
|
||||
}
|
||||
public Spec(String name, long sourceId, long sourceVersion, String sourceDatabase, String sourceTable,
|
||||
long targetResourceId, long targetSpaceId, String targetTable, int httpPort,
|
||||
String startupMode, int checkpointSeconds, long serverId) {
|
||||
this(name, sourceId, sourceVersion, sourceDatabase, sourceTable, targetResourceId, targetSpaceId,
|
||||
targetTable, httpPort, startupMode, checkpointSeconds, serverId, null, null);
|
||||
}
|
||||
/** Keep existing MySQL checkpoint fingerprints stable across the contract extension. */
|
||||
public String fingerprintText() {
|
||||
String legacy = "Spec[name="+name+", sourceId="+sourceId+", sourceVersion="+sourceVersion+
|
||||
", sourceDatabase="+sourceDatabase+", sourceTable="+sourceTable+", targetResourceId="+targetResourceId+
|
||||
", targetSpaceId="+targetSpaceId+", targetTable="+targetTable+", httpPort="+httpPort+
|
||||
", startupMode="+startupMode+", checkpointSeconds="+checkpointSeconds+", serverId="+serverId+"]";
|
||||
if(oraclePdb!=null || oracleCdbService!=null)return toString();
|
||||
String previous=toString().replace(", oraclePdb=null, oracleCdbService=null]","]");
|
||||
if(cdcChannel!=null)return previous;
|
||||
return sourceSchema == null && oracleDatabase == null ? legacy : previous.replace(", cdcChannel=null]","]");
|
||||
}
|
||||
}
|
||||
record Command(long actorId, long orgId, long taskId, long attempt, Spec spec,
|
||||
DataCollectionIntegrationService.StorageExecutionProfile target, String fingerprint,
|
||||
RecoveryEvidence recovery) implements Serializable {
|
||||
public Command(long actorId,long orgId,long taskId,long attempt,Spec spec,
|
||||
DataCollectionIntegrationService.StorageExecutionProfile target,String fingerprint) {
|
||||
this(actorId,orgId,taskId,attempt,spec,target,fingerprint,null);
|
||||
}
|
||||
}
|
||||
/** Supplied only by DataOps from its locked, owner-authorized persisted task. */
|
||||
record RecoveryEvidence(String jobId,String status,String checkpointId) implements Serializable { }
|
||||
record Check(boolean ready, String summary, String fingerprint, List<String> fields, List<String> primaryKeys)
|
||||
implements Serializable { }
|
||||
record Result(String status, String externalId, String summary, String checkpointId, Long readRows,
|
||||
Long writeRows) implements Serializable { }
|
||||
static String identity(long org, long task, long attempt) { return "realtime:" + org + ':' + task + ':' + attempt; }
|
||||
static String jobName(long task, long attempt) { return "aixun_cdc_" + task + '_' + attempt; }
|
||||
static String jobId(long org, long task, long attempt) {
|
||||
return Long.toString(DataCollectionIntegrationService.stableJobId(identity(org, task, attempt)));
|
||||
}
|
||||
}
|
||||
+15
-2
@@ -22,7 +22,12 @@ public interface TableFileIntegrationService {
|
||||
}
|
||||
}
|
||||
record DirectoryResult(State state, List<String> tables, List<DirectoryColumn> columns, int total,
|
||||
String errorSummary) implements Serializable { }
|
||||
String errorSummary, boolean confirmedMissing) implements Serializable {
|
||||
public DirectoryResult(State state, List<String> tables, List<DirectoryColumn> columns, int total,
|
||||
String errorSummary) {
|
||||
this(state, tables, columns, total, errorSummary, false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Separate, opt-in physical evidence contract. A null fact/list is unobserved, never an empty assertion. */
|
||||
default StructureResult structure(DirectoryCommand command, String expectedSha256) {
|
||||
@@ -133,8 +138,16 @@ public interface TableFileIntegrationService {
|
||||
List<Column> columns,
|
||||
PartitionSpec partitionSpec,
|
||||
ViewSpec viewSpec,
|
||||
String physicalTableComment
|
||||
String physicalTableComment,
|
||||
List<String> uniqueKeyColumns
|
||||
) implements Serializable {
|
||||
public CreateCommand(String requestId, long actorId, ConnectionProfile connection, ObjectType objectType,
|
||||
StorageFormat storageFormat, String catalogName, String namespaceName, String objectName,
|
||||
String externalLocation, List<Column> columns, PartitionSpec partitionSpec, ViewSpec viewSpec,
|
||||
String physicalTableComment) {
|
||||
this(requestId, actorId, connection, objectType, storageFormat, catalogName, namespaceName, objectName,
|
||||
externalLocation, columns, partitionSpec, viewSpec, physicalTableComment, null);
|
||||
}
|
||||
public CreateCommand(String requestId, long actorId, ConnectionProfile connection, ObjectType objectType,
|
||||
StorageFormat storageFormat, String catalogName, String namespaceName, String objectName,
|
||||
String externalLocation, List<Column> columns, PartitionSpec partitionSpec, ViewSpec viewSpec) {
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package cn.aixunkeji.common.core.enums;
|
||||
|
||||
/** Platform persistence dialect, determined once from the configured JDBC datasource. */
|
||||
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 product");
|
||||
}
|
||||
}
|
||||
@@ -10,9 +10,13 @@
|
||||
</parent>
|
||||
|
||||
<artifactId>aixun-common-maintenance</artifactId>
|
||||
<description>DataGov internal maintenance scheduling and MySQL lease-lock foundation</description>
|
||||
<description>DataGov internal maintenance scheduling and JDBC lease-lock foundation for DM and MySQL</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
|
||||
+16
-3
@@ -6,27 +6,40 @@ import java.util.Optional;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/** MySQL implementation using one conditional UPDATE as the lease-acquisition linearization point. */
|
||||
/** JDBC implementation using one conditional UPDATE as the lease-acquisition linearization point. */
|
||||
public final class JdbcMaintenanceLeaseRepository implements MaintenanceLeaseRepository {
|
||||
private final cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect;
|
||||
|
||||
|
||||
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.databaseDialect = databaseDialect;
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@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())
|
||||
);
|
||||
|
||||
@@ -16,6 +16,10 @@
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.aixunkeji</groupId>
|
||||
<artifactId>aixun-common-satoken</artifactId>
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
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;
|
||||
|
||||
@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
|
||||
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
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 {
|
||||
@Test void springResolvesActualConfiguredDatabaseAndClosesProbeConnection() throws Exception {
|
||||
for (String product : new String[]{"DM DBMS", "MySQL"}) {
|
||||
DataSource source = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
DatabaseMetaData metadata = mock(DatabaseMetaData.class);
|
||||
when(source.getConnection()).thenReturn(connection);
|
||||
when(connection.getMetaData()).thenReturn(metadata);
|
||||
when(metadata.getDatabaseProductName()).thenReturn(product);
|
||||
try (var context = new AnnotationConfigApplicationContext()) {
|
||||
context.registerBean(DataSource.class, () -> source);
|
||||
context.register(PlatformDatabaseConfiguration.class);
|
||||
context.refresh();
|
||||
assertThat(context.getBean(PlatformDatabaseDialect.class)).isEqualTo(PlatformDatabaseDialect.fromProduct(product));
|
||||
verify(connection).close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@Test void unknownDatabaseFailsWithoutSilentlyUsingMysql() throws Exception {
|
||||
DataSource source = mock(DataSource.class);
|
||||
Connection connection = mock(Connection.class);
|
||||
DatabaseMetaData metadata = mock(DatabaseMetaData.class);
|
||||
when(source.getConnection()).thenReturn(connection);
|
||||
when(connection.getMetaData()).thenReturn(metadata);
|
||||
when(metadata.getDatabaseProductName()).thenReturn("PostgreSQL");
|
||||
assertThatThrownBy(() -> new PlatformDatabaseConfiguration().platformDatabaseDialect(source)).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(connection).close();
|
||||
}
|
||||
@Test void sameClasspathIncludesBothJdbcDrivers() throws Exception {
|
||||
assertThat(Class.forName("dm.jdbc.driver.DmDriver")).isNotNull();
|
||||
assertThat(Class.forName("com.mysql.cj.jdbc.Driver")).isNotNull();
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,8 @@ public class GatewayHttpClientConfig {
|
||||
private static final String CONNECTION_TEST_SUFFIX = "/connection-tests";
|
||||
private static final String UNIFIED_INGESTION_DRAFT_PATH = "/api/dataops/v1/unified-ingestions/draft";
|
||||
private static final String UNIFIED_INGESTION_SUBMIT_PATH = "/api/dataops/v1/unified-ingestions/submit";
|
||||
private static final Pattern REALTIME_INGESTION_ACTION_PATH = Pattern.compile(
|
||||
"/api/dataops/v1/realtime-ingestions/[1-9][0-9]*/(?:CHECK|START|REFRESH|STOP|RESUME|ARCHIVE|DELETE|RECREATE)");
|
||||
private static final String DATA_PROFILE_CREATE_PATH = "/api/governance/v1/data-profiles";
|
||||
private static final String DATA_PROFILE_RETRY_PATH_PREFIX = "/api/governance/v1/data-profiles/";
|
||||
private static final Pattern NUMERIC_ID = Pattern.compile("[0-9]+");
|
||||
@@ -86,8 +88,10 @@ public class GatewayHttpClientConfig {
|
||||
&& isPositive(properties.getStandardAdoptionAiMatchResponseTimeout());
|
||||
boolean runOperationAiDiagnosis = isRunOperationAiDiagnosis(method, uri)
|
||||
&& isPositive(properties.getRunOperationAiDiagnosisResponseTimeout());
|
||||
boolean realtimeIngestionAction = isRealtimeIngestionAction(method, uri)
|
||||
&& isPositive(properties.getRealtimeIngestionActionResponseTimeout());
|
||||
return createRequestContext(uri, properties, dataProfileExecution, metadataCatalogAiDraft,
|
||||
standardAdoptionAiMatch, runOperationAiDiagnosis);
|
||||
standardAdoptionAiMatch, runOperationAiDiagnosis, realtimeIngestionAction);
|
||||
}
|
||||
|
||||
static HttpClientContext createRequestContext(HttpMethod method, URI uri, GatewayHttpClientProperties properties) {
|
||||
@@ -95,21 +99,22 @@ public class GatewayHttpClientConfig {
|
||||
}
|
||||
|
||||
static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties) {
|
||||
return createRequestContext(uri, properties, false, false, false, false);
|
||||
return createRequestContext(uri, properties, false, false, false, false, false);
|
||||
}
|
||||
|
||||
private static HttpClientContext createRequestContext(URI uri, GatewayHttpClientProperties properties,
|
||||
boolean dataProfileExecution,
|
||||
boolean metadataCatalogAiDraft,
|
||||
boolean standardAdoptionAiMatch,
|
||||
boolean runOperationAiDiagnosis) {
|
||||
boolean runOperationAiDiagnosis,
|
||||
boolean realtimeIngestionAction) {
|
||||
boolean m2StageCallback = isM2StageCallback(uri);
|
||||
boolean dataSourceConnectionTest = isDataSourceConnectionTest(uri);
|
||||
boolean unifiedIngestionDraft = isUnifiedIngestionDraft(uri);
|
||||
boolean unifiedIngestionSubmit = isUnifiedIngestionSubmit(uri);
|
||||
if (!dataProfileExecution && !m2StageCallback && !dataSourceConnectionTest && !unifiedIngestionDraft
|
||||
&& !unifiedIngestionSubmit && !metadataCatalogAiDraft && !standardAdoptionAiMatch
|
||||
&& !runOperationAiDiagnosis) return null;
|
||||
&& !runOperationAiDiagnosis && !realtimeIngestionAction) return null;
|
||||
|
||||
RequestConfig.Builder requestConfig = RequestConfig.custom();
|
||||
if (properties.getConnectionRequestTimeout() != null) {
|
||||
@@ -139,6 +144,9 @@ public class GatewayHttpClientConfig {
|
||||
if (runOperationAiDiagnosis) {
|
||||
requestConfig.setResponseTimeout(Timeout.of(properties.getRunOperationAiDiagnosisResponseTimeout()));
|
||||
}
|
||||
if (realtimeIngestionAction) {
|
||||
requestConfig.setResponseTimeout(Timeout.of(properties.getRealtimeIngestionActionResponseTimeout()));
|
||||
}
|
||||
|
||||
HttpClientContext context = HttpClientContext.create();
|
||||
context.setRequestConfig(requestConfig.build());
|
||||
@@ -175,6 +183,11 @@ public class GatewayHttpClientConfig {
|
||||
&& RUN_OPERATION_AI_DIAGNOSIS_PATH.matcher(uri.getPath()).matches();
|
||||
}
|
||||
|
||||
static boolean isRealtimeIngestionAction(String method, URI uri) {
|
||||
return "POST".equalsIgnoreCase(method) && uri != null && uri.getPath() != null
|
||||
&& REALTIME_INGESTION_ACTION_PATH.matcher(uri.getPath()).matches();
|
||||
}
|
||||
|
||||
private static boolean isPositive(Duration value) {
|
||||
return value != null && !value.isZero() && !value.isNegative();
|
||||
}
|
||||
|
||||
+5
@@ -57,6 +57,11 @@ public class GatewayHttpClientProperties {
|
||||
*/
|
||||
private Duration unifiedIngestionSubmitResponseTimeout = Duration.ofSeconds(180);
|
||||
|
||||
/**
|
||||
* 实时采集操作包含源端校验与外部作业提交,须长于 DataOps 的 120 秒 Dubbo 调用时限。
|
||||
*/
|
||||
private Duration realtimeIngestionActionResponseTimeout = Duration.ofSeconds(135);
|
||||
|
||||
/**
|
||||
* 数据画像创建及数字ID重试等待Governance同步执行完成的超时时间
|
||||
*/
|
||||
|
||||
@@ -30,12 +30,31 @@ class GatewayHttpClientConfigTest {
|
||||
assertThat(properties.getDataSourceConnectionTestResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getUnifiedIngestionDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
|
||||
assertThat(properties.getUnifiedIngestionSubmitResponseTimeout()).isEqualTo(Duration.ofSeconds(180));
|
||||
assertThat(properties.getRealtimeIngestionActionResponseTimeout()).isEqualTo(Duration.ofSeconds(135));
|
||||
assertThat(properties.getDataProfileExecutionResponseTimeout()).isEqualTo(Duration.ofSeconds(120));
|
||||
assertThat(properties.getMetadataCatalogAiDraftResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getStandardAdoptionAiMatchResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
assertThat(properties.getRunOperationAiDiagnosisResponseTimeout()).isEqualTo(Duration.ofSeconds(75));
|
||||
}
|
||||
|
||||
@Test
|
||||
void realtimeActionsHaveBoundedLongTimeoutWithoutChangingOtherRoutes() {
|
||||
for (String action : List.of("CHECK", "START", "REFRESH", "STOP", "RESUME", "ARCHIVE", "DELETE", "RECREATE")) {
|
||||
URI uri = URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/" + action);
|
||||
HttpClientContext context = GatewayHttpClientConfig.createRequestContext("POST", uri, properties);
|
||||
assertThat(context.getRequestConfig().getResponseTimeout().toDuration()).isEqualTo(Duration.ofSeconds(135));
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("GET", uri, properties)).isNull();
|
||||
}
|
||||
for (String path : List.of("/api/dataops/v1/realtime-ingestions/0/START",
|
||||
"/api/dataops/v1/realtime-ingestions/19/START/", "/api/dataops/v1/realtime-ingestions/19/start",
|
||||
"/api/dataops/v1/realtime-ingestions/19/START-extra")) {
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("POST", URI.create("http://aixun-dataops" + path), properties)).isNull();
|
||||
}
|
||||
properties.setRealtimeIngestionActionResponseTimeout(Duration.ZERO);
|
||||
assertThat(GatewayHttpClientConfig.createRequestContext("POST",
|
||||
URI.create("http://aixun-dataops/api/dataops/v1/realtime-ingestions/19/START"), properties)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createsBoundedLongTimeoutOnlyForExactRunOperationAiDiagnosisPost() {
|
||||
for (String source : List.of("SCHEDULING", "BATCH_INGESTION", "FILE_INGESTION", "M2_GOLDEN")) {
|
||||
|
||||
+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}")
|
||||
|
||||
+32
-7
@@ -75,6 +75,14 @@ public class UnifiedIngestionService {
|
||||
}
|
||||
|
||||
public SourcePage sources(String keyword) {
|
||||
return sources(keyword, false);
|
||||
}
|
||||
|
||||
public SourcePage realtimeSources(String keyword) {
|
||||
return sources(keyword, true);
|
||||
}
|
||||
|
||||
private SourcePage sources(String keyword, boolean realtime) {
|
||||
BatchActor actor = actors.current();
|
||||
var result = sources.sources(actor.actorId(), actor.orgScopeId(), List.of(), keyword, 200);
|
||||
if (result == null || !"AVAILABLE".equals(result.status()) || result.entries() == null)
|
||||
@@ -86,8 +94,12 @@ public class UnifiedIngestionService {
|
||||
&& Set.of("ORACLE", "DAMENG", "KINGBASE").contains(item.type().toUpperCase(java.util.Locale.ROOT));
|
||||
boolean available = mysql && item.previewEligible() || (sqlServer || pilot) && item.credentialConfigured()
|
||||
&& "SUCCEEDED".equals(item.status()) && item.databaseName() != null && !item.databaseName().isBlank();
|
||||
if (realtime) available = Set.of("MYSQL","SQLSERVER","ORACLE","DAMENG","KINGBASE").contains(item.type())
|
||||
&& item.credentialConfigured() && "SUCCEEDED".equals(item.status())
|
||||
&& item.databaseName() != null && !item.databaseName().isBlank();
|
||||
String reason = mysql ? item.previewReason() : sqlServer ? "请先配置数据库凭据并通过连接测试"
|
||||
: "该数据源类型暂不可用于数据采集";
|
||||
if (realtime) reason = "请在数据源管理中配置凭据并通过连接测试";
|
||||
return new Source(item.id(), item.name(), item.type(), item.status(), item.databaseName(), available,
|
||||
available ? null : reason, item.version());
|
||||
}).toList();
|
||||
@@ -163,7 +175,7 @@ public class UnifiedIngestionService {
|
||||
throw BatchIngestionException.validation("请选择Hive或Doris目标");
|
||||
var page = storage.page(null, type, true, 1, 100);
|
||||
List<Target> rows = page.getRows().stream().map(resource -> {
|
||||
var detail = storage.detail(resource.resourceId());
|
||||
var detail = storage.selectionDetail(resource.resourceId());
|
||||
List<TargetDatabase> databases = detail.spaces().stream().filter(space -> space.enabled())
|
||||
.map(space -> new TargetDatabase(space.spaceId(), space.name(), space.externalObjectId(), space.version()))
|
||||
.toList();
|
||||
@@ -322,16 +334,27 @@ public class UnifiedIngestionService {
|
||||
matchCommandTarget(verified, request, item, selected);
|
||||
collections.advance(command, "TARGET_CONFIRMED", next, null, null, null);
|
||||
return;
|
||||
} catch (TableFileErrors.Reference missing) {
|
||||
} catch (TableFileErrors.MissingTarget missing) {
|
||||
if (!item.createTarget()) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_TARGET_DIRECTORY",
|
||||
"目标目录暂不可确认,请核验目标表与字段结构", missing);
|
||||
"目标表不存在,请开启自动建表后重新提交", missing);
|
||||
}
|
||||
} catch (TableFileErrors.Reference unavailable) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_TARGET_DIRECTORY",
|
||||
"目标表暂不可确认,请核验连接、权限与目标表结构", unavailable);
|
||||
}
|
||||
var ddl = commandDdl(request, item, next);
|
||||
var prepared = new CommandContext(selected, current.tableComment(), accessVersion, context.database(), layer, ddl);
|
||||
tables.reserveCommandCreate(verified, key + "-table", ddl,
|
||||
id -> collections.advance(command, "TARGET_RESERVED", prepared, null, null, id));
|
||||
try {
|
||||
tables.reserveCommandCreate(verified, key + "-table", ddl,
|
||||
id -> collections.advance(command, "TARGET_RESERVED", prepared, null, null, id));
|
||||
} catch (TableFileErrors.TargetAppeared appeared) {
|
||||
matchCommandTarget(verified, request, item, selected);
|
||||
collections.advance(command, "TARGET_CONFIRMED", next, null, null, null);
|
||||
} catch (TableFileErrors.Conflict | TableFileErrors.Reference failure) {
|
||||
throw new UnifiedIngestionCommandStageException("INGESTION_TARGET_CREATE_CONFLICT",
|
||||
failure.getMessage(), failure);
|
||||
}
|
||||
}
|
||||
case "TARGET_RESERVED" -> {
|
||||
if (command.ddlId() == null || context.ddl() == null) throw BatchIngestionException.conflict("原建表关联缺失");
|
||||
@@ -376,6 +399,8 @@ public class UnifiedIngestionService {
|
||||
var target = tables.targetDirectory(verified, request.targetResourceId(), request.targetSpaceId(),
|
||||
EngineType.valueOf(request.targetType().name()), item.targetTable(), null, 1, 20);
|
||||
BatchTargetWizardService.matchColumns(selected.sourceColumns(), target, targetEngine(request.targetType()));
|
||||
tables.synchronizeCommandTarget(verified, request.targetResourceId(), request.targetSpaceId(),
|
||||
EngineType.valueOf(request.targetType().name()), item.targetTable(), target);
|
||||
}
|
||||
|
||||
static CreateCommand commandDdl(SubmitRequest request, SubmitItem item, CommandContext context) {
|
||||
@@ -418,7 +443,7 @@ public class UnifiedIngestionService {
|
||||
var operation = tables.commandCreateResult(verified, key + "-table", command.ddlId(), context.ddl());
|
||||
if (operation == null)
|
||||
throw BatchIngestionException.conflict("原建表请求不可验证");
|
||||
if ("REJECTED".equals(operation.state())) {
|
||||
if ("REJECTED".equals(operation.state()) && !"EXTERNAL_TABLE_ALREADY_EXISTS".equals(operation.errorCode())) {
|
||||
collections.rejectDdl(command, operation.errorCode(), operation.errorSummary());
|
||||
return;
|
||||
}
|
||||
@@ -488,7 +513,7 @@ public class UnifiedIngestionService {
|
||||
var existing = tables.targetDirectory(resourceId, spaceId, engine, targetTable, null, 1, 20);
|
||||
BatchTargetWizardService.matchColumns(selected.sourceColumns(), existing, targetEngine);
|
||||
return new TargetPreparation(existing, null, null, null, false);
|
||||
} catch (TableFileErrors.Reference exception) {
|
||||
} catch (TableFileErrors.MissingTarget exception) {
|
||||
if (!createTarget) throw exception;
|
||||
}
|
||||
// Only actual creation needs comment authority. Existing compatible tables above remain untouched.
|
||||
|
||||
+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())
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/dataops/v1/api-ingestions")
|
||||
public class ApiPollController {
|
||||
private final ApiPollService service;
|
||||
private final ApiPollProfileService profiles;
|
||||
private final ApiPreviewService previews;
|
||||
|
||||
@Log(title="API采集样本预览", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission({"aixun:dataops:file-ingestion:view", "aixun:dataops:file-ingestion:create"})
|
||||
@PostMapping("/preview")
|
||||
public R<cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPreviewResult> preview(
|
||||
@RequestBody ApiPreviewService.Command command) { return R.ok(previews.preview(command)); }
|
||||
|
||||
public record EnabledCommand(boolean enabled) { }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId) { return R.ok(profiles.view(intakeId)); }
|
||||
|
||||
@Log(title="API采集请求配置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/profile")
|
||||
public R<ApiPollProfileService.View> profile(@PathVariable long intakeId,
|
||||
@RequestBody ApiPollProfileService.Command command) {
|
||||
return R.ok(profiles.save(intakeId, command));
|
||||
}
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> state(@PathVariable long intakeId) { return R.ok(service.state(intakeId)); }
|
||||
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:view")
|
||||
@GetMapping("/{intakeId}/poll/runs")
|
||||
public R<List<ApiPollService.PollRun>> runs(@PathVariable long intakeId) { return R.ok(service.runs(intakeId)); }
|
||||
|
||||
@Log(title="API采集轮询设置", businessType=BusinessType.UPDATE, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:update")
|
||||
@PutMapping("/{intakeId}/poll")
|
||||
public R<ApiPollService.PollState> enabled(@PathVariable long intakeId, @RequestBody EnabledCommand command) {
|
||||
return R.ok(service.setEnabled(intakeId, command.enabled()));
|
||||
}
|
||||
|
||||
@Log(title="API采集立即运行", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
|
||||
@SaCheckPermission("aixun:dataops:file-ingestion:submit")
|
||||
@PostMapping("/{intakeId}/poll/run")
|
||||
public R<ApiPollService.PollRun> run(@PathVariable long intakeId) { return R.ok(service.runNow(intakeId)); }
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.ApiPollProfile;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollProfileService {
|
||||
private static final Pattern HEADER = Pattern.compile("[A-Za-z][A-Za-z0-9-]{0,63}");
|
||||
private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_]{0,63}");
|
||||
private static final Pattern PATH = Pattern.compile("\\$(?:\\.[A-Za-z_][A-Za-z0-9_-]*){0,8}");
|
||||
private static final Set<String> AUTH = Set.of("STATIC_BEARER", "CLIENT_CREDENTIALS", "PASSWORD_TOKEN", "API_KEY_HEADER", "SIGN_ONLY");
|
||||
private static final Set<String> SIGN = Set.of("NONE", "HMAC_SHA256", "RSA_SHA256");
|
||||
private final JdbcTemplate jdbc;
|
||||
private final JsonMapper json;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final FileManagedCredentialGateway credentials;
|
||||
|
||||
public record Command(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
char[] signingKey) {
|
||||
@Override public String toString() { return "ApiPollProfileCommand[signingKey=REDACTED]"; }
|
||||
}
|
||||
|
||||
public record View(String authKind, String tokenEndpoint, String tokenFormat, String clientId,
|
||||
String tokenClientField, String tokenSecretField, String tokenCredentialStyle,
|
||||
String tokenPath, String expiresPath, String requestMethod,
|
||||
Map<String, String> headers, Map<String, String> queryParameters,
|
||||
String requestBody, Integer pageSize, Integer lookbackSeconds,
|
||||
String successPath, String successValue, String signatureKind,
|
||||
String signatureTemplate, String signaturePlacement, String signatureHeader, String signatureEncoding,
|
||||
boolean signingKeyConfigured) { }
|
||||
|
||||
public View view(long intakeId) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
return view(profile(actor, intakeId));
|
||||
}
|
||||
|
||||
ApiPollProfile profile(FileIngestionActor actor, long intakeId) {
|
||||
requireApi(actor, intakeId);
|
||||
var rows = jdbc.query("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=? AND org_scope_id=?",
|
||||
(rs, index) -> rs.getString(1), intakeId, actor.orgScopeId());
|
||||
if (rows.isEmpty()) return null;
|
||||
try { return json.readValue(rows.getFirst(), ApiPollProfile.class); }
|
||||
catch (Exception failure) { throw FileIngestionException.validation("API高级配置无效"); }
|
||||
}
|
||||
|
||||
public View save(long intakeId, Command command) {
|
||||
var actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
if (command == null) throw FileIngestionException.validation("API高级配置不能为空");
|
||||
ApiPollProfile current = profile(actor, intakeId);
|
||||
String newRef = null;
|
||||
char[] supplied = command.signingKey();
|
||||
try {
|
||||
validate(command);
|
||||
String kind = command.signatureKind() == null ? "NONE" : command.signatureKind();
|
||||
String signingRef = "NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind())
|
||||
? null : current == null ? null : current.signingSecretRef();
|
||||
if (supplied != null && supplied.length > 0) {
|
||||
if ("NONE".equals(kind) || "SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("此认证方式无需单独提供签名密钥");
|
||||
newRef = credentials.provision(supplied);
|
||||
signingRef = newRef;
|
||||
}
|
||||
if (!"NONE".equals(kind) && signingRef == null && !"SIGN_ONLY".equals(command.authKind()))
|
||||
throw FileIngestionException.validation("请输入签名密钥");
|
||||
var profile = new ApiPollProfile(command.authKind(), command.tokenEndpoint(), command.tokenFormat(),
|
||||
command.clientId(), command.tokenClientField(), command.tokenSecretField(),
|
||||
command.tokenCredentialStyle(), command.tokenPath(), command.expiresPath(), command.requestMethod(),
|
||||
command.headers() == null ? Map.of() : Map.copyOf(command.headers()),
|
||||
command.queryParameters() == null ? Map.of() : Map.copyOf(command.queryParameters()),
|
||||
command.requestBody(), command.pageSize(), command.lookbackSeconds(), command.successPath(),
|
||||
command.successValue(), kind, command.signatureTemplate(), command.signaturePlacement(), command.signatureHeader(),
|
||||
command.signatureEncoding(), signingRef);
|
||||
String encoded = json.writeValueAsString(profile);
|
||||
int updated = jdbc.update("UPDATE ing_api_poll_profile SET profile_json=?,updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?",
|
||||
encoded, intakeId, actor.orgScopeId());
|
||||
if (updated == 0) jdbc.update("INSERT INTO ing_api_poll_profile(intake_id,org_scope_id,profile_json) VALUES (?,?,?)",
|
||||
intakeId, actor.orgScopeId(), encoded);
|
||||
newRef = null;
|
||||
if (current != null && current.signingSecretRef() != null &&
|
||||
!current.signingSecretRef().equals(signingRef)) safeRevoke(current.signingSecretRef());
|
||||
return view(profile);
|
||||
} catch (RuntimeException failure) {
|
||||
if (newRef != null) safeRevoke(newRef);
|
||||
throw failure;
|
||||
} finally {
|
||||
if (supplied != null) Arrays.fill(supplied, '\0');
|
||||
}
|
||||
}
|
||||
|
||||
private void requireApi(FileIngestionActor actor, long intakeId) {
|
||||
if (repository.config(actor, intakeId).sourceType() != FileSourceType.API_SAAS)
|
||||
throw FileIngestionException.validation("仅API采集可配置请求协议");
|
||||
}
|
||||
|
||||
private static View view(ApiPollProfile value) {
|
||||
if (value == null) return new View("STATIC_BEARER", null, "FORM", null,
|
||||
"client_id", "client_secret", "BODY", "$.access_token",
|
||||
"$.expires_in", "GET", Map.of(), Map.of(), null, 100, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", false);
|
||||
return new View(value.authKind(), value.tokenEndpoint(), value.tokenFormat(), value.clientId(),
|
||||
value.tokenClientField(), value.tokenSecretField(), value.tokenCredentialStyle(),
|
||||
value.tokenPath(), value.expiresPath(), value.requestMethod(), value.headers(),
|
||||
value.queryParameters(), value.requestBody(), value.pageSize(), value.lookbackSeconds(),
|
||||
value.successPath(), value.successValue(), value.signatureKind(), value.signatureTemplate(),
|
||||
value.signaturePlacement(), value.signatureHeader(), value.signatureEncoding(),
|
||||
value.signingSecretRef() != null || "SIGN_ONLY".equals(value.authKind()));
|
||||
}
|
||||
|
||||
static ApiPollProfile transientProfile(Command c, String signingRef) {
|
||||
validate(c);
|
||||
if (!"NONE".equals(c.signatureKind()) && !"SIGN_ONLY".equals(c.authKind()) && signingRef == null)
|
||||
throw FileIngestionException.validation("请输入签名密钥");
|
||||
return new ApiPollProfile(c.authKind(), c.tokenEndpoint(), c.tokenFormat(), c.clientId(),
|
||||
c.tokenClientField(), c.tokenSecretField(), c.tokenCredentialStyle(), c.tokenPath(), c.expiresPath(),
|
||||
c.requestMethod(), c.headers() == null ? Map.of() : Map.copyOf(c.headers()),
|
||||
c.queryParameters() == null ? Map.of() : Map.copyOf(c.queryParameters()), c.requestBody(),
|
||||
c.pageSize(), c.lookbackSeconds(), c.successPath(), c.successValue(), c.signatureKind(),
|
||||
c.signatureTemplate(), c.signaturePlacement(), c.signatureHeader(), c.signatureEncoding(), signingRef);
|
||||
}
|
||||
|
||||
static void validate(Command c) {
|
||||
if (!AUTH.contains(c.authKind()) || !Set.of("GET", "POST").contains(c.requestMethod()) ||
|
||||
c.pageSize() == null || c.pageSize() < 1 || c.pageSize() > 1000 ||
|
||||
c.lookbackSeconds() == null || c.lookbackSeconds() < 0 || c.lookbackSeconds() > 86400 ||
|
||||
!SIGN.contains(c.signatureKind() == null ? "NONE" : c.signatureKind()))
|
||||
throw FileIngestionException.validation("API请求配置无效");
|
||||
if ("SIGN_ONLY".equals(c.authKind()) && (c.signatureKind() == null || "NONE".equals(c.signatureKind())))
|
||||
throw FileIngestionException.validation("仅签名认证必须开启请求签名");
|
||||
if (!"STATIC_BEARER".equals(c.authKind()) && !"API_KEY_HEADER".equals(c.authKind()) &&
|
||||
!"SIGN_ONLY".equals(c.authKind())) {
|
||||
try {
|
||||
URI uri = URI.create(c.tokenEndpoint());
|
||||
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null ||
|
||||
uri.getRawQuery() != null || uri.getFragment() != null) throw new IllegalArgumentException();
|
||||
} catch (RuntimeException failure) { throw FileIngestionException.validation("认证接口必须是无密钥参数的HTTPS地址"); }
|
||||
if (!Set.of("FORM", "JSON").contains(c.tokenFormat()) ||
|
||||
c.clientId() == null || c.clientId().isBlank() || c.clientId().length() > 256 ||
|
||||
!FIELD.matcher(c.tokenClientField() == null ? "" : c.tokenClientField()).matches() ||
|
||||
!FIELD.matcher(c.tokenSecretField() == null ? "" : c.tokenSecretField()).matches() ||
|
||||
!Set.of("BODY", "BASIC").contains(c.tokenCredentialStyle()) ||
|
||||
("PASSWORD_TOKEN".equals(c.authKind()) && "BASIC".equals(c.tokenCredentialStyle())) ||
|
||||
!path(c.tokenPath()) || (c.expiresPath() != null && !path(c.expiresPath())))
|
||||
throw FileIngestionException.validation("动态Token配置无效");
|
||||
}
|
||||
checkMap(c.headers(), true);
|
||||
checkMap(c.queryParameters(), false);
|
||||
if (c.requestBody() != null && (c.requestBody().length() > 8192 ||
|
||||
(!"POST".equals(c.requestMethod()) && !c.requestBody().isBlank())))
|
||||
throw FileIngestionException.validation("请求体配置无效");
|
||||
if (c.successPath() != null && (!path(c.successPath()) || c.successValue() == null ||
|
||||
c.successValue().length() > 128)) throw FileIngestionException.validation("业务状态路径无效");
|
||||
if (!"NONE".equals(c.signatureKind())) {
|
||||
if (c.signatureTemplate() == null || c.signatureTemplate().isBlank() ||
|
||||
c.signatureTemplate().length() > 2048 || !c.signatureTemplate().matches("(?s)[A-Za-z0-9_{}$./?&=+%\\n\\r :|-]*") ||
|
||||
!Set.of("HEADER", "QUERY").contains(c.signaturePlacement()) ||
|
||||
!("HEADER".equals(c.signaturePlacement()) ? HEADER : FIELD)
|
||||
.matcher(c.signatureHeader() == null ? "" : c.signatureHeader()).matches() ||
|
||||
Set.of("authorization", "cookie", "host").contains(c.signatureHeader().toLowerCase()) ||
|
||||
!Set.of("BASE64", "HEX").contains(c.signatureEncoding()))
|
||||
throw FileIngestionException.validation("签名配置无效");
|
||||
}
|
||||
}
|
||||
|
||||
private static void checkMap(Map<String, String> values, boolean headers) {
|
||||
if (values == null) return;
|
||||
if (values.size() > 20) throw FileIngestionException.validation("请求参数过多");
|
||||
for (var item : values.entrySet()) {
|
||||
String name = item.getKey(), value = item.getValue();
|
||||
if (name == null || value == null || value.length() > 1024 || value.contains("\r") || value.contains("\n") ||
|
||||
!(headers ? HEADER : FIELD).matcher(name).matches() ||
|
||||
(headers && Set.of("authorization", "cookie", "host", "content-length", "x-sign", "x-timestamp", "x-nonce", "x-api-key")
|
||||
.contains(name.toLowerCase())) ||
|
||||
(!headers && Set.of("token", "access_token", "secret", "password", "api_key").contains(name.toLowerCase())))
|
||||
throw FileIngestionException.validation("请求参数包含不允许的字段");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean path(String value) { return value != null && PATH.matcher(value).matches(); }
|
||||
private void safeRevoke(String ref) { try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* retained safely */ } }
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/** API-only polling ownership, leases and committed watermarks. */
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPollService {
|
||||
@Autowired
|
||||
private cn.aixunkeji.common.core.enums.PlatformDatabaseDialect databaseDialect = cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG;
|
||||
private final JdbcTemplate jdbc;
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final IntegrationFileIngestionGateway integration;
|
||||
@Autowired(required = false)
|
||||
private ApiPollProfileService profiles;
|
||||
|
||||
public record PollState(long intakeId, boolean enabled, String watermark, LocalDateTime nextDueAt,
|
||||
String lastStatus, String lastErrorCode, int lastWrittenRows,
|
||||
LocalDateTime lastRunAt) { }
|
||||
public record PollRun(long runId, String triggerType, String status, int writtenRows,
|
||||
String errorCode, String watermarkBefore, String watermarkAfter,
|
||||
LocalDateTime startedAt, LocalDateTime completedAt) { }
|
||||
|
||||
public PollState state(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
List<PollState> rows = jdbc.query("""
|
||||
SELECT intake_id,enabled,watermark,next_due_at,last_status,last_error_code,
|
||||
last_written_rows,last_run_at FROM ing_api_poll_state
|
||||
WHERE intake_id=? AND org_scope_id=?
|
||||
""", (rs, index) -> new PollState(rs.getLong(1), rs.getInt(2) == 1, rs.getString(3),
|
||||
time(rs.getTimestamp(4)), rs.getString(5), rs.getString(6), rs.getInt(7),
|
||||
time(rs.getTimestamp(8))), intakeId, actor.orgScopeId());
|
||||
return rows.isEmpty() ? new PollState(intakeId, false, null, null, "NEVER", null, 0, null) : rows.getFirst();
|
||||
}
|
||||
|
||||
public List<PollRun> runs(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
requireApi(actor, intakeId);
|
||||
return jdbc.query("""
|
||||
SELECT run_id,trigger_type,run_status,written_rows,error_code,watermark_before,
|
||||
watermark_after,started_at,completed_at FROM ing_api_poll_run
|
||||
WHERE intake_id=? AND org_scope_id=? ORDER BY started_at DESC
|
||||
""" + databaseDialect.sql(" FETCH FIRST 50 ROWS ONLY", " LIMIT 50"), (rs, index) -> new PollRun(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getInt(4),
|
||||
rs.getString(5), rs.getString(6), rs.getString(7), time(rs.getTimestamp(8)),
|
||||
time(rs.getTimestamp(9))), intakeId, actor.orgScopeId());
|
||||
}
|
||||
|
||||
public PollState setEnabled(long intakeId, boolean enabled) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (enabled && !supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled,next_due_at)
|
||||
SELECT ?,?,?,?,CURRENT_TIMESTAMP FROM DUAL WHERE NOT EXISTS
|
||||
(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), enabled ? 1 : 0, intakeId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET enabled=?, actor_id=?,
|
||||
next_due_at=CASE WHEN ?=1 THEN CURRENT_TIMESTAMP ELSE next_due_at END,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
""", enabled ? 1 : 0, actor.actorId(), enabled ? 1 : 0, intakeId, actor.orgScopeId());
|
||||
return state(intakeId);
|
||||
}
|
||||
|
||||
public PollRun runNow(long intakeId) {
|
||||
FileIngestionActor actor = actors.current();
|
||||
FileIngestionPolicy.Config config = requireApi(actor, intakeId);
|
||||
if (!supported(config)) throw FileIngestionException.validation("当前API轮询配置不受支持");
|
||||
ensureState(actor, intakeId);
|
||||
return execute(actor, intakeId, "MANUAL", config);
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${datagov.api-poll.scan-delay-ms:15000}")
|
||||
public void scan() {
|
||||
List<long[]> due;
|
||||
try {
|
||||
due = jdbc.query("""
|
||||
SELECT intake_id,org_scope_id,actor_id FROM ing_api_poll_state
|
||||
WHERE enabled=1 AND next_due_at<=CURRENT_TIMESTAMP
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
ORDER BY next_due_at
|
||||
""" + databaseDialect.sql(" FETCH FIRST 10 ROWS ONLY", " LIMIT 10"), (rs, index) -> new long[]{rs.getLong(1), rs.getLong(2), rs.getLong(3)});
|
||||
} catch (RuntimeException unavailable) { return; }
|
||||
for (long[] item : due) {
|
||||
try {
|
||||
FileIngestionActor actor = new FileIngestionActor(item[2], item[1]);
|
||||
FileIngestionPolicy.Config config = requireApi(actor, item[0]);
|
||||
if (supported(config)) execute(actor, item[0], "SCHEDULED", config);
|
||||
else disableInvalid(item[0], item[1]);
|
||||
} catch (RuntimeException failure) {
|
||||
try { disableInvalid(item[0], item[1]); } catch (RuntimeException unavailable) { /* retry on next scan */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PollRun execute(FileIngestionActor actor, long intakeId, String trigger,
|
||||
FileIngestionPolicy.Config config) {
|
||||
String lease = UUID.randomUUID().toString();
|
||||
int claimed = jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET lease_id=?, lease_until=%s,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?
|
||||
AND (lease_until IS NULL OR lease_until<CURRENT_TIMESTAMP)
|
||||
""".formatted(databaseDialect.sql("DATEADD(HOUR, 2, CURRENT_TIMESTAMP)", "DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 2 HOUR)")) + ("SCHEDULED".equals(trigger) ? " AND enabled=1" : ""), lease, intakeId, actor.orgScopeId());
|
||||
if (claimed != 1) throw FileIngestionException.conflict("该API采集任务正在运行");
|
||||
long runId = IdGeneratorUtil.nextLongId();
|
||||
String before = jdbc.queryForObject("SELECT watermark FROM ing_api_poll_state WHERE intake_id=?",
|
||||
String.class, intakeId);
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_run(run_id,intake_id,org_scope_id,actor_id,trigger_type,
|
||||
started_at,run_status,watermark_before)
|
||||
VALUES(?,?,?,?,?,CURRENT_TIMESTAMP,'RUNNING',?)
|
||||
""", runId, intakeId, actor.orgScopeId(), actor.actorId(), trigger, before);
|
||||
DataCollectionIntegrationService.ApiPollResult result;
|
||||
try {
|
||||
result = integration.pollApi(actor, intakeId, config, before,
|
||||
profiles == null ? null : profiles.profile(actor, intakeId));
|
||||
} catch (RuntimeException | LinkageError unavailable) {
|
||||
result = new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_GATEWAY_UNKNOWN");
|
||||
}
|
||||
boolean success = result != null && "SUCCEEDED".equals(result.status());
|
||||
String error = success ? null : result == null ? "API_POLL_RESPONSE_MISSING" :
|
||||
FileIngestionPolicy.safeErrorCode(result.errorCode(), "API_POLL_UNKNOWN");
|
||||
String after = success ? result.watermark() : before;
|
||||
int count = success ? Math.max(0, result.writtenRows()) : 0;
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_run SET completed_at=CURRENT_TIMESTAMP,run_status=?,written_rows=?,
|
||||
error_code=?,watermark_after=? WHERE run_id=?
|
||||
""", success ? "SUCCEEDED" : "UNKNOWN", count, error, after, runId);
|
||||
jdbc.update("""
|
||||
UPDATE ing_api_poll_state SET watermark=?,last_status=?,last_error_code=?,
|
||||
last_written_rows=?,last_run_at=CURRENT_TIMESTAMP,
|
||||
next_due_at=%s,lease_id=NULL,lease_until=NULL,
|
||||
updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=? AND lease_id=?
|
||||
""".formatted(databaseDialect.sql("DATEADD(SECOND, ?, CURRENT_TIMESTAMP)", "DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ? SECOND)")), after, success ? "SUCCEEDED" : "UNKNOWN", error, count,
|
||||
config.periodSeconds(), intakeId, actor.orgScopeId(), lease);
|
||||
return new PollRun(runId, trigger, success ? "SUCCEEDED" : "UNKNOWN", count, error,
|
||||
before, after, null, null);
|
||||
}
|
||||
|
||||
private void ensureState(FileIngestionActor actor, long intakeId) {
|
||||
jdbc.update("""
|
||||
INSERT INTO ing_api_poll_state(intake_id,org_scope_id,actor_id,enabled)
|
||||
SELECT ?,?,?,0 FROM DUAL WHERE NOT EXISTS(SELECT 1 FROM ing_api_poll_state WHERE intake_id=?)
|
||||
""", intakeId, actor.orgScopeId(), actor.actorId(), intakeId);
|
||||
}
|
||||
|
||||
private FileIngestionPolicy.Config requireApi(FileIngestionActor actor, long intakeId) {
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅API来源可执行轮询");
|
||||
return config;
|
||||
}
|
||||
|
||||
private static boolean supported(FileIngestionPolicy.Config config) {
|
||||
return config.apiConnector() != null && "GENERIC_HTTPS_JSON".equals(config.apiConnector().name()) &&
|
||||
config.authMode() != null && "BEARER".equals(config.authMode().name()) &&
|
||||
config.paginationMode() != null &&
|
||||
config.maxPages() != null && config.maxPages() >= 1 && config.maxPages() <= 100 &&
|
||||
config.periodSeconds() != null && config.periodSeconds() >= 60 &&
|
||||
config.secretRef() != null;
|
||||
}
|
||||
|
||||
private void disableInvalid(long intakeId, long orgId) {
|
||||
jdbc.update("UPDATE ing_api_poll_state SET enabled=0,last_status='UNKNOWN',last_error_code='API_POLL_CONFIG_INVALID',updated_at=CURRENT_TIMESTAMP WHERE intake_id=? AND org_scope_id=?", intakeId, orgId);
|
||||
}
|
||||
|
||||
private static LocalDateTime time(Timestamp value) { return value == null ? null : value.toLocalDateTime(); }
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ApiPreviewService {
|
||||
private final FileIngestionActorProvider actors;
|
||||
private final FileIngestionRepository repository;
|
||||
private final FileManagedCredentialGateway credentials;
|
||||
private final ApiPollProfileService profiles;
|
||||
private final IntegrationFileIngestionGateway integration;
|
||||
|
||||
public record Command(Long intakeId, String endpoint, char[] credential, String paginationMode,
|
||||
String paginationField, String responsePath, ApiPollProfileService.Command profile) {
|
||||
@Override public String toString() { return "ApiPreviewCommand[REDACTED]"; }
|
||||
}
|
||||
|
||||
public ApiPreviewResult preview(Command command) {
|
||||
if (command == null || command.profile() == null) throw FileIngestionException.validation("请完善接口请求配置");
|
||||
var actor = actors.current();
|
||||
List<String> temporary = new ArrayList<>();
|
||||
try {
|
||||
ApiPollProfileService.validate(command.profile());
|
||||
String authRef = null, signingRef = null, endpoint = command.endpoint();
|
||||
if (command.intakeId() != null) {
|
||||
var config = repository.config(actor, command.intakeId());
|
||||
if (config.sourceType() != FileSourceType.API_SAAS) throw FileIngestionException.validation("仅 API 采集支持接口预览");
|
||||
authRef = config.secretRef();
|
||||
if (endpoint == null || endpoint.isBlank()) endpoint = config.endpoint();
|
||||
var old = profiles.profile(actor, command.intakeId());
|
||||
signingRef = old == null ? null : old.signingSecretRef();
|
||||
}
|
||||
if (command.credential() != null && command.credential().length > 0) {
|
||||
authRef = credentials.provision(command.credential()); temporary.add(authRef);
|
||||
}
|
||||
if (authRef == null) throw FileIngestionException.validation("请填写接口凭据");
|
||||
if (command.profile().signingKey() != null && command.profile().signingKey().length > 0) {
|
||||
signingRef = credentials.provision(command.profile().signingKey()); temporary.add(signingRef);
|
||||
}
|
||||
var profile = ApiPollProfileService.transientProfile(command.profile(), signingRef);
|
||||
try {
|
||||
return integration.previewApi(new ApiPreviewRequest(actor.actorId(), actor.orgScopeId(), endpoint,
|
||||
authRef, command.paginationMode(), command.paginationField(), command.responsePath(), profile));
|
||||
} catch (RuntimeException unavailable) {
|
||||
throw FileIngestionException.validation("接口预览暂不可用,请检查连接或稍后重试");
|
||||
}
|
||||
} finally {
|
||||
if (command.credential() != null) Arrays.fill(command.credential(), '\0');
|
||||
if (command.profile().signingKey() != null) Arrays.fill(command.profile().signingKey(), '\0');
|
||||
for (String ref : temporary) {
|
||||
try { credentials.revoke(ref); } catch (RuntimeException ignored) { /* Managed credential audit retains revocation outcome. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -259,6 +259,9 @@ public class FileIngestionService {
|
||||
throw FileIngestionException.conflict("仅草稿或就绪配置可执行能力校验");
|
||||
}
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
String code = FileIngestionPolicy.deferredAdapterCode(config);
|
||||
String summary = FileIngestionPolicy.deferredAdapterSummary(config);
|
||||
@@ -309,6 +312,9 @@ public class FileIngestionService {
|
||||
FileIngestionActor actor = actorProvider.current();
|
||||
String key = FileIngestionPolicy.requireIdempotencyKey(idempotencyKey);
|
||||
FileIngestionPolicy.Config config = repository.config(actor, intakeId);
|
||||
if (config.sourceType() == FileSourceType.API_SAAS) {
|
||||
throw FileIngestionException.conflict("API采集请使用专用轮询执行入口");
|
||||
}
|
||||
if (FileIngestionPolicy.requiresDeferredAdapter(config)) {
|
||||
repository.markCapability(actor, intakeId, AggregateCapabilityStatus.UNSUPPORTED);
|
||||
throw FileIngestionException.external(FileIngestionPolicy.deferredAdapterSummary(config));
|
||||
|
||||
+19
-2
@@ -16,6 +16,10 @@ import java.util.List;
|
||||
@Component
|
||||
public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
|
||||
DataCollectionIntegrationService.ApiPreviewResult previewApi(DataCollectionIntegrationService.ApiPreviewRequest request) {
|
||||
return integration.previewApi(request);
|
||||
}
|
||||
|
||||
@DubboReference(check = false, timeout = 190_000, retries = 0)
|
||||
private DataCollectionIntegrationService integration;
|
||||
|
||||
@@ -35,6 +39,19 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
public IntegrationFileIngestionGateway() {
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark) {
|
||||
return pollApi(actor, intakeId, config, watermark, null);
|
||||
}
|
||||
|
||||
DataCollectionIntegrationService.ApiPollResult pollApi(FileIngestionActor actor, long intakeId,
|
||||
FileIngestionPolicy.Config config, String watermark,
|
||||
DataCollectionIntegrationService.ApiPollProfile profile) {
|
||||
return integration.pollApi(new DataCollectionIntegrationService.ApiPollRequest(actor.actorId(),
|
||||
actor.orgScopeId(), intakeId, watermark, snapshot(config),
|
||||
targetProfile(actor.actorId(), actor.orgScopeId(), config), profile));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CapabilityResult checkCapability(CapabilityRequest request) {
|
||||
try {
|
||||
@@ -166,7 +183,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
"文件动作证据暂不可用");
|
||||
}
|
||||
|
||||
private DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
|
||||
long actorId, long orgScopeId, FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (storageReferences == null || config == null || config.targetStorageResourceId() == null ||
|
||||
@@ -180,7 +197,7 @@ public class IntegrationFileIngestionGateway implements FileIngestionGateway {
|
||||
resolved.serviceAccount(), resolved.secretRef(), resolved.tlsEnabled());
|
||||
}
|
||||
|
||||
private static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
static DataCollectionIntegrationService.FileExecutionSnapshot snapshot(
|
||||
FileIngestionPolicy.Config config
|
||||
) {
|
||||
if (config == null) return null;
|
||||
|
||||
+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
@@ -31,10 +31,10 @@ public class GoldenReconciliationMaintenance implements AutoCloseable {
|
||||
GoldenRunRepository repository,
|
||||
GoldenRunWorker worker,
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.core.domain.R;
|
||||
import cn.aixunkeji.common.log.annotation.Log;
|
||||
import cn.aixunkeji.common.log.enums.BusinessType;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/dataops/v1/realtime-ingestions")
|
||||
public class RealtimeController {
|
||||
private final RealtimeService service;
|
||||
public RealtimeController(RealtimeService service){this.service=service;}
|
||||
@org.springframework.beans.factory.annotation.Autowired
|
||||
private cn.aixunkeji.datagov.dataops.batchingestion.UnifiedIngestionService directory;
|
||||
@GetMapping("/source-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.SourcePage> sources(@RequestParam(required=false) String keyword){return R.ok(directory.realtimeSources(keyword));}
|
||||
@GetMapping("/relay-options") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<java.util.List<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.RelayOption>> relays(@RequestParam long sourceId){return R.ok(service.relays(sourceId));}
|
||||
@GetMapping("/source-defaults") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
public R<cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.SourceDefaults> sourceDefaults(@RequestParam long sourceId){return R.ok(service.sourceDefaults(sourceId));}
|
||||
@GetMapping @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.Page> list(@RequestParam(defaultValue="1") int pageNum,@RequestParam(defaultValue="20") int pageSize){return R.ok(service.list(pageNum,pageSize));}
|
||||
@GetMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:view")
|
||||
public R<RealtimeService.View> get(@PathVariable long id){return R.ok(service.get(id));}
|
||||
@PostMapping @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集创建",businessType=BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> create(@RequestBody Spec spec,@RequestHeader("Idempotency-Key") String key){return R.ok(service.create(spec,key));}
|
||||
@PostMapping("/{id}/{action}") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集操作",businessType=BusinessType.OTHER,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> action(@PathVariable long id,@PathVariable String action,@RequestBody RealtimeService.Action request){return R.ok(service.action(id,action,request));}
|
||||
@PutMapping("/{id}") @SaCheckPermission("aixun:dataops:realtime:manage")
|
||||
@Log(title="实时采集修改",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
|
||||
public R<RealtimeService.View> update(@PathVariable long id,@RequestBody RealtimeService.Update request){return R.ok(service.update(id,request));}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.core.exception.ServiceException;
|
||||
import cn.aixunkeji.common.json.utils.JsonUtils;
|
||||
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.*;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.StorageExecutionProfile;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
|
||||
import org.apache.dubbo.config.annotation.DubboReference;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
|
||||
@Service
|
||||
public class RealtimeService {
|
||||
private final JdbcTemplate db;
|
||||
private final TransactionTemplate tx;
|
||||
private final StorageTableFileReferenceDirectory targets;
|
||||
@DubboReference(check=false,timeout=120000,retries=0) private RealtimeCollectionService integration;
|
||||
public RealtimeService(JdbcTemplate db,TransactionTemplate tx,StorageTableFileReferenceDirectory targets) {
|
||||
this.db=db;this.tx=tx;this.targets=targets;
|
||||
}
|
||||
public record View(String id,Spec spec,String status,long version,long attempt,String externalId,
|
||||
String checkpointId,String summary,Long readRows,Long writeRows,LocalDateTime observedAt,
|
||||
List<Map<String,Object>> history) { }
|
||||
public record Page(List<View> rows,long total) { }
|
||||
public record Action(long version,String key) { }
|
||||
public record Update(long version,Spec spec) { }
|
||||
record Row(long id,long owner,long org,Spec spec,String status,long version,long attempt,String external,
|
||||
String fingerprint,String checkpoint,String summary,Long readRows,Long writeRows,
|
||||
LocalDateTime observedAt,LocalDateTime busyUntil) { }
|
||||
private long actor() {Long id=LoginHelper.getUserId();if(id==null)throw new ServiceException("请先登录");return id;}
|
||||
private long org() {Long id=LoginHelper.getDeptId();if(id==null)throw new ServiceException("缺少组织信息");return id;}
|
||||
private static void key(String k) {if(k==null||!k.matches("[A-Za-z0-9_-]{16,80}"))throw new ServiceException("请求标识无效");}
|
||||
public Page list(int page,int size) {
|
||||
if(page<1||size<1||size>100)throw new ServiceException("分页参数无效");
|
||||
long a=actor(),o=org();
|
||||
long total=db.queryForObject("SELECT COUNT(*) FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND status<>'ARCHIVED'",Long.class,o,a);
|
||||
var rows=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND status<>'ARCHIVED' ORDER BY updated_at DESC,id DESC LIMIT ? OFFSET ?",
|
||||
(rs,n)->map(rs),o,a,size,(long)(page-1)*size);
|
||||
return new Page(rows.stream().map(r->view(r,false)).toList(),total);
|
||||
}
|
||||
public View get(long id) {return view(require(id,false),true);}
|
||||
public List<RelayOption> relays(long sourceId){return integration.relays(actor(),org(),sourceId);}
|
||||
public SourceDefaults sourceDefaults(long sourceId){return integration.sourceDefaults(actor(),org(),sourceId);}
|
||||
private Row require(long id,boolean lock) {
|
||||
var rows=db.query("SELECT * FROM ing_realtime_task WHERE id=? AND org_id=? AND owner_id=?"+(lock?" FOR UPDATE":""),
|
||||
(rs,n)->map(rs),id,org(),actor());
|
||||
if(rows.size()!=1)throw new ServiceException("任务不存在或无权访问");return rows.getFirst();
|
||||
}
|
||||
public View create(Spec p,String key) {
|
||||
key(key); validate(p);
|
||||
return tx.execute(status->{
|
||||
var old=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND create_key=?",(rs,n)->map(rs),org(),actor(),key);
|
||||
if(!old.isEmpty()) {if(!old.getFirst().spec().equals(p))throw new ServiceException("请求标识已用于其他配置");return view(old.getFirst(),false);}
|
||||
long id=IdGeneratorUtil.nextLongId();
|
||||
// Resolve the owner-approved target before storing a public configuration.
|
||||
target(actor(),org(),p);
|
||||
try {db.update("INSERT INTO ing_realtime_task(id,owner_id,org_id,create_key,config_json,source_id,server_id,target_key,status,version,attempt,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?, 'DRAFT',0,0,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)",
|
||||
id,actor(),org(),key,JsonUtils.toJsonString(p),p.sourceId(),p.serverId(),p.targetResourceId()+":"+p.targetSpaceId()+":"+p.targetTable());}
|
||||
catch(org.springframework.dao.DuplicateKeyException ex){throw new ServiceException("同一源库的server-id或目标表已被实时任务占用,请检查已有任务");}
|
||||
return view(require(id,false),false);
|
||||
});
|
||||
}
|
||||
static void validate(Spec p) {
|
||||
if(p==null||p.name()==null||p.name().isBlank()||p.name().length()>100||p.sourceId()<1||p.sourceVersion()<0||
|
||||
p.targetResourceId()<1||p.targetSpaceId()<1||p.httpPort()<1||p.httpPort()>65535||p.serverId()<1||p.serverId()>4294967295L||
|
||||
p.checkpointSeconds()<10||p.checkpointSeconds()>3600||p.startupMode()==null||!Set.of("initial","latest").contains(p.startupMode()))
|
||||
throw new ServiceException("实时采集配置不完整或超出允许范围");
|
||||
if(p.sourceDatabase()==null||!p.sourceDatabase().matches("[A-Za-z_][A-Za-z0-9_.-]{0,127}"))
|
||||
throw new ServiceException("来源数据库或服务名格式无效");
|
||||
for(String v:Arrays.asList(p.sourceTable(),p.targetTable()))
|
||||
if(v==null||!v.matches("[A-Za-z_][A-Za-z0-9_]{0,63}"))throw new ServiceException("库表名称只支持字母、数字和下划线");
|
||||
for(String v:Arrays.asList(p.sourceSchema(),p.oracleDatabase(),p.oraclePdb()))
|
||||
if(v!=null&&!v.matches("[A-Za-z_][A-Za-z0-9_$#]{0,127}"))throw new ServiceException("架构、Oracle数据库或PDB名称格式无效");
|
||||
if(p.cdcChannel()!=null&&!p.cdcChannel().matches("[A-Za-z0-9_-]{1,64}"))throw new ServiceException("日志通道标识无效");
|
||||
if(p.oracleCdbService()!=null&&!p.oracleCdbService().matches("[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}"))
|
||||
throw new ServiceException("CDB根容器服务名格式无效");
|
||||
}
|
||||
public View update(long id,Update request) {
|
||||
if(request==null)throw new ServiceException("请求不能为空");validate(request.spec());
|
||||
return tx.execute(status->{
|
||||
var r=require(id,true);allowed(r,"CHECK");
|
||||
if(r.version()!=request.version() || r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))
|
||||
throw new ServiceException("任务已变化或正在处理,请刷新");
|
||||
var p=request.spec();target(r.owner(),r.org(),p);
|
||||
try {db.update("UPDATE ing_realtime_task SET config_json=?,source_id=?,server_id=?,target_key=?,fingerprint=NULL,status='DRAFT',summary=NULL,version=version+1,updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
JsonUtils.toJsonString(p),p.sourceId(),p.serverId(),p.targetResourceId()+":"+p.targetSpaceId()+":"+p.targetTable(),id);}
|
||||
catch(org.springframework.dao.DuplicateKeyException e){throw new ServiceException("server-id或目标表已被其他任务占用");}
|
||||
return view(require(id,false),false);
|
||||
});
|
||||
}
|
||||
public View action(long id,String action,Action request) {
|
||||
if(request==null)throw new ServiceException("请求不能为空");key(request.key());
|
||||
if(!Set.of("CHECK","START","RETRY","REFRESH","STOP","RESUME","ARCHIVE","DELETE","RECREATE").contains(action))throw new ServiceException("操作无效");
|
||||
Row prior=require(id,false);
|
||||
Row reserved=tx.execute(status->{
|
||||
Row r=require(id,true);
|
||||
var previous=db.queryForList("SELECT action FROM ing_realtime_event WHERE task_id=? AND request_key=?",id,request.key());
|
||||
if(!previous.isEmpty()) {
|
||||
if(!action.equals(previous.getFirst().get("ACTION"))&&!action.equals(previous.getFirst().get("action")))throw new ServiceException("请求标识已被其他操作使用");
|
||||
return null;
|
||||
}
|
||||
if(r.version()!=request.version())throw new ServiceException("任务版本已变化,请刷新");
|
||||
if(r.busyUntil()!=null&&r.busyUntil().isAfter(LocalDateTime.now()))throw new ServiceException("操作仍在处理中,请稍后刷新");
|
||||
allowed(r,action);
|
||||
// SeaTunnel 2.3.13 restores the same job ID; a new ID would start a new snapshot.
|
||||
long nextAttempt=r.attempt()+(Set.of("START","RETRY").contains(action)?1:0);
|
||||
String external=nextAttempt>0?RealtimeCollectionService.jobId(r.org(),r.id(),nextAttempt):null;
|
||||
String state=Set.of("START","RETRY","RESUME").contains(action)?"SUBMITTING":action.equals("STOP")?"STOPPING":r.status();
|
||||
db.update("UPDATE ing_realtime_task SET status=?,version=version+1,attempt=?,external_id=?,busy_until=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",state,nextAttempt,external,LocalDateTime.now().plusMinutes(3),id);
|
||||
db.update("INSERT INTO ing_realtime_event(id,task_id,request_key,action,status,created_at) VALUES(?,?,?,?, 'PENDING',CURRENT_TIMESTAMP)",IdGeneratorUtil.nextId(),id,request.key(),action);
|
||||
return require(id,false);
|
||||
});
|
||||
if(reserved==null) {
|
||||
if("RECREATE".equals(action)) {
|
||||
var replacement=db.query("SELECT * FROM ing_realtime_task WHERE org_id=? AND owner_id=? AND create_key=?",
|
||||
(rs,n)->map(rs),org(),actor(),request.key());
|
||||
if(!replacement.isEmpty())return view(replacement.getFirst(),true);
|
||||
}
|
||||
return get(id);
|
||||
}
|
||||
Row r=reserved;
|
||||
String state="UNKNOWN",summary="外部结果待确认,请刷新状态",fingerprint=r.fingerprint(),checkpoint=r.checkpoint();
|
||||
Long read=r.readRows(),written=r.writeRows(); long attempt=r.attempt(); String external=r.external();
|
||||
boolean invoked=false;
|
||||
try {
|
||||
if(action.equals("ARCHIVE") || action.equals("DELETE") && r.attempt()==0) {
|
||||
state="ARCHIVED";summary=action.equals("DELETE")?"任务已删除,历史操作记录保留":"草稿已归档";
|
||||
}
|
||||
else {
|
||||
var command=new Command(r.owner(),r.org(),r.id(),r.attempt(),r.spec(),
|
||||
Set.of("CHECK","START","RETRY","RESUME").contains(action)?target(r.owner(),r.org(),r.spec()):null,r.fingerprint(),
|
||||
Set.of("RESUME","RETRY").contains(action)?new RecoveryEvidence(prior.external(),prior.status(),prior.checkpoint()):null);
|
||||
if(action.equals("CHECK")) {
|
||||
var c=integration.prepare(command);state=c.ready()?"READY":"DRAFT";summary=c.summary();fingerprint=c.fingerprint();
|
||||
} else {
|
||||
invoked=true;
|
||||
var result=integration.execute(command,action.equals("DELETE")?"REFRESH":action,r.external(),action.equals("RESUME")?
|
||||
r.external():null);
|
||||
if(result==null || !Objects.equals(r.external(),result.externalId()))throw new IllegalStateException("CDC_RESULT_IDENTITY_MISMATCH");
|
||||
result=retainConfirmedTerminal(action,prior,result);
|
||||
state=result.status();summary=result.summary();checkpoint=result.checkpointId();read=result.readRows();written=result.writeRows();
|
||||
if("UNKNOWN".equals(state) && checkpoint==null && prior.checkpoint()!=null) {
|
||||
checkpoint=prior.checkpoint();read=prior.readRows();written=prior.writeRows();
|
||||
summary=(summary==null?"外部结果待确认":summary)+";保留上次已确认检查点,恢复时仍须验证原作业已结束和检查点有效";
|
||||
}
|
||||
if(action.equals("DELETE")) {
|
||||
if(terminal(state)) {state="ARCHIVED";summary="任务已删除,历史操作记录保留";}
|
||||
else summary="未删除:外部作业尚未确认结束,请同步状态后重试";
|
||||
}
|
||||
if("REJECTED".equals(state)) {
|
||||
attempt=prior.attempt();state=prior.status();external=prior.external();checkpoint=prior.checkpoint();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(RuntimeException ex) {
|
||||
if(action.equals("CHECK")) {state="DRAFT";fingerprint=null;summary="检查并准备未完成,请检查来源、目标授权和集成服务;如已建表会保留,请重新检查确认";}
|
||||
else if(!invoked && Set.of("START","RETRY","RESUME").contains(action)) {
|
||||
state=prior.status();attempt=prior.attempt();external=prior.external();checkpoint=prior.checkpoint();
|
||||
summary="来源或目标授权检查未通过,未提交外部作业";
|
||||
}
|
||||
}
|
||||
final String finalState=state, finalSummary=summary, finalFingerprint=fingerprint, finalCheckpoint=checkpoint,finalExternal=external;
|
||||
final Long finalRead=read, finalWritten=written;final long finalAttempt=attempt;
|
||||
return tx.execute(status->{
|
||||
boolean recreate="RECREATE".equals(action) && "ABSENT".equals(finalState);
|
||||
String storedState=recreate?"ARCHIVED":finalState;
|
||||
int changed=db.update("UPDATE ing_realtime_task SET status=?,summary=?,fingerprint=?,checkpoint_id=?,read_rows=?,write_rows=?,attempt=?,external_id=?,observed_at=CURRENT_TIMESTAMP,busy_until=NULL,version=version+1,updated_at=CURRENT_TIMESTAMP WHERE id=? AND version=?",
|
||||
storedState,finalSummary,finalFingerprint,finalCheckpoint,finalRead,finalWritten,finalAttempt,finalExternal,id,r.version());
|
||||
db.update("UPDATE ing_realtime_event SET status=?,summary=? WHERE task_id=? AND request_key=?",
|
||||
changed==1?storedState:"STALE",finalSummary,id,request.key());
|
||||
if(changed==1 && "ARCHIVED".equals(storedState)) db.update("UPDATE ing_realtime_task SET target_key=?,server_id=? WHERE id=?","archived:"+id,-id,id);
|
||||
if(changed==1 && recreate) return create(r.spec(),request.key());
|
||||
return get(id);
|
||||
});
|
||||
}
|
||||
static RealtimeCollectionService.Result retainConfirmedTerminal(String action,Row prior,RealtimeCollectionService.Result observed) {
|
||||
if("REFRESH".equals(action) && terminal(prior.status()) && "UNKNOWN".equals(observed.status()))
|
||||
return new RealtimeCollectionService.Result(prior.status(),observed.externalId(),
|
||||
"保留上次已确认的终态;本次引擎状态未能核实。检查点及计数为历史记录,恢复前仍须验证:"+
|
||||
(observed.summary()==null?"外部记录不可查询":observed.summary()),
|
||||
prior.checkpoint(),prior.readRows(),prior.writeRows());
|
||||
return observed;
|
||||
}
|
||||
static void allowed(Row r,String action) {
|
||||
if("ARCHIVED".equals(r.status()))throw new ServiceException("任务已删除或归档");
|
||||
boolean ok=switch(action) {
|
||||
case "CHECK","ARCHIVE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status());
|
||||
case "DELETE" -> r.attempt()==0 && Set.of("DRAFT","READY").contains(r.status()) || terminal(r.status());
|
||||
case "START" -> r.attempt()==0 && "READY".equals(r.status()) && r.fingerprint()!=null;
|
||||
case "RETRY" -> r.attempt()>0 && Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()==null && r.fingerprint()!=null;
|
||||
case "RESUME" -> r.attempt()>0 && (Set.of("FAILED","CANCELED").contains(r.status()) && r.checkpoint()!=null || "UNKNOWN".equals(r.status()));
|
||||
case "STOP","REFRESH" -> r.attempt()>0;
|
||||
case "RECREATE" -> r.attempt()>0 && "UNKNOWN".equals(r.status()) && r.checkpoint()==null;
|
||||
default -> false;
|
||||
};
|
||||
if(!ok)throw new ServiceException("当前状态不允许此操作;恢复需要原作业终止且有已完成checkpoint");
|
||||
}
|
||||
static boolean terminal(String state) {return Set.of("FAILED","CANCELED","SUCCEEDED").contains(state);}
|
||||
private StorageExecutionProfile target(long a,long o,Spec p) {
|
||||
var t=targets.resolveForIngestion(a,o,p.targetResourceId(),p.targetSpaceId());
|
||||
if(t.status()!=StorageTableFileReferenceDirectory.Status.AUTHORIZED||!"DORIS".equals(t.resourceType()))
|
||||
throw new ServiceException("目标Doris资源或数据库未授权或未启用");
|
||||
return new StorageExecutionProfile(p.targetResourceId(),p.targetSpaceId(),t.resourceType(),t.catalogName(),t.externalSpaceId(),t.locationUri(),t.endpointHost(),t.endpointPort(),t.serviceAccount(),t.secretRef(),t.tlsEnabled());
|
||||
}
|
||||
private View view(Row r,boolean history) {
|
||||
return new View(Long.toString(r.id()),r.spec(),r.status(),r.version(),r.attempt(),r.external(),r.checkpoint(),r.summary(),r.readRows(),r.writeRows(),r.observedAt(),
|
||||
history?db.queryForList("SELECT action,status,summary,created_at FROM ing_realtime_event WHERE task_id=? ORDER BY created_at DESC,id DESC LIMIT 50",r.id()):List.of());
|
||||
}
|
||||
private Row map(java.sql.ResultSet rs)throws java.sql.SQLException {
|
||||
var observed=rs.getTimestamp("observed_at");var busy=rs.getTimestamp("busy_until");
|
||||
return new Row(rs.getLong("id"),rs.getLong("owner_id"),rs.getLong("org_id"),JsonUtils.parseObject(rs.getString("config_json"),Spec.class),
|
||||
rs.getString("status"),rs.getLong("version"),rs.getLong("attempt"),rs.getString("external_id"),rs.getString("fingerprint"),rs.getString("checkpoint_id"),rs.getString("summary"),
|
||||
rs.getObject("read_rows")==null?null:rs.getLong("read_rows"),rs.getObject("write_rows")==null?null:rs.getLong("write_rows"),
|
||||
observed==null?null:observed.toLocalDateTime(),busy==null?null:busy.toLocalDateTime());
|
||||
}
|
||||
}
|
||||
+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()),
|
||||
|
||||
+1
-1
@@ -86,7 +86,7 @@ class SchedulingReadRetryWorker implements SmartLifecycle {
|
||||
private Attempt claim() {
|
||||
return transactions.execute(status -> {
|
||||
var rows = jdbc.query("""
|
||||
SELECT *,deadline_at<=NOW(6) AS expired FROM dev_schedule_read_attempt
|
||||
SELECT dev_schedule_read_attempt.*, CASE WHEN deadline_at<=NOW(6) THEN 1 ELSE 0 END AS expired FROM dev_schedule_read_attempt
|
||||
WHERE attempt_status IN ('PENDING','DISPATCHING','RUNNING','UNKNOWN') AND next_observe_at<=NOW(6)
|
||||
AND del_flag='0' ORDER BY next_observe_at,attempt_id LIMIT 1 FOR UPDATE SKIP LOCKED
|
||||
""",(rs,n)->new Attempt(rs.getLong("attempt_id"),policy.read(rs.getString("command_json"),Command.class),
|
||||
|
||||
+1
@@ -222,6 +222,7 @@ class SchedulingService {
|
||||
String requestHash = policy.requestHash(normalized);
|
||||
RunView replay = repository.replayRun(actor, RunAction.SUBMIT, idempotencyKey, requestHash);
|
||||
if (replay != null) return replay;
|
||||
reconcileAutomaticPrevious(actor, scheduleId);
|
||||
validateReferences(actor, toDefinition(definition), scheduleId);
|
||||
requireExecutionDependencies(actor, scheduleId, toDefinition(definition));
|
||||
requireExecutable(toDefinition(definition));
|
||||
|
||||
+23
-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,22 @@ 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 +83,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 +91,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
|
||||
);
|
||||
}
|
||||
|
||||
+34
-9
@@ -30,7 +30,9 @@ import java.sql.SQLException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Repository
|
||||
@@ -123,6 +125,8 @@ public class StorageResourceRepository {
|
||||
}
|
||||
|
||||
private void assertUnused(long resourceId, Long spaceId) {
|
||||
rejectUsed(count("SELECT COUNT(*) FROM ing_realtime_task WHERE target_key LIKE ?",
|
||||
resourceId + ":" + (spaceId == null ? "" : spaceId + ":") + "%"));
|
||||
if (spaceId == null && count("SELECT COUNT(*) FROM store_space WHERE resource_id=? AND del_flag='0'", resourceId) != 0)
|
||||
throw new StorageConflictException("请先删除未使用的空间登记");
|
||||
String[][] references = {
|
||||
@@ -458,7 +462,17 @@ public class StorageResourceRepository {
|
||||
"SELECT " + CAPACITY_COLUMNS + " FROM store_capacity_snapshot " +
|
||||
"WHERE resource_id=? AND del_flag='0' ORDER BY snapshot_id DESC LIMIT ?",
|
||||
(resultSet, rowNumber) -> mapCapacity(resultSet), resourceId, limit);
|
||||
return snapshots.stream().map(this::withDimensions).toList();
|
||||
if (snapshots.isEmpty()) return snapshots;
|
||||
String placeholders = String.join(",", java.util.Collections.nCopies(snapshots.size(), "?"));
|
||||
Map<Long, List<StorageCapacityDimensionView>> dimensions = new HashMap<>();
|
||||
jdbcTemplate.query("SELECT snapshot_id, " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id IN (" + placeholders +
|
||||
") AND del_flag='0' ORDER BY snapshot_id, dimension_name", rs -> {
|
||||
dimensions.computeIfAbsent(rs.getLong("snapshot_id"), ignored -> new ArrayList<>())
|
||||
.add(mapDimension(rs));
|
||||
}, snapshots.stream().map(StorageCapacitySnapshotView::snapshotId).toArray());
|
||||
return snapshots.stream().map(snapshot -> attachDimensions(snapshot,
|
||||
dimensions.getOrDefault(snapshot.snapshotId(), List.of()))).toList();
|
||||
}
|
||||
|
||||
void lockCapacityWindow(long resourceId) {
|
||||
@@ -861,14 +875,21 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "previous_snapshot_id"), resultSet.getString("contract_version"), List.of());
|
||||
}
|
||||
|
||||
private static final String DIMENSION_COLUMNS = """
|
||||
dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
""";
|
||||
|
||||
private StorageCapacitySnapshotView withDimensions(StorageCapacitySnapshotView snapshot) {
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("""
|
||||
SELECT dimension_name, metric_status, source_type, source_identity, observed_at,
|
||||
freshness_status, safe_error_code, safe_error_summary, total_bytes, used_bytes,
|
||||
available_bytes, value_bytes, value_percent, comparison_fingerprint, algorithm_version
|
||||
FROM store_capacity_dimension
|
||||
WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name
|
||||
""", (resultSet, rowNumber) -> new StorageCapacityDimensionView(
|
||||
List<StorageCapacityDimensionView> dimensions = jdbcTemplate.query("SELECT " + DIMENSION_COLUMNS +
|
||||
" FROM store_capacity_dimension WHERE snapshot_id=? AND del_flag='0' ORDER BY dimension_name",
|
||||
(resultSet, rowNumber) -> mapDimension(resultSet), snapshot.snapshotId());
|
||||
return attachDimensions(snapshot, dimensions);
|
||||
}
|
||||
|
||||
private static StorageCapacityDimensionView mapDimension(ResultSet resultSet) throws SQLException {
|
||||
return new StorageCapacityDimensionView(
|
||||
StorageTelemetryDimensionType.valueOf(resultSet.getString("dimension_name")),
|
||||
StorageTelemetryMetricState.valueOf(resultSet.getString("metric_status")),
|
||||
resultSet.getString("source_type"), resultSet.getString("source_identity"),
|
||||
@@ -879,7 +900,11 @@ public class StorageResourceRepository {
|
||||
nullableLong(resultSet, "total_bytes"), nullableLong(resultSet, "used_bytes"),
|
||||
nullableLong(resultSet, "available_bytes"), nullableLong(resultSet, "value_bytes"),
|
||||
resultSet.getBigDecimal("value_percent"), resultSet.getString("comparison_fingerprint"),
|
||||
resultSet.getString("algorithm_version")), snapshot.snapshotId());
|
||||
resultSet.getString("algorithm_version"));
|
||||
}
|
||||
|
||||
private static StorageCapacitySnapshotView attachDimensions(StorageCapacitySnapshotView snapshot,
|
||||
List<StorageCapacityDimensionView> dimensions) {
|
||||
if (dimensions.isEmpty()) {
|
||||
dimensions = legacyDimensions(snapshot);
|
||||
}
|
||||
|
||||
+8
@@ -83,6 +83,14 @@ public class StorageResourceService {
|
||||
return detail(currentActor(), resourceId);
|
||||
}
|
||||
|
||||
/** Selection lists need registered references, not capacity history and its per-snapshot dimensions. */
|
||||
public StorageResourceDetailView selectionDetail(long resourceId) {
|
||||
StorageActor actor = currentActor();
|
||||
StorageResourceView resource = repository.requireResource(actor, positiveId(resourceId, "资源ID"));
|
||||
return new StorageResourceDetailView(resource, List.copyOf(repository.spaces(resourceId)),
|
||||
repository.accessProfile(resourceId), List.of());
|
||||
}
|
||||
|
||||
/** Server-derived identity only; ingestion never inherits the administrator scope bypass. */
|
||||
public StorageResourceDetailView detailForIngestion(long actorId, long orgId, long resourceId) {
|
||||
if (actorId <= 0 || orgId <= 0) throw new StorageScopeException();
|
||||
|
||||
+9
-1
@@ -20,10 +20,18 @@ public final class TableFileErrors {
|
||||
NotFound() { super("表文件不存在"); }
|
||||
}
|
||||
|
||||
public static final class Reference extends RuntimeException {
|
||||
public static class Reference extends RuntimeException {
|
||||
Reference(String message) { super(message); }
|
||||
}
|
||||
|
||||
public static final class MissingTarget extends Reference {
|
||||
public MissingTarget() { super("目标表已确认不存在"); }
|
||||
}
|
||||
|
||||
public static final class TargetAppeared extends Reference {
|
||||
public TargetAppeared() { super("目标表已出现,需要重新核验结构"); }
|
||||
}
|
||||
|
||||
public static final class DirectoryBusy extends RuntimeException {
|
||||
public DirectoryBusy() { super("目标目录访问繁忙,请稍后重试"); }
|
||||
}
|
||||
|
||||
+11
@@ -107,6 +107,17 @@ class TableFilePolicy {
|
||||
throw new TableFileErrors.Validation("外部表必须提供外部位置");
|
||||
}
|
||||
validatePartition(command.engineType(), command.objectType(), columns, command.partitionPolicy());
|
||||
if (command.uniqueKeyColumns() != null && !command.uniqueKeyColumns().isEmpty()) {
|
||||
List<String> keys = identifiers(command.uniqueKeyColumns(), "唯一字段", 1, 32);
|
||||
if (command.engineType() != EngineType.DORIS || command.objectType() != ObjectType.TABLE || keys.size() > columns.size())
|
||||
throw new TableFileErrors.Validation("唯一字段仅适用于 Doris 表");
|
||||
for (int i = 0; i < keys.size(); i++) {
|
||||
ColumnDefinition column = columns.get(i);
|
||||
if (!keys.get(i).equals(column.name()) || column.nullable() ||
|
||||
java.util.Set.of("STRING", "FLOAT", "DOUBLE").contains(column.type().name()))
|
||||
throw new TableFileErrors.Validation("唯一字段必须排在表结构最前、不可空,且不能使用 STRING/FLOAT/DOUBLE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void requireCapability(EngineType engine, ObjectType objectType) {
|
||||
|
||||
+90
-2
@@ -302,16 +302,102 @@ class TableFileRepository {
|
||||
return reserveCreate(actor, key, hash, command, true);
|
||||
}
|
||||
|
||||
void synchronizeCommandTarget(TableFileActor actor, long resource, long space, EngineType engine,
|
||||
String catalog, String namespace, String name, List<ColumnDefinition> columns) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.active(jdbcTemplate,
|
||||
resource, space, actor.orgId(), actor.unrestricted());
|
||||
var ids = jdbcTemplate.query("""
|
||||
SELECT table_file_id FROM store_table_file WHERE org_id=? AND project_id IS NULL
|
||||
AND storage_resource_id=? AND storage_space_id=? AND engine_type=?
|
||||
AND catalog_name=? AND namespace_name=? AND object_name=? AND del_flag='0' FOR UPDATE
|
||||
""", (rs, n) -> rs.getLong(1), actor.orgId(), resource, space, engine.name(), catalog, namespace, name);
|
||||
for (long id : ids) {
|
||||
var before = requireDetail(actor, id);
|
||||
// Live existence cannot settle someone else's in-flight or unknown DDL outcome.
|
||||
Long unsettled = jdbcTemplate.queryForObject("""
|
||||
SELECT COUNT(*) FROM store_table_file_request WHERE table_file_id=? AND del_flag='0'
|
||||
AND action_type<>'PREVIEW' AND request_status IN ('IN_PROGRESS','UNKNOWN')
|
||||
""", Long.class, id);
|
||||
if (unsettled == null || unsettled != 0) continue;
|
||||
if (before.columns().equals(columns) && before.tableFile().executionState() == ExecutionState.CONFIRMED)
|
||||
continue;
|
||||
int changed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET columns_json=?, execution_state='CONFIRMED',
|
||||
error_code=NULL, error_summary=NULL, binding_evidence_json=NULL, last_observed_at=NOW(6),
|
||||
update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE table_file_id=? AND org_id=? AND version=? AND del_flag='0'
|
||||
""", json(columns), actor.actorId(), id, actor.orgId(), before.tableFile().version());
|
||||
if (changed != 1) throw createConflict();
|
||||
long requestId = IdGeneratorUtil.nextLongId();
|
||||
insertRequest(requestId, platformRequestId(), id, actor, "UPDATE",
|
||||
"target-sync-" + id + "-" + before.tableFile().version(), new TableFilePolicy().hash(columns), "CONFIRMED");
|
||||
insertSnapshot(requestId, id, actor, before, requireDetail(actor, id));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reservation reserveCommandCreate(TableFileActor actor, String key, String hash, CreateCommand command,
|
||||
java.util.function.Consumer<String> bind) {
|
||||
return transactionTemplate.execute(status -> {
|
||||
Reservation reservation = reserveCreate(actor, key, hash, command, false);
|
||||
Reservation reservation = replay(actor, "CREATE", key, hash);
|
||||
if (reservation == null) {
|
||||
// Serialize on the same storage identity as first-time creates, before looking up the old row.
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.active(jdbcTemplate,
|
||||
command.storageResourceId(), command.storageSpaceId(), actor.orgId(), actor.unrestricted());
|
||||
var existing = jdbcTemplate.query("""
|
||||
SELECT table_file_id FROM store_table_file
|
||||
WHERE org_id=? AND project_id IS NULL AND storage_resource_id=? AND storage_space_id=? AND engine_type=?
|
||||
AND catalog_name=? AND namespace_name=? AND object_name=? AND del_flag='0'
|
||||
FOR UPDATE
|
||||
""", (rs, n) -> rs.getLong(1), actor.orgId(), command.storageResourceId(),
|
||||
command.storageSpaceId(), command.engineType().name(), command.catalogName(),
|
||||
command.namespaceName(), command.name());
|
||||
if (existing.isEmpty()) reservation = reserveCreate(actor, key, hash, command, false);
|
||||
else if (existing.size() == 1) reservation = reserveMissingCommandTarget(actor, key, hash, command, existing.getFirst());
|
||||
else throw createConflict();
|
||||
}
|
||||
requireStored(actor, reservation.tableFileId());
|
||||
bind.accept(reservation.platformRequestId());
|
||||
return reservation;
|
||||
});
|
||||
}
|
||||
|
||||
/** Called only after live, explicit absence; keeps the original identity and immutable operation history. */
|
||||
private Reservation reserveMissingCommandTarget(TableFileActor actor, String key, String hash,
|
||||
CreateCommand command, long tableFileId) {
|
||||
var before = requireDetail(actor, tableFileId);
|
||||
var table = before.tableFile();
|
||||
if (table.objectType() != command.objectType() || !java.util.Objects.equals(table.layerId(), command.layerId()))
|
||||
throw new TableFileErrors.Conflict("旧登记的对象类型或分层不一致,请核对目标配置");
|
||||
Long unsettled = jdbcTemplate.queryForObject("""
|
||||
SELECT COUNT(*) FROM store_table_file_request WHERE table_file_id=? AND del_flag='0'
|
||||
AND action_type<>'PREVIEW' AND request_status IN ('IN_PROGRESS','UNKNOWN')
|
||||
""", Long.class, tableFileId);
|
||||
if (unsettled == null || unsettled != 0)
|
||||
throw new TableFileErrors.Conflict("目标表有正在执行或结果待确认的操作,请先核验原执行记录");
|
||||
long requestId = IdGeneratorUtil.nextLongId();
|
||||
String platformRequestId = platformRequestId();
|
||||
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.reference(jdbcTemplate,
|
||||
command.storageResourceId(), command.storageSpaceId(), actor.orgId(), actor.unrestricted(), "TABLE_CREATE");
|
||||
int changed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET columns_json=?, object_comment=?, partition_policy_json=?,
|
||||
view_definition_json=?, storage_format=?, external_location=?, execution_state='UNKNOWN',
|
||||
policy_execution_state=?, external_object_id=NULL, binding_evidence_json=NULL,
|
||||
registration_origin='CREATED', error_code='TARGET_RECREATE_PENDING',
|
||||
error_summary='目标表已不存在,等待自动重建', last_observed_at=NOW(6),
|
||||
update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE table_file_id=? AND org_id=? AND version=? AND del_flag='0'
|
||||
""", json(command.columns()), command.comment(), json(command.partitionPolicy()),
|
||||
json(command.viewDefinition()), command.storageFormat().name(), command.externalLocation(),
|
||||
command.partitionPolicy() == null ? "NOT_REQUESTED" : "UNKNOWN", actor.actorId(),
|
||||
tableFileId, actor.orgId(), table.version());
|
||||
if (changed != 1) throw createConflict();
|
||||
insertRequest(requestId, platformRequestId, tableFileId, actor, "CREATE", key, hash, "IN_PROGRESS");
|
||||
insertSnapshot(requestId, tableFileId, actor, before, command);
|
||||
return new Reservation(requestId, platformRequestId, tableFileId, false, "CREATE");
|
||||
}
|
||||
|
||||
Reservation commandReservation(TableFileActor actor, String key, String hash, String platformRequestId) {
|
||||
Reservation reservation = replay(actor, "CREATE", key, hash);
|
||||
if (reservation == null || !reservation.platformRequestId().equals(platformRequestId))
|
||||
@@ -587,12 +673,14 @@ class TableFileRepository {
|
||||
boolean retryable, String externalObjectId, String errorCode,
|
||||
String errorSummary, LocalDateTime observedAt) {
|
||||
transactionTemplate.executeWithoutResult(status -> {
|
||||
jdbcTemplate.update("""
|
||||
int completed = jdbcTemplate.update("""
|
||||
UPDATE store_table_file_request SET request_status=?, retryable=?, external_object_id=?,
|
||||
error_code=?, error_summary=?, observed_at=?, update_by=?, update_time=NOW(), version=version+1
|
||||
WHERE request_id=? AND request_status='IN_PROGRESS' AND del_flag='0'
|
||||
""", state.name(), retryable, externalObjectId, errorCode, errorSummary, observedAt,
|
||||
actor.actorId(), reservation.requestId());
|
||||
// A delayed/replayed completion must not overwrite a newer rebuild of the same table identity.
|
||||
if (completed != 1) return;
|
||||
String policyState = "PARTITION".equals(reservation.action()) ? policyState(state, errorCode) : null;
|
||||
jdbcTemplate.update("""
|
||||
UPDATE store_table_file SET execution_state=?, external_object_id=COALESCE(?, external_object_id),
|
||||
|
||||
+29
-2
@@ -69,6 +69,8 @@ public class TableFileService {
|
||||
var after = targetReferences(actor, resourceId, spaceId, EngineType.DORIS);
|
||||
if (!ref.equals(after)) throw new TableFileErrors.Reference("目标配置已变化,请重新选择");
|
||||
if ("目标目录访问繁忙,请稍后重试".equals(result.errorSummary())) throw new TableFileErrors.DirectoryBusy();
|
||||
if (result.state() == TableFileIntegrationService.State.REJECTED && result.confirmedMissing())
|
||||
throw new TableFileErrors.MissingTarget();
|
||||
if (result.state() != TableFileIntegrationService.State.CONFIRMED)
|
||||
throw new TableFileErrors.Reference(result.errorSummary());
|
||||
return result;
|
||||
@@ -97,11 +99,27 @@ public class TableFileService {
|
||||
var after = targetReferences(actor, resourceId, spaceId, engineType, strict);
|
||||
if (!ref.equals(after)) throw new TableFileErrors.Reference("目标配置已变化,请重新选择");
|
||||
if ("目标目录访问繁忙,请稍后重试".equals(result.errorSummary())) throw new TableFileErrors.DirectoryBusy();
|
||||
if (result.state() == TableFileIntegrationService.State.REJECTED && result.confirmedMissing())
|
||||
throw new TableFileErrors.MissingTarget();
|
||||
if (result.state() != TableFileIntegrationService.State.CONFIRMED)
|
||||
throw new TableFileErrors.Reference(result.errorSummary());
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Synchronize an existing registration only after ingestion has validated the live column mapping. */
|
||||
public void synchronizeCommandTarget(VerifiedIngestionCommandActor verified, long resourceId, long spaceId,
|
||||
EngineType engine, String table, TableFileIntegrationService.DirectoryResult observed) {
|
||||
verified.check();
|
||||
if (observed == null || observed.state() != TableFileIntegrationService.State.CONFIRMED
|
||||
|| observed.total() != 1 || !List.of(table).equals(observed.tables()))
|
||||
throw new TableFileErrors.Reference("目标表实时状态未确认");
|
||||
var actor = new TableFileActor(verified.actorId(), verified.orgId(), false);
|
||||
var ref = targetReferences(actor, resourceId, spaceId, engine, true);
|
||||
var columns = new TableFileBindingPolicy(policy).columns(observed.columns(), 500);
|
||||
repository.synchronizeCommandTarget(actor, resourceId, spaceId, engine, ref.catalogName(),
|
||||
ref.externalSpaceId(), table, columns);
|
||||
}
|
||||
|
||||
private StorageTableFileReferenceDirectory.Resolution targetReferences(TableFileActor actor, long resourceId,
|
||||
long spaceId, EngineType engineType) {
|
||||
return targetReferences(actor, resourceId, spaceId, engineType, false);
|
||||
@@ -144,7 +162,7 @@ public class TableFileService {
|
||||
command = new CreateCommand(command.name(), command.objectType(), null,
|
||||
command.storageResourceId(), command.storageSpaceId(), command.engineType(), command.storageFormat(),
|
||||
direct.catalogName(), direct.externalSpaceId(), command.externalLocation(), command.comment(),
|
||||
command.columns(), command.partitionPolicy(), command.viewDefinition(), command.physicalTableComment());
|
||||
command.columns(), command.partitionPolicy(), command.viewDefinition(), command.physicalTableComment(), command.uniqueKeyColumns());
|
||||
refs = new References(direct, null);
|
||||
} else {
|
||||
refs = references(actor, command.layerId(), command.storageResourceId(),
|
||||
@@ -169,6 +187,15 @@ public class TableFileService {
|
||||
References refs = references(actor, command.layerId(), command.storageResourceId(),
|
||||
command.storageSpaceId(), command.engineType(), true);
|
||||
requireLayerContract(command, refs.layer());
|
||||
// Revalidate at the reservation boundary; callers cannot turn an ambiguous read into a rebuild.
|
||||
boolean missing = false;
|
||||
try {
|
||||
targetDirectory(verified, command.storageResourceId(), command.storageSpaceId(),
|
||||
command.engineType(), command.name(), null, 1, 20);
|
||||
} catch (TableFileErrors.MissingTarget absent) {
|
||||
missing = true;
|
||||
}
|
||||
if (!missing) throw new TableFileErrors.TargetAppeared();
|
||||
return repository.reserveCommandCreate(actor, policy.idempotencyKey(key), policy.hash(command), command, bind)
|
||||
.platformRequestId();
|
||||
}
|
||||
@@ -325,7 +352,7 @@ public class TableFileService {
|
||||
connection(command.engineType(), storageRef), enumValue(TableFileIntegrationService.ObjectType.class, command.objectType()),
|
||||
enumValue(TableFileIntegrationService.StorageFormat.class, command.storageFormat()), command.catalogName(),
|
||||
command.namespaceName(), command.name(), command.externalLocation(), columns(command.columns()),
|
||||
partition(command.partitionPolicy()), view(command.viewDefinition()), command.physicalTableComment());
|
||||
partition(command.partitionPolicy()), view(command.viewDefinition()), command.physicalTableComment(), command.uniqueKeyColumns());
|
||||
}
|
||||
|
||||
private TableFileIntegrationService.PolicyCommand policyIntegrationCommand(
|
||||
|
||||
+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
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package cn.aixunkeji.datagov.dataops;
|
||||
|
||||
import cn.aixunkeji.common.core.enums.PlatformDatabaseDialect;
|
||||
import cn.aixunkeji.common.mybatis.config.PlatformDatabaseConfiguration;
|
||||
import cn.aixunkeji.datagov.maintenance.*;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
/** Explicit opt-in test, writes only inside a transaction rolled back in a dedicated test database. */
|
||||
@EnabledIfEnvironmentVariable(named="DATAGOV_DUAL_DB_TEST", matches="true")
|
||||
class PlatformDatabaseJdbcTest {
|
||||
@Test void actualDriverSelectionLeaseFencingUpsertAndRollback() throws Exception {
|
||||
String url = System.getenv("PLATFORM_DB_URL");
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
assertThat(url.contains("/aixun_datagov_dualcheck_") || (schema != null && schema.startsWith("AIXUN_DATAGOV_DUALCHECK_"))).isTrue();
|
||||
HikariConfig config = new HikariConfig();
|
||||
config.setJdbcUrl(url);
|
||||
config.setUsername(System.getenv("PLATFORM_DB_USERNAME"));
|
||||
config.setPassword(System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
config.setMaximumPoolSize(1);
|
||||
config.setMinimumIdle(0);
|
||||
if (schema != null && !schema.isBlank()) config.setSchema(schema);
|
||||
try (HikariDataSource source = new HikariDataSource(config)) {
|
||||
PlatformDatabaseDialect dialect = new PlatformDatabaseConfiguration().platformDatabaseDialect(source);
|
||||
assertThat(dialect).isEqualTo(url.startsWith("jdbc:mysql:") ? PlatformDatabaseDialect.MYSQL : PlatformDatabaseDialect.DAMENG);
|
||||
JdbcTemplate jdbc = new JdbcTemplate(source);
|
||||
var repository = new JdbcMaintenanceLeaseRepository(jdbc, dialect);
|
||||
String name = "dual-db-check-" + UUID.randomUUID();
|
||||
Instant now = Instant.now();
|
||||
long id = UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE;
|
||||
var first = new MaintenanceLeaseRequest(id, name, MaintenanceJobKind.STATUS_RECONCILIATION,
|
||||
"first", "first-token", "first-command", MaintenanceTriggerType.SCHEDULED, 0, null, now, now.plusSeconds(60));
|
||||
var second = new MaintenanceLeaseRequest(id, name, MaintenanceJobKind.STATUS_RECONCILIATION,
|
||||
"second", "second-token", "second-command", MaintenanceTriggerType.SCHEDULED, 0, null, now, now.plusSeconds(60));
|
||||
new TransactionTemplate(new DataSourceTransactionManager(source)).executeWithoutResult(status -> {
|
||||
status.setRollbackOnly();
|
||||
assertThat(repository.tryAcquire(first)).isTrue();
|
||||
assertThat(repository.tryAcquire(second)).isFalse();
|
||||
assertThatThrownBy(() -> repository.finish(name, "wrong-token", MaintenanceRunOutcome.SUCCESS, now, true)).isInstanceOf(IllegalStateException.class);
|
||||
repository.finish(name, "first-token", MaintenanceRunOutcome.SUCCESS, now, true);
|
||||
assertThat(repository.tryAcquire(first)).isFalse();
|
||||
assertThat(repository.tryAcquire(second)).isTrue();
|
||||
try {
|
||||
String encoded = Files.readAllLines(Path.of(System.getenv("DUAL_DB_SQL_FILE"))).stream()
|
||||
.filter(line -> line.startsWith("MetricFormulaStore.java:")).findFirst().orElseThrow().split("\t",2)[1];
|
||||
String sql = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
|
||||
jdbc.update(sql, id, id, id, 11L, 11L);
|
||||
jdbc.update(sql, id, id, id, 22L, 22L);
|
||||
assertThat(jdbc.queryForObject("SELECT version FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isEqualTo(1L);
|
||||
assertThat(jdbc.queryForObject("SELECT update_by FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isEqualTo(22L);
|
||||
} catch (java.io.IOException error) { throw new IllegalStateException(error); }
|
||||
String hash = jdbc.queryForObject(dialect.sql("SELECT LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST('abc' AS CLOB),DBMS_CRYPTO.HASH_SH256))) FROM DUAL", "SELECT SHA2('abc',256)"), String.class);
|
||||
assertThat(hash).isEqualTo("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
});
|
||||
assertThat(repository.find(name)).isEmpty();
|
||||
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM metric_formula_graph_guard WHERE organization_id=? AND department_id=?", Long.class, id, id)).isZero();
|
||||
}
|
||||
}
|
||||
}
|
||||
+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)){
|
||||
|
||||
+45
-2
@@ -34,6 +34,49 @@ import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class UnifiedIngestionRecoveryTest {
|
||||
@Test void ambiguousDirectoryFailureCannotStartAutomaticCreate() {
|
||||
var fixture = new CommentFixture("订单字段");
|
||||
fixture.tableComment = SourceTableComment.fromSource("订单表");
|
||||
var request = fixture.request(fixture.draft(StorageResourceType.DORIS).items().getFirst(), StorageResourceType.DORIS);
|
||||
fixture.submitReady(StorageResourceType.DORIS);
|
||||
var unavailable = mock(TableFileErrors.Reference.class);
|
||||
when(fixture.tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20))).thenThrow(unavailable);
|
||||
assertThatThrownBy(() -> fixture.consume(request))
|
||||
.isInstanceOf(UnifiedIngestionCommandStageException.class).hasMessageContaining("连接、权限");
|
||||
verify(fixture.tables, never()).reserveCommandCreate(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test void targetAppearingBeforeReservationIsRecheckedAndReused() {
|
||||
var fixture = new CommentFixture("订单字段");
|
||||
var request = fixture.request(fixture.draft(StorageResourceType.DORIS).items().getFirst(), StorageResourceType.DORIS);
|
||||
fixture.submitReady(StorageResourceType.DORIS);
|
||||
var directory = new DirectoryResult(State.CONFIRMED,List.of("orders"),
|
||||
List.of(new DirectoryColumn("id","BIGINT",19,0,false)),1,null);
|
||||
when(fixture.tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(new TableFileErrors.MissingTarget()).thenReturn(directory);
|
||||
when(fixture.tables.reserveCommandCreate(any(),any(),any(),any())).thenThrow(new TableFileErrors.TargetAppeared());
|
||||
fixture.consume(request);
|
||||
verify(fixture.collections).advance(any(),org.mockito.ArgumentMatchers.eq("TARGET_CONFIRMED"),any(),
|
||||
org.mockito.ArgumentMatchers.isNull(),org.mockito.ArgumentMatchers.isNull(),org.mockito.ArgumentMatchers.isNull());
|
||||
verify(fixture.tables,never()).executeCommandCreate(any(),any(),any(),any());
|
||||
verify(fixture.tables).synchronizeCommandTarget(any(),org.mockito.ArgumentMatchers.eq(30L),
|
||||
org.mockito.ArgumentMatchers.eq(40L),org.mockito.ArgumentMatchers.eq(EngineType.DORIS),
|
||||
org.mockito.ArgumentMatchers.eq("orders"),org.mockito.ArgumentMatchers.eq(directory));
|
||||
}
|
||||
@Test void realtimeDirectoryDoesNotReuseBatchPilotGateOrLoseCredentialGate() {
|
||||
var f=new CommentFixture("");
|
||||
when(f.sources.sources(1,2,List.of(),null,200)).thenReturn(new DataSourceDirectoryService.Result("AVAILABLE",List.of(
|
||||
new DataSourceDirectoryService.Entry(7L,"dm","DAMENG","SUCCEEDED",true,false,null,"APP",1),
|
||||
new DataSourceDirectoryService.Entry(8L,"kb","KINGBASE","SUCCEEDED",false,false,null,"app",1),
|
||||
new DataSourceDirectoryService.Entry(9L,"bad","KINGBASE","FAILED",true,false,null,"app",1))));
|
||||
assertThat(f.service.sources(null).rows()).allMatch(x->!x.available());
|
||||
assertThat(f.service.realtimeSources(null).rows()).extracting(x->x.available()).containsExactly(true,false,false);
|
||||
verify(f.sources,org.mockito.Mockito.times(2)).sources(1,2,List.of(),null,200);
|
||||
}
|
||||
|
||||
@Test void absentOrFalseConsumerSettingRejectsNewRequestsWithoutReservationOrRpc() {
|
||||
var fixture = new CommentFixture("原注释");
|
||||
@@ -269,11 +312,11 @@ class UnifiedIngestionRecoveryTest {
|
||||
when(tables.targetDirectory(any(), org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(mock(TableFileErrors.Reference.class));
|
||||
.thenThrow(new TableFileErrors.MissingTarget());
|
||||
when(tables.targetDirectory(org.mockito.ArgumentMatchers.eq(30L), org.mockito.ArgumentMatchers.eq(40L),
|
||||
any(), org.mockito.ArgumentMatchers.eq("orders"), org.mockito.ArgumentMatchers.isNull(),
|
||||
org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.eq(20)))
|
||||
.thenThrow(mock(TableFileErrors.Reference.class));
|
||||
.thenThrow(new TableFileErrors.MissingTarget());
|
||||
var view = mock(TableFileView.class);
|
||||
when(view.executionState()).thenReturn(ExecutionState.REJECTED);
|
||||
var detail = mock(TableFileDetailView.class);
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.FileSourceType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises profile persistence and secret-reference handling against the dedicated DM test schema. */
|
||||
@EnabledIfEnvironmentVariable(named = "DATAGOV_DM_SCHEMA", matches = "AIXUN_DATAGOV_DM_TEST")
|
||||
class ApiPollProfileJdbcTest {
|
||||
@Test void savesRedactedProfileAndRevokesReplacedSigningKey() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
ds.setDriverClassName("dm.jdbc.driver.DmDriver");
|
||||
ds.setUrl("jdbc:dm://" + System.getenv("DATAGOV_DM_HOST") + ":" + System.getenv("DATAGOV_DM_PORT"));
|
||||
ds.setUsername(System.getenv("DATAGOV_DM_USERNAME"));
|
||||
ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
var properties = new Properties(); properties.setProperty("schema", System.getenv("DATAGOV_DM_SCHEMA"));
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var credentials = mock(FileManagedCredentialGateway.class);
|
||||
var actor = new FileIngestionActor(900009L, 900009L);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, -900009L)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(credentials.provision(any(char[].class))).thenReturn("file:///managed/api-sign?version=v1");
|
||||
char[] signingKey = "test-signing-material".toCharArray();
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollProfileService(jdbc, JsonMapper.builder().findAndAddModules().build(),
|
||||
actors, repository, credentials);
|
||||
var first = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of("X-Tenant", "example"), Map.of("status", "paid"), "{\"page\":${page}}",
|
||||
50, 60, "$.success", "true", "HMAC_SHA256", "${method}\n${pathQuery}\n${timestamp}\n${nonce}",
|
||||
"HEADER", "X-Sign", "BASE64", signingKey);
|
||||
assertThat(service.save(-900009L, first).signingKeyConfigured()).isTrue();
|
||||
assertThat(signingKey).containsOnly('\0');
|
||||
String stored = jdbc.queryForObject("SELECT profile_json FROM ing_api_poll_profile WHERE intake_id=?",
|
||||
String.class, -900009L);
|
||||
assertThat(stored).contains("file:///managed/api-sign?version=v1").doesNotContain("test-signing-material");
|
||||
assertThat(service.view(-900009L).requestMethod()).isEqualTo("POST");
|
||||
var second = new ApiPollProfileService.Command("CLIENT_CREDENTIALS", "https://api.example.com/token",
|
||||
"FORM", "test-client", "client_id", "client_secret", "BODY", "$.access_token", "$.expires_in",
|
||||
"POST", Map.of(), Map.of(), null, 50, 0, null, null,
|
||||
"NONE", null, "HEADER", "X-Sign", "BASE64", null);
|
||||
assertThat(service.save(-900009L, second).signingKeyConfigured()).isFalse();
|
||||
verify(credentials).revoke("file:///managed/api-sign?version=v1");
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.fileingestion.*;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Exercises polling with rolled-back rows in the dedicated dual-database test schema only. */
|
||||
@EnabledIfEnvironmentVariable(named = "PLATFORM_DB_URL", matches = "jdbc:(mysql|dm):.*")
|
||||
class ApiPollServiceJdbcTest {
|
||||
@BeforeAll static void identifiers() {
|
||||
var beans = new DefaultListableBeanFactory();
|
||||
beans.registerSingleton("identifierGenerator", com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance());
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(beans);
|
||||
}
|
||||
|
||||
@Test void successfulRunCommitsWatermarkAndUnknownKeepsIt() {
|
||||
var ds = new DriverManagerDataSource();
|
||||
String url = System.getenv("PLATFORM_DB_URL");
|
||||
boolean mysql = url.startsWith("jdbc:mysql:");
|
||||
String schema = System.getenv("PLATFORM_DB_SCHEMA");
|
||||
org.junit.jupiter.api.Assumptions.assumeTrue(mysql ? url.contains("/aixun_datagov_dualcheck_") : schema != null && schema.startsWith("AIXUN_DATAGOV_DUALCHECK_"));
|
||||
ds.setUrl(url);
|
||||
ds.setUsername(System.getenv("PLATFORM_DB_USERNAME"));
|
||||
ds.setPassword(System.getenv("PLATFORM_DB_PASSWORD"));
|
||||
var properties = new Properties(); if (!mysql) properties.setProperty("schema", schema);
|
||||
ds.setConnectionProperties(properties);
|
||||
var jdbc = new JdbcTemplate(ds);
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var integration = mock(IntegrationFileIngestionGateway.class);
|
||||
var config = mock(FileIngestionPolicy.Config.class);
|
||||
var actor = new FileIngestionActor(900008L, 900008L);
|
||||
long intakeId = -900008L;
|
||||
when(actors.current()).thenReturn(actor);
|
||||
when(repository.config(actor, intakeId)).thenReturn(config);
|
||||
when(config.sourceType()).thenReturn(FileSourceType.API_SAAS);
|
||||
when(config.apiConnector()).thenReturn(FileApiConnector.GENERIC_HTTPS_JSON);
|
||||
when(config.authMode()).thenReturn(FileAuthMode.BEARER);
|
||||
when(config.paginationMode()).thenReturn(FilePaginationMode.PAGE_SIZE);
|
||||
when(config.maxPages()).thenReturn(2);
|
||||
when(config.periodSeconds()).thenReturn(60);
|
||||
when(config.secretRef()).thenReturn("file:///managed/data-source/test?version=v1");
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), isNull(), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("SUCCEEDED", 2, "2026-11-26T00:00:00Z", null));
|
||||
when(integration.pollApi(eq(actor), eq(intakeId), eq(config), eq("2026-11-26T00:00:00Z"), isNull())).thenReturn(
|
||||
new DataCollectionIntegrationService.ApiPollResult("UNKNOWN", 0, null, "API_POLL_HTTP_503"));
|
||||
new TransactionTemplate(new DataSourceTransactionManager(ds)).execute(status -> {
|
||||
status.setRollbackOnly();
|
||||
var service = new ApiPollService(jdbc, actors, repository, integration);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "databaseDialect",
|
||||
mysql ? cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.MYSQL : cn.aixunkeji.common.core.enums.PlatformDatabaseDialect.DAMENG);
|
||||
assertThat(service.state(intakeId).lastStatus()).isEqualTo("NEVER");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("SUCCEEDED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.runNow(intakeId).status()).isEqualTo("UNKNOWN");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.runs(intakeId)).hasSize(2);
|
||||
assertThat(service.setEnabled(intakeId, true).enabled()).isTrue();
|
||||
service.scan();
|
||||
assertThat(service.runs(intakeId)).hasSize(3);
|
||||
assertThat(service.runs(intakeId).getFirst().triggerType()).isEqualTo("SCHEDULED");
|
||||
assertThat(service.state(intakeId).watermark()).isEqualTo("2026-11-26T00:00:00Z");
|
||||
assertThat(service.setEnabled(intakeId, false).enabled()).isFalse();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package cn.aixunkeji.datagov.dataops.fileingestion;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class ApiPreviewServiceTest {
|
||||
@Test void unsavedPreviewUsesActorScopedReferencesAndRevokesTemporarySecret() {
|
||||
var actors = mock(FileIngestionActorProvider.class);
|
||||
var repository = mock(FileIngestionRepository.class);
|
||||
var credentials = mock(FileManagedCredentialGateway.class);
|
||||
var profiles = mock(ApiPollProfileService.class);
|
||||
var integration = mock(IntegrationFileIngestionGateway.class);
|
||||
when(actors.current()).thenReturn(new FileIngestionActor(7, 9));
|
||||
when(credentials.provision(any())).thenReturn("temporary-ref");
|
||||
when(integration.previewApi(any())).thenAnswer(call -> {
|
||||
ApiPreviewRequest request = call.getArgument(0);
|
||||
assertThat(request.actorId()).isEqualTo(7);
|
||||
assertThat(request.orgScopeId()).isEqualTo(9);
|
||||
assertThat(request.secretRef()).isEqualTo("temporary-ref");
|
||||
return new ApiPreviewResult("SUCCEEDED", null, List.of());
|
||||
});
|
||||
var profile = JsonMapper.builder().build().readValue("""
|
||||
{"authKind":"STATIC_BEARER","requestMethod":"GET","pageSize":20,"lookbackSeconds":0,"signatureKind":"NONE"}
|
||||
""", ApiPollProfileService.Command.class);
|
||||
char[] secret = "sample-test-secret".toCharArray();
|
||||
var command = new ApiPreviewService.Command(null, "https://example.test/data", secret, "PAGE_SIZE", "page", null, profile);
|
||||
var service = new ApiPreviewService(actors, repository, credentials, profiles, integration);
|
||||
assertThat(service.preview(command).status()).isEqualTo("SUCCEEDED");
|
||||
verify(credentials).revoke("temporary-ref");
|
||||
assertThat(new String(secret)).doesNotContain("sample");
|
||||
verifyNoInteractions(repository);
|
||||
doThrow(new IllegalStateException("private-internal-details")).when(integration).previewApi(any());
|
||||
assertThatThrownBy(() -> service.preview(new ApiPreviewService.Command(null, "https://example.test/data", "sample".toCharArray(), "PAGE_SIZE", "page", null, profile)))
|
||||
.isInstanceOf(FileIngestionException.class).hasMessageNotContaining("private-internal-details");
|
||||
verify(credentials, times(2)).revoke("temporary-ref");
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.*;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import java.util.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** Executes production DM repository SQL; every test rolls its synthetic records back. */
|
||||
@EnabledIfEnvironmentVariable(named="DATAGOV_DM_SCHEMA",matches="AIXUN_DATAGOV_DM_TEST")
|
||||
class RealtimeJdbcTest {
|
||||
@BeforeAll static void beans(){
|
||||
var b=new DefaultListableBeanFactory();
|
||||
b.registerSingleton("identifierGenerator",com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator.getInstance());
|
||||
b.registerSingleton("jsonMapper",JsonMapper.builder().findAndAddModules().build());
|
||||
new cn.hutool.extra.spring.SpringUtil().postProcessBeanFactory(b);
|
||||
}
|
||||
@Test void durableLifecycleReplayVersionAndScope() throws Exception {
|
||||
var ds=new DriverManagerDataSource();ds.setDriverClassName("dm.jdbc.driver.DmDriver");
|
||||
ds.setUrl("jdbc:dm://"+System.getenv("DATAGOV_DM_HOST")+":"+System.getenv("DATAGOV_DM_PORT"));
|
||||
ds.setUsername(System.getenv("DATAGOV_DM_USERNAME"));ds.setPassword(System.getenv("DATAGOV_DM_PASSWORD"));
|
||||
var props=new Properties();props.setProperty("schema",System.getenv("DATAGOV_DM_SCHEMA"));ds.setConnectionProperties(props);
|
||||
var db=new JdbcTemplate(ds);var tx=new TransactionTemplate(new DataSourceTransactionManager(ds));
|
||||
var targets=mock(StorageTableFileReferenceDirectory.class);var provider=mock(RealtimeCollectionService.class);
|
||||
when(targets.resolveForIngestion(anyLong(),anyLong(),anyLong(),anyLong())).thenReturn(new StorageTableFileReferenceDirectory.Resolution(
|
||||
StorageTableFileReferenceDirectory.Status.AUTHORIZED,"DORIS","test","test",null,"test.local",9030,"test","secret:test",false));
|
||||
var service=new RealtimeService(db,tx,targets);
|
||||
var field=RealtimeService.class.getDeclaredField("integration");field.setAccessible(true);field.set(service,provider);
|
||||
try(var login=mockStatic(LoginHelper.class)){
|
||||
login.when(LoginHelper::getUserId).thenReturn(900001L);login.when(LoginHelper::getDeptId).thenReturn(900002L);
|
||||
tx.executeWithoutResult(status->{
|
||||
status.setRollbackOnly();
|
||||
var spec=new Spec("CDC rollback test",900001,1,"source","orders",900003,900004,"target",8030,"initial",30,900005);
|
||||
String createKey=UUID.randomUUID().toString();var created=service.create(spec,createKey);
|
||||
assertThat(service.create(spec,createKey).id()).isEqualTo(created.id());
|
||||
long id=Long.parseLong(created.id());
|
||||
when(provider.prepare(any())).thenReturn(new Check(true,"ready","a".repeat(64),List.of("id"),List.of("id")));
|
||||
var ready=service.action(id,"CHECK",action(created));assertThat(ready.status()).isEqualTo("READY");
|
||||
var startKey=UUID.randomUUID().toString();
|
||||
when(provider.execute(any(),eq("START"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"unknown",null,null,null));
|
||||
var unknown=service.action(id,"START",new RealtimeService.Action(ready.version(),startKey));
|
||||
assertThat(unknown.status()).isEqualTo("UNKNOWN");assertThat(unknown.attempt()).isEqualTo(1);
|
||||
assertThat(service.action(id,"START",new RealtimeService.Action(ready.version(),startKey)).attempt()).isEqualTo(1);
|
||||
verify(provider,times(1)).execute(any(),eq("START"),any(),isNull());
|
||||
when(provider.execute(any(),eq("REFRESH"),any(),isNull())).thenAnswer(i->new Result("RUNNING",i.getArgument(2),null,"10",12L,12L));
|
||||
var running=service.action(id,"REFRESH",action(unknown));assertThat(running.writeRows()).isEqualTo(12L);
|
||||
when(provider.execute(any(),eq("STOP"),any(),isNull())).thenAnswer(i->new Result("CANCELED",i.getArgument(2),null,"11",12L,12L));
|
||||
var stopped=service.action(id,"STOP",action(running));assertThat(stopped.status()).isEqualTo("CANCELED");
|
||||
when(provider.execute(any(),eq("RESUME"),any(),anyString())).thenAnswer(i->new Result("RUNNING",i.getArgument(2),null,null,null,null));
|
||||
var resumed=service.action(id,"RESUME",action(stopped));assertThat(resumed.attempt()).isEqualTo(1);
|
||||
assertThat(resumed.externalId()).isEqualTo(stopped.externalId());
|
||||
verify(provider).execute(argThat(c->c.recovery()!=null && c.recovery().checkpointId().equals("11") &&
|
||||
c.recovery().status().equals("CANCELED") && c.recovery().jobId().equals(stopped.externalId())),eq("RESUME"),eq(stopped.externalId()),eq(stopped.externalId()));
|
||||
assertThatThrownBy(()->service.action(id,"DELETE",action(resumed))).hasMessageContaining("当前状态");
|
||||
var ended=service.action(id,"STOP",action(resumed));
|
||||
// A stale terminal record cannot hide a still-running external job.
|
||||
var denied=service.action(id,"DELETE",action(ended));
|
||||
assertThat(denied.status()).isEqualTo("RUNNING");
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
ended=service.action(id,"STOP",action(denied));
|
||||
when(provider.execute(any(),eq("REFRESH"),any(),isNull())).thenAnswer(i->new Result("FAILED",i.getArgument(2),"failed",null,12L,12L));
|
||||
var deleteRequest=action(ended);
|
||||
var deleted=service.action(id,"DELETE",deleteRequest);
|
||||
assertThat(deleted.status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.action(id,"DELETE",deleteRequest).status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.list(1,20).total()).isZero();
|
||||
assertThat(deleted.history()).isNotEmpty();
|
||||
assertThatThrownBy(()->service.action(id,"REFRESH",action(deleted))).hasMessageContaining("已删除");
|
||||
// Source server-id and target reservation must both be reusable.
|
||||
var replacement=service.create(spec,UUID.randomUUID().toString());
|
||||
assertThat(replacement.status()).isEqualTo("DRAFT");
|
||||
long replacementId=Long.parseLong(replacement.id());
|
||||
var readyAgain=service.action(replacementId,"CHECK",action(replacement));
|
||||
var unknownAgain=service.action(replacementId,"START",action(readyAgain));
|
||||
when(provider.execute(any(),eq("RECREATE"),any(),isNull())).thenAnswer(i->new Result("UNKNOWN",i.getArgument(2),"engine busy",null,null,null));
|
||||
var refused=service.action(replacementId,"RECREATE",action(unknownAgain));
|
||||
assertThat(refused.status()).isEqualTo("UNKNOWN");
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
when(provider.execute(any(),eq("RECREATE"),any(),isNull())).thenAnswer(i->new Result("ABSENT",i.getArgument(2),"verified absent",null,null,null));
|
||||
var recreateRequest=action(refused);
|
||||
var rebuilt=service.action(replacementId,"RECREATE",recreateRequest);
|
||||
assertThat(rebuilt.id()).isNotEqualTo(replacement.id());
|
||||
assertThat(rebuilt.spec()).isEqualTo(spec);
|
||||
assertThat(rebuilt.status()).isEqualTo("DRAFT");
|
||||
assertThat(rebuilt.attempt()).isZero();
|
||||
assertThat(service.get(replacementId).status()).isEqualTo("ARCHIVED");
|
||||
assertThat(service.action(replacementId,"RECREATE",recreateRequest).id()).isEqualTo(rebuilt.id());
|
||||
assertThat(service.list(1,20).total()).isEqualTo(1);
|
||||
login.when(LoginHelper::getUserId).thenReturn(900009L);
|
||||
assertThat(service.list(1,20).rows()).isEmpty();
|
||||
assertThatThrownBy(()->service.get(id)).hasMessageContaining("无权访问");
|
||||
});
|
||||
}
|
||||
}
|
||||
private static RealtimeService.Action action(RealtimeService.View view){return new RealtimeService.Action(view.version(),UUID.randomUUID().toString());}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package cn.aixunkeji.datagov.dataops.realtime;
|
||||
import cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Spec;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
class RealtimePolicyTest {
|
||||
@Test void retryRequiresConfirmedTerminalWithoutCheckpoint(){
|
||||
for(String state:java.util.List.of("FAILED","CANCELED"))
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,1,null),"RETRY")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("UNKNOWN","RUNNING","SUBMITTING","STOPPING","READY","SUCCEEDED","ARCHIVED"))
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",1,"1041"),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("FAILED",0,null),"RETRY")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void recreateOnlyUnknownWithoutCheckpoint() {
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RECREATE")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("RUNNING","SUBMITTING","STOPPING","DRAFT","ARCHIVED"))
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"RECREATE")).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"458"),"RECREATE")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void refreshPreservesConfirmedTerminalEvidenceButNeverMasksLiveOrDeleteResult(){
|
||||
var missing=new cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Result("UNKNOWN","10","历史记录不可查询",null,null,null);
|
||||
var saved=RealtimeService.retainConfirmedTerminal("REFRESH",row("CANCELED",1,"458"),missing);
|
||||
assertThat(saved.status()).isEqualTo("CANCELED");
|
||||
assertThat(saved.checkpointId()).isEqualTo("458");
|
||||
assertThat(saved.summary()).contains("历史记录","本次引擎状态未能核实");
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("REFRESH",row("RUNNING",1,"458"),missing)).isSameAs(missing);
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("DELETE",row("CANCELED",1,"458"),missing)).isSameAs(missing);
|
||||
var live=new cn.aixunkeji.datagov.integration.api.RealtimeCollectionService.Result("RUNNING","10",null,null,null,null);
|
||||
assertThat(RealtimeService.retainConfirmedTerminal("REFRESH",row("CANCELED",1,"458"),live)).isSameAs(live);
|
||||
}
|
||||
@Test void deleteOnlyDraftOrConfirmedTerminalAndCannotResurrectDeletedTask(){
|
||||
for(String state:java.util.List.of("DRAFT","READY"))
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,0,null),"DELETE")).doesNotThrowAnyException();
|
||||
for(String state:java.util.List.of("FAILED","CANCELED","SUCCEEDED")) {
|
||||
assertThatCode(()->RealtimeService.allowed(row(state,1,null),"DELETE")).doesNotThrowAnyException();
|
||||
assertThat(RealtimeService.terminal(state)).isTrue();
|
||||
}
|
||||
for(String state:java.util.List.of("RUNNING","UNKNOWN","SUBMITTING","STOPPING","PENDING","ARCHIVED")) {
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row(state,1,null),"DELETE")).isInstanceOf(RuntimeException.class);
|
||||
assertThat(RealtimeService.terminal(state)).isFalse();
|
||||
}
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("ARCHIVED",1,null),"REFRESH")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
static RealtimeService.Row row(String status,long attempt,String checkpoint){return new RealtimeService.Row(1,2,3,null,status,0,attempt,null,"a".repeat(64),checkpoint,null,null,null,null,null);}
|
||||
@Test void unknownJobCanOnlyBeRecoveredThroughGuardedSavepointPath(){
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"START")).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,"1"),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("RUNNING",1,"1"),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
}
|
||||
@Test void resumeRequiresTerminalAndCheckpoint(){
|
||||
assertThatThrownBy(()->RealtimeService.allowed(row("CANCELED",1,null),"RESUME")).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.allowed(row("CANCELED",1,"2"),"RESUME")).doesNotThrowAnyException();
|
||||
assertThatCode(()->RealtimeService.allowed(row("UNKNOWN",1,null),"REFRESH")).doesNotThrowAnyException();
|
||||
}
|
||||
@Test void rejectsSqlIdentifiersAndMissingHttpPort(){
|
||||
assertThatThrownBy(()->RealtimeService.validate(spec("orders;DROP TABLE x",8030))).isInstanceOf(RuntimeException.class);
|
||||
assertThatThrownBy(()->RealtimeService.validate(spec("orders",0))).isInstanceOf(RuntimeException.class);
|
||||
assertThatCode(()->RealtimeService.validate(spec("orders",8030))).doesNotThrowAnyException();
|
||||
}
|
||||
static Spec spec(String table,int port){return new Spec("同步",1,0,"sales",table,2,3,"orders",port,"initial",30,1001);}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package cn.aixunkeji.datagov.dataops.storage;
|
||||
|
||||
import cn.aixunkeji.common.satoken.utils.LoginHelper;
|
||||
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceView;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.List;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
class StorageSelectionDetailTest {
|
||||
@Test void selectionDoesNotLoadTelemetryHistoryAndPreservesScope() {
|
||||
var repository=mock(StorageResourceRepository.class);
|
||||
var service=new StorageResourceService(repository,mock(StorageTelemetryGateway.class),mock(StorageManagedCredentialGateway.class));
|
||||
var actor=new StorageActor(10,20,false);
|
||||
var resource=mock(StorageResourceView.class);
|
||||
when(repository.requireResource(actor,30)).thenReturn(resource);
|
||||
when(repository.spaces(30)).thenReturn(List.of());
|
||||
try(var login=mockStatic(LoginHelper.class)) {
|
||||
login.when(LoginHelper::getUserId).thenReturn(10L);
|
||||
login.when(LoginHelper::getDeptId).thenReturn(20L);
|
||||
assertThat(service.selectionDetail(30).resource()).isSameAs(resource);
|
||||
verify(repository).requireResource(actor,30);
|
||||
verify(repository).spaces(30);
|
||||
verify(repository).accessProfile(30);
|
||||
verifyNoMoreInteractions(repository);
|
||||
}
|
||||
}
|
||||
@Test void deniedResourceNeverReadsSpacesOrCredentials() {
|
||||
var repository=mock(StorageResourceRepository.class);
|
||||
var service=new StorageResourceService(repository,mock(StorageTelemetryGateway.class),mock(StorageManagedCredentialGateway.class));
|
||||
when(repository.requireResource(any(),eq(30L))).thenThrow(new StorageScopeException());
|
||||
try(var login=mockStatic(LoginHelper.class)) {
|
||||
login.when(LoginHelper::getUserId).thenReturn(10L);
|
||||
assertThatThrownBy(()->service.selectionDetail(30)).isInstanceOf(StorageScopeException.class);
|
||||
verify(repository).requireResource(any(),eq(30L));
|
||||
verifyNoMoreInteractions(repository);
|
||||
}
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package cn.aixunkeji.datagov.dataops.tablefile;
|
||||
|
||||
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.*;
|
||||
import cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.jdbc.core.*;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
class TableFileRecreationTest {
|
||||
@BeforeAll static void beans() { TableFileBindingRepositoryTest.beans(); }
|
||||
final JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
final TableFileBindingRepositoryTest.Transactions manager = spy(new TableFileBindingRepositoryTest.Transactions());
|
||||
final TableFileRepository repository = spy(new TableFileRepository(jdbc, new TransactionTemplate(manager)));
|
||||
final TableFileActorProvider.TableFileActor actor = new TableFileActorProvider.TableFileActor(10,20,false);
|
||||
final List<String> writes = new ArrayList<>();
|
||||
final TableFileView table = new TableFileView(500L,"orders",ObjectType.TABLE,20L,200L,300L,400L,
|
||||
EngineType.DORIS,StorageFormat.DORIS_NATIVE,"internal","sales",null,"internal.sales.orders",null,
|
||||
ExecutionState.CONFIRMED,null,null,4,LocalDateTime.now(),LocalDateTime.now(),"CREATED");
|
||||
final TableFileDetailView before = new TableFileDetailView(table,List.of(),null,null,
|
||||
PolicyExecutionState.NOT_REQUESTED,List.of(),null);
|
||||
|
||||
@BeforeEach @SuppressWarnings({"unchecked", "rawtypes"}) void setup() throws Exception {
|
||||
doReturn(List.of(new StorageReferenceGuard.Identity(300,20,0,"0",null)))
|
||||
.when(jdbc).query(contains("FROM store_resource"),any(RowMapper.class),any(Object[].class));
|
||||
doReturn(List.of(new StorageReferenceGuard.Identity(400,20,0,"0",300L)))
|
||||
.when(jdbc).query(contains("FROM store_space"),any(RowMapper.class),any(Object[].class));
|
||||
doReturn(List.of(500L)).when(jdbc).query(startsWith("SELECT table_file_id FROM store_table_file"),
|
||||
any(RowMapper.class),any(Object[].class));
|
||||
doReturn(before).when(repository).requireDetail(actor,500L);
|
||||
when(jdbc.query(contains("FROM store_table_file t WHERE t.table_file_id"),any(RowMapper.class),any(Object[].class)))
|
||||
.thenAnswer(call -> {
|
||||
var rs = mock(java.sql.ResultSet.class);
|
||||
when(rs.getString("object_type")).thenReturn("TABLE");
|
||||
when(rs.getString("engine_type")).thenReturn("DORIS");
|
||||
when(rs.getString("storage_format")).thenReturn("DORIS_NATIVE");
|
||||
when(rs.getString("execution_state")).thenReturn("CONFIRMED");
|
||||
when(rs.getString("policy_execution_state")).thenReturn("NOT_REQUESTED");
|
||||
return List.of(((RowMapper)call.getArgument(1)).mapRow(rs,0));
|
||||
});
|
||||
when(jdbc.queryForObject(contains("COUNT(*)"),eq(Long.class),any(Object[].class))).thenReturn(0L);
|
||||
when(jdbc.update(anyString(),any(Object[].class))).thenAnswer(call -> {
|
||||
String sql = call.getArgument(0);
|
||||
assertThat(sql.chars().filter(c -> c == '?').count()).isEqualTo(call.getArguments().length - 1);
|
||||
writes.add(sql); return 1;
|
||||
});
|
||||
}
|
||||
|
||||
@Test void missingTargetReusesIdentityAndPreservesHistoryWithAtomicCommandBinding() {
|
||||
var result = repository.reserveCommandCreate(actor,"recreate-0001","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> {
|
||||
assertThat(writes).anyMatch(sql -> sql.contains("INSERT INTO store_table_file_snapshot"));
|
||||
});
|
||||
assertThat(result.tableFileId()).isEqualTo(500L);
|
||||
assertThat(result.replayed()).isFalse();
|
||||
assertThat(writes).noneMatch(sql -> sql.contains("DELETE FROM") || sql.startsWith("INSERT INTO store_table_file("));
|
||||
assertThat(writes).anyMatch(sql -> sql.contains("TARGET_RECREATE_PENDING") && sql.contains("version=version+1"));
|
||||
verify(manager).commit(any());
|
||||
}
|
||||
|
||||
@Test void concurrentOrUnknownPreviousOperationPreventsAnotherCreate() {
|
||||
when(jdbc.queryForObject(contains("COUNT(*)"),eq(Long.class),any(Object[].class))).thenReturn(1L);
|
||||
assertThatThrownBy(() -> repository.reserveCommandCreate(actor,"recreate-0002","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> fail("must not bind")))
|
||||
.isInstanceOf(TableFileErrors.Conflict.class).hasMessageContaining("结果待确认");
|
||||
assertThat(writes).isEmpty();
|
||||
verify(manager).rollback(any());
|
||||
}
|
||||
|
||||
@Test void failedCommandBindingRollsBackRecreationReservation() {
|
||||
assertThatThrownBy(() -> repository.reserveCommandCreate(actor,"recreate-0003","hash",
|
||||
TableFileBindingRepositoryTest.selection(), request -> { throw new IllegalStateException("lost command CAS"); }))
|
||||
.hasMessage("lost command CAS");
|
||||
verify(manager).rollback(any());
|
||||
verify(manager,never()).commit(any());
|
||||
}
|
||||
|
||||
@Test void delayedOldCompletionCannotOverwriteNewRegistration() {
|
||||
doReturn(0).when(jdbc).update(startsWith("UPDATE store_table_file_request SET request_status"),any(Object[].class));
|
||||
repository.completeMutation(actor,new TableFileRepository.Reservation(1,"old",500,false,"CREATE"),
|
||||
ExecutionState.CONFIRMED,false,"old-object",null,null,LocalDateTime.now());
|
||||
assertThat(writes).isEmpty();
|
||||
}
|
||||
|
||||
@Test void compatibleLiveTargetRefreshesColumnsAndAddsSnapshotWithoutDdl() {
|
||||
repository.synchronizeCommandTarget(actor,300,400,EngineType.DORIS,"internal","sales","orders",
|
||||
TableFileBindingRepositoryTest.selection().columns());
|
||||
assertThat(writes).hasSize(3);
|
||||
assertThat(writes.getFirst()).contains("columns_json=?", "execution_state='CONFIRMED'");
|
||||
assertThat(writes.getLast()).contains("store_table_file_snapshot");
|
||||
}
|
||||
}
|
||||
+14
@@ -161,6 +161,20 @@ class TableFileServiceTest {
|
||||
storage, layers, integration);
|
||||
private final TableFileActor actor = new TableFileActor(10L, 20L, false);
|
||||
|
||||
@Test void onlyExplicitLiveAbsencePermitsRecreation() {
|
||||
when(integration.browse(any())).thenReturn(new TableFileIntegrationService.DirectoryResult(
|
||||
TableFileIntegrationService.State.REJECTED,List.of(),List.of(),0,"目标表已确认不存在",true));
|
||||
assertThatThrownBy(() -> service.targetDirectory(300,400,EngineType.HIVE,"orders",null,1,20))
|
||||
.isInstanceOf(TableFileErrors.MissingTarget.class);
|
||||
for (var state : List.of(TableFileIntegrationService.State.REJECTED,TableFileIntegrationService.State.UNKNOWN)) {
|
||||
when(integration.browse(any())).thenReturn(new TableFileIntegrationService.DirectoryResult(
|
||||
state,List.of(),List.of(),0,"权限不足或连接失败"));
|
||||
assertThatThrownBy(() -> service.targetDirectory(300,400,EngineType.HIVE,"orders",null,1,20))
|
||||
.isExactlyInstanceOf(TableFileErrors.Reference.class);
|
||||
}
|
||||
org.mockito.Mockito.verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void references() {
|
||||
when(actorProvider.current()).thenReturn(actor);
|
||||
|
||||
+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(),
|
||||
|
||||
+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();
|
||||
|
||||
+51
-16
@@ -10,44 +10,79 @@ 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,
|
||||
'method',g.http_method,'path',g.relative_path,'auth',g.auth_modes_json,'issuer',g.issuer,'audience',g.audience,
|
||||
'scopes',g.caller_scopes_json,'secret',g.secret_ref,'traffic',g.traffic_policy_json,'security',g.security_requirements_json,
|
||||
'policyStatus',g.policy_status,'applicationStatus',g.application_status) AS CLOB),DBMS_CRYPTO.HASH_SH256))) AS stored_sha,
|
||||
LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(JSON_OBJECT('apiId' VALUE g.api_id,'apiVersion' VALUE g.api_version,'model' VALUE g.model_sha256,'schema' VALUE g.dataset_schema_sha256,
|
||||
'method' VALUE g.http_method,'path' VALUE g.relative_path,'auth' VALUE g.auth_modes_json,'issuer' VALUE g.issuer,'audience' VALUE g.audience,
|
||||
'scopes' VALUE g.caller_scopes_json,'secret' VALUE g.secret_ref,'traffic' VALUE g.traffic_policy_json,'security' VALUE g.security_requirements_json,
|
||||
'policyStatus' VALUE g.policy_status,'applicationStatus' VALUE g.application_status) AS CLOB),DBMS_CRYPTO.HASH_SH256))) AS stored_sha,
|
||||
g.auth_modes_json AS auth_json,g.traffic_policy_json AS traffic_json,g.security_requirements_json AS security_json,
|
||||
(NULLIF(TRIM(g.issuer),'') IS NOT NULL) AS issuer_configured,
|
||||
(NULLIF(TRIM(g.audience),'') IS NOT NULL) AS audience_configured,
|
||||
(NULLIF(TRIM(g.secret_ref),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.issuer),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.audience),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.secret_ref),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(TRIM(scope_value) AS CLOB),DBMS_CRYPTO.HASH_SH256))) END),JSON_ARRAY())
|
||||
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,
|
||||
CASE WHEN NULLIF(TRIM(g.issuer),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.audience),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN NULLIF(TRIM(g.secret_ref),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
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,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.authModes') AS auth_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.traffic') AS traffic_json,
|
||||
JSON_EXTRACT(s.policy_payload_json,'$.security') AS security_json,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL) AS issuer_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL) AS audience_configured,
|
||||
(JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL) AS secret_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE LOWER(RAWTOHEX(DBMS_CRYPTO.HASH(CAST(TRIM(scope_value) AS CLOB),DBMS_CRYPTO.HASH_SH256))) END),JSON_ARRAY())
|
||||
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,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.issuer'))),'') IS NOT NULL THEN 1 ELSE 0 END AS issuer_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.audience'))),'') IS NOT NULL THEN 1 ELSE 0 END AS audience_configured,
|
||||
CASE WHEN JSON_TYPE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))='STRING' AND NULLIF(TRIM(JSON_UNQUOTE(JSON_EXTRACT(s.policy_payload_json,'$.secretRef'))),'') IS NOT NULL THEN 1 ELSE 0 END AS secret_configured,
|
||||
(SELECT COALESCE(JSON_ARRAYAGG(CASE WHEN LENGTH(TRIM(scope_value))=0
|
||||
THEN 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
|
||||
ELSE SHA2(TRIM(scope_value),256) END),JSON_ARRAY())
|
||||
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;
|
||||
|
||||
+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){
|
||||
|
||||
+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;}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# 达梦、金仓原生 CDC 交付记录
|
||||
|
||||
2026-11-24 更新:达梦归档窗口已改为连续分批推进,取消累计 2000 文件上限;本地插件及页面已发布,原任务从保存点 67 恢复后完成检查点 68–70。详见 `evidence/dameng-window-20261124.md`(项目根目录)。下文原始发布记录保留其当时验收边界。
|
||||
|
||||
2026-11-23,用户授权“继续补齐达梦和金仓的功能”。自研插件运行在现有 SeaTunnel 2.3.13,不新增常驻服务,不依赖 DMHS、FlySync 或 Kafka。代码、部署和真实业务验收分别记录。
|
||||
|
||||
## 实现
|
||||
|
||||
- Dameng-Native-CDC:通过 DBMS_LOGMNR 读取达梦归档日志;Kingbase-Native-CDC:通过金仓 JDBC 复制协议读取 test_decoding 槽。
|
||||
- 增删改转为 SeaTunnel RowKind,沿用 Doris Unique Key、删除及两阶段提交。
|
||||
- initial:保存日志低水位,按组合主键每页读取 500 行,分页位置与日志起点一起进入检查点;完成快照后重放扫描期间的日志。追平前可能暂时看到旧值,不能将快照中间状态作为一致性验收。
|
||||
- latest:达梦从启动时 CUR_LSN 开始;金仓从专用复制槽确认位置继续,页面明确区分语义。
|
||||
- 检查点保存位置、数据库身份、结构/主键签名、快照分页位置和归档清单;金仓仅在成功检查点后反馈 WAL。缺日志、换库、结构变化时停止,不自动跳过。
|
||||
- 页面、任务生成、只读前置检查、中文错误提示已接入。日志通道改为可选,现有 MySQL/Oracle/SQL Server 路径保留。
|
||||
- 新增 realtime-ingestions/source-options,复用组织授权目录,保留凭据和连接成功限制;实时采集不再使用批量采集试点 ID 名单。批量入口规则不变。
|
||||
|
||||
## 支持边界与剩余工作
|
||||
|
||||
1. 单表、并行度 1、有主键;目标列名及顺序一致,Doris Unique Key 与源主键一致。首次全量目标必须为空,恢复沿用原检查点。
|
||||
2. 普通数字、字符串、日期时间;小数精度不超过 38。LOB、二进制、数组、带时区字段和自动 DDL 不支持,校验拒绝。标识符限字母、数字、下划线、美元符和井号。
|
||||
3. 达梦按检查点连续推进归档窗口,每轮最多加入 64 个新文件,另外保留未结束事务需要的旧文件及边界文件;不再限制累计历史文件为 2000。缺失所需日志、事务边界或提交位置无法确认时停止,不跳到最新日志。仅缩小插件读取范围,不删除源库归档;每批约 20000 行和查询超时限制仍保留。归档生成频率决定同步延迟。真实长事务及跨重启仍需验收。
|
||||
4. 金仓单事务最多 10000 变更事件。实际版本的系统视图、复制协议和提交位置语义需真实源库验收。
|
||||
5. 真实源库断网、跨重启恢复和数据一致性未验收,不以序列化测试推导业务 exactly-once。
|
||||
|
||||
## 源库准备
|
||||
|
||||
- 达梦:本地归档,ARCH_INI=1、RLOG_APPEND_LOGIC=2、RLOG_LLOG_COMPRESS=0、LOGMNR_DELAY_ANALYZE=0,源表/日志视图/LogMiner 权限。程序不自动调整全局参数或授权。
|
||||
- 金仓:wal_level=logical、源表 REPLICA IDENTITY FULL、复制权限和专用 test_decoding 槽。槽名由源 ID/架构/表的 SHA-256 稳定生成,校验提示具体名称,由 DBA 预建;不能共用或提前推进。
|
||||
- 页面已确认“企管_达梦”连接成功,可列出 ENTERPRISE_MANAGEMENT 的 10 张表。当前授权目录无金仓数据源。此前平台测试库的日志参数检查不能代替此业务源检查。
|
||||
|
||||
依据:[达梦 LogMiner 官方说明](https://eco.dameng.com/document/dm/zh-cn/pm/dbms_logmnr-package)、[达梦日志视图](https://eco.dameng.com/document/dm/zh-cn/pm/dm8-admin-manual-appendix2.html)。金仓使用现有官方驱动的 KBConnection/KBReplicationStream API,兼容性以实际版本测试为准。
|
||||
|
||||
## 验证
|
||||
|
||||
- PASS:独立 Java 8 插件构建,14 项测试,含完整事务、失败检查点不反馈、组合主键分页续读、结束快照保持日志低水位。
|
||||
- PASS:后端定向测试及新增目录测试。原批次有 8 项数据库/进程测试跳过,未计作通过。
|
||||
- PASS:前端定向 lint 和生产构建。前端制品首次比对仅发现 Finder 的 .DS_Store 差异,清理该文件后比对通过。
|
||||
- PASS:实际 SeaTunnel 2.3.13 离线发现两个插件及驱动;镜像包含插件映射。
|
||||
- NOT_RUN:真实金仓;达梦/金仓增删改落库、事务回滚、快照期间写入、长事务、跨重启及完整人工 UAT。未执行业务源 DML、DDL 或全局参数调整。
|
||||
|
||||
构建入口:script/quality/check.sh --native-cdc。插件 JAR 位于本模块 target/;Docker 构建使用 --build-context native_cdc=aixun-modules/aixun-integration/seatunnel-native-cdc/target,避免重复复制 JAR。
|
||||
|
||||
## 发布与恢复
|
||||
|
||||
应用服务使用 script/datagov/deploy.sh;SeaTunnel 使用现有 deploy-seatunnel-cdc.py,在无运行/待提交任务时更换镜像,保留网络、IP、端口、挂载和秘密。无需迁移。
|
||||
|
||||
本地发布 PASS(制品读回、配置保持通过):
|
||||
|
||||
| 服务 | 最终镜像标签 | image ID 前缀 |
|
||||
| --- | --- | --- |
|
||||
| SeaTunnel | 2.3.13-native-vendor-20261123-r3 | d6104ac41277 |
|
||||
| integration | native-vendor-cdc-20261123-r3 | 36520937a13b |
|
||||
| dataops | native-vendor-cdc-20261123 | 8d4c7594844d |
|
||||
| frontend | native-vendor-cdc-20261123-r3 | 81059f83dfdc |
|
||||
|
||||
17:54 Browser 实测:达梦选项可选、默认架构带入、全量选项可用;创建“达梦CDC前置校验(未启动)”并执行只读 CHECK,实际业务源返回 **ARCH_INI 应为 1,当前为 0**。外部作业为空,未启动写入。草稿目标 cdc_dm_probe 仅是校验占位,未创建该表;正式测试前须编辑为真实兼容目标表。截图:evidence/native-cdc-20261123.png。
|
||||
|
||||
真实 CDC 验收 BLOCKED:业务达梦未启用归档,当前无金仓数据源;未调整业务库全局配置。源码/本地发布 PASS_WITH_LIMITATION,仍有上文归档窗口长期运行缺口,不报告“全部完成”。
|
||||
|
||||
应用恢复引用各服务发布结果中的 recoveryImageId(integration c3e40cd9f6d7、dataops a85f41c94e47、frontend fed48622ed22);SeaTunnel 可恢复本次工作前的 2.3.13-cdc-complete-20261123(f9a236287c22)。不删除源表、目标表、数据卷和检查点。
|
||||
|
||||
2026-11-24 Oracle 更新:已补齐官方 Oracle-CDC 2.3.13 的 CDB/PDB 配置、前置检查及元数据/快照会话适配;真实 Oracle 端到端仍为 NOT_RUN。详见项目根目录 evidence/oracle-pdb-20261124.md。
|
||||
@@ -0,0 +1,16 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>cn.aixunkeji.datagov.integration</groupId>
|
||||
<artifactId>connector-aixun-native-cdc</artifactId>
|
||||
<version>2.3.13-1</version>
|
||||
<properties><maven.compiler.release>8</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||
<dependencies>
|
||||
<dependency><groupId>com.kingbase8</groupId><artifactId>kingbase8</artifactId><version>9.0.1.jre7</version><scope>system</scope><systemPath>${project.basedir}/../../../script/datagov/m2/seatunnel/local/artifacts/kingbase8-9.0.1.jre7.jar</systemPath></dependency>
|
||||
<dependency><groupId>org.apache.seatunnel</groupId><artifactId>seatunnel-api</artifactId><version>2.3.13</version><scope>provided</scope></dependency>
|
||||
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.12.2</version><scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
<build><plugins>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.15.0</version></plugin>
|
||||
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.5.3</version></plugin>
|
||||
</plugins></build>
|
||||
</project>
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Transaction framing independent of driver or engine, with a hard memory limit. */
|
||||
public final class CommittedBatch {
|
||||
public static final class Transaction {
|
||||
public final String lsn;
|
||||
public final List<KingbaseChangeDecoder.Change> changes;
|
||||
Transaction(String lsn,List<KingbaseChangeDecoder.Change> changes){this.lsn=lsn;this.changes=Collections.unmodifiableList(changes);}
|
||||
}
|
||||
private final KingbaseChangeDecoder decoder=new KingbaseChangeDecoder();
|
||||
private final int maxChanges;
|
||||
private List<KingbaseChangeDecoder.Change> pending;
|
||||
private String xid;
|
||||
public CommittedBatch(int maxChanges){if(maxChanges<1)throw new IllegalArgumentException();this.maxChanges=maxChanges;}
|
||||
public Transaction accept(String lsn,String message){
|
||||
LogPosition.lsn(lsn);
|
||||
if(message.matches("BEGIN [0-9]+")){
|
||||
if(pending!=null)throw new IllegalArgumentException("Overlapping transactions");
|
||||
xid=message.substring(6);pending=new ArrayList<>();return null;
|
||||
}
|
||||
if(message.startsWith("COMMIT ")){
|
||||
if(pending==null||!message.equals("COMMIT "+xid))throw new IllegalArgumentException("Mismatched commit");
|
||||
Transaction result=new Transaction(lsn,pending);pending=null;xid=null;return result;
|
||||
}
|
||||
if(pending==null)throw new IllegalArgumentException("Change outside transaction");
|
||||
if(pending.size()>=maxChanges)throw new IllegalArgumentException("Transaction exceeds configured change limit");
|
||||
pending.add(decoder.decode(message));return null;
|
||||
}
|
||||
public void requireComplete(){if(pending!=null)throw new IllegalArgumentException("Incomplete transaction; no position acknowledged");}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Inclusive DM LSN ranges; sequence continuity, not an assumed LSN increment, detects gaps. */
|
||||
final class DamengArchiveWindow {
|
||||
static final int NEW_FILES_PER_POLL=64;
|
||||
static final class File {
|
||||
final String name;
|
||||
final long sequence,first,last;
|
||||
File(String name,long sequence,long first,long last) {
|
||||
if(name==null||name.isEmpty()||first<0||last<first)throw new IllegalArgumentException("达梦归档元数据不完整");
|
||||
this.name=name;this.sequence=sequence;this.first=first;this.last=last;
|
||||
}
|
||||
}
|
||||
static List<File> select(List<File> catalog,NativeLogSource.Split state) {
|
||||
if(catalog.isEmpty())throw new IllegalArgumentException("达梦没有可挖掘的归档日志");
|
||||
catalog=new ArrayList<>(catalog);catalog.sort(Comparator.comparingLong(f->f.sequence));
|
||||
int start=0;
|
||||
if(state.anchor!=null) {
|
||||
start=-1;
|
||||
for(int i=0;i<catalog.size();i++)if(state.anchor.equals(catalog.get(i).name)){start=i;break;}
|
||||
if(start<0)throw new IllegalArgumentException("恢复所需起始归档已清理,禁止跳过日志");
|
||||
}
|
||||
Set<String> names=new HashSet<>();for(File f:catalog)names.add(f.name);
|
||||
if(!names.containsAll(state.archives))throw new IllegalArgumentException("检查点所需归档存在缺口,停止采集");
|
||||
List<File> result=new ArrayList<>();int fresh=0;File previous=null;
|
||||
for(int i=start;i<catalog.size();i++) {
|
||||
File f=catalog.get(i);
|
||||
// The next window includes pinned old files plus at most 64 newly scanned files.
|
||||
if(state.archiveSequence==null || f.sequence>state.archiveSequence) {
|
||||
if(fresh==NEW_FILES_PER_POLL)break;
|
||||
fresh++;
|
||||
}
|
||||
if(previous!=null&&(f.sequence!=previous.sequence+1||f.first<previous.first||f.last<previous.last))
|
||||
throw new IllegalArgumentException("达梦归档序号不连续或存在重复归档,禁止跳过日志");
|
||||
result.add(f);previous=f;
|
||||
}
|
||||
if(state.archiveSequence!=null && result.get(result.size()-1).sequence<state.archiveSequence)
|
||||
throw new IllegalArgumentException("检查点之后的归档记录发生回退");
|
||||
return result;
|
||||
}
|
||||
static List<File> retain(List<File> scanned,Long earliestOpen) {
|
||||
int index=scanned.size()-1; // Keep the boundary file to validate continuity on the next poll.
|
||||
if(earliestOpen!=null) {
|
||||
index=-1;
|
||||
for(int i=0;i<scanned.size();i++) {
|
||||
File f=scanned.get(i);
|
||||
if(f.first<=earliestOpen && f.last>=earliestOpen){index=i;break;}
|
||||
}
|
||||
if(index<0)throw new IllegalArgumentException("未结束事务的起始归档不完整,禁止推进日志范围");
|
||||
}
|
||||
return new ArrayList<>(scanned.subList(index,scanned.size()));
|
||||
}
|
||||
static List<String> names(List<File> files){List<String> names=new ArrayList<>();for(File f:files)names.add(f.name);return names;}
|
||||
|
||||
/** Rebuilt from the pinned prefix on every poll, so in-flight transactions need no row buffer. */
|
||||
static final class Transactions {
|
||||
final Map<String,Long> open=new HashMap<>();
|
||||
final Set<String> missingStart=new HashSet<>();
|
||||
final Set<String> missingCommit=new HashSet<>();
|
||||
final Set<String> committed=new HashSet<>();
|
||||
final long first,cutoff,end;
|
||||
Transactions(long first,long cutoff){this(first,cutoff,Long.MAX_VALUE);}
|
||||
Transactions(long first,long cutoff,long end){this.first=first;this.cutoff=cutoff;this.end=end;}
|
||||
void accept(String xid,String operation,long scn,Long start,Long commit,boolean target) {
|
||||
if("INTERNAL".equals(operation))return;
|
||||
if(xid==null||xid.isEmpty())throw new IllegalArgumentException("日志缺少事务标识,不能安全推进归档范围");
|
||||
if(start!=null && start>0 && start<=scn && start>=first)open.merge(xid,start,Math::min);
|
||||
if("START".equals(operation)) {open.put(xid,scn);missingStart.remove(xid);committed.remove(xid);missingCommit.remove(xid);return;}
|
||||
if(!open.containsKey(xid)) {open.put(xid,scn);missingStart.add(xid);}
|
||||
if(target && (commit==null||commit<=0))missingCommit.add(xid);
|
||||
if(target && commit!=null && commit>cutoff && (missingStart.contains(xid)||(start!=null&&start>0&&start<first)))
|
||||
throw new IllegalArgumentException("待同步事务的起始日志缺失,禁止输出不完整事务");
|
||||
if(commit!=null&&commit>0&&commit<=end)committed.add(xid);
|
||||
if("COMMIT".equals(operation)||"ROLLBACK".equals(operation)||"XA_COMMIT".equals(operation)) {
|
||||
if(!"ROLLBACK".equals(operation)&&scn>cutoff&&missingCommit.contains(xid))
|
||||
throw new IllegalArgumentException("达梦未返回完整提交位置,禁止跳过已提交变更");
|
||||
open.remove(xid);missingStart.remove(xid);missingCommit.remove(xid);
|
||||
}
|
||||
}
|
||||
Long earliestOpen() {
|
||||
for(String xid:committed){
|
||||
if(missingCommit.contains(xid))throw new IllegalArgumentException("达梦提交位置不完整,禁止推进归档范围");
|
||||
open.remove(xid);missingStart.remove(xid);
|
||||
}
|
||||
if(!missingStart.isEmpty())throw new IllegalArgumentException("未结束事务缺少起始日志,不能安全推进归档范围");
|
||||
return open.isEmpty()?null:Collections.min(open.values());
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
import org.apache.seatunnel.api.source.SeaTunnelSource;
|
||||
import org.apache.seatunnel.api.table.factory.TableSourceFactory;
|
||||
import org.apache.seatunnel.api.configuration.util.OptionRule;
|
||||
public final class DamengFactory implements TableSourceFactory {
|
||||
public String factoryIdentifier(){return "Dameng-Native-CDC";}
|
||||
public Class<? extends SeaTunnelSource> getSourceClass(){return DamengSource.class;}
|
||||
public OptionRule optionRule(){return OptionRule.builder().build();}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
public final class DamengSource extends NativeLogSource {
|
||||
public String getPluginName(){return "Dameng-Native-CDC";}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/** Strict decoder for the test_decoding text contract; unknown messages fail closed. */
|
||||
public final class KingbaseChangeDecoder {
|
||||
public static final class Change {
|
||||
public final String schema,table,operation;
|
||||
public final Map<String,String> before,after;
|
||||
Change(String schema,String table,String operation,Map<String,String> before,Map<String,String> after){
|
||||
this.schema=schema;this.table=table;this.operation=operation;this.before=before;this.after=after;
|
||||
}
|
||||
}
|
||||
public Change decode(String text) {
|
||||
Cursor c=new Cursor(text);c.expect("table ");String schema=c.identifier();c.expect(".");
|
||||
String table=c.identifier();c.expect(": ");String op=c.until(':');c.expect(":");c.space();
|
||||
Map<String,String> old=Collections.emptyMap(), next=Collections.emptyMap();
|
||||
switch(op){
|
||||
case "INSERT": next=c.fields(false);break;
|
||||
case "DELETE": old=c.fields(false);break;
|
||||
case "UPDATE":
|
||||
c.expect("old-key: ");old=c.fields(true);c.expect("new-tuple: ");next=c.fields(false);break;
|
||||
default: throw new IllegalArgumentException("Unsupported logical operation (including TRUNCATE)");
|
||||
}
|
||||
c.space();if(!c.end())throw new IllegalArgumentException("Unparsed logical message");
|
||||
return new Change(schema,table,op,old,next);
|
||||
}
|
||||
private static final class Cursor {
|
||||
final String text;int pos;
|
||||
Cursor(String text){this.text=Objects.requireNonNull(text);}
|
||||
boolean end(){return pos==text.length();}
|
||||
void space(){while(!end()&&text.charAt(pos)==' ')pos++;}
|
||||
void expect(String s){if(!text.startsWith(s,pos))throw new IllegalArgumentException("Unsupported logical decoding syntax");pos+=s.length();}
|
||||
String until(char ch){int start=pos;while(!end()&&text.charAt(pos)!=ch)pos++;if(end())throw new IllegalArgumentException("Truncated logical message");return text.substring(start,pos);}
|
||||
String quoted(char quote){
|
||||
pos++;StringBuilder result=new StringBuilder();
|
||||
while(!end()){
|
||||
char ch=text.charAt(pos++);
|
||||
if(ch==quote){if(!end()&&text.charAt(pos)==quote){pos++;result.append(ch);}else return result.toString();}
|
||||
else result.append(ch);
|
||||
}
|
||||
throw new IllegalArgumentException("Unterminated logical value");
|
||||
}
|
||||
String identifier(){
|
||||
if(!end()&&text.charAt(pos)=='"')return quoted('"');
|
||||
int start=pos;while(!end()&&(Character.isLetterOrDigit(text.charAt(pos))||"_$".indexOf(text.charAt(pos))>=0))pos++;
|
||||
if(start==pos)throw new IllegalArgumentException("Invalid logical identifier");return text.substring(start,pos);
|
||||
}
|
||||
Map<String,String> fields(boolean stopAtNew){
|
||||
Map<String,String> values=new LinkedHashMap<>();
|
||||
while(true){
|
||||
space();if(end()||stopAtNew&&text.startsWith("new-tuple: ",pos))return values;
|
||||
String name=identifier();expect("[");until(']');expect("]:");
|
||||
String value;
|
||||
if(!end()&&text.charAt(pos)=='\'')value=quoted('\'');
|
||||
else {int start=pos;while(!end()&&text.charAt(pos)!=' ')pos++;value=text.substring(start,pos);
|
||||
if("null".equals(value))value=null;
|
||||
else if(!value.matches("[-+0-9.eE]+|true|false|t|f"))throw new IllegalArgumentException("Unsupported logical value or unchanged TOAST");}
|
||||
if(values.containsKey(name))throw new IllegalArgumentException("Duplicate logical column");
|
||||
values.put(name,value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
import org.apache.seatunnel.api.source.SeaTunnelSource;
|
||||
import org.apache.seatunnel.api.table.factory.TableSourceFactory;
|
||||
import org.apache.seatunnel.api.configuration.util.OptionRule;
|
||||
public final class KingbaseFactory implements TableSourceFactory {
|
||||
public String factoryIdentifier(){return "Kingbase-Native-CDC";}
|
||||
public Class<? extends SeaTunnelSource> getSourceClass(){return KingbaseSource.class;}
|
||||
public OptionRule optionRule(){return OptionRule.builder().build();}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
public final class KingbaseSource extends NativeLogSource {
|
||||
public String getPluginName(){return "Kingbase-Native-CDC";}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package cn.aixunkeji.datagov.integration.cdc;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.math.BigInteger;
|
||||
|
||||
/** Committed position only. Never checkpoint a half-decoded transaction. */
|
||||
public final class LogPosition implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public final String position;
|
||||
public final String identity;
|
||||
public LogPosition(String position, String identity) {
|
||||
if (position == null || identity == null) throw new IllegalArgumentException("Missing log identity");
|
||||
this.position = position; this.identity = identity;
|
||||
}
|
||||
public static BigInteger lsn(String value) {
|
||||
if (value == null || !value.matches("[0-9A-Fa-f]{1,8}/[0-9A-Fa-f]{1,8}"))
|
||||
throw new IllegalArgumentException("Invalid WAL position");
|
||||
String[] parts=value.split("/");
|
||||
return new BigInteger(parts[0],16).shiftLeft(32).add(new BigInteger(parts[1],16));
|
||||
}
|
||||
}
|
||||
某些文件未显示,因为此 diff 中更改的文件太多 显示更多
在新工单中引用
屏蔽一个用户