Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.dataops;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
/** DataGov data ingestion, storage, development, and operations deployment unit. */
@EnableDubbo
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class AiXunDataOpsApplication {
public static void main(String[] args) {
SpringApplication.run(AiXunDataOpsApplication.class, args);
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class SqlProcessingSuggestionActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long orgId = LoginHelper.getDeptId();
if (actorId == null || orgId == null || actorId <= 0 || orgId <= 0) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
return new Actor(actorId, orgId, LoginHelper.isSuperAdmin(actorId));
}
record Actor(long actorId, long orgId, boolean unrestricted) {
/** The current RCP6 login context exposes department as the governing organization scope. */
long departmentId() {
return orgId;
}
}
}
@@ -0,0 +1,78 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.common.core.domain.PageResult;
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.dataops.api.aiassistant.SqlProcessingSuggestionApi.StateRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionView;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/ai-assistant/sql-processing/suggestions")
public class SqlProcessingSuggestionController {
private final SqlProcessingSuggestionService service;
@SaCheckPermission("aixun:ai:assistant:view")
@GetMapping
public R<PageResult<SuggestionView>> list(
@RequestParam(required = false) String status,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.list(status, pageNum, pageSize));
}
@SaCheckPermission("aixun:ai:assistant:view")
@GetMapping("/{suggestionId}")
public R<SuggestionView> detail(@PathVariable long suggestionId) {
return R.ok(service.detail(suggestionId));
}
@Log(title = "SQL与加工AI建议生成", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:ai:assistant:generate")
@PostMapping
public R<SuggestionView> generate(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody SuggestionRequest request
) {
return R.ok(service.generate(idempotencyKey, request));
}
@Log(title = "SQL与加工AI建议采纳", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:ai:assistant:adopt")
@PostMapping("/{suggestionId}/adopt")
public R<SuggestionView> adopt(
@PathVariable long suggestionId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody StateRequest request
) {
return R.ok(service.adopt(suggestionId, idempotencyKey, request));
}
@Log(title = "SQL与加工AI建议忽略", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:ai:assistant:adopt")
@PostMapping("/{suggestionId}/ignore")
public R<SuggestionView> ignore(
@PathVariable long suggestionId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody StateRequest request
) {
return R.ok(service.ignore(suggestionId, idempotencyKey, request));
}
}
@@ -0,0 +1,60 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import org.springframework.http.HttpStatus;
final class SqlProcessingSuggestionDomainException extends RuntimeException {
static final int VALIDATION_CODE = 126401;
static final int FORBIDDEN_CODE = 126403;
static final int NOT_FOUND_CODE = 126404;
static final int CONFLICT_CODE = 126409;
static final int EVIDENCE_CODE = 126422;
static final int PROVIDER_CODE = 126503;
private final int code;
private final HttpStatus status;
private SqlProcessingSuggestionDomainException(int code, HttpStatus status, String message) {
super(message);
this.code = code;
this.status = status;
}
static SqlProcessingSuggestionDomainException validation(String message) {
return new SqlProcessingSuggestionDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static SqlProcessingSuggestionDomainException forbidden() {
return new SqlProcessingSuggestionDomainException(
FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问SQL与加工建议"
);
}
static SqlProcessingSuggestionDomainException notFound() {
return new SqlProcessingSuggestionDomainException(
NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "SQL与加工建议不存在"
);
}
static SqlProcessingSuggestionDomainException conflict(String message) {
return new SqlProcessingSuggestionDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
static SqlProcessingSuggestionDomainException evidenceInsufficient() {
return new SqlProcessingSuggestionDomainException(
EVIDENCE_CODE, HttpStatus.UNPROCESSABLE_ENTITY, "证据不足,未生成建议草稿"
);
}
static SqlProcessingSuggestionDomainException provider(String message) {
return new SqlProcessingSuggestionDomainException(PROVIDER_CODE, HttpStatus.SERVICE_UNAVAILABLE, message);
}
int code() {
return code;
}
HttpStatus status() {
return status;
}
}
@@ -0,0 +1,110 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.datagov.dataops.aiassistant.SqlProcessingSuggestionActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRef;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionRequest;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.TrustedScopeColumn;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.TrustedScopeEvidence;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.TrustedScopeQuery;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.TrustedScopeState;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileTrustedScopeOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Resolves every requested reference from the current actor-scoped, confirmed table-file scope. */
@Component
@RequiredArgsConstructor
class SqlProcessingSuggestionEvidenceResolver {
private static final Pattern TABLE_REFERENCE = Pattern.compile("table-file:(\\d+)");
private static final Pattern COLUMN_REFERENCE = Pattern.compile(
"table-file:(\\d+)/column/([A-Za-z_][A-Za-z0-9_$-]{0,127})");
private static final Set<String> SUPPORTED_KINDS = Set.of("METADATA");
private static final Duration MAX_AGE = Duration.ofMinutes(5);
private final TableFileTrustedScopeOwner trustedScopeOwner;
List<EvidenceRef> resolve(Actor actor, SuggestionRequest request) {
if (actor == null || request == null || request.tableFileId() == null || request.tableFileId() <= 0) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
List<EvidenceRequest> requested = request.evidence();
if (requested == null || requested.isEmpty() || requested.size() > 32) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
long tableFileId = request.tableFileId();
TrustedScopeEvidence scope = trustedScopeOwner.resolve(new TrustedScopeQuery(
actor.actorId(), actor.orgId(), actor.departmentId(), tableFileId, null, null));
requireCurrentConfirmedScope(scope, tableFileId);
Set<String> seen = new HashSet<>();
List<EvidenceRef> resolved = requested.stream().map(item -> resolveOne(item, scope, tableFileId, seen)).toList();
if (resolved.size() != requested.size()) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
return List.copyOf(resolved);
}
private EvidenceRef resolveOne(EvidenceRequest request, TrustedScopeEvidence scope, long tableFileId,
Set<String> seen) {
if (request == null || request.reference() == null || request.kind() == null
|| !SUPPORTED_KINDS.contains(request.kind()) || !seen.add(request.reference())) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
Matcher table = TABLE_REFERENCE.matcher(request.reference());
if (table.matches()) {
requireSameTable(table.group(1), tableFileId);
return new EvidenceRef(request.reference(), request.kind(),
"已确认当前对象结构证据,版本 " + scope.sourceVersion() + ",字段数 " + scope.columns().size(),
scope.sourceVersion(), scope.observedAt(), scope.canonicalSha256());
}
Matcher column = COLUMN_REFERENCE.matcher(request.reference());
if (!column.matches()) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
requireSameTable(column.group(1), tableFileId);
TrustedScopeColumn resolvedColumn = scope.columns().stream()
.filter(value -> value != null && request.reference().equals(value.resourceRef()))
.findFirst()
.orElseThrow(SqlProcessingSuggestionDomainException::evidenceInsufficient);
return new EvidenceRef(request.reference(), request.kind(),
"已确认字段结构证据:" + resolvedColumn.name() + ",类型 " + resolvedColumn.type()
+ ",版本 " + scope.sourceVersion(),
scope.sourceVersion(), scope.observedAt(), scope.canonicalSha256());
}
private static void requireCurrentConfirmedScope(TrustedScopeEvidence scope, long tableFileId) {
if (scope == null || scope.state() != TrustedScopeState.CONFIRMED
|| scope.tableFileId() != tableFileId
|| scope.sourceVersion() == null || scope.sourceVersion() < 0
|| scope.observedAt() == null || scope.observedAt().isAfter(LocalDateTime.now().plusMinutes(1))
|| scope.observedAt().isBefore(LocalDateTime.now().minus(MAX_AGE))
|| scope.canonicalSha256() == null || !scope.canonicalSha256().matches("[0-9a-fA-F]{64}")
|| !sourceRef(tableFileId).equals(scope.sourceRef()) || scope.columns() == null) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
}
private static void requireSameTable(String rawId, long tableFileId) {
try {
if (Long.parseLong(rawId) != tableFileId) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
} catch (NumberFormatException exception) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
}
private static String sourceRef(long tableFileId) {
return "table-file:" + tableFileId;
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes = SqlProcessingSuggestionController.class)
class SqlProcessingSuggestionExceptionHandler {
@ExceptionHandler(SqlProcessingSuggestionDomainException.class)
ResponseEntity<R<Void>> handle(SqlProcessingSuggestionDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
@ExceptionHandler(DataIntegrityViolationException.class)
ResponseEntity<R<Void>> handleConstraintFailure(DataIntegrityViolationException exception) {
return ResponseEntity.status(409).body(R.fail(
SqlProcessingSuggestionDomainException.CONFLICT_CODE,
"建议状态未保存,请刷新后重试"
));
}
}
@@ -0,0 +1,228 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRef;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.StateRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionStatus;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.MapperFeature;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Component
class SqlProcessingSuggestionPolicy {
private static final Pattern IDEMPOTENCY_KEY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
private static final Pattern OBJECT_REF = Pattern.compile(
"[A-Za-z_][A-Za-z0-9_$-]{0,127}(?:\\.[A-Za-z_][A-Za-z0-9_$-]{0,127}){0,3}"
);
private static final Pattern SOURCE_OBJECT = Pattern.compile(
"(?i)\\b(?:from|join)\\s+([A-Za-z_][A-Za-z0-9_$-]{0,127}(?:\\.[A-Za-z_][A-Za-z0-9_$-]{0,127}){0,3})"
);
private static final Pattern FORBIDDEN_SQL = Pattern.compile(
"(?is)(?:;|--|/\\*|\\*/|`|\\$\\{|#\\{|\\b(?:insert|update|delete|drop|alter|create|truncate|merge|call|exec|execute|grant|revoke|load|outfile|dumpfile)\\b)"
);
private static final Pattern INJECTION = Pattern.compile(
"(?is)(?:ignore\\s+(?:all|any|previous)|system\\s+prompt|developer\\s+message|reveal\\s+(?:the\\s+)?(?:prompt|secret)|jailbreak|do\\s+not\\s+follow)"
);
private static final Pattern SENSITIVE = Pattern.compile(
"(?i)(?:password|passwd|token|secret|credential|authorization|private[_-]?key|access[_-]?key|jdbc:|connection[_-]?string)"
);
private static final Set<String> OBJECT_TYPES = Set.of("TABLE", "VIEW", "DATASET");
private final JsonMapper mapper;
SqlProcessingSuggestionPolicy(JsonMapper jsonMapper) {
this.mapper = jsonMapper.rebuild()
.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
.build();
}
SuggestionRequest normalize(SuggestionRequest raw) {
if (raw == null) throw SqlProcessingSuggestionDomainException.validation("建议请求不能为空");
String requestId = required(raw.requestId(), "请求标识", 128);
if (!IDEMPOTENCY_KEY.matcher(requestId).matches()) {
throw SqlProcessingSuggestionDomainException.validation("请求标识格式无效");
}
String objectRef = required(raw.objectRef(), "对象范围", 512);
if (!OBJECT_REF.matcher(objectRef).matches()) {
throw SqlProcessingSuggestionDomainException.validation("对象范围必须是未加引号的限定对象名");
}
String objectType = required(raw.objectType(), "对象类型", 32).toUpperCase(Locale.ROOT);
if (!OBJECT_TYPES.contains(objectType)) {
throw SqlProcessingSuggestionDomainException.validation("对象类型不受支持");
}
String instruction = text(raw.instruction(), "");
bounded(instruction, "建议说明", 2000);
rejectUntrustedText(instruction, "建议说明");
String sql = required(raw.sqlDraft(), "SQL草稿", 16_000);
String safeSql = safeSql(sql, objectRef);
String processing = required(raw.processingDraft(), "加工草稿", 4000);
rejectUntrustedText(processing, "加工草稿");
if (FORBIDDEN_SQL.matcher(processing).find()) {
throw SqlProcessingSuggestionDomainException.validation("加工草稿包含不可执行内容");
}
List<EvidenceRequest> evidence = normalizeEvidenceRequests(raw.evidence());
if (evidence.isEmpty()) throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
return new SuggestionRequest(requestId, objectRef, objectType, instruction, safeSql, processing, evidence,
raw.tableFileId());
}
String idempotencyKey(String value) {
String normalized = required(value, "幂等键", 128);
if (!IDEMPOTENCY_KEY.matcher(normalized).matches()) {
throw SqlProcessingSuggestionDomainException.validation("幂等键格式无效");
}
return normalized;
}
StateRequest state(StateRequest raw) {
if (raw == null || raw.version() == null || raw.version() < 0) {
throw SqlProcessingSuggestionDomainException.validation("状态版本不能为空且不得小于0");
}
String reason = required(raw.reason(), "操作原因", 500);
rejectUntrustedText(reason, "操作原因");
return new StateRequest(raw.version(), reason);
}
SuggestionStatus status(String value) {
if (value == null || value.isBlank()) return null;
try {
return SuggestionStatus.valueOf(value.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException exception) {
throw SqlProcessingSuggestionDomainException.validation("建议状态无效");
}
}
int page(Integer value) {
return boundedNumber(value == null ? 1 : value, 1, 10_000, "页码");
}
int size(Integer value) {
return boundedNumber(value == null ? 20 : value, 1, 100, "分页大小");
}
long id(long value) {
if (value <= 0) throw SqlProcessingSuggestionDomainException.validation("建议标识无效");
return value;
}
String requestHash(SuggestionRequest request) {
return sha256(json(request));
}
String actionHash(long suggestionId, String action, StateRequest request) {
return sha256(json(List.of(action, suggestionId, request.version(), request.reason())));
}
String json(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JacksonException exception) {
throw SqlProcessingSuggestionDomainException.validation("建议请求无法规范化");
}
}
List<EvidenceRef> evidence(String json) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, EvidenceRef.class));
} catch (JacksonException exception) {
throw new IllegalStateException("已保存的建议证据无法读取", exception);
}
}
private String safeSql(String raw, String objectRef) {
String sql = raw.trim();
if (sql.isEmpty() || !sql.matches("(?is)^(select|with)\\b.*")) {
throw SqlProcessingSuggestionDomainException.validation("SQL草稿只允许以SELECT或WITH开头");
}
if (sql.indexOf('\0') >= 0 || FORBIDDEN_SQL.matcher(sql).find()
|| Pattern.compile("(?is)\\b(?:select\\s+.*\\s+into|for\\s+update|lock\\s+in\\s+share\\s+mode)\\b").matcher(sql).find()) {
throw SqlProcessingSuggestionDomainException.validation("SQL草稿不是安全的单条只读语句");
}
rejectUntrustedText(sql, "SQL草稿");
Matcher matcher = SOURCE_OBJECT.matcher(sql);
List<String> objects = new ArrayList<>();
while (matcher.find()) objects.add(matcher.group(1));
if (objects.isEmpty() || objects.stream().anyMatch(value -> !value.equalsIgnoreCase(objectRef))) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
return sql;
}
private List<EvidenceRequest> normalizeEvidenceRequests(List<EvidenceRequest> raw) {
if (raw == null || raw.size() > 32) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
List<EvidenceRequest> normalized = new ArrayList<>();
for (EvidenceRequest item : raw) {
if (item == null) {
throw SqlProcessingSuggestionDomainException.evidenceInsufficient();
}
String reference = required(item.reference(), "证据引用", 512);
String kind = required(item.kind(), "证据类型", 64).toUpperCase(Locale.ROOT);
if (!kind.matches("[A-Z][A-Z0-9_.-]{0,31}")) {
throw SqlProcessingSuggestionDomainException.validation("证据类型格式无效");
}
rejectUntrustedText(reference, "证据引用");
normalized.add(new EvidenceRequest(reference, kind));
}
normalized.sort(Comparator.comparing(EvidenceRequest::reference).thenComparing(EvidenceRequest::kind));
return List.copyOf(normalized);
}
private String required(String value, String label, int maxLength) {
String normalized = text(value, "");
if (normalized.isBlank()) throw SqlProcessingSuggestionDomainException.validation(label + "不能为空");
bounded(normalized, label, maxLength);
return normalized;
}
private void bounded(String value, String label, int maxLength) {
if (value.length() > maxLength) {
throw SqlProcessingSuggestionDomainException.validation(label + "超过长度限制");
}
}
private int boundedNumber(int value, int minimum, int maximum, String label) {
if (value < minimum || value > maximum) {
throw SqlProcessingSuggestionDomainException.validation(label + "超出范围");
}
return value;
}
private void rejectUntrustedText(String value, String label) {
if (INJECTION.matcher(value).find()) {
throw SqlProcessingSuggestionDomainException.validation(label + "包含提示注入内容");
}
if (SENSITIVE.matcher(value).find()) {
throw SqlProcessingSuggestionDomainException.validation(label + "包含敏感信息");
}
}
private static String text(String value, String fallback) {
return value == null ? fallback : value.trim();
}
private static String sha256(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (Exception exception) {
throw new IllegalStateException("SHA-256不可用", exception);
}
}
}
@@ -0,0 +1,42 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.datagov.integration.api.aiassistant.AiProviderApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
class SqlProcessingSuggestionProviderGateway {
@DubboReference(check = false, timeout = 8_000, retries = 0)
private AiProviderApi provider;
SqlProcessingSuggestionProviderGateway() {
}
SqlProcessingSuggestionProviderGateway(AiProviderApi provider) {
this.provider = provider;
}
AiProviderApi.SuggestionResponse complete(long actorId, AiProviderApi.CompletionRequest request) {
try {
AiProviderApi.SuggestionResponse response = provider.complete(actorId, request);
if (response == null || response.status() == null || response.code() == null) {
throw SqlProcessingSuggestionDomainException.provider("Provider返回无效结果,未保存建议");
}
if (!"DRAFT".equals(response.status())) {
throw SqlProcessingSuggestionDomainException.provider(
switch (response.code()) {
case "AI_DISABLED" -> "AI辅助已关闭,未生成建议";
case "REAL_MODEL_NOT_CONFIGURED" -> "真实模型尚未配置或验证,未生成建议";
default -> "Provider未返回可审查草稿,未保存建议";
}
);
}
return response;
} catch (SqlProcessingSuggestionDomainException exception) {
throw exception;
} catch (RuntimeException | LinkageError exception) {
throw SqlProcessingSuggestionDomainException.provider("Provider不可用,未生成建议");
}
}
}
@@ -0,0 +1,183 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.aiassistant.SqlProcessingSuggestionActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRef;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.StateRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionStatus;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionView;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
@Repository
class SqlProcessingSuggestionRepository {
private static final String COLUMNS = """
s.suggestion_id,s.request_id,s.object_ref,s.object_type,s.instruction,s.sql_draft,
s.processing_draft,s.evidence_json,s.title,s.summary,s."MODEL",s.provider_version,
s.confidence,s.impact_summary,s.suggestion_status,s.error_code,s.error_summary,
s.version,s.create_time,s.update_time
""";
private final JdbcTemplate jdbc;
private final TransactionTemplate transactions;
private final SqlProcessingSuggestionPolicy policy;
SqlProcessingSuggestionRepository(
JdbcTemplate jdbc,
TransactionTemplate transactions,
SqlProcessingSuggestionPolicy policy
) {
this.jdbc = jdbc;
this.transactions = transactions;
this.policy = policy;
}
SuggestionView byIdempotency(Actor actor, String idempotencyKey) {
List<SuggestionView> rows = jdbc.query(
"SELECT " + COLUMNS + " FROM dev_ai_dataops_suggestion s "
+ "WHERE s.org_id=? AND (s.actor_id=? OR ?=1) AND s.idempotency_key=? AND s.del_flag='0'",
(rs, row) -> map(rs), actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0, idempotencyKey);
return rows.isEmpty() ? null : rows.getFirst();
}
String requestHashByIdempotency(Actor actor, String idempotencyKey) {
List<String> rows = jdbc.query("""
SELECT request_sha256 FROM dev_ai_dataops_suggestion
WHERE org_id=? AND (actor_id=? OR ?=1) AND idempotency_key=? AND del_flag='0'
""", (rs, row) -> rs.getString(1), actor.orgId(), actor.actorId(),
actor.unrestricted() ? 1 : 0, idempotencyKey);
return rows.isEmpty() ? null : rows.getFirst();
}
SuggestionView byId(Actor actor, long suggestionId) {
List<SuggestionView> rows = jdbc.query(
"SELECT " + COLUMNS + " FROM dev_ai_dataops_suggestion s "
+ "WHERE s.suggestion_id=? AND s.org_id=? AND (s.actor_id=? OR ?=1) AND s.del_flag='0'",
(rs, row) -> map(rs), suggestionId, actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0);
if (rows.isEmpty()) throw SqlProcessingSuggestionDomainException.notFound();
return rows.getFirst();
}
PageResult<SuggestionView> page(Actor actor, String status, int pageNum, int pageSize) {
String scope = "s.org_id=? AND (s.actor_id=? OR ?=1) AND s.del_flag='0'";
Object[] scopeArgs = {actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0};
String statusClause = status == null ? "" : " AND s.suggestion_status=?";
Object[] countArgs = status == null
? scopeArgs : new Object[]{actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0, status};
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM dev_ai_dataops_suggestion s WHERE " + scope + statusClause,
Long.class, countArgs);
Object[] rowArgs = status == null
? new Object[]{actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0, pageSize, (pageNum - 1) * pageSize}
: new Object[]{actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0, status, pageSize, (pageNum - 1) * pageSize};
List<SuggestionView> rows = jdbc.query(
"SELECT " + COLUMNS + " FROM dev_ai_dataops_suggestion s WHERE " + scope + statusClause
+ " ORDER BY s.update_time DESC,s.suggestion_id DESC LIMIT ? OFFSET ?",
(rs, row) -> map(rs), rowArgs);
return PageResult.build(rows, total == null ? 0 : total);
}
SuggestionView insert(
Actor actor,
String idempotencyKey,
String requestHash,
cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionRequest request,
List<EvidenceRef> evidence,
cn.aixunkeji.datagov.integration.api.aiassistant.AiProviderApi.SuggestionResponse provider,
BigDecimal confidence,
String impactSummary
) {
long id = IdGeneratorUtil.nextLongId();
jdbc.update("""
INSERT INTO dev_ai_dataops_suggestion(
suggestion_id,request_id,actor_id,org_id,idempotency_key,request_sha256,
object_ref,object_type,table_file_id,instruction,sql_draft,processing_draft,evidence_json,
title,summary,\"MODEL\",provider_version,confidence,impact_summary,suggestion_status,
error_code,error_summary,version,create_dept,create_by,create_time,update_by,update_time,del_flag
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, 'DRAFT',NULL,NULL,0,?,?,NOW(),?,NOW(),'0')
""",
id, request.requestId(), actor.actorId(), actor.orgId(), idempotencyKey, requestHash,
request.objectRef(), request.objectType(), request.tableFileId(), request.instruction(), request.sqlDraft(), request.processingDraft(),
policy.json(evidence), provider.title(), provider.summary(), provider.model(), provider.providerVersion(),
confidence, impactSummary, actor.orgId(), actor.actorId(), actor.actorId());
return byId(actor, id);
}
SuggestionView changeState(Actor actor, long suggestionId, String action, String idempotencyKey,
String requestHash, StateRequest request) {
return transactions.execute(status -> {
List<ActionRecord> existing = jdbc.query("""
SELECT request_sha256,request_status FROM dev_ai_dataops_suggestion_action
WHERE suggestion_id=? AND actor_id=? AND org_id=? AND action_type=? AND idempotency_key=? AND del_flag='0'
""", (rs, row) -> new ActionRecord(rs.getString(1), rs.getString(2)),
suggestionId, actor.actorId(), actor.orgId(), action, idempotencyKey);
if (!existing.isEmpty()) {
if (!requestHash.equals(existing.getFirst().requestHash())) {
throw SqlProcessingSuggestionDomainException.conflict("同一幂等键不能用于不同状态请求");
}
return byId(actor, suggestionId);
}
SuggestionView current = byId(actor, suggestionId);
if (current.status() != SuggestionStatus.DRAFT) {
throw SqlProcessingSuggestionDomainException.conflict("建议已处理,不能重复采纳或忽略");
}
long actionId = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO dev_ai_dataops_suggestion_action(
action_id,suggestion_id,actor_id,org_id,action_type,idempotency_key,request_sha256,
request_status,reason,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,'IN_PROGRESS',?,?,NOW(),?,NOW(),'0',0)
""", actionId, suggestionId, actor.actorId(), actor.orgId(), action, idempotencyKey,
requestHash, request.reason(), actor.actorId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) {
throw SqlProcessingSuggestionDomainException.conflict("状态请求正在处理,请稍后重试");
}
String target = "ADOPT".equals(action) ? "ADOPTED" : "IGNORED";
int changed = jdbc.update("""
UPDATE dev_ai_dataops_suggestion
SET suggestion_status=?,update_by=?,update_time=NOW(),version=version+1
WHERE suggestion_id=? AND org_id=? AND (actor_id=? OR ?=1)
AND suggestion_status='DRAFT' AND version=? AND del_flag='0'
""", target, actor.actorId(), suggestionId, actor.orgId(), actor.actorId(),
actor.unrestricted() ? 1 : 0, request.version());
if (changed != 1) throw SqlProcessingSuggestionDomainException.conflict("建议版本已变化,请刷新后重试");
jdbc.update("""
UPDATE dev_ai_dataops_suggestion_action
SET request_status='COMPLETED',update_by=?,update_time=NOW(),version=version+1
WHERE action_id=? AND request_status='IN_PROGRESS' AND del_flag='0'
""", actor.actorId(), actionId);
return byId(actor, suggestionId);
});
}
private SuggestionView map(ResultSet rs) throws SQLException {
return new SuggestionView(
rs.getLong("suggestion_id"), rs.getString("request_id"), rs.getString("object_ref"),
rs.getString("object_type"), rs.getString("instruction"), rs.getString("sql_draft"),
rs.getString("processing_draft"), policy.evidence(rs.getString("evidence_json")),
rs.getString("title"), rs.getString("summary"), rs.getString("model"), rs.getString("provider_version"),
rs.getBigDecimal("confidence"), rs.getString("impact_summary"),
SuggestionStatus.valueOf(rs.getString("suggestion_status")), rs.getString("error_code"),
rs.getString("error_summary"), rs.getLong("version"), localDateTime(rs.getTimestamp("create_time")),
localDateTime(rs.getTimestamp("update_time"))
);
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
private record ActionRecord(String requestHash, String status) {
}
}
@@ -0,0 +1,112 @@
package cn.aixunkeji.datagov.dataops.aiassistant;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.datagov.dataops.aiassistant.SqlProcessingSuggestionActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.EvidenceRef;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.StateRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionRequest;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionStatus;
import cn.aixunkeji.datagov.dataops.api.aiassistant.SqlProcessingSuggestionApi.SuggestionView;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileCodeDevelopmentReferenceDirectory;
import cn.aixunkeji.datagov.integration.api.aiassistant.AiProviderApi;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service
@RequiredArgsConstructor
class SqlProcessingSuggestionService {
private final SqlProcessingSuggestionActorProvider actorProvider;
private final SqlProcessingSuggestionPolicy policy;
private final SqlProcessingSuggestionRepository repository;
private final SqlProcessingSuggestionProviderGateway providerGateway;
private final TableFileCodeDevelopmentReferenceDirectory tableDirectory;
private final SqlProcessingSuggestionEvidenceResolver evidenceResolver;
SuggestionView generate(String idempotencyKey, SuggestionRequest raw) {
Actor actor = actorProvider.current();
String key = policy.idempotencyKey(idempotencyKey);
SuggestionRequest request = policy.normalize(raw);
String requestHash = policy.requestHash(request);
requireAuthorizedObject(actor, request);
List<EvidenceRef> evidence = evidenceResolver.resolve(actor, request);
SuggestionView replay = repository.byIdempotency(actor, key);
if (replay != null) return replayOrConflict(actor, key, requestHash, replay);
AiProviderApi.SuggestionResponse provider = providerGateway.complete(actor.actorId(),
new AiProviderApi.CompletionRequest(
request.requestId(), "SQL_PROCESSING",
"只生成可审查的结构化建议草稿;不得执行SQL、写入表、提交代码、运行任务或输出秘密。",
prompt(request), evidenceSummary(evidence), 1024));
try {
return repository.insert(actor, key, requestHash, request, evidence, provider,
BigDecimal.ZERO, "仅影响当前SQL与加工建议草稿;采纳不会触发保存、预览、提交或运行");
} catch (DuplicateKeyException exception) {
SuggestionView concurrent = repository.byIdempotency(actor, key);
if (concurrent == null) throw SqlProcessingSuggestionDomainException.conflict("建议生成结果不可确认");
return replayOrConflict(actor, key, requestHash, concurrent);
}
}
PageResult<SuggestionView> list(String status, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
SuggestionStatus normalized = policy.status(status);
return repository.page(actor, normalized == null ? null : normalized.name(), policy.page(pageNum), policy.size(pageSize));
}
SuggestionView detail(long suggestionId) {
return repository.byId(actorProvider.current(), policy.id(suggestionId));
}
SuggestionView adopt(long suggestionId, String idempotencyKey, StateRequest request) {
return changeState(suggestionId, idempotencyKey, request, "ADOPT");
}
SuggestionView ignore(long suggestionId, String idempotencyKey, StateRequest request) {
return changeState(suggestionId, idempotencyKey, request, "IGNORE");
}
private SuggestionView changeState(long suggestionId, String idempotencyKey, StateRequest raw, String action) {
Actor actor = actorProvider.current();
long id = policy.id(suggestionId);
String key = policy.idempotencyKey(idempotencyKey);
StateRequest request = policy.state(raw);
return repository.changeState(actor, id, action, key, policy.actionHash(id, action, request), request);
}
private SuggestionView replayOrConflict(Actor actor, String key, String requestHash, SuggestionView view) {
String storedHash = repository.requestHashByIdempotency(actor, key);
if (!requestHash.equals(storedHash)) {
throw SqlProcessingSuggestionDomainException.conflict("同一幂等键不能用于不同建议请求");
}
return view;
}
private static String prompt(SuggestionRequest request) {
return "对象范围=" + request.objectRef() + ";对象类型=" + request.objectType()
+ ";用户说明=" + request.instruction() + ";SQL草稿=" + request.sqlDraft()
+ ";加工草稿=" + request.processingDraft();
}
private void requireAuthorizedObject(Actor actor, SuggestionRequest request) {
if (request.tableFileId() == null || request.tableFileId() <= 0) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
TableFileCodeDevelopmentReferenceDirectory.Resolution resolution = tableDirectory.resolve(
actor.actorId(), actor.orgId(), actor.unrestricted(), java.util.List.of(request.tableFileId()));
if (resolution.status() != TableFileCodeDevelopmentReferenceDirectory.Status.AUTHORIZED
|| resolution.tables().size() != 1
|| !resolution.tables().getFirst().qualifiedName().equalsIgnoreCase(request.objectRef())) {
throw SqlProcessingSuggestionDomainException.forbidden();
}
}
private static String evidenceSummary(List<EvidenceRef> evidence) {
return evidence.stream()
.map(e -> e.kind() + ":" + e.reference() + "=" + e.summary())
.reduce((left, right) -> left + "\n" + right).orElse("");
}
}
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertDutyDirectory;
import org.springframework.stereotype.Component;
@Component
final class AlertDutyDirectoryAdapter implements AlertDutyDirectory {
private final AlertEventEvaluationRepository repository;
AlertDutyDirectoryAdapter(AlertEventEvaluationRepository repository) {
this.repository = repository;
}
@Override
public DutyResult listOpenDuty(DutyQuery query) {
return repository.duty(query);
}
}
@@ -0,0 +1,22 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class AlertEventActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long orgId = LoginHelper.getDeptId();
String actorName = LoginHelper.getUsername();
if (actorId == null || orgId == null || actorId <= 0 || orgId <= 0
|| actorName == null || actorName.isBlank()) {
throw AlertEventDomainException.forbidden();
}
return new Actor(actorId, orgId, actorName, LoginHelper.isSuperAdmin(actorId));
}
record Actor(long actorId, long orgId, String actorName, boolean unrestricted) {
}
}
@@ -0,0 +1,160 @@
package cn.aixunkeji.datagov.dataops.alertevent;
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.dataops.api.alertevent.AlertEventApi.AssignRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventDetailView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventStatus;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventSummary;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.IdentityCandidate;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotifyRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PageView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PostmortemRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.ProcessRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleSaveRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleStatusRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.VerifyRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.WriteView;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/alert-events")
public class AlertEventController {
private final AlertEventService service;
@SaCheckPermission("aixun:dataops:alert-event:view")
@GetMapping
public R<PageView<EventSummary>> list(
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Source source,
@RequestParam(required = false) Severity severity,
@RequestParam(required = false) EventStatus status,
@RequestParam(required = false) String dataDomainCode,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.events(keyword, source, severity, status, null, dataDomainCode, pageNum, pageSize));
}
@SaCheckPermission("aixun:dataops:alert-event:view")
@GetMapping("/{eventId}")
public R<EventDetailView> detail(@PathVariable long eventId) {
return R.ok(service.detail(eventId));
}
@SaCheckPermission("aixun:dataops:alert-event:view")
@GetMapping("/rules")
public R<PageView<RuleView>> rules(
@RequestParam(required = false) String keyword,
@RequestParam(required = false) Source source,
@RequestParam(required = false) Boolean enabled,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.rules(keyword, source, enabled, pageNum, pageSize));
}
@SaCheckPermission("aixun:dataops:alert-event:view")
@GetMapping("/identity-candidates")
public R<List<IdentityCandidate>> identityCandidates(@RequestParam String keyword,
@RequestParam(defaultValue = "20") Integer limit) {
return R.ok(service.identityCandidates(keyword, limit));
}
@Log(title = "新增告警规则", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:rule-create")
@PostMapping("/rules")
public R<WriteView<RuleView>> createRule(@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody RuleSaveRequest request) {
return R.ok(service.createRule(idempotencyKey, request));
}
@Log(title = "修改告警规则", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:rule-update")
@PutMapping("/rules/{ruleId}")
public R<WriteView<RuleView>> updateRule(@PathVariable long ruleId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody RuleSaveRequest request) {
return R.ok(service.updateRule(ruleId, idempotencyKey, request));
}
@Log(title = "启停告警规则", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:rule-status")
@PutMapping("/rules/{ruleId}/status")
public R<WriteView<RuleView>> updateRuleStatus(@PathVariable long ruleId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody RuleStatusRequest request) {
return R.ok(service.updateRuleStatus(ruleId, idempotencyKey, request));
}
@Log(title = "记录告警站内通知", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:notify")
@PostMapping("/{eventId}/notifications")
public R<WriteView<EventDetailView>> notifyEvent(@PathVariable long eventId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody NotifyRequest request) {
return R.ok(service.notifyEvent(eventId, idempotencyKey, request));
}
@Log(title = "分派告警事件", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:assign")
@PostMapping("/{eventId}/assignment")
public R<WriteView<EventDetailView>> assignEvent(@PathVariable long eventId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody AssignRequest request) {
return R.ok(service.assignEvent(eventId, idempotencyKey, request));
}
@Log(title = "处置告警事件", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:process")
@PostMapping("/{eventId}/processing")
public R<WriteView<EventDetailView>> processEvent(@PathVariable long eventId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody ProcessRequest request) {
return R.ok(service.processEvent(eventId, idempotencyKey, request));
}
@Log(title = "验证关闭告警事件", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:verify")
@PostMapping("/{eventId}/verification")
public R<WriteView<EventDetailView>> verifyEvent(@PathVariable long eventId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody VerifyRequest request) {
return R.ok(service.verifyEvent(eventId, idempotencyKey, request));
}
@Log(title = "维护告警复盘", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:alert-event:postmortem")
@PutMapping("/{eventId}/postmortem")
public R<WriteView<EventDetailView>> savePostmortem(@PathVariable long eventId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody PostmortemRequest request) {
return R.ok(service.savePostmortem(eventId, idempotencyKey, request));
}
}
@@ -0,0 +1,72 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import org.springframework.http.HttpStatus;
final class AlertEventDomainException extends RuntimeException {
private final int code;
private final HttpStatus status;
private AlertEventDomainException(int code, HttpStatus status, String message) {
super(message);
this.code = code;
this.status = status;
}
static AlertEventDomainException validation(String message) {
return new AlertEventDomainException(126301, HttpStatus.BAD_REQUEST, message);
}
static AlertEventDomainException forbidden() {
return new AlertEventDomainException(126303, HttpStatus.FORBIDDEN, "无权访问告警事件");
}
static AlertEventDomainException notFound() {
return new AlertEventDomainException(126304, HttpStatus.NOT_FOUND, "告警事件不存在");
}
static AlertEventDomainException ruleNotFound() {
return new AlertEventDomainException(126305, HttpStatus.NOT_FOUND, "告警规则不存在");
}
static AlertEventDomainException conflict(String message) {
return new AlertEventDomainException(126309, HttpStatus.CONFLICT, message);
}
static AlertEventDomainException identityUnavailable() {
return new AlertEventDomainException(126350, HttpStatus.SERVICE_UNAVAILABLE,
"责任人信息暂不可验证,本次操作已停止");
}
static AlertEventDomainException ownerUnavailable() {
return new AlertEventDomainException(126351, HttpStatus.SERVICE_UNAVAILABLE,
"运行事实暂不可用,本次评估已停止");
}
static AlertEventDomainException limitExceeded(String message) {
return new AlertEventDomainException(126352, HttpStatus.PAYLOAD_TOO_LARGE, message);
}
static AlertEventDomainException requestUnavailable() {
return new AlertEventDomainException(126353, HttpStatus.SERVICE_UNAVAILABLE,
"告警请求暂不可记录,本次操作已停止");
}
static AlertEventDomainException deliveryChannelUnavailable() {
return new AlertEventDomainException(126354, HttpStatus.SERVICE_UNAVAILABLE,
"通知渠道尚未就绪,本次未发送,请联系管理员核对受管配置");
}
static AlertEventDomainException deliveryUnknown() {
return new AlertEventDomainException(126355, HttpStatus.SERVICE_UNAVAILABLE,
"投递结果暂不可确认,请查询原请求回执");
}
int code() {
return code;
}
HttpStatus status() {
return status;
}
}
@@ -0,0 +1,213 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.EvaluationBatch;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.OwnerEvaluation;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.Rule;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Metric;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Operator;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.TaskSummary;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.DirectoryState;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.OwnerListResult;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.OwnerQuery;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@Component
final class AlertEventEvaluationEngine {
private final AlertOccurrenceBindingPolicy bindings;
AlertEventEvaluationEngine(AlertOccurrenceBindingPolicy bindings){this.bindings=bindings;}
EvaluationBatch evaluate(Rule rule, TaskLogOwnerDirectory directory, LocalDateTime observedAt) {
return evaluate(rule,directory,observedAt,java.time.ZoneId.systemDefault().getId(),new AlertOccurrenceBindingPolicy.Budget());
}
EvaluationBatch evaluate(Rule rule, TaskLogOwnerDirectory directory, LocalDateTime observedAt,String zone,AlertOccurrenceBindingPolicy.Budget budget) {
if (rule == null || directory == null || observedAt == null || !rule.enabled()) {
throw new IllegalArgumentException("enabled rule, owner directory and observation time are required");
}
cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source expectedSource = taskLogSource(rule);
if (directory.source() != expectedSource) {
throw AlertEventDomainException.ownerUnavailable();
}
OwnerQuery query = new OwnerQuery(rule.primaryUserId(), rule.orgId(), true, null, null,
rule.projectRef(), null, observedAt.minusMinutes(rule.observationMinutes()), observedAt,
AlertEventPolicy.MAX_OWNER_ROWS);
OwnerListResult result = directory.list(query);
if (result == null || result.state() != DirectoryState.AVAILABLE || result.rows() == null) {
throw AlertEventDomainException.ownerUnavailable();
}
if (result.total() < 0 || result.total() > AlertEventPolicy.MAX_OWNER_ROWS
|| result.rows().size() > AlertEventPolicy.MAX_OWNER_ROWS) {
throw AlertEventDomainException.limitExceeded("单条规则的运行事实超过50000行");
}
if (result.total() != result.rows().size()) {
throw AlertEventDomainException.ownerUnavailable();
}
Set<Long> runIds = new HashSet<>();
Map<Long, List<TaskSummary>> owners = new LinkedHashMap<>();
for (TaskSummary row : result.rows()) {
validateRow(rule, expectedSource, row, runIds);
if (rule.dataDomainCode() != null && !rule.dataDomainCode().equals(row.dataDomainCode())) {
continue;
}
owners.computeIfAbsent(row.ownerObjectId(), ignored -> new ArrayList<>()).add(row);
}
boolean unchanged=false;
if(owners.values().stream().anyMatch(rows->rows.size()<=AlertOccurrenceBindingPolicy.MAX_RUNS)){
try{
OwnerListResult second=directory.list(query);
if(second!=null&&second.state()==DirectoryState.AVAILABLE&&second.total()==result.total()&&second.rows().size()==second.total()){
Set<Long> secondIds=new HashSet<>();for(var row:second.rows())validateRow(rule,expectedSource,row,secondIds);
unchanged=bindings.inputHash(result.rows()).equals(bindings.inputHash(second.rows()));
}
}catch(RuntimeException changed){/* Original evaluation remains valid as its first observation; no partial history is bound. */}
}
final boolean verified=unchanged;
List<OwnerEvaluation> evaluations = owners.values().stream()
.map(rows -> {var value=evaluateOwner(rule,rows,observedAt);return value.withBinding(bindings.capture(rule,rows,value,observedAt,zone,verified,budget));})
.sorted(Comparator.comparingLong(OwnerEvaluation::ownerObjectId))
.toList();
return new EvaluationBatch(evaluations, result.rows().size());
}
private static void validateRow(Rule rule,
cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source expectedSource,
TaskSummary row,
Set<Long> runIds) {
if (row == null || row.source() != expectedSource || row.runId() == null || row.runId() <= 0
|| !runIds.add(row.runId()) || row.ownerObjectId() == null || row.ownerObjectId() <= 0
|| row.ownerObjectName() == null || row.ownerObjectName().isBlank()
|| row.orgId() == null || row.orgId() != rule.orgId() || row.status() == null
|| row.createdAt() == null || row.createdAt().isAfter(row.updatedAt() == null ? row.createdAt() : row.updatedAt())
|| (rule.projectRef() != null && !rule.projectRef().equals(row.projectRef()))) {
throw AlertEventDomainException.ownerUnavailable();
}
if (row.startedAt() != null && row.completedAt() != null && row.completedAt().isBefore(row.startedAt())) {
throw AlertEventDomainException.ownerUnavailable();
}
}
private static OwnerEvaluation evaluateOwner(Rule rule, List<TaskSummary> rows, LocalDateTime observedAt) {
TaskSummary first = rows.getFirst();
for (TaskSummary row : rows) {
if (!Objects.equals(first.ownerObjectName(), row.ownerObjectName())
|| !Objects.equals(first.projectRef(), row.projectRef())
|| !Objects.equals(first.dataDomainCode(), row.dataDomainCode())) {
throw AlertEventDomainException.ownerUnavailable();
}
}
MetricResult metric = metric(rule.metric(), rows);
String fingerprint = AlertEventPolicy.sha256(Long.toString(rule.orgId()), Long.toString(rule.ruleId()),
rule.source().name(), Long.toString(first.ownerObjectId()), value(first.projectRef()),
value(first.dataDomainCode()));
String evidence = evidence(rows);
LocalDateTime observedFrom = rows.stream().map(TaskSummary::createdAt)
.min(LocalDateTime::compareTo).orElse(observedAt);
return new OwnerEvaluation(rule.ruleId(), rule.orgId(), rule.source(), fingerprint,
first.ownerObjectId(), first.ownerObjectName(), first.projectRef(), first.dataDomainCode(),
metric.known(), metric.known() && compare(metric.value(), rule.threshold(), rule.operator()),
metric.value(), metric.sampleCount(), evidence, observedFrom, observedAt);
}
private static MetricResult metric(Metric metric, List<TaskSummary> rows) {
if (rows.isEmpty()) {
return MetricResult.unknown();
}
return switch (metric) {
case FAILED_COUNT -> MetricResult.known(BigDecimal.valueOf(rows.stream()
.filter(row -> row.status() == Status.FAILED).count()), rows.size());
case BACKLOG_COUNT -> MetricResult.known(BigDecimal.valueOf(rows.stream()
.filter(row -> row.status() == Status.PENDING || row.status() == Status.SUBMITTED
|| row.status() == Status.RUNNING).count()), rows.size());
case FAILURE_RATE_PERCENT -> failureRate(rows);
case MAX_DURATION_MS -> maximumDuration(rows);
};
}
private static MetricResult failureRate(List<TaskSummary> rows) {
long terminal = rows.stream().filter(row -> row.status() == Status.SUCCEEDED
|| row.status() == Status.FAILED || row.status() == Status.CANCELED).count();
if (terminal == 0) {
return MetricResult.unknown();
}
long failed = rows.stream().filter(row -> row.status() == Status.FAILED).count();
BigDecimal rate = BigDecimal.valueOf(failed).multiply(BigDecimal.valueOf(100))
.divide(BigDecimal.valueOf(terminal), 6, RoundingMode.HALF_UP).stripTrailingZeros();
return MetricResult.known(rate, terminal);
}
private static MetricResult maximumDuration(List<TaskSummary> rows) {
List<Long> durations = rows.stream()
.filter(row -> row.startedAt() != null && row.completedAt() != null)
.map(row -> Duration.between(row.startedAt(), row.completedAt()).toMillis())
.toList();
if (durations.isEmpty()) {
return MetricResult.unknown();
}
return MetricResult.known(BigDecimal.valueOf(durations.stream().mapToLong(Long::longValue).max()
.orElseThrow()), durations.size());
}
private static boolean compare(BigDecimal actual, BigDecimal threshold, Operator operator) {
int comparison = actual.compareTo(threshold);
return switch (operator) {
case GT -> comparison > 0;
case GTE -> comparison >= 0;
case LT -> comparison < 0;
case LTE -> comparison <= 0;
};
}
private static String evidence(List<TaskSummary> rows) {
List<TaskSummary> sorted = rows.stream().sorted(Comparator.comparing(TaskSummary::runId)).toList();
List<String> fields = new ArrayList<>();
for (TaskSummary row : sorted) {
fields.add(row.source().name());
fields.add(Long.toString(row.runId()));
fields.add(Long.toString(row.ownerObjectId()));
fields.add(row.status().name());
fields.add(value(row.startedAt()));
fields.add(value(row.completedAt()));
fields.add(value(row.createdAt()));
fields.add(value(row.updatedAt()));
}
return AlertEventPolicy.sha256(fields.toArray(String[]::new));
}
private static cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source taskLogSource(Rule rule) {
return switch (rule.source()) {
case SCHEDULING -> cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source.SCHEDULING;
case BATCH_INGESTION -> cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source.BATCH_INGESTION;
case FILE_INGESTION -> cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source.FILE_INGESTION;
};
}
private static String value(Object value) {
return value == null ? "" : value.toString();
}
private record MetricResult(boolean known, BigDecimal value, long sampleCount) {
static MetricResult unknown() {
return new MetricResult(false, null, 0);
}
static MetricResult known(BigDecimal value, long sampleCount) {
return new MetricResult(true, value, sampleCount);
}
}
}
@@ -0,0 +1,570 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventIdentityGateway.Identity;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.OwnerEvaluation;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.Rule;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertDutyDirectory.DutyItem;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertDutyDirectory.DutyQuery;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertDutyDirectory.DutyResult;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventStatus;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotificationType;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Repository
class AlertEventEvaluationRepository {
private static final String RULE_SELECT = """
SELECT r.rule_id, r.org_id, r.rule_name, r.source_type, r.metric_type, r.operator_type,
r.threshold_value, r.severity, r.observation_minutes, r.trigger_count, r.recovery_count,
r.aggregate_minutes, r.silence_minutes, r.project_ref, r.data_domain_code,
r.primary_user_id, r.escalation_user_id, r.escalation_wait_minutes, r.enabled_flag,
r.version, r.create_time, r.update_time
FROM ops_alert_rule r
""";
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final AlertOccurrenceBindingRepository bindings;
AlertEventEvaluationRepository(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate,AlertOccurrenceBindingRepository bindings) {
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
this.bindings=bindings;
}
List<Rule> enabledRules() {
List<Rule> rows = jdbcTemplate.query(RULE_SELECT + """
WHERE r.enabled_flag='1' AND r.del_flag='0'
ORDER BY r.org_id, r.rule_id
LIMIT 1001
""", (resultSet, rowNum) -> AlertEventJdbcRepository.mapRule(resultSet));
if (rows.size() > AlertEventPolicy.MAX_ENABLED_RULES) {
throw AlertEventDomainException.limitExceeded("启用的告警规则超过1000条");
}
return rows;
}
List<EscalationCandidate> pendingEscalations(LocalDateTime observedAt) {
List<EscalationCandidate> rows = jdbcTemplate.query("""
SELECT e.event_id, e.org_id, e.rule_id, r.escalation_user_id
FROM ops_alert_event e
JOIN ops_alert_rule r ON r.rule_id=e.rule_id AND r.org_id=e.org_id AND r.del_flag='0'
WHERE e.del_flag='0' AND r.enabled_flag='1'
AND e.event_status IN ('OPEN', 'ASSIGNED', 'PROCESSING')
AND r.escalation_user_id IS NOT NULL
AND TIMESTAMPADD(MINUTE,r.escalation_wait_minutes,e.opened_at) <= ?
AND NOT EXISTS (
SELECT 1 FROM ops_alert_notification n
WHERE n.event_id=e.event_id AND n.org_id=e.org_id
AND n.notification_type='ESCALATION'
AND n.recipient_user_id=r.escalation_user_id
AND n.dedup_key='LEVEL-1' AND n.del_flag='0'
)
ORDER BY e.opened_at, e.event_id
LIMIT 5001
""", (resultSet, rowNum) -> new EscalationCandidate(resultSet.getLong("event_id"),
resultSet.getLong("org_id"), resultSet.getLong("rule_id"),
resultSet.getLong("escalation_user_id")), Timestamp.valueOf(observedAt));
if (rows.size() > AlertEventPolicy.MAX_FINGERPRINTS) {
throw AlertEventDomainException.limitExceeded("待升级告警超过5000条");
}
return rows;
}
void apply(String evaluationKey, LocalDateTime observedAt, List<EvaluationWork> work,
List<EscalationCandidate> escalationCandidates, Map<Long, Identity> identities) {
validateWork(evaluationKey, observedAt, work, escalationCandidates, identities);
Boolean completed = transactionTemplate.execute(status -> {
lockRules(work,escalationCandidates);
for (EvaluationWork item : work.stream().sorted(java.util.Comparator.comparingLong((EvaluationWork w)->w.rule().orgId()).thenComparingLong(w->w.rule().ruleId())).toList()) {
Identity primary = requireIdentity(identities, item.rule().primaryUserId(), item.rule().orgId());
for (OwnerEvaluation evaluation : item.evaluations()) {
applyOne(evaluationKey, item.rule(), evaluation, primary);
}
}
for (EscalationCandidate candidate : escalationCandidates) {
applyEscalation(evaluationKey, observedAt, candidate, identities);
}
return Boolean.TRUE;
});
if (!Boolean.TRUE.equals(completed)) {
throw AlertEventDomainException.requestUnavailable();
}
}
DutyResult duty(DutyQuery query) {
if (query == null || query.actorId() <= 0 || query.orgId() <= 0
|| query.limit() < 1 || query.limit() > 100) {
throw new IllegalArgumentException("alert duty query is invalid");
}
StringBuilder where = new StringBuilder("""
WHERE e.org_id=? AND e.del_flag='0'
AND e.event_status IN ('OPEN', 'ASSIGNED', 'PROCESSING')
""");
List<Object> parameters = new ArrayList<>();
parameters.add(query.orgId());
append(where, parameters, "e.project_ref", normalizeScope(query.projectRef()));
append(where, parameters, "e.data_domain_code", normalizeScope(query.dataDomainCode()));
long total = requireCount(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ops_alert_event e " + where,
Long.class, parameters.toArray()));
long unassignedTotal = requireCount(jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM ops_alert_event e " + where + " AND e.assignee_user_id IS NULL",
Long.class, parameters.toArray()));
List<Object> rowParameters = new ArrayList<>(parameters);
rowParameters.add(query.limit());
List<DutyItem> rows = jdbcTemplate.query("""
SELECT e.event_id, e.rule_name, e.owner_object_id, e.owner_object_name,
e.severity, e.event_status, COALESCE(e.assignee_user_id, e.primary_user_id) responsible_user_id
FROM ops_alert_event e
""" + where + " ORDER BY e.severity, e.opened_at, e.event_id LIMIT ?",
(resultSet, rowNum) -> new DutyItem(resultSet.getLong("event_id"),
resultSet.getString("rule_name"), resultSet.getLong("owner_object_id"),
resultSet.getString("owner_object_name"), Severity.valueOf(resultSet.getString("severity")),
EventStatus.valueOf(resultSet.getString("event_status")),
resultSet.getLong("responsible_user_id")), rowParameters.toArray());
return new DutyResult(rows, total, unassignedTotal);
}
private void applyOne(String evaluationKey, Rule rule, OwnerEvaluation evaluation, Identity primary) {
StateRow state = lockState(evaluation);
if (state != null && evaluationKey.equals(state.lastEvaluationKey())) {
return;
}
assertEvaluation(rule, evaluation, state);
if (!evaluation.known()) {
saveUnknownState(evaluationKey, evaluation, state);
return;
}
EventRuntime active = lockActiveEvent(evaluation.orgId(), evaluation.fingerprint());
int triggerStreak;
int recoveryStreak;
String knownState;
LocalDateTime nextOpenAt = state == null ? null : state.nextOpenAt();
if (evaluation.breached()) {
knownState = "BREACHED";
triggerStreak = state != null && "BREACHED".equals(state.lastKnownState())
? Math.min(rule.triggerCount(), state.triggerStreak() + 1) : 1;
recoveryStreak = 0;
if (active != null) {
if (insertOccurrence(evaluationKey,active.eventId(), evaluation)) {
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event
SET current_metric_value=?, occurrence_count=occurrence_count+1,
last_occurred_at=?, version=version+1
WHERE event_id=? AND org_id=? AND version=?
AND event_status IN ('OPEN', 'ASSIGNED', 'PROCESSING') AND del_flag='0'
""", evaluation.metricValue(), Timestamp.valueOf(evaluation.observedTo()), active.eventId(),
evaluation.orgId(), active.version()), "活动告警事件状态已变化");
nextOpenAt = later(nextOpenAt, evaluation.observedTo().plusMinutes(rule.aggregateMinutes()));
}
} else if (triggerStreak >= rule.triggerCount()
&& (nextOpenAt == null || !evaluation.observedTo().isBefore(nextOpenAt))) {
createOpenEvent(evaluationKey, rule, evaluation, primary);
nextOpenAt = later(evaluation.observedTo().plusMinutes(rule.aggregateMinutes()),
evaluation.observedTo().plusMinutes(rule.silenceMinutes()));
}
} else {
knownState = "HEALTHY";
triggerStreak = 0;
recoveryStreak = state != null && "HEALTHY".equals(state.lastKnownState())
? Math.min(rule.recoveryCount(), state.recoveryStreak() + 1) : 1;
if (active != null && recoveryStreak >= rule.recoveryCount()) {
autoResolve(evaluationKey, rule, evaluation, primary, active);
}
}
saveKnownState(evaluationKey, evaluation, state, triggerStreak, recoveryStreak, knownState, nextOpenAt);
}
private void createOpenEvent(String evaluationKey, Rule rule, OwnerEvaluation evaluation, Identity primary) {
long eventId = IdGeneratorUtil.nextLongId();
jdbcTemplate.update("""
INSERT INTO ops_alert_event (
event_id, rule_id, org_id, rule_name, source_type, fingerprint,
owner_object_id, owner_object_name, project_ref, data_domain_code,
metric_type, operator_type, threshold_value, current_metric_value, severity,
event_status, occurrence_count, primary_user_id, primary_user_name,
opened_at, last_occurred_at, create_dept
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'OPEN', 1, ?, ?, ?, ?, ?)
""", eventId, rule.ruleId(), rule.orgId(), rule.name(), rule.source().name(), evaluation.fingerprint(),
evaluation.ownerObjectId(), evaluation.ownerObjectName(), evaluation.projectRef(),
evaluation.dataDomainCode(), rule.metric().name(), rule.operator().name(), rule.threshold(),
evaluation.metricValue(), rule.severity().name(), rule.primaryUserId(), primary.displayName(),
Timestamp.valueOf(evaluation.observedTo()), Timestamp.valueOf(evaluation.observedTo()), rule.orgId());
insertOccurrenceRow(evaluationKey,eventId, evaluation);
insertNotification(eventId, rule.orgId(), NotificationType.OPEN, primary,
"告警已开启:" + rule.name() + " / " + evaluation.ownerObjectName(), "OPEN", evaluationKey);
insertTimeline(eventId, rule.orgId(), "OPEN", null, EventStatus.OPEN, evaluationKey, "达到连续触发条件");
}
private void autoResolve(String evaluationKey, Rule rule, OwnerEvaluation evaluation, Identity primary,
EventRuntime active) {
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event
SET event_status='RESOLVED', current_metric_value=?, resolved_at=?, version=version+1
WHERE event_id=? AND org_id=? AND version=?
AND event_status IN ('OPEN', 'ASSIGNED', 'PROCESSING') AND del_flag='0'
""", evaluation.metricValue(), Timestamp.valueOf(evaluation.observedTo()), active.eventId(),
rule.orgId(), active.version()), "活动告警事件状态已变化");
insertNotification(active.eventId(), rule.orgId(), NotificationType.RECOVERY, primary,
"告警已恢复:" + rule.name() + " / " + evaluation.ownerObjectName(), "RECOVERY", evaluationKey);
insertTimeline(active.eventId(), rule.orgId(), "AUTO_RECOVERY", active.status(), EventStatus.RESOLVED,
evaluationKey, "达到连续恢复条件");
}
private void applyEscalation(String evaluationKey, LocalDateTime observedAt,
EscalationCandidate candidate, Map<Long, Identity> identities) {
List<EscalationRuntime> rows = jdbcTemplate.query("""
SELECT e.event_id, e.event_status, e.version, e.opened_at, e.rule_name, e.owner_object_name,
r.escalation_user_id, r.escalation_wait_minutes, r.enabled_flag
FROM ops_alert_event e
JOIN ops_alert_rule r ON r.rule_id=e.rule_id AND r.org_id=e.org_id AND r.del_flag='0'
WHERE e.event_id=? AND e.org_id=? AND e.rule_id=? AND e.del_flag='0'
FOR UPDATE
""", (resultSet, rowNum) -> new EscalationRuntime(resultSet.getLong("event_id"),
EventStatus.valueOf(resultSet.getString("event_status")), resultSet.getLong("version"),
localDateTime(resultSet.getTimestamp("opened_at")), resultSet.getString("rule_name"),
resultSet.getString("owner_object_name"), nullableLong(resultSet, "escalation_user_id"),
resultSet.getInt("escalation_wait_minutes"), "1".equals(resultSet.getString("enabled_flag"))),
candidate.eventId(), candidate.orgId(), candidate.ruleId());
if (rows.isEmpty()) {
return;
}
EscalationRuntime event = rows.getFirst();
if (!event.enabled() || event.escalationUserId() == null
|| event.escalationUserId() != candidate.recipientUserId()
|| (event.status() != EventStatus.OPEN && event.status() != EventStatus.ASSIGNED
&& event.status() != EventStatus.PROCESSING)
|| observedAt.isBefore(event.openedAt().plusMinutes(event.waitMinutes()))) {
return;
}
Integer existing = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM ops_alert_notification
WHERE event_id=? AND org_id=? AND notification_type='ESCALATION'
AND recipient_user_id=? AND dedup_key='LEVEL-1' AND del_flag='0'
""", Integer.class, event.eventId(), candidate.orgId(), candidate.recipientUserId());
if (existing != null && existing > 0) {
return;
}
Identity recipient = requireIdentity(identities, candidate.recipientUserId(), candidate.orgId());
insertNotification(event.eventId(), candidate.orgId(), NotificationType.ESCALATION, recipient,
"告警超时升级:" + event.ruleName() + " / " + event.ownerObjectName(), "LEVEL-1", evaluationKey);
insertTimeline(event.eventId(), candidate.orgId(), "ESCALATE", event.status(), event.status(),
evaluationKey, "达到升级等待时间");
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event SET version=version+1
WHERE event_id=? AND org_id=? AND version=? AND event_status=? AND del_flag='0'
""", event.eventId(), candidate.orgId(), event.version(), event.status().name()),
"活动告警事件状态已变化");
}
private StateRow lockState(OwnerEvaluation evaluation) {
List<StateRow> rows = jdbcTemplate.query("""
SELECT evaluation_state_id, owner_object_id, owner_object_name, project_ref, data_domain_code,
trigger_streak, recovery_streak, last_known_state, last_evaluation_key,
next_open_at, version
FROM ops_alert_evaluation_state
WHERE org_id=? AND rule_id=? AND fingerprint=? AND del_flag='0'
FOR UPDATE
""", (resultSet, rowNum) -> new StateRow(resultSet.getLong("evaluation_state_id"),
resultSet.getLong("owner_object_id"), resultSet.getString("owner_object_name"),
resultSet.getString("project_ref"), resultSet.getString("data_domain_code"),
resultSet.getInt("trigger_streak"), resultSet.getInt("recovery_streak"),
resultSet.getString("last_known_state"), resultSet.getString("last_evaluation_key"),
localDateTime(resultSet.getTimestamp("next_open_at")), resultSet.getLong("version")),
evaluation.orgId(), evaluation.ruleId(), evaluation.fingerprint());
return rows.isEmpty() ? null : rows.getFirst();
}
private EventRuntime lockActiveEvent(long orgId, String fingerprint) {
List<EventRuntime> rows = jdbcTemplate.query("""
SELECT event_id, event_status, version
FROM ops_alert_event
WHERE org_id=? AND fingerprint=? AND event_status IN ('OPEN', 'ASSIGNED', 'PROCESSING')
AND del_flag='0'
FOR UPDATE
""", (resultSet, rowNum) -> new EventRuntime(resultSet.getLong("event_id"),
EventStatus.valueOf(resultSet.getString("event_status")), resultSet.getLong("version")),
orgId, fingerprint);
if (rows.size() > 1) {
throw AlertEventDomainException.ownerUnavailable();
}
return rows.isEmpty() ? null : rows.getFirst();
}
private void saveUnknownState(String evaluationKey, OwnerEvaluation evaluation, StateRow state) {
if (state == null) {
jdbcTemplate.update("""
INSERT INTO ops_alert_evaluation_state (
evaluation_state_id, rule_id, org_id, fingerprint, owner_object_id, owner_object_name,
project_ref, data_domain_code, trigger_streak, recovery_streak, last_evaluation_key,
create_dept
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
""", IdGeneratorUtil.nextLongId(), evaluation.ruleId(), evaluation.orgId(), evaluation.fingerprint(),
evaluation.ownerObjectId(), evaluation.ownerObjectName(), evaluation.projectRef(),
evaluation.dataDomainCode(), evaluationKey, evaluation.orgId());
} else {
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_evaluation_state
SET owner_object_name=?, last_evaluation_key=?, version=version+1
WHERE evaluation_state_id=? AND version=? AND del_flag='0'
""", evaluation.ownerObjectName(), evaluationKey, state.stateId(), state.version()),
"告警评估状态已变化");
}
}
private void saveKnownState(String evaluationKey, OwnerEvaluation evaluation, StateRow state,
int triggerStreak, int recoveryStreak, String knownState,
LocalDateTime nextOpenAt) {
if (state == null) {
jdbcTemplate.update("""
INSERT INTO ops_alert_evaluation_state (
evaluation_state_id, rule_id, org_id, fingerprint, owner_object_id, owner_object_name,
project_ref, data_domain_code, trigger_streak, recovery_streak, last_known_state,
last_metric_value, last_evidence_sha256, last_evaluation_key, next_open_at,
last_observed_at, create_dept
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), evaluation.ruleId(), evaluation.orgId(), evaluation.fingerprint(),
evaluation.ownerObjectId(), evaluation.ownerObjectName(), evaluation.projectRef(),
evaluation.dataDomainCode(), triggerStreak, recoveryStreak, knownState, evaluation.metricValue(),
evaluation.evidenceSha256(), evaluationKey, timestamp(nextOpenAt),
Timestamp.valueOf(evaluation.observedTo()), evaluation.orgId());
} else {
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_evaluation_state
SET owner_object_name=?, trigger_streak=?, recovery_streak=?, last_known_state=?, last_metric_value=?,
last_evidence_sha256=?, last_evaluation_key=?, next_open_at=?, last_observed_at=?,
version=version+1
WHERE evaluation_state_id=? AND version=? AND del_flag='0'
""", evaluation.ownerObjectName(), triggerStreak, recoveryStreak, knownState, evaluation.metricValue(),
evaluation.evidenceSha256(), evaluationKey, timestamp(nextOpenAt),
Timestamp.valueOf(evaluation.observedTo()), state.stateId(), state.version()),
"告警评估状态已变化");
}
}
private boolean insertOccurrence(String evaluationKey,long eventId, OwnerEvaluation evaluation) {
Integer count = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM ops_alert_occurrence
WHERE event_id=? AND evidence_sha256=? AND del_flag='0'
""", Integer.class, eventId, evaluation.evidenceSha256());
if (count != null && count > 0) {
return false;
}
insertOccurrenceRow(evaluationKey,eventId, evaluation);
return true;
}
private void insertOccurrenceRow(String evaluationKey,long eventId, OwnerEvaluation evaluation) {
long occurrenceId=IdGeneratorUtil.nextLongId();
requireChanged(jdbcTemplate.update("""
INSERT INTO ops_alert_occurrence (
occurrence_id, event_id, org_id, metric_value, sample_count, evidence_sha256,
observed_from, observed_to, create_dept
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", occurrenceId, eventId, evaluation.orgId(), evaluation.metricValue(),
evaluation.sampleCount(), evaluation.evidenceSha256(), Timestamp.valueOf(evaluation.observedFrom()),
Timestamp.valueOf(evaluation.observedTo()), evaluation.orgId()),"发生记录未完整写入");
bindings.insert(evaluationKey,eventId,occurrenceId,evaluation);
}
private void insertNotification(long eventId, long orgId, NotificationType type, Identity recipient,
String content, String dedupKey, String requestId) {
jdbcTemplate.update("""
INSERT INTO ops_alert_notification (
notification_id, event_id, org_id, notification_type, notification_status,
recipient_user_id, recipient_user_name, content_summary, dedup_key, request_id, create_dept
) VALUES (?, ?, ?, ?, 'RECORDED', ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), eventId, orgId, type.name(), recipient.userId(),
recipient.displayName(), bounded(content, 512), dedupKey, requestId, orgId);
}
private void insertTimeline(long eventId, long orgId, String action, EventStatus from, EventStatus to,
String requestId, String reason) {
jdbcTemplate.update("""
INSERT INTO ops_alert_timeline (
timeline_id, event_id, org_id, action_type, from_status, to_status,
actor_user_id, actor_name, request_id, reason_summary, create_dept
) VALUES (?, ?, ?, ?, ?, ?, NULL, '系统', ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), eventId, orgId, action, name(from), to.name(), requestId,
bounded(reason, 500), orgId);
}
private void lockRules(List<EvaluationWork> work,List<EscalationCandidate> escalations) {
var ordered=new java.util.TreeMap<RuleKey,Rule>();
for(var w:work)ordered.put(new RuleKey(w.rule().orgId(),w.rule().ruleId()),w.rule());
Set<RuleKey> exclusive=new HashSet<>();for(var e:escalations){var key=new RuleKey(e.orgId(),e.ruleId());exclusive.add(key);ordered.putIfAbsent(key,null);}
for(var entry:ordered.entrySet()){
var key=entry.getKey();
var rows=jdbcTemplate.query(RULE_SELECT+" WHERE r.org_id=? AND r.rule_id=? AND r.del_flag='0'"+(exclusive.contains(key)?" FOR UPDATE":" FOR UPDATE"),
(r,n)->AlertEventJdbcRepository.mapRule(r),key.org(),key.id());
if(entry.getValue()!=null&&(rows.size()!=1||!entry.getValue().equals(rows.getFirst())||!rows.getFirst().enabled()))throw AlertEventDomainException.conflict("告警规则已变化,本轮评估已停止");
}
}
private record RuleKey(long org,long id) implements Comparable<RuleKey>{public int compareTo(RuleKey other){int value=Long.compare(org,other.org);return value==0?Long.compare(id,other.id):value;}}
private static void assertEvaluation(Rule rule, OwnerEvaluation evaluation, StateRow state) {
if (evaluation.ruleId() != rule.ruleId() || evaluation.orgId() != rule.orgId()
|| evaluation.source() != rule.source() || evaluation.ownerObjectId() <= 0
|| evaluation.ownerObjectName() == null || evaluation.ownerObjectName().isBlank()
|| evaluation.fingerprint() == null || evaluation.fingerprint().length() != 64
|| evaluation.observedFrom() == null || evaluation.observedTo() == null
|| evaluation.observedFrom().isAfter(evaluation.observedTo())
|| (evaluation.known() && (evaluation.metricValue() == null || evaluation.metricValue().signum() < 0
|| evaluation.sampleCount() <= 0 || evaluation.evidenceSha256() == null
|| evaluation.evidenceSha256().length() != 64))
|| (!evaluation.known() && (evaluation.breached() || evaluation.metricValue() != null
|| evaluation.sampleCount() != 0))
|| (state != null && (state.ownerObjectId() != evaluation.ownerObjectId()
|| !java.util.Objects.equals(state.projectRef(), evaluation.projectRef())
|| !java.util.Objects.equals(state.dataDomainCode(), evaluation.dataDomainCode())))) {
throw AlertEventDomainException.ownerUnavailable();
}
}
private static void validateWork(String evaluationKey, LocalDateTime observedAt, List<EvaluationWork> work,
List<EscalationCandidate> candidates, Map<Long, Identity> identities) {
if (evaluationKey == null || evaluationKey.isBlank() || evaluationKey.length() > 128
|| observedAt == null || work == null || candidates == null || identities == null) {
throw new IllegalArgumentException("alert evaluation work is invalid");
}
int count = 0;
Set<String> fingerprints = new HashSet<>();
Set<Long> rules = new HashSet<>();
for (EvaluationWork item : work) {
if (item == null || item.rule() == null || item.evaluations() == null
|| !rules.add(item.rule().ruleId())) {
throw AlertEventDomainException.ownerUnavailable();
}
count += item.evaluations().size();
for (OwnerEvaluation evaluation : item.evaluations()) {
if (!fingerprints.add(evaluation.fingerprint())) {
throw AlertEventDomainException.ownerUnavailable();
}
}
}
if (count > AlertEventPolicy.MAX_FINGERPRINTS) {
throw AlertEventDomainException.limitExceeded("单轮告警评估超过5000个指纹");
}
}
private static Identity requireIdentity(Map<Long, Identity> identities, long userId, long orgId) {
Identity identity = identities.get(userId);
if (identity == null || identity.orgId() != orgId) {
throw AlertEventDomainException.identityUnavailable();
}
return identity;
}
private static void append(StringBuilder where, List<Object> parameters, String column, String value) {
if (value != null) {
where.append(" AND ").append(column).append("=?");
parameters.add(value);
}
}
private static String normalizeScope(String value) {
if (value == null || value.isBlank()) {
return null;
}
String normalized = value.trim();
if (normalized.length() > 100) {
throw new IllegalArgumentException("alert duty scope is invalid");
}
return normalized;
}
private static long requireCount(Long value) {
if (value == null || value < 0) {
throw AlertEventDomainException.requestUnavailable();
}
return value;
}
private static LocalDateTime later(LocalDateTime left, LocalDateTime right) {
if (left == null) return right;
if (right == null) return left;
return left.isAfter(right) ? left : right;
}
private static Timestamp timestamp(LocalDateTime value) {
return value == null ? null : Timestamp.valueOf(value);
}
private static String name(Enum<?> value) {
return value == null ? null : value.name();
}
private static String bounded(String value, int maximum) {
return value.length() <= maximum ? value : value.substring(0, maximum);
}
private static void requireChanged(int changed, String message) {
if (changed != 1) {
throw AlertEventDomainException.conflict(message);
}
}
private static Long nullableLong(ResultSet resultSet, String column) throws SQLException {
long value = resultSet.getLong(column);
return resultSet.wasNull() ? null : value;
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
record EvaluationWork(Rule rule, List<OwnerEvaluation> evaluations) {
EvaluationWork {
evaluations = evaluations == null ? List.of() : List.copyOf(evaluations);
}
}
record EscalationCandidate(long eventId, long orgId, long ruleId, long recipientUserId) {
}
private record StateRow(
long stateId,
long ownerObjectId,
String ownerObjectName,
String projectRef,
String dataDomainCode,
int triggerStreak,
int recoveryStreak,
String lastKnownState,
String lastEvaluationKey,
LocalDateTime nextOpenAt,
long version
) {
}
private record EventRuntime(long eventId, EventStatus status, long version) {
}
private record EscalationRuntime(
long eventId,
EventStatus status,
long version,
LocalDateTime openedAt,
String ruleName,
String ownerObjectName,
Long escalationUserId,
int waitMinutes,
boolean enabled
) {
}
}
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes = {AlertEventController.class, ExternalAlertDeliveryController.class})
class AlertEventExceptionHandler {
@ExceptionHandler(AlertEventDomainException.class)
ResponseEntity<R<Void>> handle(AlertEventDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,17 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.IdentityCandidate;
import java.util.Collection;
import java.util.List;
import java.util.Map;
interface AlertEventIdentityGateway {
Map<Long, Identity> requireActiveUsers(long orgId, Collection<Long> userIds);
List<IdentityCandidate> searchActiveUsers(long orgId, String keyword, int limit);
record Identity(long userId, long orgId, String userName, String displayName) {
}
}
@@ -0,0 +1,703 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventIdentityGateway.Identity;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.Rule;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventPolicy.NormalizedPostmortem;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventPolicy.NormalizedRule;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventDetailView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventStatus;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventSummary;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Metric;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotificationStatus;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotificationType;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotificationView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.OccurrenceView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Operator;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PageView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PostmortemView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.ProcessAction;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.TimelineView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.VerifyAction;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.WriteView;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.core.JacksonException;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.JavaType;
import tools.jackson.databind.json.JsonMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
@Repository
class AlertEventJdbcRepository {
private static final String RULE_SELECT = """
SELECT r.rule_id, r.org_id, r.rule_name, r.source_type, r.metric_type, r.operator_type,
r.threshold_value, r.severity, r.observation_minutes, r.trigger_count, r.recovery_count,
r.aggregate_minutes, r.silence_minutes, r.project_ref, r.data_domain_code,
r.primary_user_id, r.escalation_user_id, r.escalation_wait_minutes, r.enabled_flag,
r.version, r.create_time, r.update_time
FROM ops_alert_rule r
""";
private static final String EVENT_SELECT = """
SELECT e.event_id, e.rule_id, e.rule_name, e.source_type, e.owner_object_id,
e.owner_object_name, e.project_ref, e.data_domain_code, e.metric_type,
e.operator_type, e.threshold_value, e.current_metric_value, e.severity,
e.event_status, e.occurrence_count, e.primary_user_id, e.primary_user_name,
e.assignee_user_id, e.assignee_user_name, e.opened_at, e.last_occurred_at,
e.resolved_at, e.verified_at, e.closed_at, e.version
FROM ops_alert_event e
""";
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final JsonMapper objectMapper;
AlertEventJdbcRepository(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate,
JsonMapper objectMapper) {
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
this.objectMapper = objectMapper;
}
RulePage pageRules(Actor actor, String keyword, Source source, Boolean enabled, int pageNum, int pageSize) {
StringBuilder where = new StringBuilder(" WHERE r.org_id=? AND r.del_flag='0'");
List<Object> parameters = new ArrayList<>();
parameters.add(actor.orgId());
if (keyword != null) {
where.append(" AND (r.rule_name LIKE ? ESCAPE '=' OR CAST(r.rule_id AS CHAR) LIKE ? ESCAPE '=')");
String pattern = contains(keyword);
parameters.add(pattern);
parameters.add(pattern);
}
append(where, parameters, "r.source_type", name(source));
append(where, parameters, "r.enabled_flag", enabled == null ? null : enabled ? "1" : "0");
Long total = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ops_alert_rule r" + where,
Long.class, parameters.toArray());
List<Object> pageParameters = new ArrayList<>(parameters);
pageParameters.add(pageSize);
pageParameters.add(offset(pageNum, pageSize));
List<Rule> rows = jdbcTemplate.query(RULE_SELECT + where
+ " ORDER BY r.update_time DESC, r.rule_id DESC LIMIT ? OFFSET ?",
(resultSet, rowNum) -> mapRule(resultSet), pageParameters.toArray());
return new RulePage(rows, total == null ? 0 : total);
}
Rule requireRule(Actor actor, long ruleId) {
List<Rule> rows = jdbcTemplate.query(RULE_SELECT
+ " WHERE r.rule_id=? AND r.org_id=? AND r.del_flag='0'",
(resultSet, rowNum) -> mapRule(resultSet), ruleId, actor.orgId());
if (rows.isEmpty()) {
throw AlertEventDomainException.ruleNotFound();
}
return rows.getFirst();
}
WriteView<RuleView> createRule(Actor actor, NormalizedRule rule, Map<Long, Identity> identities,
String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/rules";
return idempotent(actor, "POST", path, key, requestHash, RuleView.class, requestId -> {
long ruleId = IdGeneratorUtil.nextLongId();
try {
jdbcTemplate.update("""
INSERT INTO ops_alert_rule (
rule_id, org_id, rule_name, source_type, metric_type, operator_type,
threshold_value, severity, observation_minutes, trigger_count, recovery_count,
aggregate_minutes, silence_minutes, project_ref, data_domain_code, primary_user_id,
escalation_user_id, escalation_wait_minutes, enabled_flag,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", ruleId, actor.orgId(), rule.name(), rule.source().name(), rule.metric().name(),
rule.operator().name(), rule.threshold(), rule.severity().name(), rule.observationMinutes(),
rule.triggerCount(), rule.recoveryCount(), rule.aggregateMinutes(), rule.silenceMinutes(),
rule.projectRef(), rule.dataDomainCode(), rule.primaryUserId(), rule.escalationUserId(),
rule.escalationWaitMinutes(), rule.enabled() ? "1" : "0", actor.orgId(), actor.actorId(),
actor.actorId());
} catch (DuplicateKeyException exception) {
throw AlertEventDomainException.conflict("同一组织内已存在同名告警规则");
}
return ruleView(requireRule(actor, ruleId), identities);
});
}
WriteView<RuleView> updateRule(Actor actor, long ruleId, NormalizedRule rule,
Map<Long, Identity> identities, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/rules/" + ruleId;
return idempotent(actor, "PUT", path, key, requestHash, RuleView.class, requestId -> {
requireRule(actor, ruleId);
int changed;
try {
changed = jdbcTemplate.update("""
UPDATE ops_alert_rule
SET rule_name=?, source_type=?, metric_type=?, operator_type=?, threshold_value=?,
severity=?, observation_minutes=?, trigger_count=?, recovery_count=?,
aggregate_minutes=?, silence_minutes=?, project_ref=?, data_domain_code=?,
primary_user_id=?, escalation_user_id=?, escalation_wait_minutes=?, enabled_flag=?,
update_by=?, version=version+1
WHERE rule_id=? AND org_id=? AND version=? AND del_flag='0'
""", rule.name(), rule.source().name(), rule.metric().name(), rule.operator().name(),
rule.threshold(), rule.severity().name(), rule.observationMinutes(), rule.triggerCount(),
rule.recoveryCount(), rule.aggregateMinutes(), rule.silenceMinutes(), rule.projectRef(),
rule.dataDomainCode(), rule.primaryUserId(), rule.escalationUserId(),
rule.escalationWaitMinutes(), rule.enabled() ? "1" : "0", actor.actorId(), ruleId,
actor.orgId(), rule.version());
} catch (DuplicateKeyException exception) {
throw AlertEventDomainException.conflict("同一组织内已存在同名告警规则");
}
requireChanged(changed, "规则版本已变化,请刷新后重试");
return ruleView(requireRule(actor, ruleId), identities);
});
}
WriteView<RuleView> updateRuleStatus(Actor actor, long ruleId, boolean enabled, long version,
Map<Long, Identity> identities, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/rules/" + ruleId + "/status";
return idempotent(actor, "PUT", path, key, requestHash, RuleView.class, requestId -> {
requireRule(actor, ruleId);
int changed = jdbcTemplate.update("""
UPDATE ops_alert_rule
SET enabled_flag=?, update_by=?, version=version+1
WHERE rule_id=? AND org_id=? AND version=? AND del_flag='0'
""", enabled ? "1" : "0", actor.actorId(), ruleId, actor.orgId(), version);
requireChanged(changed, "规则版本已变化,请刷新后重试");
return ruleView(requireRule(actor, ruleId), identities);
});
}
PageView<EventSummary> pageEvents(Actor actor, String keyword, Source source, Severity severity,
EventStatus eventStatus, String projectRef, String dataDomainCode,
int pageNum, int pageSize) {
StringBuilder where = new StringBuilder(" WHERE e.org_id=? AND e.del_flag='0'");
List<Object> parameters = new ArrayList<>();
parameters.add(actor.orgId());
if (keyword != null) {
where.append(" AND (e.rule_name LIKE ? ESCAPE '=' OR e.owner_object_name LIKE ? ESCAPE '='")
.append(" OR CAST(e.event_id AS CHAR) LIKE ? ESCAPE '=')");
String pattern = contains(keyword);
parameters.add(pattern);
parameters.add(pattern);
parameters.add(pattern);
}
append(where, parameters, "e.source_type", name(source));
append(where, parameters, "e.severity", name(severity));
append(where, parameters, "e.event_status", name(eventStatus));
append(where, parameters, "e.project_ref", projectRef);
append(where, parameters, "e.data_domain_code", dataDomainCode);
Long total = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ops_alert_event e" + where,
Long.class, parameters.toArray());
List<Object> pageParameters = new ArrayList<>(parameters);
pageParameters.add(pageSize);
pageParameters.add(offset(pageNum, pageSize));
List<EventSummary> rows = jdbcTemplate.query(EVENT_SELECT + where
+ " ORDER BY e.last_occurred_at DESC, e.event_id DESC LIMIT ? OFFSET ?",
(resultSet, rowNum) -> mapEvent(resultSet), pageParameters.toArray());
return new PageView<>(rows, total == null ? 0 : total);
}
EventDetailView detail(Actor actor, long eventId) {
EventSummary summary = requireEvent(actor.orgId(), eventId, false);
List<OccurrenceView> occurrences = jdbcTemplate.query("""
SELECT occurrence_id, metric_value, sample_count, evidence_sha256,
observed_from, observed_to, create_time
FROM ops_alert_occurrence
WHERE event_id=? AND org_id=? AND del_flag='0'
ORDER BY observed_to DESC, occurrence_id DESC
LIMIT 100
""", (resultSet, rowNum) -> new OccurrenceView(resultSet.getLong("occurrence_id"),
resultSet.getBigDecimal("metric_value"), resultSet.getLong("sample_count"),
resultSet.getString("evidence_sha256"), localDateTime(resultSet.getTimestamp("observed_from")),
localDateTime(resultSet.getTimestamp("observed_to")),
localDateTime(resultSet.getTimestamp("create_time"))), eventId, actor.orgId());
List<NotificationView> notifications = jdbcTemplate.query("""
SELECT notification_id, notification_type, notification_status, recipient_user_id,
recipient_user_name, content_summary, create_time, mailbox_state, mailbox_message_id, mailbox_attempted_at
FROM ops_alert_notification
WHERE event_id=? AND org_id=? AND del_flag='0'
ORDER BY create_time DESC, notification_id DESC
LIMIT 100
""", (resultSet, rowNum) -> new NotificationView(resultSet.getLong("notification_id"),
NotificationType.valueOf(resultSet.getString("notification_type")),
NotificationStatus.valueOf(resultSet.getString("notification_status")),
resultSet.getLong("recipient_user_id"), resultSet.getString("recipient_user_name"),
resultSet.getString("content_summary"), localDateTime(resultSet.getTimestamp("create_time")),
resultSet.getString("mailbox_state"), nullableLong(resultSet, "mailbox_message_id"),
localDateTime(resultSet.getTimestamp("mailbox_attempted_at"))),
eventId, actor.orgId());
List<TimelineView> timeline = jdbcTemplate.query("""
SELECT timeline_id, action_type, from_status, to_status, actor_user_id,
actor_name, request_id, reason_summary, create_time
FROM ops_alert_timeline
WHERE event_id=? AND org_id=? AND del_flag='0'
ORDER BY create_time, timeline_id
LIMIT 200
""", (resultSet, rowNum) -> new TimelineView(resultSet.getLong("timeline_id"),
resultSet.getString("action_type"), enumValue(EventStatus.class, resultSet.getString("from_status")),
EventStatus.valueOf(resultSet.getString("to_status")), nullableLong(resultSet, "actor_user_id"),
resultSet.getString("actor_name"), resultSet.getString("request_id"),
resultSet.getString("reason_summary"), localDateTime(resultSet.getTimestamp("create_time"))),
eventId, actor.orgId());
PostmortemView postmortem = findPostmortem(actor.orgId(), eventId);
return new EventDetailView(summary, occurrences, notifications, timeline, postmortem);
}
ScheduledNotification workflowNotification(Actor actor, long eventId, String key, String commandSha) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/notifications";
// The existing business request hash also binds the workflow's version, recipient and options.
var request = replay(actor, "POST", path, key, commandSha, EventDetailView.class);
if (request == null) return null;
var rows = jdbcTemplate.query("""
SELECT notification_id,event_id,recipient_user_id,content_summary,request_id,mailbox_state,mailbox_message_id
FROM ops_alert_notification WHERE org_id=? AND event_id=? AND request_id=? AND del_flag='0'
""", (rs, row) -> new ScheduledNotification(rs.getLong(1), rs.getLong(2), rs.getLong(3),
rs.getString(4), rs.getString(5), rs.getString(6), rs.getObject(7, Long.class)), actor.orgId(), eventId, request.requestId());
if (rows.size() != 1) throw AlertEventDomainException.requestUnavailable();
return rows.getFirst();
}
boolean reserveMailbox(Actor actor, ScheduledNotification notification) {
return jdbcTemplate.update("UPDATE ops_alert_notification SET mailbox_state='SUBMITTING',mailbox_attempted_at=NOW(6) "
+ "WHERE org_id=? AND notification_id=? AND event_id=? AND recipient_user_id=? AND mailbox_state='RECORDED' AND del_flag='0'",
actor.orgId(), notification.id(), notification.eventId(), notification.recipientId()) == 1;
}
void mailboxResult(Actor actor, ScheduledNotification notification, Long messageId) {
jdbcTemplate.update("UPDATE ops_alert_notification SET mailbox_state=?,mailbox_message_id=? "
+ "WHERE org_id=? AND notification_id=? AND event_id=? AND recipient_user_id=? AND mailbox_state<>'STORED' AND del_flag='0'",
messageId == null ? "UNKNOWN" : "STORED", messageId, actor.orgId(), notification.id(), notification.eventId(), notification.recipientId());
}
record ScheduledNotification(long id, long eventId, long recipientId, String summary, String requestId,
String mailboxState, Long messageId) { }
WriteView<EventDetailView> notifyEvent(Actor actor, long eventId, Identity recipient, String reason,
long version, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/notifications";
return idempotent(actor, "POST", path, key, requestHash, EventDetailView.class, requestId -> {
EventSummary event = requireEvent(actor.orgId(), eventId, true);
requireVersion(event, version);
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event SET update_by=?, version=version+1
WHERE event_id=? AND org_id=? AND version=? AND del_flag='0'
""", actor.actorId(), eventId, actor.orgId(), version), "事件版本已变化,请刷新后重试");
insertNotification(eventId, actor.orgId(), NotificationType.MANUAL, recipient,
"告警事件通知:" + event.ruleName() + " / " + event.ownerObjectName(), "MANUAL:" + requestId,
requestId, actor.actorId());
insertTimeline(eventId, actor.orgId(), "NOTIFY", event.status(), event.status(), actor.actorId(),
actor.actorName(), requestId, reason, actor.actorId());
return detail(actor, eventId);
});
}
WriteView<EventDetailView> assignEvent(Actor actor, long eventId, Identity assignee, String reason,
long version, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/assignment";
return idempotent(actor, "POST", path, key, requestHash, EventDetailView.class, requestId -> {
EventSummary event = requireEvent(actor.orgId(), eventId, true);
requireVersion(event, version);
if (event.status() != EventStatus.OPEN && event.status() != EventStatus.ASSIGNED
&& event.status() != EventStatus.PROCESSING) {
throw AlertEventDomainException.conflict("当前状态不可分派");
}
EventStatus next = event.status() == EventStatus.OPEN ? EventStatus.ASSIGNED : event.status();
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event
SET assignee_user_id=?, assignee_user_name=?, event_status=?, update_by=?, version=version+1
WHERE event_id=? AND org_id=? AND version=? AND event_status=? AND del_flag='0'
""", assignee.userId(), assignee.displayName(), next.name(), actor.actorId(), eventId,
actor.orgId(), version, event.status().name()), "事件状态或版本已变化,请刷新后重试");
insertTimeline(eventId, actor.orgId(), event.assigneeUserId() == null ? "ASSIGN" : "REASSIGN",
event.status(), next, actor.actorId(), actor.actorName(), requestId, reason, actor.actorId());
return detail(actor, eventId);
});
}
WriteView<EventDetailView> processEvent(Actor actor, long eventId, ProcessAction action, String reason,
long version, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/processing";
return idempotent(actor, "POST", path, key, requestHash, EventDetailView.class, requestId -> {
EventSummary event = requireEvent(actor.orgId(), eventId, true);
requireVersion(event, version);
EventStatus expected = action == ProcessAction.START_PROCESSING
? EventStatus.ASSIGNED : EventStatus.PROCESSING;
EventStatus next = action == ProcessAction.START_PROCESSING
? EventStatus.PROCESSING : EventStatus.RESOLVED;
if (event.status() != expected) {
throw AlertEventDomainException.conflict("当前状态不可执行该处置动作");
}
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event
SET event_status=?, resolved_at=CASE WHEN ?='RESOLVED' THEN NOW(6) ELSE resolved_at END,
update_by=?, version=version+1
WHERE event_id=? AND org_id=? AND version=? AND event_status=? AND del_flag='0'
""", next.name(), next.name(), actor.actorId(), eventId, actor.orgId(), version,
expected.name()), "事件状态或版本已变化,请刷新后重试");
insertTimeline(eventId, actor.orgId(), action.name(), expected, next, actor.actorId(),
actor.actorName(), requestId, reason, actor.actorId());
return detail(actor, eventId);
});
}
WriteView<EventDetailView> verifyEvent(Actor actor, long eventId, VerifyAction action, String reason,
long version, String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/verification";
return idempotent(actor, "POST", path, key, requestHash, EventDetailView.class, requestId -> {
EventSummary event = requireEvent(actor.orgId(), eventId, true);
requireVersion(event, version);
EventStatus expected = action == VerifyAction.VERIFY ? EventStatus.RESOLVED : EventStatus.VERIFIED;
EventStatus next = action == VerifyAction.VERIFY ? EventStatus.VERIFIED : EventStatus.CLOSED;
if (event.status() != expected) {
throw AlertEventDomainException.conflict("当前状态不可执行该验证动作");
}
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event
SET event_status=?, verified_at=CASE WHEN ?='VERIFIED' THEN NOW(6) ELSE verified_at END,
closed_at=CASE WHEN ?='CLOSED' THEN NOW(6) ELSE closed_at END,
update_by=?, version=version+1
WHERE event_id=? AND org_id=? AND version=? AND event_status=? AND del_flag='0'
""", next.name(), next.name(), next.name(), actor.actorId(), eventId, actor.orgId(), version,
expected.name()), "事件状态或版本已变化,请刷新后重试");
insertTimeline(eventId, actor.orgId(), action.name(), expected, next, actor.actorId(),
actor.actorName(), requestId, reason, actor.actorId());
return detail(actor, eventId);
});
}
WriteView<EventDetailView> savePostmortem(Actor actor, long eventId, NormalizedPostmortem postmortem,
String key, String requestHash) {
String path = "/api/dataops/v1/alert-events/" + eventId + "/postmortem";
return idempotent(actor, "PUT", path, key, requestHash, EventDetailView.class, requestId -> {
EventSummary event = requireEvent(actor.orgId(), eventId, true);
requireVersion(event, postmortem.eventVersion());
if (event.status() != EventStatus.RESOLVED && event.status() != EventStatus.VERIFIED
&& event.status() != EventStatus.CLOSED) {
throw AlertEventDomainException.conflict("事件恢复后才能维护复盘");
}
List<PostmortemVersion> existing = jdbcTemplate.query("""
SELECT postmortem_id, version FROM ops_alert_postmortem
WHERE event_id=? AND org_id=? AND del_flag='0' FOR UPDATE
""", (resultSet, rowNum) -> new PostmortemVersion(resultSet.getLong(1), resultSet.getLong(2)),
eventId, actor.orgId());
if (existing.isEmpty()) {
if (postmortem.postmortemVersion() != null) {
throw AlertEventDomainException.conflict("复盘版本已变化,请刷新后重试");
}
jdbcTemplate.update("""
INSERT INTO ops_alert_postmortem (
postmortem_id, event_id, org_id, summary_text, root_cause, impact_text,
corrective_actions, evidence_refs_json, author_user_id, author_name,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), eventId, actor.orgId(), postmortem.summary(),
postmortem.rootCause(), postmortem.impact(), postmortem.correctiveActions(),
json(postmortem.evidenceRefs()), actor.actorId(), actor.actorName(), actor.orgId(),
actor.actorId(), actor.actorId());
} else {
PostmortemVersion current = existing.getFirst();
if (postmortem.postmortemVersion() == null
|| current.version() != postmortem.postmortemVersion()) {
throw AlertEventDomainException.conflict("复盘版本已变化,请刷新后重试");
}
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_postmortem
SET summary_text=?, root_cause=?, impact_text=?, corrective_actions=?, evidence_refs_json=?,
author_user_id=?, author_name=?, update_by=?, version=version+1
WHERE postmortem_id=? AND org_id=? AND version=? AND del_flag='0'
""", postmortem.summary(), postmortem.rootCause(), postmortem.impact(),
postmortem.correctiveActions(), json(postmortem.evidenceRefs()), actor.actorId(),
actor.actorName(), actor.actorId(), current.postmortemId(), actor.orgId(), current.version()),
"复盘版本已变化,请刷新后重试");
}
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_event SET update_by=?, version=version+1
WHERE event_id=? AND org_id=? AND version=? AND event_status=? AND del_flag='0'
""", actor.actorId(), eventId, actor.orgId(), postmortem.eventVersion(), event.status().name()),
"事件状态或版本已变化,请刷新后重试");
insertTimeline(eventId, actor.orgId(), "POSTMORTEM", event.status(), event.status(), actor.actorId(),
actor.actorName(), requestId, "复盘已更新", actor.actorId());
return detail(actor, eventId);
});
}
Set<Long> ruleIdentityIds(Collection<Rule> rules) {
Set<Long> ids = new LinkedHashSet<>();
for (Rule rule : rules) {
ids.add(rule.primaryUserId());
if (rule.escalationUserId() != null) {
ids.add(rule.escalationUserId());
}
}
return Set.copyOf(ids);
}
static RuleView ruleView(Rule rule, Map<Long, Identity> identities) {
Identity primary = requireIdentity(identities, rule.primaryUserId());
Identity escalation = rule.escalationUserId() == null
? null : requireIdentity(identities, rule.escalationUserId());
return new RuleView(rule.ruleId(), rule.orgId(), rule.name(), rule.source(), rule.metric(), rule.operator(),
rule.threshold(), rule.severity(), rule.observationMinutes(), rule.triggerCount(), rule.recoveryCount(),
rule.aggregateMinutes(), rule.silenceMinutes(), rule.projectRef(), rule.dataDomainCode(),
rule.primaryUserId(), primary.displayName(), rule.escalationUserId(),
escalation == null ? null : escalation.displayName(), rule.escalationWaitMinutes(), rule.enabled(),
rule.version(), rule.createdAt(), rule.updatedAt());
}
private EventSummary requireEvent(long orgId, long eventId, boolean forUpdate) {
List<EventSummary> rows = jdbcTemplate.query(EVENT_SELECT
+ " WHERE e.event_id=? AND e.org_id=? AND e.del_flag='0'" + (forUpdate ? " FOR UPDATE" : ""),
(resultSet, rowNum) -> mapEvent(resultSet), eventId, orgId);
if (rows.isEmpty()) {
throw AlertEventDomainException.notFound();
}
return rows.getFirst();
}
private PostmortemView findPostmortem(long orgId, long eventId) {
List<PostmortemView> rows = jdbcTemplate.query("""
SELECT postmortem_id, summary_text, root_cause, impact_text, corrective_actions,
evidence_refs_json, author_user_id, author_name, version, create_time, update_time
FROM ops_alert_postmortem
WHERE event_id=? AND org_id=? AND del_flag='0'
""", (resultSet, rowNum) -> new PostmortemView(resultSet.getLong("postmortem_id"),
resultSet.getString("summary_text"), resultSet.getString("root_cause"),
resultSet.getString("impact_text"), resultSet.getString("corrective_actions"),
readStringList(resultSet.getString("evidence_refs_json")), resultSet.getLong("author_user_id"),
resultSet.getString("author_name"), resultSet.getLong("version"),
localDateTime(resultSet.getTimestamp("create_time")),
localDateTime(resultSet.getTimestamp("update_time"))), eventId, orgId);
return rows.isEmpty() ? null : rows.getFirst();
}
private void insertNotification(long eventId, long orgId, NotificationType type, Identity recipient,
String summary, String dedupKey, String requestId, Long actorId) {
jdbcTemplate.update("""
INSERT INTO ops_alert_notification (
notification_id, event_id, org_id, notification_type, notification_status,
recipient_user_id, recipient_user_name, content_summary, dedup_key, request_id,
create_dept, create_by
) VALUES (?, ?, ?, ?, 'RECORDED', ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), eventId, orgId, type.name(), recipient.userId(),
recipient.displayName(), bounded(summary, 512), dedupKey, requestId, orgId, actorId);
}
private void insertTimeline(long eventId, long orgId, String action, EventStatus from, EventStatus to,
Long actorId, String actorName, String requestId, String reason, Long createBy) {
jdbcTemplate.update("""
INSERT INTO ops_alert_timeline (
timeline_id, event_id, org_id, action_type, from_status, to_status,
actor_user_id, actor_name, request_id, reason_summary, create_dept, create_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), eventId, orgId, action, name(from), to.name(), actorId,
actorName, requestId, bounded(reason, 500), orgId, createBy);
}
private <T> WriteView<T> idempotent(Actor actor, String method, String path, String key, String hash,
Class<T> resultType, Function<String, T> action) {
try {
WriteView<T> result = transactionTemplate.execute(status -> {
WriteView<T> replay = replay(actor, method, path, key, hash, resultType);
if (replay != null) {
return replay;
}
long numericRequestId = IdGeneratorUtil.nextLongId();
String requestId = Long.toString(numericRequestId);
jdbcTemplate.update("""
INSERT INTO ops_alert_idempotency_request (
request_id, actor_id, org_id, request_method, request_path, idempotency_key,
request_sha256, request_status, create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, 'IN_PROGRESS', ?, ?, ?)
""", numericRequestId, actor.actorId(), actor.orgId(), method, path, key, hash,
actor.orgId(), actor.actorId(), actor.actorId());
WriteView<T> completed = new WriteView<>(requestId, action.apply(requestId));
requireChanged(jdbcTemplate.update("""
UPDATE ops_alert_idempotency_request
SET request_status='COMPLETED', response_json=?, update_by=?, version=version+1
WHERE request_id=? AND request_status='IN_PROGRESS' AND del_flag='0'
""", json(completed), actor.actorId(), numericRequestId), "幂等请求状态已变化");
return completed;
});
if (result == null) {
throw AlertEventDomainException.requestUnavailable();
}
return result;
} catch (DuplicateKeyException exception) {
WriteView<T> replay = replay(actor, method, path, key, hash, resultType);
if (replay != null) {
return replay;
}
throw AlertEventDomainException.conflict("幂等请求正在处理,请稍后重试");
}
}
private <T> WriteView<T> replay(Actor actor, String method, String path, String key, String hash,
Class<T> resultType) {
List<RequestRow> rows = jdbcTemplate.query("""
SELECT request_sha256, request_status, response_json
FROM ops_alert_idempotency_request
WHERE actor_id=? AND org_id=? AND request_method=? AND request_path=?
AND idempotency_key=? AND del_flag='0'
""", (resultSet, rowNum) -> new RequestRow(resultSet.getString(1), resultSet.getString(2),
resultSet.getString(3)), actor.actorId(), actor.orgId(), method, path, key);
if (rows.isEmpty()) {
return null;
}
if (rows.size() != 1) {
throw AlertEventDomainException.requestUnavailable();
}
RequestRow row = rows.getFirst();
if (!hash.equals(row.hash())) {
throw AlertEventDomainException.conflict("同一幂等键不能用于不同请求");
}
if (!"COMPLETED".equals(row.status()) || row.responseJson() == null) {
throw AlertEventDomainException.conflict("幂等请求正在处理,请稍后重试");
}
try {
JavaType type = objectMapper.getTypeFactory().constructParametricType(WriteView.class, resultType);
return objectMapper.readValue(row.responseJson(), type);
} catch (JacksonException exception) {
throw AlertEventDomainException.requestUnavailable();
}
}
private String json(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JacksonException exception) {
throw AlertEventDomainException.requestUnavailable();
}
}
private List<String> readStringList(String value) {
try {
return objectMapper.readValue(value, new TypeReference<>() { });
} catch (JacksonException exception) {
throw AlertEventDomainException.requestUnavailable();
}
}
static Rule mapRule(ResultSet resultSet) throws SQLException {
return new Rule(resultSet.getLong("rule_id"), resultSet.getLong("org_id"),
resultSet.getString("rule_name"), Source.valueOf(resultSet.getString("source_type")),
Metric.valueOf(resultSet.getString("metric_type")),
Operator.valueOf(resultSet.getString("operator_type")), resultSet.getBigDecimal("threshold_value"),
Severity.valueOf(resultSet.getString("severity")), resultSet.getInt("observation_minutes"),
resultSet.getInt("trigger_count"), resultSet.getInt("recovery_count"),
resultSet.getInt("aggregate_minutes"), resultSet.getInt("silence_minutes"),
resultSet.getString("project_ref"), resultSet.getString("data_domain_code"),
resultSet.getLong("primary_user_id"), nullableLong(resultSet, "escalation_user_id"),
resultSet.getInt("escalation_wait_minutes"), "1".equals(resultSet.getString("enabled_flag")),
resultSet.getLong("version"), localDateTime(resultSet.getTimestamp("create_time")),
localDateTime(resultSet.getTimestamp("update_time")));
}
private static EventSummary mapEvent(ResultSet resultSet) throws SQLException {
return new EventSummary(resultSet.getLong("event_id"), resultSet.getLong("rule_id"),
resultSet.getString("rule_name"), Source.valueOf(resultSet.getString("source_type")),
resultSet.getLong("owner_object_id"), resultSet.getString("owner_object_name"),
resultSet.getString("project_ref"), resultSet.getString("data_domain_code"),
Metric.valueOf(resultSet.getString("metric_type")),
Operator.valueOf(resultSet.getString("operator_type")), resultSet.getBigDecimal("threshold_value"),
resultSet.getBigDecimal("current_metric_value"), Severity.valueOf(resultSet.getString("severity")),
EventStatus.valueOf(resultSet.getString("event_status")), resultSet.getLong("occurrence_count"),
resultSet.getLong("primary_user_id"), resultSet.getString("primary_user_name"),
nullableLong(resultSet, "assignee_user_id"), resultSet.getString("assignee_user_name"),
localDateTime(resultSet.getTimestamp("opened_at")),
localDateTime(resultSet.getTimestamp("last_occurred_at")),
localDateTime(resultSet.getTimestamp("resolved_at")),
localDateTime(resultSet.getTimestamp("verified_at")),
localDateTime(resultSet.getTimestamp("closed_at")), resultSet.getLong("version"));
}
private static Identity requireIdentity(Map<Long, Identity> identities, long userId) {
Identity identity = identities.get(userId);
if (identity == null) {
throw AlertEventDomainException.identityUnavailable();
}
return identity;
}
private static void requireVersion(EventSummary event, long version) {
if (event.version() != version) {
throw AlertEventDomainException.conflict("事件版本已变化,请刷新后重试");
}
}
private static void requireChanged(int changed, String message) {
if (changed != 1) {
throw AlertEventDomainException.conflict(message);
}
}
private static void append(StringBuilder where, List<Object> parameters, String column, Object value) {
if (value == null) {
return;
}
where.append(" AND ").append(column).append("=?");
parameters.add(value);
}
private static String contains(String value) {
return "%" + value.replace("=", "==").replace("%", "=%").replace("_", "=_") + "%";
}
private static long offset(int pageNum, int pageSize) {
try {
return Math.multiplyExact((long) pageNum - 1, pageSize);
} catch (ArithmeticException exception) {
throw AlertEventDomainException.validation("页码过大");
}
}
private static String name(Enum<?> value) {
return value == null ? null : value.name();
}
private static <E extends Enum<E>> E enumValue(Class<E> type, String value) {
return value == null ? null : Enum.valueOf(type, value);
}
private static Long nullableLong(ResultSet resultSet, String column) throws SQLException {
long value = resultSet.getLong(column);
return resultSet.wasNull() ? null : value;
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
private static String bounded(String value, int maximum) {
if (value == null || value.length() <= maximum) {
return value;
}
return value.substring(0, maximum);
}
record RulePage(List<Rule> rows, long total) {
RulePage {
rows = rows == null ? List.of() : List.copyOf(rows);
}
}
private record RequestRow(String hash, String status, String responseJson) {
}
private record PostmortemVersion(long postmortemId, long version) {
}
}
@@ -0,0 +1,68 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.maintenance.JdbcMaintenanceLeaseRepository;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobDefinition;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobKind;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobRunner;
import cn.aixunkeji.datagov.maintenance.MaintenanceRunRequest;
import cn.aixunkeji.datagov.maintenance.MaintenanceRunResult;
import cn.aixunkeji.datagov.maintenance.ScheduledIdempotencyKey;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.time.Duration;
import java.time.LocalDateTime;
/** Bounded alert evaluation and in-platform escalation under the shared maintenance lease. */
@Component
public final class AlertEventMaintenance implements AutoCloseable {
private static final String JOB_NAME = "dataops.alert-event-evaluation";
private static final Duration WINDOW = Duration.ofMinutes(5);
private final AlertEventService service;
private final Clock clock = Clock.systemDefaultZone();
private final MaintenanceJobRunner runner;
private final MaintenanceJobDefinition definition = new MaintenanceJobDefinition(
1761500000000000048L,
JOB_NAME,
MaintenanceJobKind.IN_APP_ALERT,
Duration.ofMinutes(4),
Duration.ofMinutes(5)
);
public AlertEventMaintenance(AlertEventService service, JdbcTemplate jdbcTemplate) {
this.service = service;
this.runner = new MaintenanceJobRunner(
"aixun-dataops-alert-event",
new JdbcMaintenanceLeaseRepository(jdbcTemplate),
clock
);
}
@Scheduled(fixedDelayString = "${datagov.alert-event.evaluation-delay-ms:300000}")
public void evaluateScheduled() {
String key = ScheduledIdempotencyKey.forWindow(JOB_NAME, clock.instant(), WINDOW);
runner.run(definition, MaintenanceRunRequest.scheduled(key), context -> {
context.checkDeadline(clock.instant());
service.evaluate(context.idempotencyKey(), LocalDateTime.now(clock),clock.getZone().getId());
context.checkDeadline(clock.instant());
});
}
public MaintenanceRunResult compensate(String idempotencyKey, long actorId, String reason) {
return runner.run(definition, MaintenanceRunRequest.compensation(idempotencyKey, actorId, reason),
context -> {
context.checkDeadline(clock.instant());
service.evaluate(context.idempotencyKey(), LocalDateTime.now(clock),clock.getZone().getId());
context.checkDeadline(clock.instant());
});
}
@Override
public void close() {
runner.close();
}
}
@@ -0,0 +1,76 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Metric;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Operator;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
final class AlertEventModel {
private AlertEventModel() {
}
record Rule(
long ruleId,
long orgId,
String name,
Source source,
Metric metric,
Operator operator,
BigDecimal threshold,
Severity severity,
int observationMinutes,
int triggerCount,
int recoveryCount,
int aggregateMinutes,
int silenceMinutes,
String projectRef,
String dataDomainCode,
long primaryUserId,
Long escalationUserId,
int escalationWaitMinutes,
boolean enabled,
long version,
LocalDateTime createdAt,
LocalDateTime updatedAt
) {
}
record OwnerEvaluation(
long ruleId,
long orgId,
Source source,
String fingerprint,
long ownerObjectId,
String ownerObjectName,
String projectRef,
String dataDomainCode,
boolean known,
boolean breached,
BigDecimal metricValue,
long sampleCount,
String evidenceSha256,
LocalDateTime observedFrom,
LocalDateTime observedTo,
cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.Payload binding
) {
OwnerEvaluation(long ruleId,long orgId,Source source,String fingerprint,long ownerObjectId,String ownerObjectName,
String projectRef,String dataDomainCode,boolean known,boolean breached,BigDecimal metricValue,
long sampleCount,String evidenceSha256,LocalDateTime observedFrom,LocalDateTime observedTo){
this(ruleId,orgId,source,fingerprint,ownerObjectId,ownerObjectName,projectRef,dataDomainCode,known,breached,metricValue,sampleCount,evidenceSha256,observedFrom,observedTo,null);
}
OwnerEvaluation withBinding(cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.Payload value){
return new OwnerEvaluation(ruleId,orgId,source,fingerprint,ownerObjectId,ownerObjectName,projectRef,dataDomainCode,known,breached,metricValue,sampleCount,evidenceSha256,observedFrom,observedTo,value);
}
}
record EvaluationBatch(List<OwnerEvaluation> rows, int sourceRowCount) {
EvaluationBatch {
rows = rows == null ? List.of() : List.copyOf(rows);
}
}
}
@@ -0,0 +1,236 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PostmortemRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleSaveRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
final class AlertEventPolicy {
static final int MAX_OWNER_ROWS = 50_000;
static final int MAX_ENABLED_RULES = 1_000;
static final int MAX_FINGERPRINTS = 5_000;
static final int MAX_PAGE_SIZE = 100;
static final int MAX_CANDIDATES = 20;
private static final List<String> SENSITIVE_MARKERS = List.of(
"password=", "passwd=", "token=", "secret=", "authorization:", "private key"
);
private AlertEventPolicy() {
}
static NormalizedRule normalizeRule(RuleSaveRequest request, boolean create) {
if (request == null) {
throw AlertEventDomainException.validation("规则内容不能为空");
}
String name = requiredText(request.name(), "规则名称", 100);
if (request.source() == null || request.metric() == null || request.operator() == null
|| request.severity() == null) {
throw AlertEventDomainException.validation("来源、指标、操作符和严重度不能为空");
}
BigDecimal threshold = request.threshold();
if (threshold == null || threshold.signum() < 0 || threshold.precision() > 24 || threshold.scale() > 6) {
throw AlertEventDomainException.validation("阈值必须是最多24位、6位小数的非负数");
}
int observationMinutes = bounded(request.observationMinutes(), 1, 1_440, "观测窗口");
int triggerCount = bounded(request.triggerCount(), 1, 20, "连续触发次数");
int recoveryCount = bounded(request.recoveryCount(), 1, 20, "连续恢复次数");
int aggregateMinutes = bounded(request.aggregateMinutes(), 1, 1_440, "聚合窗口");
int silenceMinutes = bounded(request.silenceMinutes(), 0, 10_080, "静默时间");
int escalationWaitMinutes = bounded(request.escalationWaitMinutes(), 1, 1_440, "升级等待时间");
String dataDomainCode = optionalText(request.dataDomainCode(), "数据域", 100);
if (request.primaryUserId() == null || request.primaryUserId() <= 0) {
throw AlertEventDomainException.validation("主责任人不能为空");
}
if (request.escalationUserId() != null && request.escalationUserId() <= 0) {
throw AlertEventDomainException.validation("升级责任人无效");
}
if (request.primaryUserId().equals(request.escalationUserId())) {
throw AlertEventDomainException.validation("升级责任人不能与主责任人相同");
}
if (request.enabled() == null) {
throw AlertEventDomainException.validation("启用状态不能为空");
}
if (!create && (request.version() == null || request.version() < 0)) {
throw AlertEventDomainException.validation("版本不能为空");
}
return new NormalizedRule(name, request.source(), request.metric(), request.operator(),
threshold.stripTrailingZeros(), request.severity(), observationMinutes, triggerCount, recoveryCount,
aggregateMinutes, silenceMinutes, null, dataDomainCode, request.primaryUserId(),
request.escalationUserId(), escalationWaitMinutes, request.enabled(), request.version());
}
static int pageSize(Integer pageSize) {
if (pageSize == null || pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
throw AlertEventDomainException.validation("每页条数必须在1到100之间");
}
return pageSize;
}
static int pageNumber(Integer pageNumber) {
if (pageNumber == null || pageNumber < 1) {
throw AlertEventDomainException.validation("页码必须大于0");
}
return pageNumber;
}
static String idempotencyKey(String value) {
return requiredText(value, "Idempotency-Key", 128);
}
static String reason(String value) {
return requiredSafeText(value, "原因", 500);
}
static String keyword(String value) {
if (value == null || value.isBlank()) {
return null;
}
return optionalSafeText(value, "关键字", 100);
}
static String scope(String value, String field) {
if (value == null || value.isBlank()) {
return null;
}
return optionalSafeText(value, field, 100);
}
static String candidateKeyword(String value) {
String keyword = requiredSafeText(value, "用户关键字", 100);
if (keyword.length() < 2) {
throw AlertEventDomainException.validation("用户关键字至少2个字符");
}
return keyword;
}
static int candidateLimit(Integer value) {
return bounded(value, 1, MAX_CANDIDATES, "候选人数");
}
static NormalizedPostmortem normalizePostmortem(PostmortemRequest request) {
if (request == null || request.eventVersion() == null || request.eventVersion() < 0) {
throw AlertEventDomainException.validation("复盘内容和事件版本不能为空");
}
if (request.postmortemVersion() != null && request.postmortemVersion() < 0) {
throw AlertEventDomainException.validation("复盘版本无效");
}
List<String> evidenceRefs = new ArrayList<>();
if (request.evidenceRefs().size() > 20) {
throw AlertEventDomainException.validation("证据引用不能超过20条");
}
for (String reference : request.evidenceRefs()) {
evidenceRefs.add(requiredSafeText(reference, "证据引用", 255));
}
return new NormalizedPostmortem(
requiredSafeText(request.summary(), "复盘摘要", 2_000),
requiredSafeText(request.rootCause(), "根因", 4_000),
requiredSafeText(request.impact(), "影响", 4_000),
requiredSafeText(request.correctiveActions(), "改进措施", 4_000),
List.copyOf(evidenceRefs), request.eventVersion(), request.postmortemVersion());
}
static String sha256(String... fields) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
for (String field : fields) {
byte[] bytes = (field == null ? "" : field).getBytes(StandardCharsets.UTF_8);
digest.update(Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8));
digest.update((byte) ':');
digest.update(bytes);
digest.update((byte) '|');
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
}
}
static void rejectSensitive(String value, String field) {
if (value == null) {
return;
}
String normalized = value.toLowerCase(Locale.ROOT);
if (SENSITIVE_MARKERS.stream().anyMatch(normalized::contains)) {
throw AlertEventDomainException.validation(field + "不能包含敏感信息");
}
}
private static int bounded(Integer value, int minimum, int maximum, String field) {
if (value == null || value < minimum || value > maximum) {
throw AlertEventDomainException.validation(field + "必须在" + minimum + "到" + maximum + "之间");
}
return value;
}
private static String requiredText(String value, String field, int maximum) {
if (value == null || value.isBlank()) {
throw AlertEventDomainException.validation(field + "不能为空");
}
String normalized = value.trim();
if (normalized.length() > maximum) {
throw AlertEventDomainException.validation(field + "长度不能超过" + maximum);
}
return normalized;
}
private static String requiredSafeText(String value, String field, int maximum) {
String normalized = requiredText(value, field, maximum);
rejectSensitive(normalized, field);
return normalized;
}
private static String optionalText(String value, String field, int maximum) {
if (value == null || value.isBlank()) {
return null;
}
return requiredText(value, field, maximum);
}
private static String optionalSafeText(String value, String field, int maximum) {
String normalized = optionalText(value, field, maximum);
rejectSensitive(normalized, field);
return normalized;
}
record NormalizedRule(
String name,
cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source source,
cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Metric metric,
cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Operator operator,
BigDecimal threshold,
cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity severity,
int observationMinutes,
int triggerCount,
int recoveryCount,
int aggregateMinutes,
int silenceMinutes,
String projectRef,
String dataDomainCode,
long primaryUserId,
Long escalationUserId,
int escalationWaitMinutes,
boolean enabled,
Long version
) {
}
record NormalizedPostmortem(
String summary,
String rootCause,
String impact,
String correctiveActions,
List<String> evidenceRefs,
long eventVersion,
Long postmortemVersion
) {
}
}
@@ -0,0 +1,330 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventEvaluationRepository.EscalationCandidate;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventEvaluationRepository.EvaluationWork;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventIdentityGateway.Identity;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventJdbcRepository.RulePage;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.EvaluationBatch;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.Rule;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventPolicy.NormalizedPostmortem;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventPolicy.NormalizedRule;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.AssignRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventDetailView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventStatus;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.EventSummary;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.IdentityCandidate;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.NotifyRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PageView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.PostmortemRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.ProcessRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleSaveRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleStatusRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.RuleView;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Severity;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.VerifyRequest;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.WriteView;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Service
class AlertEventService {
private final AlertEventActorProvider actorProvider;
private final AlertEventIdentityGateway identityGateway;
private final AlertEventJdbcRepository repository;
private final AlertEventEvaluationRepository evaluationRepository;
private final AlertEventEvaluationEngine evaluationEngine;
private final Map<Source, TaskLogOwnerDirectory> ownerDirectories;
AlertEventService(AlertEventActorProvider actorProvider, AlertEventIdentityGateway identityGateway,
AlertEventJdbcRepository repository,
AlertEventEvaluationRepository evaluationRepository,
AlertEventEvaluationEngine evaluationEngine,
List<TaskLogOwnerDirectory> ownerDirectories) {
this.actorProvider = actorProvider;
this.identityGateway = identityGateway;
this.repository = repository;
this.evaluationRepository = evaluationRepository;
this.evaluationEngine = evaluationEngine;
this.ownerDirectories = ownerDirectories(ownerDirectories);
}
PageView<RuleView> rules(String keyword, Source source, Boolean enabled, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
int page = AlertEventPolicy.pageNumber(pageNum);
int size = AlertEventPolicy.pageSize(pageSize);
RulePage result = repository.pageRules(actor, AlertEventPolicy.keyword(keyword), source, enabled, page, size);
Map<Long, Identity> identities = identities(actor.orgId(), repository.ruleIdentityIds(result.rows()));
return new PageView<>(result.rows().stream()
.map(rule -> AlertEventJdbcRepository.ruleView(rule, identities)).toList(), result.total());
}
WriteView<RuleView> createRule(String idempotencyKey, RuleSaveRequest request) {
Actor actor = actorProvider.current();
NormalizedRule rule = AlertEventPolicy.normalizeRule(request, true);
Map<Long, Identity> identities = identities(actor.orgId(), identityIds(rule));
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.createRule(actor, rule, identities, key, requestHash("CREATE_RULE", rule));
}
WriteView<RuleView> updateRule(long ruleId, String idempotencyKey, RuleSaveRequest request) {
Actor actor = actorProvider.current();
NormalizedRule rule = AlertEventPolicy.normalizeRule(request, false);
Map<Long, Identity> identities = identities(actor.orgId(), identityIds(rule));
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.updateRule(actor, positive(ruleId, "规则ID"), rule, identities, key,
requestHash("UPDATE_RULE", ruleId, rule));
}
WriteView<RuleView> updateRuleStatus(long ruleId, String idempotencyKey, RuleStatusRequest request) {
Actor actor = actorProvider.current();
if (request == null || request.enabled() == null || request.version() == null || request.version() < 0) {
throw AlertEventDomainException.validation("启用状态和版本不能为空");
}
long id = positive(ruleId, "规则ID");
Rule existing = repository.requireRule(actor, id);
Map<Long, Identity> identities = identities(actor.orgId(), repository.ruleIdentityIds(List.of(existing)));
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.updateRuleStatus(actor, id, request.enabled(), request.version(), identities, key,
requestHash("RULE_STATUS", id, request));
}
PageView<EventSummary> events(String keyword, Source source, Severity severity, EventStatus status,
String projectRef, String dataDomainCode, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
return repository.pageEvents(actor, AlertEventPolicy.keyword(keyword), source, severity, status,
AlertEventPolicy.scope(projectRef, "历史来源范围"),
AlertEventPolicy.scope(dataDomainCode, "数据域"), AlertEventPolicy.pageNumber(pageNum),
AlertEventPolicy.pageSize(pageSize));
}
EventDetailView detail(long eventId) {
return repository.detail(actorProvider.current(), positive(eventId, "事件ID"));
}
List<IdentityCandidate> identityCandidates(String keyword, Integer limit) {
Actor actor = actorProvider.current();
try {
return identityGateway.searchActiveUsers(actor.orgId(), AlertEventPolicy.candidateKeyword(keyword),
AlertEventPolicy.candidateLimit(limit));
} catch (AlertEventDomainException exception) {
throw exception;
} catch (RuntimeException exception) {
throw AlertEventDomainException.identityUnavailable();
}
}
WriteView<EventDetailView> notifyEvent(long eventId, String idempotencyKey, NotifyRequest request) {
Actor actor = actorProvider.current();
if (request == null || request.recipientUserId() == null || request.recipientUserId() <= 0
|| request.version() == null || request.version() < 0) {
throw AlertEventDomainException.validation("收件人和事件版本不能为空");
}
String reason = AlertEventPolicy.reason(request.reason());
Identity recipient = identities(actor.orgId(), Set.of(request.recipientUserId()))
.get(request.recipientUserId());
long id = positive(eventId, "事件ID");
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.notifyEvent(actor, id, recipient, reason, request.version(), key,
requestHash("NOTIFY", id, request.recipientUserId(), reason, request.version()));
}
WriteView<EventDetailView> assignEvent(long eventId, String idempotencyKey, AssignRequest request) {
Actor actor = actorProvider.current();
if (request == null || request.assigneeUserId() == null || request.assigneeUserId() <= 0
|| request.version() == null || request.version() < 0) {
throw AlertEventDomainException.validation("处理人和事件版本不能为空");
}
String reason = AlertEventPolicy.reason(request.reason());
Identity assignee = identities(actor.orgId(), Set.of(request.assigneeUserId()))
.get(request.assigneeUserId());
long id = positive(eventId, "事件ID");
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.assignEvent(actor, id, assignee, reason, request.version(), key,
requestHash("ASSIGN", id, request.assigneeUserId(), reason, request.version()));
}
WriteView<EventDetailView> processEvent(long eventId, String idempotencyKey, ProcessRequest request) {
Actor actor = actorProvider.current();
if (request == null || request.action() == null || request.version() == null || request.version() < 0) {
throw AlertEventDomainException.validation("处置动作和事件版本不能为空");
}
String reason = AlertEventPolicy.reason(request.reason());
long id = positive(eventId, "事件ID");
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.processEvent(actor, id, request.action(), reason, request.version(), key,
requestHash("PROCESS", id, request.action(), reason, request.version()));
}
WriteView<EventDetailView> verifyEvent(long eventId, String idempotencyKey, VerifyRequest request) {
Actor actor = actorProvider.current();
if (request == null || request.action() == null || request.version() == null || request.version() < 0) {
throw AlertEventDomainException.validation("验证动作和事件版本不能为空");
}
String reason = AlertEventPolicy.reason(request.reason());
long id = positive(eventId, "事件ID");
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.verifyEvent(actor, id, request.action(), reason, request.version(), key,
requestHash("VERIFY", id, request.action(), reason, request.version()));
}
WriteView<EventDetailView> savePostmortem(long eventId, String idempotencyKey, PostmortemRequest request) {
Actor actor = actorProvider.current();
long id = positive(eventId, "事件ID");
NormalizedPostmortem postmortem = AlertEventPolicy.normalizePostmortem(request);
String key = AlertEventPolicy.idempotencyKey(idempotencyKey);
return repository.savePostmortem(actor, id, postmortem, key,
requestHash("POSTMORTEM", id, postmortem));
}
EvaluationResult evaluate(String evaluationKey, LocalDateTime observedAt) {
return evaluate(evaluationKey,observedAt,java.time.ZoneId.systemDefault().getId());
}
EvaluationResult evaluate(String evaluationKey, LocalDateTime observedAt,String zone) {
if (evaluationKey == null || evaluationKey.isBlank() || evaluationKey.length() > 128
|| observedAt == null) {
throw new IllegalArgumentException("alert evaluation request is invalid");
}
java.time.ZoneId.of(zone);
observedAt=observedAt.truncatedTo(java.time.temporal.ChronoUnit.MICROS);
var bindingBudget=new AlertOccurrenceBindingPolicy.Budget();
List<Rule> rules = evaluationRepository.enabledRules();
List<EscalationCandidate> escalations = evaluationRepository.pendingEscalations(observedAt);
Map<Long, Set<Long>> identityIdsByOrg = new LinkedHashMap<>();
for (Rule rule : rules) {
Set<Long> ids = identityIdsByOrg.computeIfAbsent(rule.orgId(), ignored -> new LinkedHashSet<>());
ids.add(rule.primaryUserId());
if (rule.escalationUserId() != null) {
ids.add(rule.escalationUserId());
}
}
for (EscalationCandidate escalation : escalations) {
identityIdsByOrg.computeIfAbsent(escalation.orgId(), ignored -> new LinkedHashSet<>())
.add(escalation.recipientUserId());
}
Map<Long, Identity> identities = identities(identityIdsByOrg);
List<EvaluationWork> work = new ArrayList<>();
int sourceRows = 0;
int fingerprints = 0;
for (Rule rule : rules) {
EvaluationBatch batch = evaluationEngine.evaluate(rule, requireDirectory(rule.source()), observedAt,zone,bindingBudget);
sourceRows = Math.addExact(sourceRows, batch.sourceRowCount());
fingerprints = Math.addExact(fingerprints, batch.rows().size());
if (fingerprints > AlertEventPolicy.MAX_FINGERPRINTS) {
throw AlertEventDomainException.limitExceeded("单轮告警评估超过5000个指纹");
}
work.add(new EvaluationWork(rule, batch.rows()));
}
if (!work.isEmpty() || !escalations.isEmpty()) {
evaluationRepository.apply(evaluationKey, observedAt, work, escalations, identities);
}
return new EvaluationResult(rules.size(), sourceRows, fingerprints, escalations.size());
}
private Map<Long, Identity> identities(long orgId, Collection<Long> ids) {
if (ids.isEmpty()) {
return Map.of();
}
try {
Map<Long, Identity> resolved = identityGateway.requireActiveUsers(orgId, ids);
if (resolved == null || resolved.size() != ids.size() || !resolved.keySet().equals(Set.copyOf(ids))
|| resolved.values().stream().anyMatch(identity -> identity == null
|| identity.userId() <= 0 || identity.orgId() != orgId
|| identity.userName() == null || identity.userName().isBlank()
|| identity.displayName() == null || identity.displayName().isBlank())) {
throw AlertEventDomainException.identityUnavailable();
}
return Map.copyOf(resolved);
} catch (AlertEventDomainException exception) {
throw exception;
} catch (RuntimeException exception) {
throw AlertEventDomainException.identityUnavailable();
}
}
private Map<Long, Identity> identities(Map<Long, Set<Long>> idsByOrg) {
Map<Long, Identity> result = new HashMap<>();
for (Map.Entry<Long, Set<Long>> entry : idsByOrg.entrySet()) {
Map<Long, Identity> resolved = identities(entry.getKey(), entry.getValue());
for (Map.Entry<Long, Identity> identity : resolved.entrySet()) {
Identity previous = result.put(identity.getKey(), identity.getValue());
if (previous != null && previous.orgId() != identity.getValue().orgId()) {
throw AlertEventDomainException.identityUnavailable();
}
}
}
return Map.copyOf(result);
}
private TaskLogOwnerDirectory requireDirectory(Source source) {
TaskLogOwnerDirectory directory = ownerDirectories.get(source);
if (directory == null) {
throw AlertEventDomainException.ownerUnavailable();
}
return directory;
}
private static Map<Source, TaskLogOwnerDirectory> ownerDirectories(List<TaskLogOwnerDirectory> directories) {
if (directories == null) {
throw new IllegalStateException("TaskLog owner directories are unavailable");
}
Map<Source, TaskLogOwnerDirectory> result = new EnumMap<>(Source.class);
for (TaskLogOwnerDirectory directory : directories) {
Source source = switch (directory.source()) {
case SCHEDULING -> Source.SCHEDULING;
case BATCH_INGESTION -> Source.BATCH_INGESTION;
case FILE_INGESTION -> Source.FILE_INGESTION;
case M2_GOLDEN -> null;
};
if (source != null && result.put(source, directory) != null) {
throw new IllegalStateException("TaskLog owner directory is duplicated: " + source);
}
}
if (result.size() != Source.values().length) {
throw new IllegalStateException("Required TaskLog owner directories are incomplete");
}
return Map.copyOf(result);
}
private static Set<Long> identityIds(NormalizedRule rule) {
Set<Long> ids = new LinkedHashSet<>();
ids.add(rule.primaryUserId());
if (rule.escalationUserId() != null) {
ids.add(rule.escalationUserId());
}
return Set.copyOf(ids);
}
private static long positive(long value, String field) {
if (value <= 0) {
throw AlertEventDomainException.validation(field + "无效");
}
return value;
}
private static String requestHash(Object... values) {
String[] fields = new String[values.length];
for (int index = 0; index < values.length; index++) {
fields[index] = String.valueOf(values[index]);
}
return AlertEventPolicy.sha256(fields);
}
record EvaluationResult(int ruleCount, int sourceRowCount, int fingerprintCount, int escalationCount) {
}
}
@@ -0,0 +1,126 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.json.utils.JsonUtils;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventIdentityGateway.Identity;
import cn.aixunkeji.datagov.integration.api.scheduling.SchedulingOwnerExecutionService.*;
import cn.aixunkeji.resource.api.RemoteMessageService;
import cn.aixunkeji.resource.api.RemoteMessageService.*;
import cn.aixunkeji.system.api.RemoteUserService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
/** Fixed workflow alert operation. Original alert records remain the audit source. */
@Component
@RequiredArgsConstructor
public class AlertNotificationScheduledExecution {
private final AlertEventJdbcRepository repository;
private final AlertEventIdentityGateway identities;
@DubboReference(check = false, timeout = 5000, retries = 0) private RemoteUserService users;
@DubboReference(check = false, timeout = 10000, retries = 0) private RemoteMessageService messages;
public Resolution resolve(long actorId, long orgId, long eventId, Map<String, String> options) {
try {
var target = target(actorId, orgId, eventId, options);
return binding(target, eventId);
} catch (RuntimeException | LinkageError unavailable) {
return new Resolution(ResolutionState.UNAVAILABLE, eventId, null, null);
}
}
public Outcome execute(long actorId, long orgId, long eventId, String version, String sha, String key,
Map<String, String> options, long runId, boolean observe) {
if (version == null || !version.matches("[0-9]{1,19}") || sha == null || !sha.matches("[a-f0-9]{64}")) {
return failed(runId, "ALERT_NOTIFICATION_BINDING_INVALID");
}
String originalKey = AlertEventPolicy.idempotencyKey(key);
var target = target(actorId, orgId, eventId, options);
String commandSha = hash(List.of(actorId, orgId, eventId, version, sha, target.recipient().userId(), target.reason()));
var notification = repository.workflowNotification(target.actor(), eventId, originalKey, commandSha);
if (notification == null) {
if (observe) return unknown(runId);
var current = binding(target, eventId);
if (!version.equals(current.ownerVersion()) || !sha.equals(current.ownerSha256())) {
return failed(runId, "ALERT_NOTIFICATION_OWNER_CHANGED");
}
repository.notifyEvent(target.actor(), eventId, target.recipient(), target.reason(), Long.parseLong(version), originalKey, commandSha);
notification = repository.workflowNotification(target.actor(), eventId, originalKey, commandSha);
if (notification == null) return unknown(runId);
}
if (notification.recipientId() != target.recipient().userId()) return failed(runId, "ALERT_NOTIFICATION_RECIPIENT_CHANGED");
String summary = notification.summary();
if (summary.length() > 500) summary = summary.substring(0, 500);
var command = new WorkflowAlertMessage(actorId, orgId, eventId, notification.recipientId(), originalKey,
version, sha, notification.requestId(), summary);
boolean firstDispatch = !observe && repository.reserveMailbox(target.actor(), notification);
MailboxReceipt receipt = read(command);
if (firstDispatch && "NOT_FOUND".equals(receipt.state())) {
try { receipt = messages.storeWorkflowAlert(command); }
catch (RuntimeException | LinkageError unknown) { receipt = read(command); }
}
if (receipt != null && "STORED".equals(receipt.state()) && receipt.messageId() != null && receipt.messageId() > 0) {
repository.mailboxResult(target.actor(), notification, receipt.messageId());
return new Outcome(State.SUCCEEDED, runId, "/api/dataops/v1/alert-events/" + eventId,
null, "站内消息已存入收件箱", receipt.storedAt() == null ? LocalDateTime.now() : receipt.storedAt());
}
repository.mailboxResult(target.actor(), notification, null);
return unknown(runId);
}
private Target target(long actorId, long orgId, long eventId, Map<String, String> options) {
if (actorId <= 0 || orgId <= 0 || eventId <= 0 || options == null
|| !options.keySet().equals(Set.of("recipientUserId", "reason"))
|| !options.getOrDefault("recipientUserId", "").matches("[1-9][0-9]{0,18}")) {
throw AlertEventDomainException.validation("告警通知须选择同组织收件人并填写原因");
}
long recipient = Long.parseLong(options.get("recipientUserId"));
String reason = AlertEventPolicy.reason(options.get("reason"));
var grant = users.resolveWorkflowActor(actorId, orgId, "ALERT_NOTIFY");
var now = Instant.now();
if (grant == null || !grant.allowed() || grant.userId() != actorId || grant.deptId() != orgId
|| !"ALERT_NOTIFY".equals(grant.purpose()) || grant.checkedAt() == null
|| grant.checkedAt().isBefore(now.minusSeconds(30)) || grant.checkedAt().isAfter(now.plusSeconds(5))) {
throw AlertEventDomainException.forbidden();
}
var ids = new LinkedHashSet<Long>(); ids.add(actorId); ids.add(recipient);
var current = identities.requireActiveUsers(orgId, ids);
Identity caller = current.get(actorId), receiver = current.get(recipient);
if (caller == null || receiver == null || caller.orgId() != orgId || receiver.orgId() != orgId) {
throw AlertEventDomainException.forbidden();
}
var actor = new Actor(actorId, orgId, caller.displayName(), false);
repository.detail(actor, eventId);
return new Target(actor, receiver, reason);
}
private Resolution binding(Target target, long eventId) {
var summary = repository.detail(target.actor(), eventId).summary();
return new Resolution(ResolutionState.AUTHORIZED, eventId, Long.toString(summary.version()),
hash(List.of(summary, target.recipient(), target.reason())));
}
private MailboxReceipt read(WorkflowAlertMessage command) {
try { var result = messages.readWorkflowAlert(command); return result == null ? unavailable() : result; }
catch (RuntimeException | LinkageError failure) { return unavailable(); }
}
private static MailboxReceipt unavailable() { return new MailboxReceipt("UNKNOWN", null, "ALERT_MAILBOX_UNCONFIRMED", null); }
private static Outcome unknown(long run) {
return new Outcome(State.UNKNOWN, run, null, "ALERT_MAILBOX_UNCONFIRMED", "站内消息存储状态未知,请按原请求核对", LocalDateTime.now());
}
private static Outcome failed(long run, String code) {
return Outcome.failed(run, code, "告警事件或收件人依据已变化,请重新发布流程");
}
private static String hash(Object value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(JsonUtils.toJsonString(value).getBytes(StandardCharsets.UTF_8))); }
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
}
private record Target(Actor actor, Identity recipient, String reason) { }
public enum ResolutionState { AUTHORIZED, UNAVAILABLE }
public record Resolution(ResolutionState state, Long referenceId, String ownerVersion, String ownerSha256) { }
}
@@ -0,0 +1,83 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.*;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.TaskSummary;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import cn.aixunkeji.datagov.dataops.alertevent.AlertEventModel.*;
import org.springframework.stereotype.Component;
import tools.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.util.*;
@Component
class AlertOccurrenceBindingPolicy {
static final int MAX_RUNS=1000, MAX_BYTES=1048576;
static final String NOTE="当次真实Owner运行记录的冻结观察,不是外部引擎实时健康证明;运行当前状态可已改变。原连续触发/恢复窗口未逐次绑定,不能据此复算连续条件。";
private final ObjectMapper json;
AlertOccurrenceBindingPolicy(ObjectMapper json){this.json=json;}
/** Per maintenance round, to avoid retaining thousands of individually bounded payloads in heap. */
static final class Budget { private int remaining=8*MAX_BYTES; boolean reserve(int bytes){if(bytes>remaining)return false;remaining-=bytes;return true;} }
Payload capture(Rule rule,List<TaskSummary> rows,OwnerEvaluation evaluation,LocalDateTime at,String zone,boolean unchanged,Budget budget){
ZoneId.of(zone);
String state=rows.size()>MAX_RUNS?"REFERENCE_LIMIT":unchanged&&inScope(rule,rows,at)?"BOUND":"OWNER_CHANGED";
List<Run> runs=new ArrayList<>();
if("BOUND".equals(state)){
var sorted=rows.stream().sorted(Comparator.comparing(TaskSummary::runId)).toList();
for(int i=0;i<sorted.size();i++)runs.add(run(rule,sorted.get(i),evaluation,"R"+(i+1)));
}
Payload value=payload(rule,rows,evaluation,at,zone,state,List.copyOf(runs));
if("BOUND".equals(state)){
int bytes=encoded(value).getBytes(StandardCharsets.UTF_8).length;
if(bytes>MAX_BYTES||!budget.reserve(bytes))value=payload(rule,rows,evaluation,at,zone,"REFERENCE_LIMIT",List.of());
}
return value;
}
private static Payload payload(Rule rule,List<TaskSummary> rows,OwnerEvaluation e,LocalDateTime at,String zone,String state,List<Run> runs){
return new Payload(1,state,new RuleSnapshot(Long.toString(rule.ruleId()),rule.version(),rule.source(),rule.metric(),rule.operator(),decimal(rule.threshold()),rule.severity(),
rule.observationMinutes(),rule.triggerCount(),rule.recoveryCount(),rule.aggregateMinutes(),rule.silenceMinutes(),rule.enabled()),
Long.toString(rule.orgId()),Long.toString(e.ownerObjectId()),rule.projectRef(),rule.dataDomainCode(),e.projectRef(),e.dataDomainCode(),
at.minusMinutes(rule.observationMinutes()),at,zone,rule.source()==Source.SCHEDULING?"CREATED_AT":"STARTED_AT_OR_CREATED_AT",e.observedFrom(),rows.size(),e.sampleCount(),
rows.stream().filter(r->r.status()==Status.UNKNOWN).count(),decimal(e.metricValue()),e.breached(),e.evidenceSha256(),"UNBOUND",runs);
}
static Run run(Rule rule,TaskSummary row,OwnerEvaluation e,String key){
var roles=new ArrayList<String>();roles.add("INPUT");
if(row.status()==Status.UNKNOWN)roles.add("UNKNOWN");
switch(rule.metric()){
case FAILED_COUNT -> {if(row.status()==Status.FAILED)roles.add("FAILED");}
case BACKLOG_COUNT -> {if(Set.of(Status.PENDING,Status.SUBMITTED,Status.RUNNING).contains(row.status()))roles.add("BACKLOG");}
case FAILURE_RATE_PERCENT -> {if(Set.of(Status.SUCCEEDED,Status.FAILED,Status.CANCELED).contains(row.status()))roles.add("DENOMINATOR");if(row.status()==Status.FAILED)roles.add("FAILED");}
case MAX_DURATION_MS -> {if(row.startedAt()!=null&&row.completedAt()!=null){roles.add("DURATION");if(e.metricValue()!=null&&e.metricValue().compareTo(java.math.BigDecimal.valueOf(Duration.between(row.startedAt(),row.completedAt()).toMillis()))==0)roles.add("MAXIMUM");}}
}
boolean started=rule.source()!=Source.SCHEDULING&&row.startedAt()!=null;
return new Run(key,Long.toString(row.runId()),rule.source(),Long.toString(row.ownerObjectId()),Long.toString(row.orgId()),row.projectRef(),row.dataDomainCode(),row.status(),
row.startedAt(),row.completedAt(),row.createdAt(),row.updatedAt(),started?row.startedAt():row.createdAt(),started?"STARTED_AT":"CREATED_AT",List.copyOf(roles));
}
static boolean inScope(Rule rule,List<TaskSummary> rows,LocalDateTime at){
return rows.stream().allMatch(row->{var time=rule.source()!=Source.SCHEDULING&&row.startedAt()!=null?row.startedAt():row.createdAt();
return time!=null&&!time.isBefore(at.minusMinutes(rule.observationMinutes()))&&!time.isAfter(at)
&&(rule.projectRef()==null||rule.projectRef().equals(row.projectRef()))&&(rule.dataDomainCode()==null||rule.dataDomainCode().equals(row.dataDomainCode()));});
}
String inputHash(List<TaskSummary> rows){return hash(rows.stream().sorted(Comparator.comparing(TaskSummary::runId)).map(r->Arrays.asList(r.source(),r.runId(),r.ownerObjectId(),r.orgId(),r.projectRef(),r.dataDomainCode(),r.status(),r.startedAt(),r.completedAt(),r.createdAt(),r.updatedAt())).toList());}
String scopeHash(Payload p){return hash(Arrays.asList(p.orgId(),p.rule().source(),p.ownerObjectId(),p.projectRef(),p.dataDomainCode(),p.ownerProjectRef(),p.ownerDataDomainCode(),p.appliedFrom(),p.appliedTo(),p.zoneId(),p.timeBasis()));}
String encoded(Object value){return json.writeValueAsString(value);}
String hash(Object value){return sha(encoded(value));}
Payload decode(String value,String digest,int bytes){
try{
if(value==null||value.getBytes(StandardCharsets.UTF_8).length>2*MAX_BYTES)throw invalid();
Payload p=json.readValue(value,Payload.class);String canonical=encoded(p);
if(bytes!=canonical.getBytes(StandardCharsets.UTF_8).length||bytes>MAX_BYTES||!sha(canonical).equals(digest)||p.formatVersion()!=1
||!Set.of("BOUND","REFERENCE_LIMIT","OWNER_CHANGED").contains(p.state())||p.rule()==null||p.runs()==null||p.ownerRowCount()<1||p.ownerRowCount()>50000
||p.runs().size()>MAX_RUNS||("BOUND".equals(p.state())?p.runs().size()!=p.ownerRowCount():!p.runs().isEmpty())
||p.appliedFrom()==null||p.appliedTo()==null||!p.appliedFrom().isBefore(p.appliedTo())||!"UNBOUND".equals(p.streakEvidenceState()))throw invalid();
ZoneId.of(p.zoneId());id(p.orgId());id(p.ownerObjectId());id(p.rule().ruleId());
Set<String> seen=new HashSet<>();for(var r:p.runs())if(r==null||!seen.add(r.runId())||r.source()!=p.rule().source()||!r.orgId().equals(p.orgId())||!r.ownerObjectId().equals(p.ownerObjectId())||!Objects.equals(r.projectRef(),p.ownerProjectRef())||!Objects.equals(r.dataDomainCode(),p.ownerDataDomainCode()))throw invalid();
return p;
}catch(RuntimeException malformed){throw invalid();}
}
static long id(String value){try{if(value!=null&&value.matches("[1-9][0-9]{0,18}"))return Long.parseLong(value);}catch(NumberFormatException ignored){}throw invalid();}
static String decimal(java.math.BigDecimal v){return v==null?null:v.stripTrailingZeros().toPlainString();}
static String sha(String text){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}}
static AlertEventDomainException invalid(){return AlertEventDomainException.conflict("发生记录依据已变化或不可验证,请重新读取");}
}
@@ -0,0 +1,59 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.Payload;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.nio.charset.StandardCharsets;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
@Repository
class AlertOccurrenceBindingRepository {
record Head(long eventId,long occurrenceId,long orgId,long ruleId,Source source,long ownerObjectId,String projectRef,
String dataDomainCode,long eventVersion,String eventStatus,String evidenceSha256,BigDecimal metricValue,long sampleCount) { }
record Stored(long eventId,long orgId,long ruleId,long ruleVersion,Source source,long ownerObjectId,String state,
String scopeSha256,String payloadSha256,int payloadBytes,Payload payload) { }
private final JdbcTemplate jdbc;private final AlertOccurrenceBindingPolicy policy;
AlertOccurrenceBindingRepository(JdbcTemplate jdbc,AlertOccurrenceBindingPolicy policy){this.jdbc=jdbc;this.policy=policy;}
void insert(String evaluationKey,long eventId,long occurrenceId,AlertEventModel.OwnerEvaluation e){
Payload p=e.binding();
if(p==null||!Long.toString(e.ruleId()).equals(p.rule().ruleId())||!Long.toString(e.orgId()).equals(p.orgId())
||!Long.toString(e.ownerObjectId()).equals(p.ownerObjectId())||e.source()!=p.rule().source()||!Objects.equals(e.evidenceSha256(),p.originalEvidenceSha256())
||!Objects.equals(AlertOccurrenceBindingPolicy.decimal(e.metricValue()),p.metricValue())||e.sampleCount()!=p.metricSampleCount())throw AlertOccurrenceBindingPolicy.invalid();
String body=policy.encoded(p),hash=policy.hash(p);int bytes=body.getBytes(StandardCharsets.UTF_8).length;
policy.decode(body,hash,bytes);
int written=jdbc.update("""
INSERT INTO ops_alert_occurrence_binding(occurrence_id,event_id,org_id,rule_id,rule_version,source_type,owner_object_id,
format_version,binding_state,applied_from,applied_to,captured_at,zone_id,evaluation_key_sha256,scope_sha256,payload_sha256,
owner_row_count,stored_run_count,payload_bytes,payload_json,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
VALUES(?,?,?,?,?,?,?,1,?,?,?,NOW(6),?,?,?,?,?,?,?,?,?,0,NOW(6),0,NOW(6),'0',0)
""",occurrenceId,eventId,e.orgId(),e.ruleId(),p.rule().version(),e.source().name(),e.ownerObjectId(),p.state(),p.appliedFrom(),p.appliedTo(),p.zoneId(),
AlertOccurrenceBindingPolicy.sha(evaluationKey),policy.scopeHash(p),hash,p.ownerRowCount(),p.runs().size(),bytes,body,e.orgId());
if(written!=1)throw AlertEventDomainException.requestUnavailable();
}
Head head(long org,long event,long occurrence){
var rows=jdbc.query("""
SELECT e.event_id,o.occurrence_id,e.org_id,e.rule_id,e.source_type,e.owner_object_id,e.project_ref,e.data_domain_code,
e.version,e.event_status,o.evidence_sha256,o.metric_value,o.sample_count
FROM ops_alert_event e JOIN ops_alert_occurrence o ON o.event_id=e.event_id AND o.org_id=e.org_id AND o.del_flag='0'
WHERE e.org_id=? AND e.event_id=? AND o.occurrence_id=? AND e.del_flag='0'
""",(r,n)->new Head(r.getLong(1),r.getLong(2),r.getLong(3),r.getLong(4),Source.valueOf(r.getString(5)),r.getLong(6),r.getString(7),r.getString(8),r.getLong(9),r.getString(10),r.getString(11),r.getBigDecimal(12),r.getLong(13)),org,event,occurrence);
if(rows.size()!=1)throw AlertEventDomainException.notFound();return rows.getFirst();
}
Stored find(Head head){
var rows=jdbc.query("""
SELECT event_id,org_id,rule_id,rule_version,source_type,owner_object_id,binding_state,scope_sha256,payload_sha256,payload_bytes,payload_json
FROM ops_alert_occurrence_binding WHERE occurrence_id=? AND event_id=? AND org_id=? AND del_flag='0'
""",(r,n)->new Stored(r.getLong(1),r.getLong(2),r.getLong(3),r.getLong(4),Source.valueOf(r.getString(5)),r.getLong(6),r.getString(7),r.getString(8),r.getString(9),r.getInt(10),policy.decode(r.getString(11),r.getString(9),r.getInt(10))),head.occurrenceId(),head.eventId(),head.orgId());
if(rows.isEmpty())return null;if(rows.size()!=1)throw AlertOccurrenceBindingPolicy.invalid();
Stored s=rows.getFirst();Payload p=s.payload();
if(s.eventId()!=head.eventId()||s.orgId()!=head.orgId()||s.ruleId()!=head.ruleId()||s.source()!=head.source()||s.ownerObjectId()!=head.ownerObjectId()
||!s.state().equals(p.state())||!s.scopeSha256().equals(policy.scopeHash(p))||s.ruleVersion()!=p.rule().version()
||!Long.toString(s.ruleId()).equals(p.rule().ruleId())||s.source()!=p.rule().source()||!Long.toString(s.orgId()).equals(p.orgId())||!Long.toString(s.ownerObjectId()).equals(p.ownerObjectId())
||!Objects.equals(head.projectRef(),p.ownerProjectRef())||!Objects.equals(head.dataDomainCode(),p.ownerDataDomainCode())
||!Objects.equals(head.evidenceSha256(),p.originalEvidenceSha256())||!Objects.equals(AlertOccurrenceBindingPolicy.decimal(head.metricValue()),p.metricValue())||head.sampleCount()!=p.metricSampleCount())throw AlertOccurrenceBindingPolicy.invalid();
return s;
}
}
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.Source;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.Instant;
@Component
class AlertOccurrenceEvidenceAuthority {
private final AlertEventActorProvider actors;
@DubboReference(check=false,timeout=3000,retries=0)private RemoteUserService users;
AlertOccurrenceEvidenceAuthority(AlertEventActorProvider actors){this.actors=actors;}
void require(AlertEventActorProvider.Actor actor,Source source){
String purpose="ALERT_OCCURRENCE_"+source.name();if(!actor.equals(actors.current()))throw AlertEventDomainException.forbidden();
try{var now=Instant.now();var d=users.resolveAssetActor(actor.actorId(),actor.orgId(),purpose);
if(d!=null&&d.allowed()&&d.userId()==actor.actorId()&&d.deptId()==actor.orgId()&&purpose.equals(d.purpose())&&d.checkedAt()!=null
&&!d.checkedAt().isBefore(now.minusSeconds(10))&&!d.checkedAt().isAfter(now.plusSeconds(5))&&actor.equals(actors.current()))return;
}catch(RuntimeException unavailable){/* No author or maintenance fallback. */}throw AlertEventDomainException.forbidden();
}
}
@@ -0,0 +1,13 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.View;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/dataops/v1/alert-events")
public class AlertOccurrenceEvidenceController {
private final AlertOccurrenceEvidenceService service;
public AlertOccurrenceEvidenceController(AlertOccurrenceEvidenceService service){this.service=service;}
@GetMapping("/{eventId}/occurrences/{occurrenceId}/evidence") @SaCheckPermission("aixun:dataops:alert-event:view")
public R<View> read(@PathVariable String eventId,@PathVariable String occurrenceId){return R.ok(service.read(eventId,occurrenceId));}
@ExceptionHandler(AlertEventDomainException.class)org.springframework.http.ResponseEntity<R<Void>> error(AlertEventDomainException e){return org.springframework.http.ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
}
@@ -0,0 +1,9 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=AlertOccurrenceEvidenceDirectory.VERSION,timeout=15000,retries=0)
public class AlertOccurrenceEvidenceDubboService implements AlertOccurrenceEvidenceDirectory {
private final AlertOccurrenceEvidenceService service;
public AlertOccurrenceEvidenceDubboService(AlertOccurrenceEvidenceService service){this.service=service;}
@Override public Evidence current(Selection selection){return service.current(selection);}
}
@@ -0,0 +1,52 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertOccurrenceEvidenceDirectory.*;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.*;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
class AlertOccurrenceEvidenceService {
private final AlertEventActorProvider actors;private final AlertOccurrenceEvidenceAuthority authority;
private final AlertOccurrenceBindingRepository repository;private final AlertOccurrenceBindingPolicy policy;
private final List<TaskLogOwnerDirectory> owners;
AlertOccurrenceEvidenceService(AlertEventActorProvider actors,AlertOccurrenceEvidenceAuthority authority,
AlertOccurrenceBindingRepository repository,AlertOccurrenceBindingPolicy policy,List<TaskLogOwnerDirectory> owners){
this.actors=actors;this.authority=authority;this.repository=repository;this.policy=policy;this.owners=owners;
}
View read(String event,String occurrence){
var actor=actors.current();long eventId=AlertOccurrenceBindingPolicy.id(event),occurrenceId=AlertOccurrenceBindingPolicy.id(occurrence);
View before=read(actor,eventId,occurrenceId);View after=read(actor,eventId,occurrenceId);
if(!before.equals(after))throw AlertOccurrenceBindingPolicy.invalid();return after;
}
Evidence current(Selection requested){
if(requested==null||requested.references()==null||requested.references().isEmpty()||requested.references().size()>20)throw AlertOccurrenceBindingPolicy.invalid();
var actor=actors.current();Set<String> unique=new HashSet<>();var refs=new ArrayList<Reference>();var views=new ArrayList<View>();int count=0;
for(var ref:requested.references()){
if(ref==null||ref.eventVersion()<0||ref.payloadSha256()==null||!ref.payloadSha256().matches("[a-f0-9]{64}")||!unique.add(ref.eventId()+":"+ref.occurrenceId()))throw AlertOccurrenceBindingPolicy.invalid();
View view=read(actor,AlertOccurrenceBindingPolicy.id(ref.eventId()),AlertOccurrenceBindingPolicy.id(ref.occurrenceId()));if(!ref.equals(view.reference())||!"BOUND".equals(view.state())||view.payload()==null)throw AlertOccurrenceBindingPolicy.invalid();
count+=view.payload().runs().size();if(count>1000)throw AlertEventDomainException.limitExceeded("所选发生记录超过1000条运行,请缩小选择");
refs.add(ref);views.add(view);
}
for(var view:views){var ref=view.reference();if(!view.equals(read(actor,AlertOccurrenceBindingPolicy.id(ref.eventId()),AlertOccurrenceBindingPolicy.id(ref.occurrenceId()))))throw AlertOccurrenceBindingPolicy.invalid();authority.require(actor,view.source());}
Selection selection=new Selection(List.copyOf(refs));return new Evidence(selection,List.copyOf(views),policy.hash(Arrays.asList(actor.actorId(),actor.orgId(),selection,views)));
}
private View read(AlertEventActorProvider.Actor actor,long event,long occurrence){
var h=repository.head(actor.orgId(),event,occurrence);authority.require(actor,h.source());
var s=repository.find(h);Payload p=s==null?null:s.payload();
if(p!=null&&"BOUND".equals(s.state())){
var dirs=owners.stream().filter(d->d.source().name().equals(h.source().name())).toList();if(dirs.size()!=1)throw AlertEventDomainException.ownerUnavailable();
for(var run:p.runs()){
var result=dirs.getFirst().find(new OwnerScope(actor.actorId(),actor.orgId(),actor.unrestricted()),AlertOccurrenceBindingPolicy.id(run.runId()));
var row=result==null?null:result.row();
if(result==null||result.state()!=DirectoryState.AVAILABLE||row==null||row.runId()==null||!run.runId().equals(Long.toString(row.runId()))
||row.orgId()==null||row.orgId()!=actor.orgId()||row.ownerObjectId()==null||row.ownerObjectId()!=h.ownerObjectId()||row.source()==null||!row.source().name().equals(h.source().name())
||!Objects.equals(row.projectRef(),run.projectRef())||!Objects.equals(row.dataDomainCode(),run.dataDomainCode()))throw AlertEventDomainException.forbidden();
}
}
if(!h.equals(repository.head(actor.orgId(),event,occurrence)))throw AlertOccurrenceBindingPolicy.invalid();
authority.require(actor,h.source());
return new View(new Reference(Long.toString(event),Long.toString(occurrence),h.eventVersion(),s==null?null:s.payloadSha256()),s==null?"LEGACY_UNBOUND":s.state(),h.source(),h.eventStatus(),p,
s==null?"此历史发生记录未绑定规则版本和运行集合,不能从当前规则补写过去依据。":AlertOccurrenceBindingPolicy.NOTE);
}
}
@@ -0,0 +1,33 @@
package cn.aixunkeji.datagov.dataops.alertevent;
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.notification.ExternalAlertDeliveryService.*;
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/alert-events/{eventId}/external-deliveries")
class ExternalAlertDeliveryController {
private final ExternalAlertDeliveryFacade service;
@GetMapping("/channels") @SaCheckPermission("aixun:dataops:alert-event:view")
R<List<Channel>> channels(@PathVariable long eventId) { return R.ok(service.channels(eventId)); }
@GetMapping @SaCheckPermission("aixun:dataops:alert-event:view")
R<List<Receipt>> history(@PathVariable long eventId) { return R.ok(service.history(eventId)); }
@GetMapping("/{requestKey}") @SaCheckPermission("aixun:dataops:alert-event:view")
R<Receipt> read(@PathVariable long eventId, @PathVariable String requestKey) { return R.ok(service.read(eventId, requestKey)); }
@PostMapping("/{requestKey}/cancellation") @SaCheckPermission("aixun:dataops:alert-event:notify")
@Log(title = "取消未开始的告警外发", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
R<Receipt> cancelUnsubmitted(@PathVariable long eventId, @PathVariable String requestKey) {
return R.ok(service.cancelUnsubmitted(eventId, requestKey));
}
@PostMapping @SaCheckPermission("aixun:dataops:alert-event:notify")
@Log(title = "外发告警通知", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
R<Receipt> send(@PathVariable long eventId, @RequestHeader("Idempotency-Key") String key,
@RequestBody ExternalAlertDeliveryFacade.SendRequest request) {
return R.ok(service.send(eventId, key, request));
}
}
@@ -0,0 +1,55 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.integration.api.notification.ExternalAlertDeliveryService;
import cn.aixunkeji.datagov.integration.api.notification.ExternalAlertDeliveryService.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.function.Supplier;
@Service
class ExternalAlertDeliveryFacade {
private final AlertEventActorProvider actors;
private final AlertEventJdbcRepository events;
@DubboReference(version = ExternalAlertDeliveryService.VERSION, group = ExternalAlertDeliveryService.GROUP, check = false, retries = 0, timeout = 30000)
private ExternalAlertDeliveryService delivery;
ExternalAlertDeliveryFacade(AlertEventActorProvider actors, AlertEventJdbcRepository events) { this.actors = actors; this.events = events; }
record SendRequest(String channelId, String targetKey, Long eventVersion) { }
List<Channel> channels(long eventId) {
var actor = actors.current(); events.detail(actor, eventId);
return invoke(() -> delivery.channels(new Scope(actor.actorId(), actor.orgId())));
}
Receipt send(long eventId, String key, SendRequest request) {
var actor = actors.current();
var event = events.detail(actor, eventId).summary();
if (request == null || request.eventVersion() == null || request.eventVersion() != event.version())
throw AlertEventDomainException.conflict("事件版本已变化,请刷新后确认发送内容");
return invoke(() -> delivery.send(new Command(new Scope(actor.actorId(), actor.orgId()), eventId, event.version(),
key, request.channelId(), request.targetKey(), event.source().name(), event.severity().name(), event.status().name())));
}
Receipt read(long eventId, String key) {
var actor = actors.current(); events.detail(actor, eventId);
return invoke(() -> delivery.read(new Scope(actor.actorId(), actor.orgId()), eventId, key));
}
List<Receipt> history(long eventId) {
var actor = actors.current(); events.detail(actor, eventId);
return invoke(() -> delivery.history(new Scope(actor.actorId(), actor.orgId()), eventId));
}
Receipt cancelUnsubmitted(long eventId, String key) {
var actor = actors.current(); events.detail(actor, eventId);
return invoke(() -> delivery.cancelUnsubmitted(new Scope(actor.actorId(), actor.orgId()), eventId, key));
}
private static <T> T invoke(Supplier<T> action) {
try { return action.get(); }
catch (IllegalArgumentException rejected) {
String code = rejected.getMessage() == null ? "" : rejected.getMessage();
throw switch (code) {
case "ALERT_CHANNEL_NOT_READY", "ALERT_CHANNEL_NOT_CONFIGURED" -> AlertEventDomainException.deliveryChannelUnavailable();
case "ALERT_DELIVERY_FORBIDDEN", "ALERT_DELIVERY_SCOPE_MISMATCH" -> AlertEventDomainException.forbidden();
case "ALERT_DELIVERY_KEY_CONFLICT" -> AlertEventDomainException.conflict("请求编号已有其他投递,请核对原请求");
case "ALERT_DELIVERY_INVALID", "ALERT_DELIVERY_KEY_INVALID", "ALERT_EVENT_INVALID" -> AlertEventDomainException.validation("通知请求无效,请重新核对事件与渠道");
default -> AlertEventDomainException.deliveryUnknown();
};
} catch (RuntimeException uncertain) { throw AlertEventDomainException.deliveryUnknown(); }
}
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextReader;
import cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextDirectory.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import static cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextReader.*;
@Component @RequiredArgsConstructor
final class P22OwnerContext implements PageAssistContextReader {
private final AlertEventService service;
@Override public String pageId(){return "P22";}
@Override public Snapshot read(Request r){
qualifiers(r);var v=service.detail(numeric(r)).summary();
return snapshot(r,v.version(),"status",v.status(),"severity",v.severity(),"occurrenceCount",v.occurrenceCount(),"lastOccurredAt",v.lastOccurredAt(),"version",v.version());
}
}
@@ -0,0 +1,95 @@
package cn.aixunkeji.datagov.dataops.alertevent;
import cn.aixunkeji.datagov.dataops.api.alertevent.AlertEventApi.IdentityCandidate;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.domain.vo.RemoteUserVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Fail-closed adapter over the RCP6 identity source; no profile is persisted here. */
@Component
final class Rcp6AlertEventIdentityGateway implements AlertEventIdentityGateway {
private static final String ACTIVE = "0";
@DubboReference(check = false, timeout = 5_000, retries = 0)
private RemoteUserService remoteUserService;
Rcp6AlertEventIdentityGateway() {
}
Rcp6AlertEventIdentityGateway(RemoteUserService remoteUserService) {
this.remoteUserService = remoteUserService;
}
@Override
public Map<Long, Identity> requireActiveUsers(long orgId, Collection<Long> userIds) {
if (orgId <= 0 || userIds == null) {
throw new IllegalStateException("identity scope is invalid");
}
Set<Long> required = new LinkedHashSet<>();
for (Long userId : userIds) {
if (userId == null || userId <= 0 || !required.add(userId)) {
throw new IllegalStateException("identity request is malformed");
}
}
if (required.isEmpty()) {
return Map.of();
}
List<RemoteUserVo> users = service().selectListByIds(required);
if (users == null || users.size() != required.size()) {
throw new IllegalStateException("RCP6 identity result is incomplete");
}
Map<Long, Identity> result = new HashMap<>();
for (RemoteUserVo user : users) {
if (user == null || user.getUserId() == null || !required.contains(user.getUserId())
|| user.getDeptId() == null || user.getStatus() == null
|| user.getUserName() == null || user.getUserName().isBlank()
|| !ACTIVE.equals(user.getStatus()) || user.getDeptId() != orgId) {
throw new IllegalStateException("RCP6 identity result is inactive, out of scope or malformed");
}
String displayName = user.getNickName() == null || user.getNickName().isBlank()
? user.getUserName() : user.getNickName();
Identity identity = new Identity(user.getUserId(), user.getDeptId(), user.getUserName(), displayName);
if (result.put(user.getUserId(), identity) != null) {
throw new IllegalStateException("RCP6 identity result contains duplicates");
}
}
return Map.copyOf(result);
}
@Override
public List<IdentityCandidate> searchActiveUsers(long orgId, String keyword, int limit) {
List<RemoteUserService.ActiveUserCandidate> users =
service().searchActiveUsersByDept(orgId, keyword, limit);
if (users == null || users.size() > limit) {
throw new IllegalStateException("RCP6 identity candidates are unavailable");
}
Set<Long> seen = new HashSet<>();
return users.stream().map(user -> {
if (user == null || user.userId() == null || user.userId() <= 0
|| user.deptId() == null || user.deptId() != orgId
|| user.userName() == null || user.userName().isBlank()
|| !ACTIVE.equals(user.status()) || !seen.add(user.userId())) {
throw new IllegalStateException("RCP6 identity candidate is malformed or out of scope");
}
return new IdentityCandidate(user.userId(), user.userName(),
user.nickName() == null || user.nickName().isBlank() ? user.userName() : user.nickName());
}).toList();
}
private RemoteUserService service() {
if (remoteUserService == null) {
throw new IllegalStateException("RCP6 identity service is unavailable");
}
return remoteUserService;
}
}
@@ -0,0 +1,5 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
/** Authenticated RCP6 principal and organization scope. */
public record BatchActor(long actorId, long orgScopeId) {
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
/** Resolves scope from the authenticated session and never from request headers. */
@Component
public class BatchActorProvider {
public BatchActor current() {
Long actorId = LoginHelper.getUserId();
Long orgScopeId = LoginHelper.getDeptId();
if (actorId == null || actorId <= 0 || orgScopeId == null || orgScopeId <= 0) {
throw BatchIngestionException.forbidden();
}
return new BatchActor(actorId, orgScopeId);
}
}
@@ -0,0 +1,191 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
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.dataops.api.batchingestion.BatchArrivalValidationCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchArrivalValidationView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchCheckpointView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchReadyCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchResumeCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchRunView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchSubmitCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskCreateCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskPageView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskUpdateCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskView;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/batch-ingestions")
public class BatchIngestionController {
private final BatchIngestionService service;
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping
public R<BatchTaskPageView> page(
@RequestParam(required = false) String keyword,
@RequestParam(required = false) BatchIngestionStatus status,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.page(keyword, null, status, pageNum, pageSize));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/{taskId}")
public R<BatchTaskView> find(@PathVariable long taskId) {
return R.ok(service.find(taskId));
}
@Log(title = "批量采集任务创建", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:create")
@PostMapping
public R<BatchTaskView> create(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchTaskCreateCommand command
) {
return R.ok(service.create(idempotencyKey, command).value());
}
@Log(title = "批量采集任务更新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:update")
@PutMapping("/{taskId}")
public R<BatchTaskView> update(
@PathVariable long taskId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchTaskUpdateCommand command
) {
return R.ok(service.update(taskId, idempotencyKey, command).value());
}
@Log(title = "批量采集草稿删除", businessType = BusinessType.DELETE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:delete")
@DeleteMapping("/{taskId}")
public R<Void> delete(
@PathVariable long taskId,
@RequestParam long version,
@RequestHeader("Idempotency-Key") String idempotencyKey
) {
service.delete(taskId, version, idempotencyKey);
return R.ok();
}
@Log(title = "批量采集READY校验", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:update")
@PostMapping("/{taskId}/ready")
public R<BatchTaskView> ready(
@PathVariable long taskId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchReadyCommand command
) {
return R.ok(service.ready(taskId, idempotencyKey, command));
}
@Log(title = "批量采集任务提交", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:submit")
@PostMapping("/{taskId}/submit")
public R<BatchRunView> submit(
@PathVariable long taskId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchSubmitCommand command
) {
return R.ok(service.submit(taskId, idempotencyKey, command));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/{taskId}/runs")
public R<List<BatchRunView>> runs(@PathVariable long taskId) {
return R.ok(service.runs(taskId));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/runs/{runId}")
public R<BatchRunView> run(@PathVariable long runId) {
return R.ok(service.run(runId));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/runs/{runId}/checkpoints")
public R<List<BatchCheckpointView>> checkpoints(@PathVariable long runId) {
return R.ok(service.checkpoints(runId));
}
@Log(title = "批量采集状态刷新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission(value = {"aixun:dataops:batch-ingestion:view", "aixun:dataops:batch-ingestion:submit"},
mode = cn.dev33.satoken.annotation.SaMode.AND)
@PostMapping("/runs/{runId}/observe")
public R<BatchRunView> observe(@PathVariable long runId,
@RequestBody cn.aixunkeji.datagov.dataops.api.batchingestion.BatchObservationCommand command) {
return R.ok(service.observe(runId, command));
}
@Log(title = "批量采集失败续传", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:resume")
@PostMapping("/runs/{runId}/resume")
public R<BatchRunView> resume(
@PathVariable long runId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchResumeCommand command
) {
return R.ok(service.resume(runId, idempotencyKey, command));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/runs/{runId}/submission")
public R<cn.aixunkeji.datagov.dataops.api.batchingestion.BatchSubmissionRecoveryView> recovery(@PathVariable long runId) {
return R.ok(service.recovery(runId));
}
@Log(title = "批量采集关闭未发出尝试", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission(value = {"aixun:dataops:batch-ingestion:view", "aixun:dataops:batch-ingestion:submit",
"aixun:dataops:batch-ingestion:update"}, mode = cn.dev33.satoken.annotation.SaMode.AND)
@PostMapping("/runs/{runId}/close-not-sent")
public R<BatchTaskView> closeNotSent(@PathVariable long runId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody cn.aixunkeji.datagov.dataops.api.batchingestion.BatchCloseSubmissionCommand command) {
return R.ok(service.closeNotSent(runId, idempotencyKey, command));
}
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
@GetMapping("/runs/{runId}/arrival-validations")
public R<List<BatchArrivalValidationView>> validations(@PathVariable long runId) {
return R.ok(service.validations(runId));
}
@Log(title = "批量采集到数校验", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-ingestion:validate")
@PostMapping("/runs/{runId}/arrival-validations")
public R<BatchArrivalValidationView> validateArrival(
@PathVariable long runId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchArrivalValidationCommand command
) {
return R.ok(service.validateArrival(runId, idempotencyKey, command));
}
}
@@ -0,0 +1,33 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.Map;
@RestControllerAdvice(basePackages = "cn.aixunkeji.datagov.dataops.batchingestion")
public class BatchIngestionErrorHandler {
@ExceptionHandler(BatchIngestionException.class)
public ResponseEntity<R<Object>> handle(BatchIngestionException exception) {
return switch (exception.kind()) {
case VALIDATION -> response(HttpStatus.BAD_REQUEST, 121401, exception.getMessage(), null);
case FORBIDDEN -> response(HttpStatus.FORBIDDEN, 121403, "无权访问批量采集资源", null);
case NOT_FOUND -> response(HttpStatus.NOT_FOUND, 121404, "批量采集资源不存在", null);
case CONFLICT -> response(HttpStatus.CONFLICT, 121409, exception.getMessage(), exception.currentVersion());
case EXTERNAL -> response(HttpStatus.UNPROCESSABLE_ENTITY, 121422, exception.getMessage(), null);
};
}
private static ResponseEntity<R<Object>> response(HttpStatus status, int code, String message,
Long currentVersion) {
R<Object> body = R.fail(code, message);
if (currentVersion != null) {
body.setData(Map.of("currentVersion", currentVersion));
}
return ResponseEntity.status(status).body(body);
}
}
@@ -0,0 +1,53 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
public final class BatchIngestionException extends RuntimeException {
private final Kind kind;
private final Long currentVersion;
private BatchIngestionException(Kind kind, String message, Long currentVersion) {
super(message);
this.kind = kind;
this.currentVersion = currentVersion;
}
public Kind kind() {
return kind;
}
public Long currentVersion() {
return currentVersion;
}
public static BatchIngestionException validation(String message) {
return new BatchIngestionException(Kind.VALIDATION, message, null);
}
public static BatchIngestionException conflict(String message) {
return new BatchIngestionException(Kind.CONFLICT, message, null);
}
public static BatchIngestionException versionConflict(long currentVersion) {
return new BatchIngestionException(Kind.CONFLICT, "任务版本已变化,请刷新后重试", currentVersion);
}
public static BatchIngestionException forbidden() {
return new BatchIngestionException(Kind.FORBIDDEN, "无权访问批量采集资源", null);
}
public static BatchIngestionException notFound() {
return new BatchIngestionException(Kind.NOT_FOUND, "批量采集资源不存在", null);
}
public static BatchIngestionException external(String message) {
return new BatchIngestionException(Kind.EXTERNAL, message, null);
}
public enum Kind {
VALIDATION,
CONFLICT,
FORBIDDEN,
NOT_FOUND,
EXTERNAL
}
}
@@ -0,0 +1,435 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchFieldMappingCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchFieldTransform;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchFilterOperator;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionMode;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskConfiguration;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
public final class BatchIngestionPolicy {
private static final Pattern NAME = Pattern.compile("[\\p{L}\\p{N}._ -]{2,128}");
private static final Pattern CODE = Pattern.compile("[A-Za-z0-9._:-]{2,64}");
private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_$]{0,127}");
private static final Pattern OBJECT = Pattern.compile("[A-Za-z_][A-Za-z0-9_$.-]{0,254}");
private static final Pattern TYPE = Pattern.compile("[A-Za-z][A-Za-z0-9_(), ]{0,63}");
private static final Pattern IDEMPOTENCY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
private static final Pattern ERROR_CODE = Pattern.compile("[A-Za-z0-9._:-]{1,64}");
private static final Pattern EXTERNAL_ID = Pattern.compile("[A-Za-z0-9._:-]{1,128}");
private static final Pattern EVIDENCE_REF = Pattern.compile("[A-Za-z0-9:/._-]{1,512}");
private static final Pattern UNSAFE_FILTER = Pattern.compile("(;|--|/\\*|\\*/|#)");
private static final Pattern SENSITIVE_TEXT = Pattern.compile(
"(?i)(password|passwd|pwd|token|secret|authorization|credential|connection.?string|private.?key|api.?key)" +
"\\s*[:=]\\s*[^,;\\s]+"
);
private static final Pattern INTERNAL_FAILURE_TEXT = Pattern.compile(
"(?is)(jdbc:|preparedstatement|sqlstate|bad sql grammar|com\\.mysql|org\\.springframework\\.jdbc|" +
"\\b(select|insert|update|delete|merge|alter|create|drop|truncate)\\b|store_[a-z0-9_]+)"
);
private static final Set<String> SOURCE_CONNECTORS = Set.of("JDBC", "MYSQL");
private static final Set<String> TARGET_CONNECTORS = Set.of("HIVE", "DORIS");
private static final Set<String> STRING_TYPES = Set.of("STRING", "VARCHAR", "CHAR", "TEXT");
private BatchIngestionPolicy() {
}
public static TaskConfig normalize(BatchTaskConfiguration command) {
if (command == null || command.name() == null || !NAME.matcher(command.name().trim()).matches() ||
command.sourceRefId() <= 0 || command.targetRefId() <= 0 || command.mode() == null) {
throw BatchIngestionException.validation("批量任务基本参数无效");
}
String sourceConnector = upper(command.sourceConnector());
String targetConnector = upper(command.targetConnector());
if (!SOURCE_CONNECTORS.contains(sourceConnector) || !TARGET_CONNECTORS.contains(targetConnector)) {
throw BatchIngestionException.validation("首版仅支持JDBC/MySQL源和Hive/Doris目标");
}
String sourceObject = object(command.sourceObject(), "源对象无效");
String targetObject = object(command.targetObject(), "目标对象无效");
if (command.parallelism() < 1 || command.parallelism() > 200) {
throw BatchIngestionException.validation("并行度必须在1到200之间");
}
String incrementalField = optionalField(command.incrementalField(), "增量字段无效");
if (command.mode() == BatchIngestionMode.INCREMENTAL && incrementalField == null) {
throw BatchIngestionException.validation("增量模式必须配置增量字段");
}
if (command.mode() == BatchIngestionMode.FULL && incrementalField != null) {
throw BatchIngestionException.validation("全量模式不得配置增量字段");
}
String partitionField = optionalField(command.partitionField(), "分区字段无效");
if (command.parallelism() > 1 && partitionField == null) {
throw BatchIngestionException.validation("并行度大于1时必须配置分区字段");
}
Integer checkpointInterval = command.checkpointIntervalSeconds();
if (command.checkpointEnabled()) {
if (checkpointInterval == null || checkpointInterval < 10 || checkpointInterval > 86400) {
throw BatchIngestionException.validation("启用checkpoint时必须配置10到86400秒间隔");
}
} else if (checkpointInterval != null) {
throw BatchIngestionException.validation("关闭checkpoint时不得配置间隔");
}
List<MappingConfig> mappings = normalizeMappings(command.mappings());
return new TaskConfig(command.name().trim(), null, command.sourceRefId(),
command.targetRefId(), sourceConnector, targetConnector, sourceObject, targetObject, command.mode(),
incrementalField, partitionField, command.parallelism(), command.checkpointEnabled(),
checkpointInterval, mappings);
}
public static String requireIdempotencyKey(String key) {
if (key == null || !IDEMPOTENCY.matcher(key).matches()) {
throw BatchIngestionException.validation("Idempotency-Key格式无效");
}
return key;
}
public static String normalizeReason(String reason) {
if (reason == null || reason.trim().isEmpty() || reason.trim().length() > 500) {
throw BatchIngestionException.validation("操作原因长度必须为1到500字");
}
return reason.trim();
}
public static String normalizeOptionalScope(String value, String label) {
if (value == null || value.isBlank()) {
return null;
}
return code(value, label + "无效");
}
public static String normalizeKeyword(String value) {
if (value == null || value.isBlank()) {
return null;
}
String keyword = value.trim();
if (keyword.length() > 128 || UNSAFE_FILTER.matcher(keyword).find()) {
throw BatchIngestionException.validation("查询关键词无效");
}
return keyword;
}
public static int normalizePageNum(Integer pageNum) {
return pageNum == null ? 1 : Math.max(1, pageNum);
}
public static int normalizePageSize(Integer pageSize) {
int normalized = pageSize == null ? 20 : pageSize;
if (normalized < 1 || normalized > 100) {
throw BatchIngestionException.validation("分页大小必须在1到100之间");
}
return normalized;
}
public static void requireStatus(BatchIngestionStatus actual, BatchIngestionStatus required, String action) {
if (actual != required) {
throw BatchIngestionException.conflict("当前状态为" + actual + ",不允许" + action);
}
}
public static void requireFreshCheckpoint(BatchIntegrationGateway.CheckpointEvidence evidence,
BatchRunRecord run, LocalDateTime now) {
if (evidence == null || !evidence.completed() || evidence.runId() != run.runId() ||
evidence.externalJobId() == null || !evidence.externalJobId().equals(run.externalJobId()) ||
evidence.checkpointId() == null || evidence.checkpointId().isBlank() ||
evidence.checkpointSequence() < 0 || evidence.evidenceRef() == null || evidence.evidenceRef().isBlank() ||
safeExternalId(evidence.checkpointId()) == null || safeEvidenceRef(evidence.evidenceRef()) == null ||
evidence.evidenceAt() == null || evidence.evidenceAt().isBefore(now.minusHours(24)) ||
evidence.evidenceAt().isAfter(now.plusMinutes(5))) {
throw BatchIngestionException.external("缺少属于该失败运行的有效checkpoint证据");
}
}
public static String arrivalStatus(BatchIntegrationGateway.ArrivalEvidence evidence,
String expectedBatchNo, LocalDateTime now) {
if (evidence == null || evidence.batchNo() == null || evidence.batchNo().isBlank() ||
expectedBatchNo == null || !expectedBatchNo.equals(evidence.batchNo()) ||
evidence.sourceCount() == null || evidence.targetCount() == null || evidence.duplicateCount() == null ||
evidence.sourceCount() < 0 || evidence.targetCount() < 0 || evidence.duplicateCount() < 0 ||
evidence.checksum() == null || evidence.checksum().isBlank() ||
evidence.evidenceAt() == null || evidence.evidenceAt().isBefore(now.minusHours(24)) ||
evidence.evidenceAt().isAfter(now.plusMinutes(5)) ||
evidence.evidenceRef() == null || safeEvidenceRef(evidence.evidenceRef()) == null) {
return "UNKNOWN";
}
return evidence.sourceCount().equals(evidence.targetCount()) && evidence.duplicateCount() == 0 ?
"PASS" : "FAIL";
}
public static String safeSummary(String value) {
if (value == null || value.isBlank()) {
return null;
}
String normalized = value.replaceAll("[\\p{Cntrl}]+", " ").trim();
if (INTERNAL_FAILURE_TEXT.matcher(normalized).find()) {
return "内部数据处理失败,请刷新后重试;若持续失败请联系管理员";
}
String redacted = SENSITIVE_TEXT.matcher(normalized).replaceAll("$1=[REDACTED]");
return redacted.substring(0, Math.min(512, redacted.length()));
}
static ItemFailure itemFailure(RuntimeException exception) {
if (exception instanceof BatchIngestionException batch) {
return switch (batch.kind()) {
case VALIDATION -> new ItemFailure("FAILED", "UNIFIED_VALIDATION_FAILED",
safeSummary(batch.getMessage()), false);
case CONFLICT -> new ItemFailure("FAILED", "UNIFIED_CONFLICT",
safeSummary(batch.getMessage()), false);
case FORBIDDEN -> new ItemFailure("FAILED", "UNIFIED_FORBIDDEN",
"无权执行当前采集子项", false);
case NOT_FOUND -> new ItemFailure("FAILED", "UNIFIED_REFERENCE_NOT_FOUND",
"采集引用不存在或已失效,请刷新后重试", false);
case EXTERNAL -> new ItemFailure("UNKNOWN", "UNIFIED_EXTERNAL_UNAVAILABLE",
safeSummary(batch.getMessage()), true);
};
}
if (exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Validation ||
exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.Validation ||
exception instanceof cn.aixunkeji.datagov.dataops.storage.StorageValidationException) {
return new ItemFailure("FAILED", "UNIFIED_VALIDATION_FAILED",
safeSummary(exception.getMessage()), false);
}
if (exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Conflict ||
exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.Conflict ||
exception instanceof cn.aixunkeji.datagov.dataops.storage.StorageConflictException) {
return new ItemFailure("FAILED", "UNIFIED_CONFLICT", safeSummary(exception.getMessage()), false);
}
if (exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Scope ||
exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.Scope ||
exception instanceof cn.aixunkeji.datagov.dataops.storage.StorageScopeException) {
return new ItemFailure("FAILED", "UNIFIED_FORBIDDEN", "无权执行当前采集子项", false);
}
if (exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.NotFound ||
exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.NotFound ||
exception instanceof cn.aixunkeji.datagov.dataops.storage.StorageNotFoundException) {
return new ItemFailure("FAILED", "UNIFIED_REFERENCE_NOT_FOUND",
"采集引用不存在或已失效,请刷新后重试", false);
}
if (exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.ReferenceUnavailable ||
exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.Reference ||
hasDataAccessCause(exception)) {
return new ItemFailure("UNKNOWN", "UNIFIED_EXTERNAL_UNAVAILABLE",
"外部目录或平台存储暂不可确认,请稍后刷新状态", true);
}
return new ItemFailure("UNKNOWN", "UNIFIED_ITEM_UNKNOWN",
"采集子项结果暂不可确认,请稍后刷新状态", true);
}
private static boolean hasDataAccessCause(Throwable value) {
Throwable current = value;
for (int depth = 0; current != null && depth < 8; depth++, current = current.getCause()) {
if (current instanceof org.springframework.dao.DataAccessException ||
current instanceof java.sql.SQLException) return true;
}
return false;
}
record ItemFailure(String status, String code, String summary, boolean retryable) { }
public static String safeErrorCode(String value, String fallback) {
return value != null && ERROR_CODE.matcher(value).matches() ? value : fallback;
}
public static String safeExternalId(String value) {
return value != null && EXTERNAL_ID.matcher(value).matches() ? value : null;
}
public static String safeEvidenceRef(String value) {
return value != null && EVIDENCE_REF.matcher(value).matches() ? value : null;
}
public static String sha256(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256不可用", exception);
}
}
public static String deleteHash(long taskId, long expectedVersion, long orgScopeId) {
return sha256("DELETE\n" + taskId + "|" + expectedVersion + "|" + orgScopeId);
}
private static List<MappingConfig> normalizeMappings(List<BatchFieldMappingCommand> commands) {
if (commands == null || commands.isEmpty() || commands.size() > 500) {
throw BatchIngestionException.validation("字段映射必须包含1到500项");
}
Set<String> sources = new HashSet<>();
Set<String> targets = new HashSet<>();
List<MappingConfig> mappings = new ArrayList<>();
int order = 0;
for (BatchFieldMappingCommand command : commands) {
order++;
if (command == null) {
throw BatchIngestionException.validation("字段映射不能为空");
}
String source = field(command.sourceField(), "源字段无效");
String target = field(command.targetField(), "目标字段无效");
if (!sources.add(source.toLowerCase(Locale.ROOT)) || !targets.add(target.toLowerCase(Locale.ROOT))) {
throw BatchIngestionException.validation("源字段或目标字段重复");
}
String sourceType = type(command.sourceType());
String targetType = type(command.targetType());
BatchFieldTransform transform = command.transform() == null ? BatchFieldTransform.NONE : command.transform();
String defaultValue = normalizeDefault(command.defaultValue());
validateTransform(transform, sourceType, targetType, defaultValue);
List<String> filterValues = normalizeFilterValues(command.filterOperator(), command.filterValues());
mappings.add(new MappingConfig(order, source, target, sourceType, targetType, transform, defaultValue,
command.filterOperator(), filterValues));
}
return List.copyOf(mappings);
}
private static void validateTransform(BatchFieldTransform transform, String sourceType, String targetType,
String defaultValue) {
int sourceSeconds = cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.temporalPrecision(sourceType);
int targetSeconds = cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.temporalPrecision(targetType);
boolean temporal = sourceSeconds >= 0 || targetSeconds >= 0;
if (temporal && (sourceSeconds < 0 || targetSeconds < sourceSeconds ||
!baseType(targetType).equals("DATETIME") && !sourceType.equals(targetType) || transform != BatchFieldTransform.NONE)) {
throw BatchIngestionException.validation("时间映射须保持原值且目标小数秒位数不得低于源字段");
}
if (transform == BatchFieldTransform.NONE && !sourceType.equals(targetType) && !temporal) {
throw BatchIngestionException.validation("字段类型不同时必须显式配置转换");
}
if (transform == BatchFieldTransform.CAST && sourceType.equals(targetType)) {
throw BatchIngestionException.validation("相同类型不得配置CAST转换");
}
if (Set.of(BatchFieldTransform.TRIM, BatchFieldTransform.UPPER, BatchFieldTransform.LOWER).contains(transform) &&
!STRING_TYPES.contains(baseType(targetType))) {
throw BatchIngestionException.validation("文本转换只适用于字符类型");
}
if (transform == BatchFieldTransform.DEFAULT_IF_NULL && defaultValue == null) {
throw BatchIngestionException.validation("DEFAULT_IF_NULL必须配置默认值");
}
if (transform != BatchFieldTransform.DEFAULT_IF_NULL && defaultValue != null) {
throw BatchIngestionException.validation("默认值与当前转换类型冲突");
}
}
private static List<String> normalizeFilterValues(BatchFilterOperator operator, List<String> values) {
List<String> safe = values == null ? List.of() : values.stream().map(BatchIngestionPolicy::filterValue).toList();
if (operator == null) {
if (!safe.isEmpty()) {
throw BatchIngestionException.validation("过滤值必须绑定固定操作符");
}
return List.of();
}
int size = safe.size();
boolean valid = switch (operator) {
case IS_NULL, IS_NOT_NULL -> size == 0;
case BETWEEN -> size == 2;
case IN, NOT_IN -> size >= 1 && size <= 100;
default -> size == 1;
};
if (!valid) {
throw BatchIngestionException.validation("过滤值数量与操作符不匹配");
}
return List.copyOf(safe);
}
private static String filterValue(String value) {
if (value == null || value.length() > 256 || UNSAFE_FILTER.matcher(value).find()) {
throw BatchIngestionException.validation("过滤值禁止SQL、注释和分号");
}
return value.trim();
}
private static String normalizeDefault(String value) {
if (value == null || value.isBlank()) {
return null;
}
if (value.length() > 512 || UNSAFE_FILTER.matcher(value).find()) {
throw BatchIngestionException.validation("默认值格式无效");
}
return value.trim();
}
private static String code(String value, String message) {
if (value == null || !CODE.matcher(value.trim()).matches()) {
throw BatchIngestionException.validation(message);
}
return value.trim();
}
private static String field(String value, String message) {
if (value == null || !FIELD.matcher(value.trim()).matches()) {
throw BatchIngestionException.validation(message);
}
return value.trim();
}
private static String optionalField(String value, String message) {
return value == null || value.isBlank() ? null : field(value, message);
}
private static String object(String value, String message) {
if (value == null || !OBJECT.matcher(value.trim()).matches()) {
throw BatchIngestionException.validation(message);
}
return value.trim();
}
private static String type(String value) {
if (value == null || !TYPE.matcher(value.trim()).matches()) {
throw BatchIngestionException.validation("字段类型无效");
}
String normalized = value.trim().toUpperCase(Locale.ROOT);
if (Set.of("DATETIME", "TIMESTAMP").contains(baseType(normalized)) &&
cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.temporalPrecision(normalized) < 0)
throw BatchIngestionException.validation("小数秒位数必须为0到6的整数");
return normalized;
}
private static String baseType(String value) {
int bracket = value.indexOf('(');
return bracket < 0 ? value : value.substring(0, bracket);
}
private static String upper(String value) {
return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
}
public record TaskConfig(
String name,
String dataDomainCode,
long sourceRefId,
long targetRefId,
String sourceConnector,
String targetConnector,
String sourceObject,
String targetObject,
BatchIngestionMode mode,
String incrementalField,
String partitionField,
int parallelism,
boolean checkpointEnabled,
Integer checkpointIntervalSeconds,
List<MappingConfig> mappings
) {
}
public record MappingConfig(
int order,
String sourceField,
String targetField,
String sourceType,
String targetType,
BatchFieldTransform transform,
String defaultValue,
BatchFilterOperator filterOperator,
List<String> filterValues
) {
}
}
@@ -0,0 +1,533 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchArrivalValidationCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchArrivalValidationView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchCheckpointView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchFieldMappingView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchReadyCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchResumeCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchRunView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchSubmitCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskCreateCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskPageView;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskUpdateCommand;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskView;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class BatchIngestionService {
private static final String GATEWAY_UNKNOWN_CODE = "BATCH_GATEWAY_UNKNOWN";
private static final String GATEWAY_UNKNOWN_SUMMARY = "批量采集网关未返回可靠证据";
private static final String READY_READ_UNKNOWN_CODE = "BATCH_READY_READ_UNAVAILABLE";
private static final String READY_READ_UNKNOWN_SUMMARY = "源或目标结构暂不可读取,请稍后重新校验";
private final BatchActorProvider actorProvider;
private final BatchIngestionRepository repository;
private final BatchIntegrationGateway gateway;
private final JsonMapper objectMapper;
private final UnifiedIngestionSourceGateway dataSourceDirectory;
private final BatchTargetWizardService targetWizard;
private void requireDataSource(BatchActor actor, long sourceId) {
try {
var result = dataSourceDirectory.sources(actor.actorId(), actor.orgScopeId(), List.of(sourceId), null, 1);
if (result == null || !"AVAILABLE".equals(result.status()) || result.entries() == null ||
result.entries().size() != 1 || result.entries().getFirst() == null ||
!Long.valueOf(sourceId).equals(result.entries().getFirst().id()) ||
"PAUSED".equals(result.entries().getFirst().status()) ||
"CANCELED".equals(result.entries().getFirst().status())) {
throw BatchIngestionException.external("数据源不可用或未获授权,请刷新后重试");
}
} catch (RuntimeException | LinkageError exception) {
throw BatchIngestionException.external("数据源不可用或未获授权,请刷新后重试");
}
}
public BatchTaskPageView page(String keyword, String dataDomainCode,
BatchIngestionStatus status, Integer pageNum, Integer pageSize) {
return repository.list(actorProvider.current(), BatchIngestionPolicy.normalizeKeyword(keyword),
BatchIngestionPolicy.normalizeOptionalScope(dataDomainCode, "数据域"), status,
BatchIngestionPolicy.normalizePageNum(pageNum), BatchIngestionPolicy.normalizePageSize(pageSize));
}
public BatchTaskView find(long taskId) {
return repository.find(actorProvider.current(), taskId);
}
public BatchIngestionRepository.MutationResult<BatchTaskView> create(
String idempotencyKey, BatchTaskCreateCommand command
) {
BatchActor actor = actorProvider.current();
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
BatchIngestionPolicy.TaskConfig config = BatchIngestionPolicy.normalize(command);
requireDataSource(actor, config.sourceRefId());
targetWizard.validateConfig(actor, config);
String payload = write(new SnapshotEnvelope("CONFIGURATION", null, 0L, config));
return repository.create(actor, key, requestHash("CREATE", payload), config, payload,
BatchIngestionPolicy.sha256(payload));
}
public BatchIngestionRepository.MutationResult<BatchTaskView> update(
long taskId, String idempotencyKey, BatchTaskUpdateCommand command
) {
if (command == null || command.version() < 0) {
throw BatchIngestionException.validation("任务版本无效");
}
BatchActor actor = actorProvider.current();
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
BatchIngestionPolicy.TaskConfig config = BatchIngestionPolicy.normalize(command);
requireDataSource(actor, config.sourceRefId());
targetWizard.validateConfig(actor, config);
String payload = write(new SnapshotEnvelope("CONFIGURATION", taskId, command.version() + 1, config));
return repository.update(actor, taskId, command.version(), key,
requestHash("UPDATE", taskId + "|" + command.version() + "|" + payload), config, payload,
BatchIngestionPolicy.sha256(payload));
}
public void delete(long taskId, long expectedVersion, String idempotencyKey) {
BatchActor actor = actorProvider.current();
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
repository.delete(actor, taskId, expectedVersion, key,
BatchIngestionPolicy.deleteHash(taskId, expectedVersion, actor.orgScopeId()));
}
public BatchTaskView ready(long taskId, String idempotencyKey, BatchReadyCommand command) {
return ready(actorProvider.current(), null, taskId, idempotencyKey, command);
}
BatchTaskView ready(VerifiedIngestionCommandActor verified, long taskId, String key, BatchReadyCommand command) {
verified.checkSubmit();
return ready(verified.batchActor(), verified, taskId, key, command);
}
private BatchTaskView ready(BatchActor actor, VerifiedIngestionCommandActor verified,
long taskId, String idempotencyKey, BatchReadyCommand command) {
if (command == null || command.version() < 0) {
throw BatchIngestionException.validation("任务版本无效");
}
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
BatchTaskView task = repository.find(actor, taskId);
requireDataSource(actor, task.sourceRefId());
String hash = requestHash("READY", taskId + "|" + command.version());
BatchIngestionRepository.RequestReservation reservation = repository.reserveAction(actor, "READY", key,
hash, taskId, null, null);
if (!reservation.created()) {
return repository.taskResponse(actor, reservation.record());
}
try {
requireVersion(task, command.version());
BatchIngestionPolicy.requireStatus(task.status(), BatchIngestionStatus.DRAFT, "READY校验");
if (verified == null) targetWizard.validateConfig(actor, toConfig(task));
else targetWizard.validateConfig(actor, toConfig(task), verified);
} catch (BatchIngestionException exception) {
if (exception.kind() == BatchIngestionException.Kind.EXTERNAL) {
repository.failRequest(actor, reservation, true, READY_READ_UNKNOWN_CODE, READY_READ_UNKNOWN_SUMMARY, true);
throw BatchIngestionException.external(READY_READ_UNKNOWN_SUMMARY);
}
repository.failRequest(actor, reservation, false,
exception.currentVersion() == null ? "BATCH_STATE_CONFLICT" : "BATCH_VERSION_CONFLICT",
exception.getMessage(), false);
throw exception;
} catch (TableFileErrors.Scope | TableFileErrors.NotFound | TableFileErrors.Validation | TableFileErrors.Conflict exception) {
repository.failRequest(actor, reservation, false, "BATCH_READY_PRECHECK_REJECTED", "目标资源前置校验未通过,请检查访问权限与当前配置", false);
// Keep the existing TableFileErrorHandler's typed HTTP/business error response.
throw exception;
} catch (RuntimeException exception) {
repository.failRequest(actor, reservation, true, READY_READ_UNKNOWN_CODE, READY_READ_UNKNOWN_SUMMARY, true);
throw BatchIngestionException.external(READY_READ_UNKNOWN_SUMMARY);
}
BatchIntegrationGateway.CapabilityCheckResult capability;
try {
var capabilityRequest = new BatchIntegrationGateway.CapabilityCheckRequest(
actor.actorId(), actor.orgScopeId(), taskId, task.sourceRefId(), task.targetRefId(),
task.sourceConnector(), task.targetConnector(),
"batch:" + taskId + ":" + task.currentSnapshotId() + ":ready", toConfig(task));
capability = verified == null ? gateway.checkCapabilities(capabilityRequest)
: gateway.checkCapabilities(verified, capabilityRequest);
} catch (RuntimeException | LinkageError exception) {
repository.failRequest(actor, reservation, true, GATEWAY_UNKNOWN_CODE,
GATEWAY_UNKNOWN_SUMMARY, true);
throw BatchIngestionException.external(GATEWAY_UNKNOWN_SUMMARY);
}
LocalDateTime now = LocalDateTime.now();
if (capability == null || !capability.supportedAndFresh(now)) {
boolean unsupported = capability != null &&
(capability.source() == BatchIntegrationGateway.CapabilityState.UNSUPPORTED ||
capability.target() == BatchIntegrationGateway.CapabilityState.UNSUPPORTED ||
capability.connector() == BatchIntegrationGateway.CapabilityState.UNSUPPORTED);
String code = capability == null ? GATEWAY_UNKNOWN_CODE :
BatchIngestionPolicy.safeErrorCode(capability.errorCode(),
unsupported ? "BATCH_CAPABILITY_UNSUPPORTED" : GATEWAY_UNKNOWN_CODE);
String summary = readyFailureSummary(code, unsupported);
if ("BATCH_TARGET_MAPPING_MISMATCH".equals(code) && capability != null && capability.fieldIssue() != null &&
capability.fieldIssue().safeSummary() != null) summary = capability.fieldIssue().safeSummary();
repository.failRequest(actor, reservation, !unsupported,
code, summary, !unsupported);
throw BatchIngestionException.external(summary);
}
try {
return repository.completeReady(actor, reservation, taskId, command.version(),
capability.checkedAt(), capability.expiresAt());
} catch (BatchIngestionException exception) {
repository.failRequest(actor, reservation, false, "BATCH_READY_CONFLICT",
"READY校验完成前任务版本发生变化", false);
throw exception;
}
}
public BatchRunView submit(long taskId, String idempotencyKey, BatchSubmitCommand command) {
if (command == null || command.version() < 0) {
throw BatchIngestionException.validation("任务版本无效");
}
BatchActor actor = actorProvider.current();
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
BatchTaskView task = repository.find(actor, taskId);
requireDataSource(actor, task.sourceRefId());
String payload = write(new SnapshotEnvelope("SUBMISSION", taskId, command.version(), toConfig(task)));
String snapshotHash = BatchIngestionPolicy.sha256(payload);
String requestHash = requestHash("SUBMIT", taskId + "|" + command.version() + "|" + snapshotHash);
BatchIngestionRepository.RunStart start = repository.beginSubmit(actor, taskId, command.version(), key,
requestHash, payload, snapshotHash);
if (!start.created()) {
return start.view();
}
BatchIntegrationGateway.SubmissionResult result;
try {
targetWizard.validateConfig(actor, toConfig(task));
} catch (RuntimeException | LinkageError exception) {
return repository.applySubmission(actor, start.record().runId(), new BatchIntegrationGateway.SubmissionResult(
null, "PRE_SUBMIT_REJECTED", BatchIngestionStatus.UNKNOWN, false, "BATCH_SCHEMA_RECHECK_REJECTED",
"源或目标结构校验未通过,未发出外部作业,请查看提交记录后修订",
cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.SubmissionEvidence.NOT_SENT));
}
if (!repository.beginDispatch(actor, start.record().runId())) return repository.findRun(actor, start.record().runId());
try {
result = gateway.submit(new BatchIntegrationGateway.SubmissionRequest(
actor.actorId(), actor.orgScopeId(), taskId, start.record().definitionId(), start.record().snapshotId(),
start.record().runId(), start.record().requestId(), start.externalActionKey(), snapshotHash,
task.sourceRefId(), task.targetRefId(), task.sourceConnector(), task.targetConnector(),
toConfig(task), start.record().batchNo()));
} catch (RuntimeException | LinkageError exception) {
result = unknownSubmission();
}
return repository.applySubmission(actor, start.record().runId(), result);
}
public List<BatchRunView> runs(long taskId) {
return repository.listRuns(actorProvider.current(), taskId);
}
BatchTaskView create(VerifiedIngestionCommandActor verified, String key, BatchTaskCreateCommand command,
java.util.function.Consumer<Long> bind) {
verified.checkSubmit();
var actor = verified.batchActor();
var config = BatchIngestionPolicy.normalize(command);
requireDataSource(actor, config.sourceRefId());
targetWizard.validateConfig(actor, config, verified);
String payload = write(new SnapshotEnvelope("CONFIGURATION", null, 0L, config));
verified.checkSubmit();
return repository.commandTransaction(() -> {
var task = repository.create(actor, BatchIngestionPolicy.requireIdempotencyKey(key),
requestHash("CREATE", payload), config, payload, BatchIngestionPolicy.sha256(payload)).value();
bind.accept(task.taskId());
return task;
});
}
BatchTaskView find(VerifiedIngestionCommandActor verified, long taskId) {
verified.check();
return repository.find(verified.batchActor(), taskId);
}
BatchRunView reserveSubmission(VerifiedIngestionCommandActor verified, long taskId, String key,
java.util.function.Consumer<Long> bind) {
verified.checkSubmit();
var actor = verified.batchActor();
var task = repository.find(actor, taskId);
requireDataSource(actor, task.sourceRefId());
targetWizard.validateConfig(actor, toConfig(task), verified);
String payload = write(new SnapshotEnvelope("SUBMISSION", taskId, task.version(), toConfig(task)));
String hash = BatchIngestionPolicy.sha256(payload);
verified.checkSubmit();
return repository.beginSubmit(actor, taskId, task.version(), BatchIngestionPolicy.requireIdempotencyKey(key),
requestHash("SUBMIT", taskId + "|" + task.version() + "|" + hash), payload, hash, bind).view();
}
BatchRunView dispatch(VerifiedIngestionCommandActor verified, long runId, Runnable bindFence) {
verified.checkSubmit();
var actor = verified.batchActor();
var run = repository.runRecord(actor, runId);
var task = repository.find(actor, run.taskId());
// Recovery never recreates a run or invokes submission for an uncertain journal.
if (!"PREPARED".equals(repository.recovery(actor, runId).phase()) || task.capabilityExpiresAt() == null ||
!task.capabilityExpiresAt().isAfter(LocalDateTime.now())) {
bindFence.run();
return repository.findRun(actor, runId);
}
if (task.currentSnapshotId() != run.snapshotId()) throw BatchIngestionException.conflict("原运行快照已变化");
requireDataSource(actor, task.sourceRefId());
targetWizard.validateConfig(actor, toConfig(task), verified);
String hash = repository.snapshotSha256(actor, task.taskId(), run.snapshotId());
verified.checkSubmit();
boolean dispatch = repository.commandTransaction(() -> {
if (!repository.beginDispatch(actor, runId)) return Boolean.FALSE;
bindFence.run();
return Boolean.TRUE;
});
if (!dispatch) return repository.findRun(actor, runId);
BatchIntegrationGateway.SubmissionResult result;
try {
result = gateway.submit(verified, new BatchIntegrationGateway.SubmissionRequest(actor.actorId(), actor.orgScopeId(),
task.taskId(), run.definitionId(), run.snapshotId(), run.runId(), run.requestId(),
"batch:" + task.taskId() + ":" + run.snapshotId() + ":submit", hash, task.sourceRefId(), task.targetRefId(), task.sourceConnector(),
task.targetConnector(), toConfig(task), run.batchNo()));
} catch (RuntimeException | LinkageError ignored) {
result = unknownSubmission();
}
return repository.applySubmission(actor, runId, result);
}
BatchRunView run(VerifiedIngestionCommandActor verified, long runId) {
verified.check();
return repository.findRun(verified.batchActor(), runId);
}
public BatchRunView run(long runId) {
return repository.findRun(actorProvider.current(), runId);
}
public BatchRunView observe(long runId,
cn.aixunkeji.datagov.dataops.api.batchingestion.BatchObservationCommand command) {
return observe(actorProvider.current(), runId, command);
}
BatchRunView observe(VerifiedIngestionCommandActor verified, long runId,
cn.aixunkeji.datagov.dataops.api.batchingestion.BatchObservationCommand command) {
verified.check();
return observe(verified.batchActor(), runId, command);
}
private BatchRunView observe(BatchActor actor, long runId,
cn.aixunkeji.datagov.dataops.api.batchingestion.BatchObservationCommand command) {
if (command == null || command.version() < 0) {
throw BatchIngestionException.validation("运行版本无效");
}
var context = repository.observationContext(actor, runId, command.version());
var run = context.run();
if (run.status() == BatchIngestionStatus.SUCCEEDED || run.status() == BatchIngestionStatus.FAILED ||
run.status() == BatchIngestionStatus.CANCELED) return run;
if (context.observedJobId() == null) return run;
var request = new cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.BatchObservationRequest(
actor.actorId(), actor.orgScopeId(), context.task().sourceRefId(), run.taskId(), run.runId(),
run.snapshotId(), context.snapshotHash(), run.runType(), context.observedJobId());
cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.BatchObservationResult result;
try {
result = gateway.observe(request);
} catch (RuntimeException | LinkageError exception) {
result = null;
}
return repository.applyObservation(actor, context, result);
}
public List<BatchCheckpointView> checkpoints(long runId) {
return repository.checkpoints(actorProvider.current(), runId);
}
public cn.aixunkeji.datagov.dataops.api.batchingestion.BatchSubmissionRecoveryView recovery(long runId) {
return repository.recovery(actorProvider.current(), runId);
}
public BatchTaskView closeNotSent(long runId, String idempotencyKey,
cn.aixunkeji.datagov.dataops.api.batchingestion.BatchCloseSubmissionCommand command) {
if (command == null || command.version() < 0 || command.taskVersion() < 0)
throw BatchIngestionException.validation("运行或任务版本无效");
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
String reason = BatchIngestionPolicy.normalizeReason(command.reason());
return repository.closeNotSent(actorProvider.current(), runId, command.version(), command.taskVersion(), key,
requestHash("CLOSE_NOT_SENT", runId + "|" + command.version() + "|" + command.taskVersion() + "|" + reason), reason);
}
public BatchRunView resume(long runId, String idempotencyKey, BatchResumeCommand command) {
BatchActor actor = actorProvider.current();
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
String reason = BatchIngestionPolicy.normalizeReason(command == null ? null : command.reason());
BatchRunRecord parent = repository.runRecord(actor, runId);
BatchIngestionPolicy.requireStatus(parent.status(), BatchIngestionStatus.FAILED, "续传");
if (!parent.checkpointEnabled() || BatchIngestionPolicy.safeExternalId(parent.externalJobId()) == null) {
throw BatchIngestionException.conflict("失败运行缺少可续传的checkpoint配置或外部作业标识");
}
BatchTaskView immutableTask = repository.find(actor, parent.taskId());
requireDataSource(actor, immutableTask.sourceRefId());
if (immutableTask.currentSnapshotId() != parent.snapshotId()) {
throw BatchIngestionException.conflict("当前任务快照与失败运行不一致,不能安全续传");
}
String snapshotSha256 = repository.snapshotSha256(actor, parent.taskId(), parent.snapshotId());
String hash = requestHash("RESUME", runId + "|" + parent.snapshotId() + "|" + reason);
BatchIngestionRepository.RequestReservation reservation = repository.reserveAction(actor, "RESUME", key,
hash, parent.taskId(), parent.runId(), reason);
if (!reservation.created()) {
return repository.runResponse(actor, reservation.record());
}
BatchIntegrationGateway.CheckpointEvidence evidence;
try {
evidence = gateway.checkpointEvidence(new BatchIntegrationGateway.CheckpointRequest(parent.taskId(),
parent.runId(), parent.snapshotId(), parent.externalJobId(),
"batch:" + parent.runId() + ":" + parent.snapshotId() + ":checkpoint"));
} catch (RuntimeException | LinkageError exception) {
repository.failRequest(actor, reservation, true, GATEWAY_UNKNOWN_CODE,
GATEWAY_UNKNOWN_SUMMARY, true);
throw BatchIngestionException.external(GATEWAY_UNKNOWN_SUMMARY);
}
try {
BatchIngestionPolicy.requireFreshCheckpoint(evidence, parent, LocalDateTime.now());
} catch (BatchIngestionException exception) {
boolean unknown = evidence == null || evidence.errorCode() != null;
repository.failRequest(actor, reservation, unknown,
evidence == null ? GATEWAY_UNKNOWN_CODE :
BatchIngestionPolicy.safeErrorCode(evidence.errorCode(), "BATCH_CHECKPOINT_REJECTED"),
unknown ? GATEWAY_UNKNOWN_SUMMARY : "缺少属于该失败运行的有效checkpoint证据", unknown);
throw exception;
}
BatchIngestionRepository.RunStart start = repository.createResumeRun(actor, reservation, parent,
evidence, hash);
if (!start.created()) {
return start.view();
}
BatchIntegrationGateway.SubmissionResult result;
try {
result = gateway.resume(new BatchIntegrationGateway.ResumeRequest(
actor.actorId(), actor.orgScopeId(), parent.taskId(), parent.runId(), start.record().runId(),
parent.snapshotId(),
start.record().requestId(), parent.externalJobId(), evidence.checkpointId(), reason,
start.externalActionKey(), snapshotSha256, immutableTask.sourceRefId(), immutableTask.targetRefId(),
immutableTask.sourceConnector(), immutableTask.targetConnector(), toConfig(immutableTask),
start.record().batchNo()));
} catch (RuntimeException | LinkageError exception) {
result = unknownSubmission();
}
return repository.applySubmission(actor, start.record().runId(), result);
}
public List<BatchArrivalValidationView> validations(long runId) {
return repository.validations(actorProvider.current(), runId);
}
public BatchArrivalValidationView validateArrival(long runId, String idempotencyKey,
BatchArrivalValidationCommand command) {
return validateArrival(actorProvider.current(), runId, idempotencyKey, command);
}
BatchArrivalValidationView validateArrival(VerifiedIngestionCommandActor verified, long runId,
String idempotencyKey, BatchArrivalValidationCommand command) {
verified.check();
return validateArrival(verified.batchActor(), runId, idempotencyKey, command);
}
private BatchArrivalValidationView validateArrival(BatchActor actor, long runId, String idempotencyKey,
BatchArrivalValidationCommand command) {
String key = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
String reason = BatchIngestionPolicy.normalizeReason(command == null ? null : command.reason());
BatchRunRecord run = repository.runRecord(actor, runId);
BatchIngestionPolicy.requireStatus(run.status(), BatchIngestionStatus.SUCCEEDED, "到数校验");
if (BatchIngestionPolicy.safeExternalId(run.externalJobId()) == null) {
throw BatchIngestionException.conflict("成功运行缺少可靠外部作业标识");
}
String hash = requestHash("VALIDATE", runId + "|" + run.snapshotId() + "|" + reason);
BatchIngestionRepository.RequestReservation reservation = repository.reserveArrival(actor, run, key,
hash, reason);
if (!reservation.created()) {
return repository.validationResponse(actor, reservation.record());
}
String actionKey = "batch:" + run.runId() + ":" + run.snapshotId() + ":validate";
BatchIntegrationGateway.ArrivalEvidence evidence;
try {
evidence = gateway.validateArrival(new BatchIntegrationGateway.ArrivalValidationRequest(run.taskId(),
run.runId(), run.snapshotId(), run.externalJobId(), actionKey, run.batchNo()));
} catch (RuntimeException | LinkageError exception) {
evidence = unknownArrival();
}
if (evidence == null) {
evidence = unknownArrival();
}
String status = BatchIngestionPolicy.arrivalStatus(evidence, run.batchNo(), LocalDateTime.now());
return repository.completeArrival(actor, reservation, run, evidence, status);
}
private static void requireVersion(BatchTaskView task, long expectedVersion) {
if (task.version() != expectedVersion) {
throw BatchIngestionException.versionConflict(task.version());
}
}
private static BatchIngestionPolicy.TaskConfig toConfig(BatchTaskView task) {
return new BatchIngestionPolicy.TaskConfig(task.name(), task.dataDomainCode(),
task.sourceRefId(), task.targetRefId(), task.sourceConnector(), task.targetConnector(),
task.sourceObject(), task.targetObject(), task.mode(), task.incrementalField(), task.partitionField(),
task.parallelism(), task.checkpointEnabled(), task.checkpointIntervalSeconds(),
task.mappings().stream().map(BatchIngestionService::toMapping).toList());
}
private static BatchIngestionPolicy.MappingConfig toMapping(BatchFieldMappingView mapping) {
return new BatchIngestionPolicy.MappingConfig(mapping.mappingOrder(), mapping.sourceField(),
mapping.targetField(), mapping.sourceType(), mapping.targetType(), mapping.transform(),
mapping.defaultValue(), mapping.filterOperator(), mapping.filterValues());
}
private String write(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JacksonException exception) {
throw new IllegalStateException("批量任务结构化配置序列化失败", exception);
}
}
private static String requestHash(String action, String value) {
return BatchIngestionPolicy.sha256(action + "\n" + value);
}
private static String readyFailureSummary(String code, boolean unsupported) {
if ("BATCH_TARGET_TABLE_MISSING".equals(code)) return "目标表不存在,请先在表文件管理中创建或选择已有目标表";
if ("BATCH_TARGET_MAPPING_MISMATCH".equals(code)) return "目标表字段与映射不兼容,请检查字段名称和类型";
if ("BATCH_TARGET_ACCESS_DENIED".equals(code)) return "目标表访问被拒绝,请检查目标资源账号权限";
if ("BATCH_TARGET_UNAVAILABLE".equals(code)) return "目标表暂不可查询,请检查目标资源连接后重新校验";
if (!unsupported) {
return "批量采集能力暂不可验证,请稍后重试";
}
return switch (code) {
case "BATCH_REFERENCE_INCOMPLETE" -> "目标资源访问配置或数据库空间不完整,请重新选择目标资源和数据库";
case "BATCH_SOURCE_OUTSIDE_SCOPE", "BATCH_SOURCE_SCOPE_MISMATCH" ->
"来源不属于当前组织或数据域,请重新选择来源";
case "BATCH_SOURCE_CONNECTOR_UNSUPPORTED" -> "来源不支持当前批量任务,请检查数据源类型和连接状态";
case "BATCH_TARGET_CONNECTOR_UNSUPPORTED" -> "目标资源不支持当前批量任务,请检查Hive或Doris资源配置";
case "BATCH_EXECUTION_SHAPE_UNSUPPORTED", "BATCH_CHECKPOINT_CONTRACT_INVALID",
"BATCH_EXECUTION_CONTRACT_INVALID" -> "任务执行配置不完整,请检查目标数据库、表名和采集方式";
case "BATCH_MAPPING_UNSUPPORTED" -> "字段映射不符合当前执行规则,请检查字段和转换";
default -> "源、目标或执行配置不支持当前批量任务,请检查后重试";
};
}
private static BatchIntegrationGateway.SubmissionResult unknownSubmission() {
return new BatchIntegrationGateway.SubmissionResult(null, "GATEWAY_UNKNOWN",
BatchIngestionStatus.UNKNOWN, true, GATEWAY_UNKNOWN_CODE, GATEWAY_UNKNOWN_SUMMARY);
}
private static BatchIntegrationGateway.ArrivalEvidence unknownArrival() {
return new BatchIntegrationGateway.ArrivalEvidence(null, null, null, null, null, null, null,
true, GATEWAY_UNKNOWN_CODE, GATEWAY_UNKNOWN_SUMMARY);
}
private record SnapshotEnvelope(String kind, Long taskId, long revision,
BatchIngestionPolicy.TaskConfig configuration) { }
}
@@ -0,0 +1,168 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.TaskSummary;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/** Owner-side batch run directory; it exposes no mapping, checkpoint body, parameter or secretRef. */
@Component
@RequiredArgsConstructor
public class BatchIngestionTaskLogDirectory implements TaskLogOwnerDirectory {
private static final String FROM = """
FROM ops_job_run r
JOIN ing_batch_task t ON t.definition_id=r.definition_id AND t.del_flag='0'
""";
private final JdbcTemplate jdbcTemplate;
@Override
public Source source() {
return Source.BATCH_INGESTION;
}
@Override
public OwnerListResult list(OwnerQuery query) {
try {
QueryParts parts = where(query, null);
Long total = jdbcTemplate.queryForObject("SELECT COUNT(*) " + FROM + parts.where(), Long.class,
parts.parameters().toArray());
List<Object> parameters = new ArrayList<>(parts.parameters());
parameters.add(query.limit());
List<TaskSummary> rows = jdbcTemplate.query(select() + parts.where()
+ " ORDER BY r.update_time DESC, r.run_id DESC LIMIT ?",
(resultSet, rowNum) -> map(resultSet), parameters.toArray());
return OwnerListResult.available(rows, total == null ? 0 : total);
} catch (RuntimeException exception) {
return OwnerListResult.unavailable();
}
}
@Override
public OwnerDetailResult find(OwnerScope scope, long runId) {
try {
OwnerQuery query = new OwnerQuery(scope.actorId(), scope.orgId(), scope.unrestricted(), null, null,
null, null, null, null, 1);
QueryParts parts = where(query, runId);
List<TaskSummary> rows = jdbcTemplate.query(select() + parts.where(),
(resultSet, rowNum) -> map(resultSet), parts.parameters().toArray());
return rows.isEmpty() ? OwnerDetailResult.notFound() : OwnerDetailResult.available(rows.getFirst());
} catch (RuntimeException exception) {
return OwnerDetailResult.unavailable();
}
}
private static String select() {
return """
SELECT r.run_id, t.task_id, t.task_name, t.org_scope_id, t.project_code, t.data_domain_code,
r.run_type, r.run_status, r.source_status, r.seatunnel_job_id, r.error_summary,
r.started_at, r.completed_at, r.create_time, r.update_time
""" + FROM;
}
private static QueryParts where(OwnerQuery query, Long runId) {
StringBuilder where = new StringBuilder(" WHERE t.org_scope_id=? AND r.del_flag='0'");
List<Object> parameters = new ArrayList<>();
parameters.add(query.orgId());
if (!query.unrestricted()) {
where.append(" AND r.actor_id=?");
parameters.add(query.actorId());
}
if (runId != null) {
where.append(" AND r.run_id=?");
parameters.add(runId);
}
appendFilters(where, parameters, query);
return new QueryParts(where.toString(), parameters);
}
private static void appendFilters(StringBuilder where, List<Object> parameters, OwnerQuery query) {
if (query.keyword() != null) {
String pattern = "%" + escapeLike(query.keyword()) + "%";
where.append(" AND (t.task_name LIKE ? ESCAPE '=' OR CAST(r.run_id AS CHAR) LIKE ? ESCAPE '=')");
parameters.add(pattern);
parameters.add(pattern);
}
if (query.projectRef() != null) {
where.append(" AND t.project_code=?");
parameters.add(query.projectRef());
}
if (query.taskType() != null) {
where.append(" AND r.run_type=?");
parameters.add(query.taskType());
}
appendStatus(where, parameters, query.status());
appendTime(where, parameters, query.startedFrom(), query.startedTo());
}
private static void appendStatus(StringBuilder where, List<Object> parameters, Status status) {
if (status == null) return;
if (status == Status.SUBMITTED) {
where.append(" AND r.run_status='PENDING' AND r.source_status LIKE 'SUBMITTED%'");
} else if (status == Status.PENDING) {
where.append(" AND r.run_status='PENDING' AND ")
.append("(r.source_status IS NULL OR r.source_status NOT LIKE 'SUBMITTED%')");
} else if (status == Status.UNKNOWN) {
where.append(" AND r.run_status IN ('UNKNOWN','PAUSED')");
} else {
where.append(" AND r.run_status=?");
parameters.add(status.name());
}
}
private static void appendTime(StringBuilder where, List<Object> parameters, LocalDateTime from, LocalDateTime to) {
if (from != null) {
where.append(" AND COALESCE(r.started_at,r.create_time)>=?");
parameters.add(Timestamp.valueOf(from));
}
if (to != null) {
where.append(" AND COALESCE(r.started_at,r.create_time)<=?");
parameters.add(Timestamp.valueOf(to));
}
}
private static TaskSummary map(ResultSet resultSet) throws SQLException {
String runStatus = resultSet.getString("run_status");
String sourceStatus = resultSet.getString("source_status");
return new TaskSummary(Source.BATCH_INGESTION, resultSet.getLong("run_id"),
resultSet.getLong("task_id"), resultSet.getString("task_name"), resultSet.getLong("org_scope_id"),
resultSet.getString("project_code"), resultSet.getString("data_domain_code"),
resultSet.getString("run_type"), normalizeStatus(runStatus, sourceStatus), sourceStatus, null,
resultSet.getString("seatunnel_job_id"), resultSet.getString("error_summary"),
localDateTime(resultSet.getTimestamp("started_at")), localDateTime(resultSet.getTimestamp("completed_at")),
localDateTime(resultSet.getTimestamp("create_time")), localDateTime(resultSet.getTimestamp("update_time")));
}
static Status normalizeStatus(String runStatus, String sourceStatus) {
if ("PENDING".equals(runStatus) && sourceStatus != null && sourceStatus.startsWith("SUBMITTED")) {
return Status.SUBMITTED;
}
try {
return runStatus == null || "PAUSED".equals(runStatus) ? Status.UNKNOWN : Status.valueOf(runStatus);
} catch (IllegalArgumentException exception) {
return Status.UNKNOWN;
}
}
private static String escapeLike(String value) {
return value.replace("=", "==").replace("%", "=%").replace("_", "=_");
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
private record QueryParts(String where, List<Object> parameters) {
}
}
@@ -0,0 +1,20 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.integration.api.aiassistant.*;
import static cn.aixunkeji.datagov.integration.api.aiassistant.WorkbenchObjectDirectory.*;
import static cn.aixunkeji.datagov.integration.api.aiassistant.WorkbenchObjectReader.*;
import static cn.aixunkeji.datagov.dataops.workbenchobject.EngineeringObjectProjection.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.databind.ObjectMapper;
import java.util.*;
@Component @RequiredArgsConstructor
final class BatchIngestionWorkbenchObject implements WorkbenchObjectReader {
private final BatchIngestionService service;private final ObjectMapper json;
public Set<String> types(){return Set.of("BATCH_INGESTION");}
public Snapshot read(Request request){
var value=service.find(numeric(request));editable(value.status().name());
var config=fields(json,value,"name","sourceRefId","targetRefId","sourceConnector","targetConnector","sourceObject","targetObject","mode","incrementalField","partitionField","parallelism","checkpointEnabled","checkpointIntervalSeconds");
config.put("mappings",value.mappings().stream().map(v->fields(json,v,"sourceField","targetField","sourceType","targetType","transform","defaultValue","filterOperator","filterValues")).toList());
return snapshot(request,value.version(),value.name(),value.status().name(),config);
}
}
@@ -0,0 +1,200 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.TargetFieldIssue;
import java.time.LocalDateTime;
/** Bounded integration port. A real SeaTunnel bridge is owned by the later integration task. */
public interface BatchIntegrationGateway {
CapabilityCheckResult checkCapabilities(CapabilityCheckRequest request);
SubmissionResult submit(SubmissionRequest request);
default CapabilityCheckResult checkCapabilities(VerifiedIngestionCommandActor verified, CapabilityCheckRequest request) {
throw BatchIngestionException.forbidden();
}
default SubmissionResult submit(VerifiedIngestionCommandActor verified, SubmissionRequest request) {
throw BatchIngestionException.forbidden();
}
default cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.BatchObservationResult observe(
cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.BatchObservationRequest request
) {
return new cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.BatchObservationResult(
request.taskId(), request.runId(), request.snapshotId(), request.externalJobId(),
"UNKNOWN", "UNKNOWN", true, "BATCH_OBSERVATION_UNAVAILABLE",
"外部状态暂不可用,请稍后重试", LocalDateTime.now());
}
CheckpointEvidence checkpointEvidence(CheckpointRequest request);
SubmissionResult resume(ResumeRequest request);
ArrivalEvidence validateArrival(ArrivalValidationRequest request);
enum CapabilityState {
SUPPORTED,
UNSUPPORTED,
UNKNOWN
}
record CapabilityCheckRequest(
long actorId,
long orgScopeId,
long taskId,
long sourceRefId,
long targetRefId,
String sourceConnector,
String targetConnector,
String externalActionKey,
BatchIngestionPolicy.TaskConfig snapshot
) {
CapabilityCheckRequest(long taskId, long sourceRefId, long targetRefId, String sourceConnector,
String targetConnector, String externalActionKey) {
this(0, 0, taskId, sourceRefId, targetRefId, sourceConnector, targetConnector,
externalActionKey, null);
}
}
record CapabilityCheckResult(
CapabilityState source,
CapabilityState target,
CapabilityState connector,
LocalDateTime checkedAt,
LocalDateTime expiresAt,
String errorCode,
String errorSummary,
TargetFieldIssue fieldIssue
) {
public CapabilityCheckResult(CapabilityState source, CapabilityState target, CapabilityState connector,
LocalDateTime checkedAt, LocalDateTime expiresAt, String errorCode, String errorSummary) {
this(source, target, connector, checkedAt, expiresAt, errorCode, errorSummary, null);
}
public boolean supportedAndFresh(LocalDateTime now) {
return source == CapabilityState.SUPPORTED && target == CapabilityState.SUPPORTED &&
connector == CapabilityState.SUPPORTED && checkedAt != null && expiresAt != null &&
!checkedAt.isAfter(now.plusMinutes(5)) && expiresAt.isAfter(now);
}
}
record SubmissionRequest(
long actorId,
long orgScopeId,
long taskId,
long definitionId,
long snapshotId,
long runId,
String requestId,
String externalActionKey,
String snapshotSha256,
long sourceRefId,
long targetRefId,
String sourceConnector,
String targetConnector,
BatchIngestionPolicy.TaskConfig snapshot,
String batchNo
) {
SubmissionRequest(long taskId, long definitionId, long snapshotId, long runId, String requestId,
String externalActionKey, String snapshotSha256, long sourceRefId, long targetRefId,
String sourceConnector, String targetConnector) {
this(0, 0, taskId, definitionId, snapshotId, runId, requestId, externalActionKey, snapshotSha256,
sourceRefId, targetRefId, sourceConnector, targetConnector, null, null);
}
}
record SubmissionResult(
String externalJobId,
String sourceStatus,
BatchIngestionStatus normalizedStatus,
boolean retryable,
String errorCode,
String errorSummary,
cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.SubmissionEvidence submissionEvidence
) {
public SubmissionResult(String externalJobId, String sourceStatus, BatchIngestionStatus normalizedStatus,
boolean retryable, String errorCode, String errorSummary) {
this(externalJobId, sourceStatus, normalizedStatus, retryable, errorCode, errorSummary,
cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.SubmissionEvidence.UNCONFIRMED);
}
}
record CheckpointRequest(
long taskId,
long runId,
long snapshotId,
String externalJobId,
String externalActionKey
) {
}
record CheckpointEvidence(
long runId,
String externalJobId,
boolean completed,
String checkpointId,
long checkpointSequence,
LocalDateTime evidenceAt,
String evidenceRef,
String errorCode,
String errorSummary
) {
}
record ResumeRequest(
long actorId,
long orgScopeId,
long taskId,
long parentRunId,
long resumedRunId,
long snapshotId,
String requestId,
String externalJobId,
String checkpointId,
String reason,
String externalActionKey,
String snapshotSha256,
long sourceRefId,
long targetRefId,
String sourceConnector,
String targetConnector,
BatchIngestionPolicy.TaskConfig snapshot,
String batchNo
) {
ResumeRequest(long taskId, long parentRunId, long resumedRunId, long snapshotId, String requestId,
String externalJobId, String checkpointId, String reason, String externalActionKey) {
this(0, 0, taskId, parentRunId, resumedRunId, snapshotId, requestId, externalJobId, checkpointId,
reason, externalActionKey, null, 0, 0, null, null, null, null);
}
}
record ArrivalValidationRequest(
long taskId,
long runId,
long snapshotId,
String externalJobId,
String externalActionKey,
String batchNo
) {
ArrivalValidationRequest(long taskId, long runId, long snapshotId, String externalJobId,
String externalActionKey) {
this(taskId, runId, snapshotId, externalJobId, externalActionKey, null);
}
}
record ArrivalEvidence(
String batchNo,
Long sourceCount,
Long targetCount,
String checksum,
Long duplicateCount,
LocalDateTime evidenceAt,
String evidenceRef,
boolean retryable,
String errorCode,
String errorSummary
) {
}
}
@@ -0,0 +1,17 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
/** Internal run facts required for fail-closed resume and validation decisions. */
public record BatchRunRecord(
long runId,
long taskId,
long definitionId,
long snapshotId,
String requestId,
String batchNo,
BatchIngestionStatus status,
String externalJobId,
boolean checkpointEnabled
) {
}
@@ -0,0 +1,25 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.integration.api.datasource.BatchTargetExistenceService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
class BatchTargetExistenceGateway {
@DubboReference(version = BatchTargetExistenceService.VERSION, group = BatchTargetExistenceService.GROUP,
check = false, timeout = 30_000, retries = 0)
private BatchTargetExistenceService service;
BatchTargetExistenceService.Result check(BatchTargetExistenceService.Request request) {
try {
BatchTargetExistenceService.Result result = service.check(request);
if (result != null && result.items() != null) return result;
} catch (RuntimeException | LinkageError ignored) {
// The application service maps this to per-table UNKNOWN without exposing RPC details.
}
return new BatchTargetExistenceService.Result(List.of());
}
}
@@ -0,0 +1,160 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.*;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.MysqlTargetType;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.TargetEngine;
import cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryColumn;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
/** Lossless logical carrier types; original native metadata remains visible in every draft. */
final class BatchTargetTypePolicy {
private static final List<ColumnType> INTEGERS = List.of(ColumnType.TINYINT, ColumnType.SMALLINT, ColumnType.INT, ColumnType.BIGINT);
private static final Pattern TARGET_TYPE = Pattern.compile("([A-Z]+)(?:\\(([0-9]{1,9})(?:,([0-9]{1,9}))?\\))?");
/** Legacy callers were Doris-only; all decisions still come from the canonical Integration contract. */
static ColumnDefinition propose(Column column) {
return propose(column, TargetEngine.DORIS);
}
static ColumnDefinition propose(Column column, TargetEngine engine) {
MysqlTargetType mapped = canonical(column, engine);
return targetDefinition(column, mapped.targetType());
}
static MysqlTargetType canonical(Column column, TargetEngine engine) {
if (column == null || column.nullable() == null)
throw invalid("源字段精度或可空性不完整,请重新读取结构");
MysqlTargetType mapped = DataSourceObjects.mysqlTargetType(column, engine);
if (!mapped.supported()) {
throw invalid(mapped.errorSummary() == null ? "源字段类型无法安全映射,请重新读取结构" : mapped.errorSummary());
}
return mapped;
}
private static ColumnDefinition targetDefinition(Column source, String declaration) {
var matcher = TARGET_TYPE.matcher(declaration == null ? "" : declaration);
if (!matcher.matches()) throw invalid("统一字段映射合同返回了无法识别的目标类型");
ColumnType type;
try { type = ColumnType.valueOf(matcher.group(1)); }
catch (IllegalArgumentException exception) { throw invalid("统一字段映射合同返回了不支持的目标类型"); }
Integer first = number(matcher.group(2));
Integer second = number(matcher.group(3));
Integer precision = null;
Integer scale = null;
if (type == ColumnType.DECIMAL) {
precision = first;
scale = second;
} else if (Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(type)) {
precision = first;
} else if (type == ColumnType.DATETIME) {
scale = first;
} else if (first != null || second != null) {
throw invalid("统一字段映射合同返回了无效的目标类型参数");
}
return new ColumnDefinition(source.name(), type, source.nullable(), precision, scale, source.sourceComment().value());
}
static void requireSourceComment(Column source) {
if (source.sourceComment().state() == DataSourceObjects.CommentState.UNKNOWN ||
source.sourceComment().state() == DataSourceObjects.CommentState.UNSUPPORTED)
throw invalid("源字段注释无法原样保留:" + source.name() + ";请重新读取结构或检查源注释");
}
static boolean fits(ColumnDefinition source, ColumnDefinition target) {
if (source == null || source.type() == null || source.nullable() == null || target == null || target.type() == null || target.nullable() == null ||
Boolean.TRUE.equals(source.nullable()) && !target.nullable()) return false;
if (Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(target.type()) &&
(target.precision() == null || target.precision() < 1 ||
target.precision() > (target.type() == ColumnType.CHAR ? 255 : 65533))) return false;
if (target.type() == ColumnType.DECIMAL && (target.precision() == null || target.scale() == null ||
target.precision() < 1 || target.precision() > 38 || target.scale() < 0 || target.scale() > target.precision())) return false;
if (INTEGERS.contains(source.type()) && INTEGERS.contains(target.type()))
return INTEGERS.indexOf(target.type()) >= INTEGERS.indexOf(source.type());
if (source.type() == ColumnType.FLOAT && target.type() == ColumnType.DOUBLE) return true;
if (Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(source.type())) {
return target.type() == ColumnType.STRING ||
Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(target.type()) && target.precision() != null &&
target.precision() >= source.precision();
}
if (source.type() != target.type()) return false;
if (source.type() == ColumnType.DATETIME) return source.precision() == null && target.precision() == null &&
validScale(source.scale()) && validScale(target.scale()) && seconds(target.scale()) >= seconds(source.scale());
if (source.type() == ColumnType.DECIMAL) return target.precision() != null && target.scale() != null &&
target.precision() <= 38 && target.scale() >= source.scale() &&
target.precision() - target.scale() >= source.precision() - source.scale();
return true;
}
static ColumnDefinition observed(DirectoryColumn c) {
return observed(c, TargetEngine.DORIS);
}
static ColumnDefinition observed(DirectoryColumn c, TargetEngine engine) {
if (c == null || c.nativeType() == null || c.nullable() == null)
throw invalid("目标字段结构不完整,请重新读取");
String base = c.nativeType().toUpperCase(Locale.ROOT).replaceAll("[ (].*", "");
if (Set.of("DECIMALV2", "DECIMALV3").contains(base)) base = "DECIMAL";
if (Set.of("TEXT", "LONGTEXT").contains(base)) base = "STRING";
if ("INTEGER".equals(base)) base = "INT";
if ("BOOL".equals(base)) base = "BOOLEAN";
if ("DATEV2".equals(base)) base = "DATE";
if ("DATETIMEV2".equals(base) || "TIMESTAMP".equals(base) && engine == TargetEngine.DORIS) base = "DATETIME";
if ("DATETIME".equals(base) && (cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.temporalPrecision(c.nativeType()) < 0 ||
cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.temporalPrecision(c.nativeType()) != c.scale()))
throw invalid("目标字段“" + c.name() + "”的小数秒位数不完整,请重新读取结构");
ColumnType type;
try { type = ColumnType.valueOf(base); } catch (IllegalArgumentException e) { throw invalid("目标字段类型暂不支持"); }
Integer precision = Set.of(ColumnType.VARCHAR, ColumnType.CHAR, ColumnType.DECIMAL).contains(type) ? c.precision() : null;
var column = new ColumnDefinition(c.name(), type, c.nullable(), precision,
type == ColumnType.DECIMAL || type == ColumnType.DATETIME ? c.scale() : null, null);
if (!fits(column, column)) throw invalid("目标字段“" + c.name() + "”的长度或精度不完整,请重新读取结构");
return column;
}
static void requireFits(ColumnDefinition source, ColumnDefinition target) {
if (fits(source, target)) return;
String reason;
if (Boolean.TRUE.equals(source.nullable()) && Boolean.FALSE.equals(target.nullable())) reason = "源允许空值,目标不允许空值";
else if (Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(source.type()) &&
Set.of(ColumnType.CHAR, ColumnType.VARCHAR).contains(target.type())) reason = "目标字符字节长度不足";
else if (source.type() == ColumnType.DECIMAL && target.type() == ColumnType.DECIMAL) reason = "目标整数位或小数位容量不足";
else if (source.type() == ColumnType.DATETIME && target.type() == ColumnType.DATETIME) reason = "目标时间精度低于源字段或小数秒位数无效";
else reason = "类型不兼容或目标范围缩窄";
throw invalid("字段“" + source.name() + "” → “" + target.name() + "”:源所需 " + typeLabel(source) +
",目标 " + typeLabel(target) + "," + reason + ";请重新匹配字段");
}
private static String typeLabel(ColumnDefinition c) {
if (c.type() == ColumnType.DATETIME) return "DATETIME(" + seconds(c.scale()) + ")";
return c.type().name() + (c.precision() == null ? "" : "(" + c.precision() + (c.scale() == null ? "" : "," + c.scale()) + ")");
}
static String logicalType(ColumnDefinition c) {
if (c.type() == ColumnType.DATETIME) return "DATETIME(" + seconds(c.scale()) + ")";
if (c.type() == ColumnType.DECIMAL) return "DECIMAL(" + c.precision() + "," + c.scale() + ")";
if (Set.of(ColumnType.VARCHAR, ColumnType.CHAR, ColumnType.STRING).contains(c.type())) return "STRING";
return c.type().name();
}
static String sourceLogicalType(Column source, ColumnDefinition target) {
if (source.nativeType() == null || source.nativeType().isBlank()) return logicalType(target);
String base = source.nativeType().toUpperCase(Locale.ROOT).replaceAll("[ (].*", "");
return Set.of("DATETIME", "TIMESTAMP").contains(base) ? base + "(" + source.scale() + ")" : logicalType(target);
}
static boolean declaredTypeMatches(String expected, String declared) {
if (expected.equals(declared)) return true;
// BL05 persisted temporal carriers used bare DATETIME for both source kinds at p0.
return Set.of("DATETIME(0)", "TIMESTAMP(0)").contains(expected) && Set.of("DATETIME", "TIMESTAMP").contains(declared);
}
private static int seconds(Integer scale) { return scale == null ? 0 : scale; }
private static Integer number(String value) {
try { return value == null ? null : Integer.valueOf(value); }
catch (NumberFormatException exception) { throw invalid("统一字段映射合同返回了无效的目标类型参数"); }
}
private static boolean validScale(Integer scale) { return scale == null || scale >= 0 && scale <= 6; }
static BatchIngestionException invalid(String message) { return BatchIngestionException.validation(message); }
}
@@ -0,0 +1,78 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
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.dataops.api.batchingestion.BatchTargetWizardApi.*;
import cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/batch-ingestions/target-wizard")
public class BatchTargetWizardController {
private final BatchTargetWizardService service;
private static final Set<String> CONTEXT = Set.of("sourceId", "sourceObject", "resourceId", "spaceId");
private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = new com.fasterxml.jackson.databind.ObjectMapper();
@SaCheckPermission(value={"aixun:dataops:batch-ingestion:view", "aixun:dataops:table-file:view"}, mode=SaMode.AND)
@GetMapping("/tables")
@Log(title="批采目标表目录", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
public R<DirectoryResult> tables(@RequestParam long resourceId,
@RequestParam long spaceId, @RequestParam(required=false) String table,
@RequestParam(required=false) String keyword, @RequestParam(defaultValue="1") int pageNum,
@RequestParam(defaultValue="20") int pageSize) {
return R.ok(service.directory(resourceId, spaceId, table, keyword, pageNum, pageSize));
}
@SaCheckPermission(value={"aixun:dataops:batch-ingestion:view", "aixun:dataops:table-file:view", "aixun:integration:data-source:browse"}, mode=SaMode.AND)
@Log(title="批采目标结构草案", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
@PostMapping("/draft")
public R<Draft> draft(@RequestBody Map<String,Object> body) {
keys(body, CONTEXT);
return R.ok(service.draft(convert(body, Context.class)));
}
@SaCheckPermission(value={"aixun:dataops:batch-ingestion:view", "aixun:dataops:table-file:view", "aixun:integration:data-source:browse"}, mode=SaMode.AND)
@Log(title="批采目标字段匹配", businessType=BusinessType.OTHER, isSaveRequestData=false, isSaveResponseData=false)
@PostMapping("/match")
public R<Matched> match(@RequestBody Map<String,Object> body) {
keys(body, Set.of("context", "name", "selectedColumns")); keys(body.get("context"), CONTEXT);
return R.ok(service.match(convert(body, Match.class)));
}
@SaCheckPermission(value={"aixun:dataops:batch-ingestion:view", "aixun:dataops:table-file:view"}, mode=SaMode.AND)
@Log(title="批采目标表存在性检查", businessType=BusinessType.OTHER,
isSaveRequestData=false, isSaveResponseData=false)
@PostMapping("/target-existence")
public R<TargetExistenceResult> targetExistence(@RequestBody Map<String,Object> body) {
keys(body, Set.of("resourceId", "spaceId", "tables"));
if (!(body.get("tables") instanceof List<?> tables) || tables.isEmpty() || tables.size() > 50)
throw BatchIngestionException.validation("请选择要检查的目标表,单次最多50张");
return R.ok(service.checkTargetExistence(convert(body, TargetExistenceCommand.class)));
}
@SaCheckPermission(value={"aixun:dataops:batch-ingestion:view", "aixun:dataops:table-file:view",
"aixun:integration:data-source:browse", "aixun:dataops:table-file:create"}, mode=SaMode.AND)
@Log(title="批采确认创建目标表", businessType=BusinessType.INSERT, isSaveRequestData=false, isSaveResponseData=false)
@PostMapping("/create")
public R<Created> create(@RequestHeader("Idempotency-Key") String key, @RequestBody Map<String,Object> body) {
keys(body, Set.of("context", "sourceFingerprint", "name", "columns")); keys(body.get("context"), CONTEXT);
if (!(body.get("columns") instanceof List<?> columns) || columns.isEmpty() || columns.size() > 100)
throw BatchIngestionException.validation("请选择字段");
columns.forEach(column -> keys(column, Set.of("name", "type", "nullable", "precision", "scale", "comment")));
return R.ok(service.create(key, convert(body, Confirm.class)));
}
static void keys(Object body, Set<String> allowed) {
if (!(body instanceof Map<?,?> map) || !allowed.containsAll(map.keySet()))
throw BatchIngestionException.validation("请求字段无效,请重新选择");
}
private static <T> T convert(Object body, Class<T> type) {
try { return MAPPER.convertValue(body, type); }
catch (IllegalArgumentException e) { throw BatchIngestionException.validation("请求字段类型无效,请重新选择"); }
}
}
@@ -0,0 +1,320 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.*;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTargetWizardApi.*;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.*;
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileService;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.TargetEngine;
import cn.aixunkeji.datagov.integration.api.datasource.BatchTargetExistenceService;
import cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult;
import cn.aixunkeji.datagov.integration.api.tablefile.UnifiedIngestionSourceService;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import java.util.*;
/** FR-ING-0304/0305: compose existing owner services, never duplicate table creation. */
@Service
@RequiredArgsConstructor
public class BatchTargetWizardService {
private static final Set<String> SAFE_EXISTENCE_REASONS = Set.of(
"目标表已存在",
"目标表不存在",
"目标表暂不可查询,请检查连接或读取权限",
"目标连接或权限暂不可用,无法确认目标表是否存在",
"目标表标识或目标访问配置无效,请重新选择目标资源",
"目标连接暂不可用,请稍后重新检查",
"Hive目标连接暂不可用,请稍后重新检查"
);
private final BatchActorProvider actors;
private final StorageTableFileReferenceDirectory storage;
private final TableFileService tables;
private final BatchIngestionRepository repository;
private final BatchTargetExistenceGateway targetExistence;
@DubboReference(check = false, timeout = 8000, retries = 0)
private DataCollectionIntegrationService integration;
@DubboReference(check = false, timeout = 8000, retries = 0,
version = UnifiedIngestionSourceService.VERSION, group = UnifiedIngestionSourceService.GROUP)
private UnifiedIngestionSourceService unifiedSources;
public DirectoryResult directory(long resource, long space, String table, String keyword, int page, int size) {
return tables.targetDirectory(resource, space, EngineType.DORIS, table, keyword, page, size);
}
public TargetExistenceResult checkTargetExistence(TargetExistenceCommand command) {
if (command == null || command.resourceId() <= 0 || command.spaceId() <= 0 ||
command.tables() == null || command.tables().isEmpty() || command.tables().size() > 50) {
throw invalid("请选择要检查的目标表,单次最多50张");
}
LinkedHashSet<String> tablesToCheck = new LinkedHashSet<>();
for (String table : command.tables()) {
if (table == null || !table.matches("[A-Za-z_][A-Za-z0-9_$]{0,127}") || !tablesToCheck.add(table)) {
throw invalid("目标表列表包含重复或非法名称,请重新选择");
}
}
List<String> tableList = List.copyOf(tablesToCheck);
BatchActor actor = actors.current();
var before = storage.resolve(actor.actorId(), actor.orgScopeId(), command.resourceId(), command.spaceId());
if (before.status() == StorageTableFileReferenceDirectory.Status.OUTSIDE_SCOPE) {
throw BatchIngestionException.forbidden();
}
if (before.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED ||
!Set.of("DORIS", "HIVE").contains(before.resourceType())) {
return unknownTargets(tablesToCheck, "目标资源或数据库当前不可用,请重新选择");
}
var profile = new DataCollectionIntegrationService.StorageExecutionProfile(command.resourceId(),
command.spaceId(), before.resourceType(), before.catalogName(), before.externalSpaceId(),
before.locationUri(), before.endpointHost(), before.endpointPort(), before.serviceAccount(),
before.secretRef(), before.tlsEnabled(), null);
List<String> objects = tableList.stream()
.map(table -> before.externalSpaceId() + "." + table).toList();
var response = targetExistence.check(new BatchTargetExistenceService.Request(actor.actorId(),
actor.orgScopeId(), profile, objects));
var after = storage.resolve(actor.actorId(), actor.orgScopeId(), command.resourceId(), command.spaceId());
if (!before.equals(after)) {
return unknownTargets(tablesToCheck, "目标配置已变化,请重新检查");
}
if (response.items().size() != objects.size()) {
return unknownTargets(tablesToCheck, "目标检查服务暂不可用,请稍后重试");
}
Map<String, BatchTargetExistenceService.Item> byObject = new HashMap<>();
for (var item : response.items()) {
if (item == null || item.targetObject() == null || item.state() == null ||
byObject.putIfAbsent(item.targetObject(), item) != null) {
return unknownTargets(tablesToCheck, "目标检查结果不完整,请重新检查");
}
}
List<TargetExistenceItem> items = new ArrayList<>();
for (int index = 0; index < objects.size(); index++) {
var observed = byObject.get(objects.get(index));
if (observed == null) return unknownTargets(tablesToCheck, "目标检查结果不完整,请重新检查");
items.add(new TargetExistenceItem(tableList.get(index),
TargetExistenceState.valueOf(observed.state().name()), safeExistenceReason(observed)));
}
return new TargetExistenceResult(List.copyOf(items));
}
private static TargetExistenceResult unknownTargets(Collection<String> tables, String reason) {
return new TargetExistenceResult(tables.stream()
.map(table -> new TargetExistenceItem(table, TargetExistenceState.UNKNOWN, reason)).toList());
}
private static String safeExistenceReason(BatchTargetExistenceService.Item item) {
if (SAFE_EXISTENCE_REASONS.contains(item.reason())) {
return item.reason();
}
return switch (item.state()) {
case EXISTS -> "目标表已存在";
case MISSING -> "目标表不存在";
case UNKNOWN -> "目标表状态暂不可确认,请重新检查";
};
}
public Draft draft(Context context) {
var schema = createSource(context);
List<Column> source = schema.columns();
// Also proves the selected database really exists, even when no tables have been registered.
directory(context.resourceId(), context.spaceId(), null, null, 1, 20);
List<Field> fields = source.stream().map(c -> {
var view = new SourceColumn(c.name(), c.type(), c.ordinal(), c.nullable(), c.masked(),
c.nativeType(), c.precision(), c.scale(), c.octetLength());
try { return new Field(view, BatchTargetTypePolicy.propose(c, TargetEngine.DORIS), null); }
catch (BatchIngestionException e) { return new Field(view, null, e.getMessage()); }
}).toList();
return new Draft(fingerprint(context, schema), fields, schema.tableComment().value(), schema.tableComment().state().name());
}
public Matched match(Match request) {
if (request == null) throw invalid("请选择来源和目标表");
List<Column> source = source(request.context());
List<Column> selected = selected(source, request.selectedColumns());
var target = directory(request.context().resourceId(), request.context().spaceId(),
request.name(), null, 1, 20);
return new Matched(matchColumns(selected, target, TargetEngine.DORIS));
}
public Created create(String key, Confirm request) {
if (request == null || request.context() == null || request.columns() == null || request.columns().isEmpty() ||
request.columns().size() > 100 || request.name() == null || !request.name().matches("[A-Za-z_][A-Za-z0-9_]{0,127}"))
throw invalid("请填写新表名称并选择字段");
Context context = request.context();
var schema = createSource(context);
List<Column> source = schema.columns();
if (!fingerprint(context, schema).equals(request.sourceFingerprint()))
throw BatchIngestionException.conflict("源结构已变化,请重新生成建表草案");
String physicalComment = UnifiedIngestionService.requireTableComment(schema.tableComment());
List<Column> selected = selected(source, request.columns().stream().map(ColumnDefinition::name).toList());
for (int i = 0; i < selected.size(); i++) {
BatchTargetTypePolicy.requireSourceComment(selected.get(i));
if (!Objects.equals(selected.get(i).sourceComment().value(), request.columns().get(i).comment()))
throw invalid("字段“" + selected.get(i).name() + "”的建表注释已偏离源结构,请重新生成建表草案");
BatchTargetTypePolicy.requireFits(BatchTargetTypePolicy.propose(selected.get(i), TargetEngine.DORIS), request.columns().get(i));
}
if (Set.of(ColumnType.FLOAT, ColumnType.DOUBLE, ColumnType.STRING).contains(request.columns().getFirst().type()))
throw invalid("首列不能作为Doris键,请将整数、日期或定长字段放在首列");
var target = validateContext(context);
if (target.catalogName() == null || target.catalogName().isBlank() ||
target.externalSpaceId() == null || target.externalSpaceId().isBlank())
throw invalid("目标数据库标识不完整,请重新选择");
var operation = tables.create(key, new CreateCommand(request.name(), ObjectType.TABLE,
null, context.resourceId(), context.spaceId(), EngineType.DORIS, StorageFormat.DORIS_NATIVE,
target.catalogName(), target.externalSpaceId(), null, "批量采集目标表", request.columns(), null, null, physicalComment));
if (operation.result().tableFile().executionState() != ExecutionState.CONFIRMED)
return new Created(operation, List.of());
// Never release READY solely on registration or the DDL return status.
var current = createSource(context);
if (!fingerprint(context, current).equals(request.sourceFingerprint()))
throw BatchIngestionException.conflict("建表后源结构发生变化;新表已保留,请重新读取结构");
var observedTarget = directory(context.resourceId(), context.spaceId(), request.name(), null, 1, 20);
return new Created(operation, matchColumns(selected, observedTarget, TargetEngine.DORIS));
}
List<Column> source(Context context) {
validateContext(context);
var actor = actors.current();
String[] object = context.sourceObject().split("\\.");
try {
var result = integration.sourceSchema(new DataCollectionIntegrationService.SourceSchemaRequest(actor.actorId(),
actor.orgScopeId(), context.sourceId(), object[0], String.join(".", java.util.Arrays.copyOfRange(object, 1, object.length))));
if (result == null || result.isEmpty() || result.size() > 100 || result.stream().anyMatch(Objects::isNull))
throw invalid("源结构不完整");
return result;
} catch (RuntimeException | LinkageError e) {
throw BatchIngestionException.external("源结构不可读取,请在数据源管理重新测试连接");
}
}
UnifiedIngestionSourceService.SchemaResult createSource(Context context) {
validateContext(context);
var actor = actors.current();
String[] object = context.sourceObject().split("\\.");
try {
var result = unifiedSources.schema(actor.actorId(), actor.orgScopeId(), context.sourceId(), object[0],
String.join(".", Arrays.copyOfRange(object, 1, object.length)));
if (result == null || !"AVAILABLE".equals(result.status()) || result.columns() == null ||
result.columns().isEmpty() || result.columns().size() > 100 || result.columns().stream().anyMatch(Objects::isNull))
throw invalid("源结构不完整");
return result;
} catch (RuntimeException | LinkageError e) {
throw BatchIngestionException.external("源结构不可读取,请在数据源管理重新测试连接");
}
}
private StorageTableFileReferenceDirectory.Resolution validateContext(Context context) {
if (context == null || context.sourceId() <= 0 || context.resourceId() <= 0 || context.spaceId() <= 0 ||
context.sourceObject() == null || !context.sourceObject().matches("[A-Za-z_][A-Za-z0-9_$]{0,127}(?:\\.[A-Za-z_][A-Za-z0-9_$]{0,127}){1,2}"))
throw invalid("请选择源表和目标数据库");
var actor = actors.current();
var resource = storage.resolve(actor.actorId(), actor.orgScopeId(), context.resourceId(), context.spaceId());
if (resource == null || resource.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED) throw BatchIngestionException.forbidden();
if (!"DORIS".equals(resource.resourceType())) throw invalid("请选择Doris数据库");
return resource;
}
/** Revalidate live source/target on save, READY and immediately before a new submission. */
public void validateConfig(BatchActor actor, BatchIngestionPolicy.TaskConfig config) {
validateConfig(actor, config, null);
}
void validateConfig(BatchActor actor, BatchIngestionPolicy.TaskConfig config,
VerifiedIngestionCommandActor verified) {
if (verified != null) verified.checkSubmit();
String[] sourceObject = config.sourceObject().split("\\.");
if (sourceObject.length != 2 && sourceObject.length != 3) throw invalid("请选择源数据库和表");
String[] object = config.targetObject().split("\\.");
if (object.length != 2) throw invalid("请选择目标数据库和表");
var ref = verified == null ? storage.resolveObject(actor.actorId(), actor.orgScopeId(), config.targetRefId(), object[0])
: storage.resolveObjectForIngestion(actor.actorId(), actor.orgScopeId(), config.targetRefId(), object[0]);
if (ref.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED || ref.spaceId() == null)
throw BatchIngestionException.forbidden();
if (!config.targetConnector().equals(ref.resourceType()))
throw invalid("目标类型与存储资源不一致");
String sourceTable = String.join(".", java.util.Arrays.copyOfRange(sourceObject, 1, sourceObject.length));
List<Column> source = verified == null ? null : verified.sourceSchema(config.sourceRefId(), sourceObject[0], sourceTable);
if (source == null) {
var sourceResult = unifiedSources.schema(actor.actorId(), actor.orgScopeId(), config.sourceRefId(), sourceObject[0], sourceTable);
if (sourceResult == null || !"AVAILABLE".equals(sourceResult.status()) || sourceResult.columns() == null ||
sourceResult.columns().isEmpty()) throw BatchIngestionException.external("源结构暂不可读取,请刷新后重试");
source = sourceResult.columns();
}
var target = verified == null ? tables.targetDirectory(config.targetRefId(), ref.spaceId(),
EngineType.valueOf(config.targetConnector()), object[1], null, 1, 20)
: tables.targetDirectory(verified, config.targetRefId(), ref.spaceId(),
EngineType.valueOf(config.targetConnector()), object[1], null, 1, 20);
TargetEngine engine = TargetEngine.valueOf(config.targetConnector());
Set<String> selected = new HashSet<>();
for (var mapping : config.mappings()) {
var input = source.stream().filter(c -> c.name().equals(mapping.sourceField())).findFirst()
.orElseThrow(() -> invalid("源字段“" + mapping.sourceField() + "”已不存在,请重新读取结构"));
var output = target.columns().stream().filter(c -> sameFieldName(c.name(), mapping.targetField())).findFirst()
.orElseThrow(() -> invalid("目标字段“" + mapping.targetField() + "”已不存在,请重新匹配"));
var mapped = BatchTargetTypePolicy.canonical(input, engine);
var actual = BatchTargetTypePolicy.observed(output, engine);
BatchTargetTypePolicy.requireFits(BatchTargetTypePolicy.propose(input, engine), actual);
if (!BatchTargetTypePolicy.declaredTypeMatches(mapped.targetType(), mapping.sourceType()) ||
!BatchTargetTypePolicy.declaredTypeMatches(mapped.targetType(), mapping.targetType()))
throw invalid("字段“" + input.name() + "” → “" + output.name() + "”的映射类型与真实结构不一致,当前应为 " + mapped.targetType() + ";请重新匹配字段");
if (!selected.add(output.name().toLowerCase(Locale.ROOT)))
throw invalid("目标字段“" + output.name() + "”被重复映射,请调整映射");
}
for (var column : target.columns())
if (!selected.contains(column.name().toLowerCase(Locale.ROOT)) && !Boolean.TRUE.equals(column.nullable()))
throw invalid("目标表存在未映射的必填字段“" + column.name() + "”,请补全映射");
}
static List<Column> selected(List<Column> source, List<String> names) {
if (names == null || names.isEmpty()) return source;
if (names.size() > 100 || new HashSet<>(names).size() != names.size()) throw invalid("所选字段重复或超出范围");
return names.stream().map(name -> source.stream().filter(c -> c.name().equals(name)).findFirst()
.orElseThrow(() -> invalid("源字段已变化,请重新读取结构"))).toList();
}
static List<BatchFieldMappingCommand> matchColumns(List<Column> source, DirectoryResult target) {
return matchColumns(source, target, TargetEngine.DORIS, true);
}
static List<BatchFieldMappingCommand> matchColumns(List<Column> source, DirectoryResult target,
TargetEngine engine) {
return matchColumns(source, target, engine, false);
}
private static List<BatchFieldMappingCommand> matchColumns(List<Column> source, DirectoryResult target,
TargetEngine engine, boolean legacyLabels) {
List<BatchFieldMappingCommand> result = new ArrayList<>();
Set<String> chosen = new HashSet<>();
for (var c : source) {
var mapped = BatchTargetTypePolicy.canonical(c, engine);
var expected = BatchTargetTypePolicy.propose(c, engine);
var found = target.columns().stream().filter(t -> sameFieldName(t.name(), c.name())).findFirst()
.orElseThrow(() -> invalid("目标表缺少字段“" + c.name() + "”,请调整映射或选择其他表"));
var actual = BatchTargetTypePolicy.observed(found, engine);
BatchTargetTypePolicy.requireFits(expected, actual);
chosen.add(found.name().toLowerCase(Locale.ROOT));
// New unified-ingestion mappings persist the canonical target declaration. The two labels stay equal
// because NONE is the verified carrier; native source metadata travels separately at execution time.
String targetType = legacyLabels ? BatchTargetTypePolicy.logicalType(actual) : mapped.targetType();
String sourceType = legacyLabels ? BatchTargetTypePolicy.sourceLogicalType(c, actual) : targetType;
result.add(new BatchFieldMappingCommand(c.name(), found.name(), sourceType, targetType,
BatchFieldTransform.NONE, null, null, List.of()));
}
for (var c : target.columns()) {
if (!chosen.contains(c.name().toLowerCase(Locale.ROOT)) && !Boolean.TRUE.equals(c.nullable()))
throw invalid("目标表还有必填字段“" + c.name() + "”,请选择完整映射或其他目标表");
}
return List.copyOf(result);
}
private static boolean sameFieldName(String left, String right) {
return left != null && right != null && left.equalsIgnoreCase(right);
}
static String fingerprint(Context context, List<Column> source) {
return BatchIngestionPolicy.sha256(context.toString() + "|" + source.toString());
}
static String fingerprint(Context context, UnifiedIngestionSourceService.SchemaResult source) {
return BatchIngestionPolicy.sha256(context + "|" + source.columns() + "|" + source.tableComment());
}
private static BatchIngestionException invalid(String message) { return BatchIngestionException.validation(message); }
}
@@ -0,0 +1,10 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.Instant;
@Component
class CollectionNodeTaskAuthority {
@DubboReference(check=false,timeout=5000,retries=0)private RemoteUserService users;
void require(BatchActor actor){String purpose="NODE_TASK_ASSIST_VIEW";try{var d=users.resolveAssetActor(actor.actorId(),actor.orgScopeId(),purpose);var now=Instant.now();if(d!=null&&d.allowed()&&d.userId()==actor.actorId()&&d.deptId()==actor.orgScopeId()&&purpose.equals(d.purpose())&&d.checkedAt()!=null&&!d.checkedAt().isBefore(now.minusSeconds(10))&&!d.checkedAt().isAfter(now.plusSeconds(5)))return;}catch(RuntimeException denied){}throw BatchIngestionException.forbidden();}
}
@@ -0,0 +1,8 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.CollectionNodeTaskDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=CollectionNodeTaskDirectory.VERSION)
public class CollectionNodeTaskDubboService implements CollectionNodeTaskDirectory {
private final CollectionNodeTaskOwner owner;public CollectionNodeTaskDubboService(CollectionNodeTaskOwner owner){this.owner=owner;}
public Requirement current(String taskId,long expectedVersion){return owner.current(taskId,expectedVersion);}
}
@@ -0,0 +1,17 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.CollectionNodeTaskDirectory.Requirement;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import tools.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@Service @RequiredArgsConstructor
class CollectionNodeTaskOwner {
private final BatchActorProvider actors;private final CollectionNodeTaskAuthority authority;private final BatchIngestionRepository repository;private final ObjectMapper json;
@Transactional(readOnly=true,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public Requirement current(String taskId,long expectedVersion){long id=id(taskId);if(expectedVersion<0)throw BatchIngestionException.conflict("任务版本无效");var actor=actors.current();authority.require(actor);var task=repository.find(actor,id);if(task.taskId()!=id||task.orgScopeId()!=actor.orgScopeId()||task.version()!=expectedVersion||task.currentSnapshotId()<=0)throw BatchIngestionException.conflict("任务版本或范围已变化");if(!Set.of("JDBC","MYSQL").contains(task.sourceConnector())||!Set.of("HIVE","DORIS").contains(task.targetConnector())||task.mode()==null||task.parallelism()<1)throw BatchIngestionException.conflict("任务需求未完整记录");String snapshot=repository.snapshotSha256(actor,id,task.currentSnapshotId());String hash=hash(List.of(task,snapshot));authority.require(actor);if(!actor.equals(actors.current())||!task.equals(repository.find(actor,id))||!snapshot.equals(repository.snapshotSha256(actor,id,task.currentSnapshotId())))throw BatchIngestionException.conflict("任务记录已变化,请重读");return new Requirement(actor.actorId(),actor.orgScopeId(),taskId,task.version(),Long.toString(task.currentSnapshotId()),task.sourceConnector(),task.targetConnector(),task.mode().name(),task.parallelism(),task.status().name(),hash);}
private String hash(Object value){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsString(value).getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException e){throw new IllegalStateException(e);}}
static long id(String value){try{long n=Long.parseLong(value);if(n>0&&Long.toString(n).equals(value))return n;}catch(RuntimeException ignored){}throw BatchIngestionException.conflict("任务标识无效");}
}
@@ -0,0 +1,91 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.engineering.EngineeringContextDirectory.*;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchTaskCreateCommand;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.EngineType;
import cn.aixunkeji.datagov.dataops.storage.StorageLakehouseReferenceDirectory;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileService;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.TargetEngine;
import cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.databind.ObjectMapper;
/** Read-only projection of original batch source, target and mapping policies. */
@Component @RequiredArgsConstructor
public class EngineeringBatchContextOwner {
private final UnifiedIngestionSourceGateway sources;
private final StorageLakehouseReferenceDirectory storage;
private final TableFileService tables;
private final BatchIngestionService batches;
private final BatchTargetWizardService wizard;
private final BatchActorProvider actors;
private final ObjectMapper json;
public record Snapshot(List<Fact> facts,List<Source> sources,Target target) { }
public Snapshot read(long user,long department,boolean unrestricted,Selection selection) {
var actor=actors.current();if(actor.actorId()!=user||actor.orgScopeId()!=department)throw BatchIngestionException.forbidden();
var chosen=selection.batch();long sourceId=Long.parseLong(chosen.sourceId()),resourceId=Long.parseLong(chosen.resourceId()),spaceId=Long.parseLong(chosen.spaceId());
var directory=sources.sources(user,department,List.of(sourceId),null,1);
if(directory==null||!"AVAILABLE".equals(directory.status())||directory.entries()==null||directory.entries().size()!=1)throw unavailable();
var source=directory.entries().getFirst();
if(source.id()==null||source.id()!=sourceId||source.version()<0||!source.previewEligible()||!Set.of("MYSQL","SQLSERVER").contains(source.type()))throw unavailable();
String[] sourceParts=chosen.sourceObject().split("\\.");
if(!sourceParts[0].equals(source.databaseName())||"MYSQL".equals(source.type())&&sourceParts.length!=2)throw unavailable();
var resolution=storage.resolve(user,department,unrestricted,resourceId,spaceId);
if(resolution==null||resolution.status()!=StorageLakehouseReferenceDirectory.Status.AUTHORIZED||resolution.mapping()==null||resolution.resourceType()==null||!Set.of("DORIS","HIVE").contains(resolution.resourceType().name()))throw unavailable();
var scope=resolution.mapping();String[] targetParts=chosen.targetObject().split("\\.");
if(scope.profileVersion()==null||scope.profileVersion()<0||scope.resourceVersion()<0||scope.spaceVersion()<0||!targetParts[0].equals(scope.namespaceName()))throw unavailable();
String engine=resolution.resourceType().name();
var schema=sources.schema(user,department,sourceId,sourceParts[0],String.join(".",Arrays.copyOfRange(sourceParts,1,sourceParts.length)));
if(schema==null||!"AVAILABLE".equals(schema.status())||schema.columns()==null||schema.columns().isEmpty()||schema.columns().size()>100)throw unavailable();
var sourceFields=new ArrayList<Field>();var proposed=new ArrayList<Field>();var seen=new HashSet<String>();
for(var column:schema.columns()) {
if(column==null||column.name()==null||!seen.add(column.name()))throw unavailable();
if(column.masked())continue;
sourceFields.add(new Field(column.name(),column.nativeType()==null?column.type():column.nativeType(),column.nullable(),column.precision(),column.scale()));
try {var definition=BatchTargetTypePolicy.propose(column,TargetEngine.valueOf(engine));var canonical=BatchTargetTypePolicy.canonical(column,TargetEngine.valueOf(engine));proposed.add(new Field(column.name(),canonical.targetType(),definition.nullable(),definition.precision(),definition.scale()));}
catch(BatchIngestionException unsupported) { /* Visible metadata does not imply a supported lossless carrier. */ }
}
if(sourceFields.isEmpty()||proposed.isEmpty())throw unavailable();
var destination=tables.targetDirectory(resourceId,spaceId,EngineType.valueOf(engine),targetParts[1],null,1,100);
if(destination==null||destination.state()!=TableFileIntegrationService.State.CONFIRMED||destination.columns()==null||destination.columns().isEmpty()||destination.columns().size()>100)throw unavailable();
var targetFields=new ArrayList<Field>();seen.clear();
for(var column:destination.columns()) {
var definition=BatchTargetTypePolicy.observed(column,TargetEngine.valueOf(engine));
if(!seen.add(definition.name().toLowerCase(Locale.ROOT)))throw unavailable();
targetFields.add(new Field(definition.name(),definition.type().name(),definition.nullable(),definition.precision(),definition.scale()));
}
var target=new Target(chosen.resourceId(),scope.resourceVersion(),scope.profileVersion(),chosen.spaceId(),scope.spaceVersion(),engine,scope.namespaceName());
var facts=new ArrayList<Fact>();
facts.add(new Fact("SOURCE_CONFIG","DATA_SOURCE",chosen.sourceId(),String.valueOf(source.version()),sha(Arrays.asList(source.id(),source.type(),source.version(),chosen.sourceObject())),"AUTHORIZED",source.type(),List.of()));
facts.add(new Fact("TARGET_TABLE","STORAGE_TABLE",chosen.resourceId(),String.valueOf(scope.resourceVersion()),sha(Arrays.asList(target,chosen.targetObject(),targetFields)),"CONFIRMED","OBSERVED_SCHEMA",List.copyOf(targetFields)));
if(selection.editedObject()!=null) {
var edited=selection.editedObject();var current=batches.find(Long.parseLong(edited.id()));
if(current==null||current.taskId()!=Long.parseLong(edited.id())||current.orgScopeId()!=department||current.version()!=edited.version())throw unavailable();
facts.add(new Fact("EDITED","BATCH_INGESTION",edited.id(),String.valueOf(current.version()),sha(current),current.status().name(),"DEFINITION_ONLY",List.of()));
}
var observed=new Source("S1",chosen.sourceId(),source.version(),source.name(),sourceParts[0],String.join(".",Arrays.copyOfRange(sourceParts,1,sourceParts.length)),sha(Arrays.asList(sourceId,source.version(),chosen.sourceObject(),sourceFields,proposed)),List.copyOf(sourceFields),List.copyOf(proposed));
return new Snapshot(List.copyOf(facts),List.of(observed),target);
}
public void validate(Selection selection,Map<String,Object> values,Context proof) {
Set<String> allowed=Set.of("name","sourceRefId","targetRefId","sourceConnector","targetConnector","sourceObject","targetObject","mode","incrementalField","partitionField","parallelism","checkpointEnabled","checkpointIntervalSeconds","mappings");
var chosen=selection.batch();
if(values==null||!allowed.containsAll(values.keySet())||!chosen.sourceId().equals(values.get("sourceRefId"))||!chosen.resourceId().equals(values.get("targetRefId"))||!chosen.sourceObject().equals(values.get("sourceObject"))||!chosen.targetObject().equals(values.get("targetObject")))throw unavailable();
if(proof==null||proof.sources().size()!=1||proof.target()==null||!proof.target().type().equals(values.get("targetConnector")))throw unavailable();
var sourceNames=proof.sources().getFirst().sourceFields().stream().map(Field::name).collect(java.util.stream.Collectors.toSet());
var targetNames=proof.facts().stream().filter(f->"TARGET_TABLE".equals(f.key())).flatMap(f->f.fields().stream()).map(Field::name).collect(java.util.stream.Collectors.toSet());
if(!(values.get("mappings") instanceof List<?> mappings)||mappings.isEmpty()||mappings.size()>100)throw unavailable();
Set<String> mappingKeys=Set.of("sourceField","targetField","sourceType","targetType","transform","defaultValue","filterOperator","filterValues");
for(var raw:mappings)if(!(raw instanceof Map<?,?> mapping)||!mappingKeys.containsAll(mapping.keySet())||!sourceNames.contains(mapping.get("sourceField"))||!targetNames.contains(mapping.get("targetField")))throw unavailable();
var command=json.convertValue(values,BatchTaskCreateCommand.class);
var normalized=BatchIngestionPolicy.normalize(command);
wizard.validateConfig(actors.current(),normalized);
}
private String sha(Object value){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsString(value).getBytes(StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException impossible){throw new IllegalStateException(impossible);}}
private static BatchIngestionException unavailable(){return BatchIngestionException.external("当前批量接入来源、目标或版本无法确认,请重新核对");}
}
@@ -0,0 +1,92 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.ByteMetricObservation;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.CollectionStatus;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.Metric;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.MetricSourceType;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.MetricStatus;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
final class IngestionCollectionPolicy {
private IngestionCollectionPolicy() { }
static CollectionStatus status(List<String> itemStatuses) {
if (itemStatuses == null || itemStatuses.isEmpty()) return CollectionStatus.UNKNOWN;
List<String> statuses = itemStatuses.stream().map(IngestionCollectionPolicy::normalizedStatus).toList();
if (statuses.stream().anyMatch("SUBMITTING"::equals))
return CollectionStatus.SUBMITTING;
if (statuses.stream().allMatch("SUCCEEDED"::equals)) return CollectionStatus.SUCCEEDED;
if (statuses.stream().allMatch("FAILED"::equals)) return CollectionStatus.FAILED;
if (statuses.stream().allMatch("CANCELED"::equals)) return CollectionStatus.CANCELED;
if (statuses.stream().allMatch("UNKNOWN"::equals)) return CollectionStatus.UNKNOWN;
if (statuses.stream().anyMatch(status ->
"FAILED".equals(status) || "CANCELED".equals(status) || "UNKNOWN".equals(status)))
return CollectionStatus.PARTIAL;
if (statuses.stream().anyMatch(status -> "RUNNING".equals(status) || "SUCCEEDED".equals(status)))
return CollectionStatus.RUNNING;
return CollectionStatus.SUBMITTED;
}
static Metric aggregate(List<Metric> metrics) {
if (metrics == null || metrics.isEmpty()) return notObserved();
List<Metric> safe = metrics.stream().filter(Objects::nonNull).toList();
if (safe.isEmpty() || safe.stream().allMatch(metric -> metric.status() == MetricStatus.NOT_OBSERVED))
return notObserved();
List<Metric> observed = safe.stream()
.filter(metric -> metric.status() == MetricStatus.OBSERVED && metric.value() != null).toList();
if (observed.size() != safe.size()) {
return new Metric(null, observed.isEmpty() ? MetricStatus.UNKNOWN : MetricStatus.PARTIAL,
null, null, latestObservedAt(safe));
}
try {
long total = 0;
for (Metric metric : observed) total = Math.addExact(total, metric.value());
MetricSourceType sourceType = observed.stream().map(Metric::sourceType).distinct().count() == 1
? observed.getFirst().sourceType() : null;
String source = observed.stream().map(Metric::source).distinct().count() == 1
? observed.getFirst().source() : null;
return new Metric(total, MetricStatus.OBSERVED, sourceType, source, latestObservedAt(observed));
} catch (ArithmeticException exception) {
return new Metric(null, MetricStatus.UNKNOWN, null, null, latestObservedAt(observed));
}
}
static void validateByteObservation(ByteMetricObservation observation) {
if (observation == null || observation.status() == null ||
(observation.status() != MetricStatus.OBSERVED && observation.status() != MetricStatus.UNKNOWN) ||
observation.sourceType() == null ||
(observation.sourceType() != MetricSourceType.INTEGRATION &&
observation.sourceType() != MetricSourceType.EXTERNAL_ENGINE) ||
observation.source() == null || observation.source().isBlank() || observation.source().length() > 128 ||
observation.source().chars().anyMatch(Character::isISOControl) || observation.observedAt() == null) {
throw BatchIngestionException.validation("数据字节指标缺少可信来源、状态或观测时间");
}
if (observation.status() == MetricStatus.OBSERVED &&
(observation.value() == null || observation.value() < 0)) {
throw BatchIngestionException.validation("已观测的数据字节指标必须提供非负真实值");
}
if (observation.status() == MetricStatus.UNKNOWN && observation.value() != null) {
throw BatchIngestionException.validation("未知的数据字节指标不得携带数值");
}
}
static Metric notObserved() {
return new Metric(null, MetricStatus.NOT_OBSERVED, null, null, null);
}
private static String normalizedStatus(String status) {
if (status == null) return "UNKNOWN";
return switch (status) {
case "PENDING", "SUBMITTING", "READY", "DRAFT", "SUBMITTED", "RUNNING", "SUCCEEDED",
"FAILED", "CANCELED", "UNKNOWN" -> status;
default -> "UNKNOWN";
};
}
private static LocalDateTime latestObservedAt(List<Metric> metrics) {
return metrics.stream().map(Metric::observedAt).filter(Objects::nonNull)
.max(LocalDateTime::compareTo).orElse(null);
}
}
@@ -0,0 +1,550 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.*;
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceType;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
@Repository
@RequiredArgsConstructor
public class IngestionCollectionRepository {
// Payload version 1 uses a fixed typed codec, independent of HTTP long/string rendering settings.
private static final tools.jackson.databind.json.JsonMapper COMMAND_JSON =
tools.jackson.databind.json.JsonMapper.builder().findAndAddModules().build();
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
// Isolated strict decoder: historical worker serialization and hashes remain unchanged.
private static final tools.jackson.databind.json.JsonMapper COPY_JSON =
tools.jackson.databind.json.JsonMapper.builder(tools.jackson.core.json.JsonFactory.builder()
.enable(tools.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION).build())
.findAndAddModules()
.enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES)
.enable(tools.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS).build();
static BatchIngestionException unavailableCopy() {
return BatchIngestionException.conflict("该记录的原配置不完整,暂不能复制");
}
CollectionConfigurationCopy configurationCopy(BatchActor actor, long collectionId) {
return transactionTemplate.execute(status -> {
var payloads = jdbcTemplate.query("""
SELECT request_payload, payload_version, payload_sha256, request_sha256, item_count
FROM ing_ingestion_collection
WHERE collection_id=? AND org_scope_id=? AND actor_id=? AND del_flag='0'
""", (rs, n) -> new CopyPayload(rs.getString("request_payload"), rs.getInt("payload_version"),
rs.getString("payload_sha256"), rs.getString("request_sha256"), rs.getInt("item_count")),
collectionId, actor.orgScopeId(), actor.actorId());
if (payloads.size() != 1) throw BatchIngestionException.notFound();
CopyPayload stored = payloads.getFirst();
SubmitRequest request;
try {
if (stored.version() != 1 || stored.payload() == null ||
stored.payload().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1_048_576)
throw unavailableCopy();
request = COPY_JSON.readValue(stored.payload(), SubmitRequest.class);
if (request == null || request.items() == null || request.items().isEmpty() || request.items().size() > 50 ||
stored.count() != request.items().size() ||
!BatchIngestionPolicy.sha256(COMMAND_JSON.writeValueAsString(request)).equals(stored.payloadHash()) ||
!BatchIngestionPolicy.sha256("COLLECTION_SUBMIT\n" + request).equals(stored.requestHash()))
throw unavailableCopy();
} catch (RuntimeException exception) {
// Never expose parser messages, raw JSON or invalid values.
throw unavailableCopy();
}
var rows = jdbcTemplate.query("""
SELECT collection_item_id, item_order, source_id, source_database, source_table
FROM ing_ingestion_collection_item
WHERE collection_id=? AND org_scope_id=? AND create_by=? AND del_flag='0' ORDER BY item_order
""", (rs, n) -> new CopyItem(rs.getLong("collection_item_id"), rs.getInt("item_order"),
rs.getLong("source_id"), rs.getString("source_database"), rs.getString("source_table")),
collectionId, actor.orgScopeId(), actor.actorId());
if (rows.size() != request.items().size()) throw unavailableCopy();
var ids = new java.util.HashSet<Long>();
for (int index = 0; index < rows.size(); index++) {
var row = rows.get(index);
var item = request.items().get(index);
if (item == null || row.id() <= 0 || !ids.add(row.id()) || row.order() != index + 1 ||
row.sourceId() != item.sourceId() || !Objects.equals(row.database(), item.sourceDatabase()) ||
!Objects.equals(row.table(), item.sourceTable())) throw unavailableCopy();
}
return new CollectionConfigurationCopy(collectionId,
rows.stream().map(row -> new ConfigurationCopyItem(row.id(), row.order())).toList(), request);
});
}
private record CopyPayload(String payload, int version, String payloadHash, String requestHash, int count) { }
private record CopyItem(long id, int order, long sourceId, String database, String table) { }
public Long replayedCollectionId(BatchActor actor, String idempotencyKey, String requestHash) {
CollectionRow existing = findByKey(actor, idempotencyKey);
return existing == null ? null : replay(existing, requestHash).collectionId();
}
public Reservation reserve(BatchActor actor, String idempotencyKey, String requestHash, SubmitRequest request) {
String payload = COMMAND_JSON.writeValueAsString(request);
if (payload == null || payload.length() > 1_048_576)
throw BatchIngestionException.validation("采集配置超过可受理大小");
try {
return Objects.requireNonNull(transactionTemplate.execute(status -> {
CollectionRow existing = findByKey(actor, idempotencyKey);
if (existing != null) return replay(existing, requestHash);
cn.aixunkeji.datagov.dataops.storage.StorageReferenceGuard.reference(jdbcTemplate, request.targetResourceId(), request.targetSpaceId(), actor.orgScopeId(), false, "COLLECTION");
long collectionId = IdGeneratorUtil.nextLongId();
jdbcTemplate.update("""
INSERT INTO ing_ingestion_collection(
collection_id, collection_name, org_scope_id, actor_id, idempotency_key,
request_sha256, request_payload, payload_version, payload_sha256,
collection_status, item_count, accepted_count, failed_count,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, 'SUBMITTING', ?, 0, 0, ?, ?, ?)
""", collectionId, request.name().trim(), actor.orgScopeId(), actor.actorId(),
idempotencyKey, requestHash, payload, BatchIngestionPolicy.sha256(payload), request.items().size(), actor.orgScopeId(), actor.actorId(),
actor.actorId());
for (int index = 0; index < request.items().size(); index++) {
SubmitItem item = request.items().get(index);
jdbcTemplate.update("""
INSERT INTO ing_ingestion_collection_item(
collection_item_id, collection_id, item_order, org_scope_id,
source_id, source_version, source_name, source_database, source_table,
target_resource_id, target_resource_version, target_space_id, target_space_version,
target_type, target_layer, target_table, item_status, processing_phase, next_attempt_at,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SUBMITTING', 'PENDING', NOW(6), ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), collectionId, index + 1, actor.orgScopeId(),
item.sourceId(), item.sourceVersion(), item.sourceName().trim(), item.sourceDatabase(),
item.sourceTable(), request.targetResourceId(), request.targetResourceVersion(),
request.targetSpaceId(), request.targetSpaceVersion(), request.targetType().name(),
request.layer().name(), item.targetTable(), actor.orgScopeId(), actor.actorId(), actor.actorId());
}
return new Reservation(collectionId, true);
}));
} catch (DuplicateKeyException exception) {
CollectionRow existing = findByKey(actor, idempotencyKey);
if (existing != null) return replay(existing, requestHash);
throw BatchIngestionException.conflict("采集集合幂等请求冲突,请刷新后重试");
}
}
record Command(long itemId, long collectionId, long actorId, long orgId, int itemOrder,
String key, String requestHash, String payload, String payloadHash, String phase,
long version, String token, String context, String contextHash,
Long taskId, Long runId, String ddlId) {
SubmitRequest request() {
SubmitRequest value = COMMAND_JSON.readValue(payload, SubmitRequest.class);
if (value == null || !BatchIngestionPolicy.sha256(COMMAND_JSON.writeValueAsString(value)).equals(payloadHash) ||
!BatchIngestionPolicy.sha256("COLLECTION_SUBMIT\n" + value).equals(requestHash) ||
value.items() == null || itemOrder < 1 || itemOrder > value.items().size())
throw BatchIngestionException.conflict("原采集请求校验失败");
return value;
}
SubmitItem item() { return request().items().get(itemOrder - 1); }
UnifiedIngestionService.CommandContext validated() {
var value = COMMAND_JSON.readValue(context, UnifiedIngestionService.CommandContext.class);
if (value == null || !BatchIngestionPolicy.sha256(COMMAND_JSON.writeValueAsString(value)).equals(contextHash))
throw BatchIngestionException.conflict("原采集校验上下文不可验证");
return value;
}
}
/** One bounded claim, never a transaction around network work. Legacy rows cannot enter the queue. */
Command claim(boolean observing) {
return transactionTemplate.execute(status -> {
String phases = observing ? "'TARGET_DISPATCHING','OBSERVING'"
: "'PENDING','VALIDATED','TARGET_RESERVED','TARGET_CONFIRMED','TASK_BOUND','READY','RUN_BOUND'";
var rows = jdbcTemplate.query("""
SELECT i.collection_item_id FROM ing_ingestion_collection_item i
JOIN ing_ingestion_collection c ON c.collection_id=i.collection_id AND c.org_scope_id=i.org_scope_id
AND c.actor_id=i.create_by AND c.del_flag='0'
WHERE i.del_flag='0' AND c.payload_version=1 AND c.request_payload IS NOT NULL
AND c.payload_sha256 IS NOT NULL AND i.processing_phase IN (
""" + phases + """
) AND (i.next_attempt_at IS NULL OR i.next_attempt_at<=NOW(6))
AND (i.claim_until IS NULL OR i.claim_until<=NOW(6))
ORDER BY i.next_attempt_at, i.collection_item_id LIMIT 1 FOR UPDATE SKIP LOCKED
""", (rs, n) -> rs.getLong(1));
if (rows.isEmpty()) return null;
long id = rows.getFirst();
String token = java.util.UUID.randomUUID().toString();
jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET claim_token=?, claim_until=TIMESTAMPADD(SECOND,120,NOW(6)),
version=version+1 WHERE collection_item_id=?
""", token, id);
return jdbcTemplate.queryForObject("""
SELECT i.*, c.actor_id, c.idempotency_key, c.request_sha256, c.request_payload, c.payload_sha256
FROM ing_ingestion_collection_item i JOIN ing_ingestion_collection c ON c.collection_id=i.collection_id
WHERE i.collection_item_id=? AND i.claim_token=?
""", (rs, n) -> new Command(id, rs.getLong("collection_id"), rs.getLong("actor_id"),
rs.getLong("org_scope_id"), rs.getInt("item_order"), rs.getString("idempotency_key"),
rs.getString("request_sha256"), rs.getString("request_payload"), rs.getString("payload_sha256"),
rs.getString("processing_phase"), rs.getLong("version"), token,
rs.getString("validated_context_json"), rs.getString("validated_context_sha256"),
rs.getObject("task_id", Long.class), rs.getObject("run_id", Long.class), rs.getString("target_create_request_id")), id, token);
});
}
void advance(Command command, String phase, UnifiedIngestionService.CommandContext context,
Long taskId, Long runId, String ddlId) {
String json = context == null ? null : COMMAND_JSON.writeValueAsString(context);
int changed = jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET processing_phase=?,
validated_context_json=COALESCE(?,validated_context_json),
validated_context_sha256=COALESCE(?,validated_context_sha256),
task_id=COALESCE(task_id,?), run_id=COALESCE(run_id,?),
target_create_request_id=COALESCE(target_create_request_id,?),
target_create_state=CASE WHEN ?='TARGET_CONFIRMED' AND target_create_request_id IS NOT NULL THEN 'CONFIRMED'
WHEN ?='TARGET_RESERVED' THEN 'UNKNOWN' ELSE target_create_state END,
target_database=COALESCE(?,target_database), layer_id=COALESCE(?,layer_id), layer_name=COALESCE(?,layer_name),
command_error_code=NULL, command_error_summary=NULL, claim_token=NULL, claim_until=NULL,
next_attempt_at=CASE WHEN ? IN ('TARGET_DISPATCHING','OBSERVING') THEN TIMESTAMPADD(SECOND,5,NOW(6))
ELSE NOW(6) END, version=version+1, update_time=NOW(6)
WHERE collection_item_id=? AND org_scope_id=? AND create_by=? AND version=?
AND processing_phase=? AND claim_token=? AND claim_until>NOW(6) AND del_flag='0'
AND (task_id IS NULL OR ? IS NULL OR task_id=?)
AND (run_id IS NULL OR ? IS NULL OR run_id=?)
AND (target_create_request_id IS NULL OR ? IS NULL OR target_create_request_id=?)
""", phase, json, json == null ? null : BatchIngestionPolicy.sha256(json), taskId, runId, ddlId, phase, phase,
context == null ? null : context.database(), context == null || context.layer() == null ? null : context.layer().layerId(),
context == null || context.layer() == null ? null : context.layer().layerName(), phase,
command.itemId(), command.orgId(), command.actorId(), command.version(), command.phase(), command.token(),
taskId, taskId, runId, runId, ddlId, ddlId);
if (changed != 1) throw BatchIngestionException.conflict("采集命令已变化或租约已过期");
}
void block(Command command, boolean observing) {
block(command, observing, "INGESTION_COMMAND_BLOCKED", "原采集命令暂不可继续,请核验当前权限、配置及执行记录");
}
void deferDirectoryRead(Command command) {
jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET claim_token=NULL, claim_until=NULL,
next_attempt_at=TIMESTAMPADD(SECOND,10,NOW(6)), version=version+1, update_time=NOW(6)
WHERE collection_item_id=? AND org_scope_id=? AND create_by=? AND version=? AND claim_token=?
AND claim_until>NOW(6) AND processing_phase=? AND del_flag='0'
""", command.itemId(), command.orgId(), command.actorId(), command.version(), command.token(), command.phase());
}
void block(Command command, boolean observing, String errorCode, String errorSummary) {
// A command blocker is separate from immutable run/DDL evidence; never marks an external job failed.
jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET processing_phase=?, command_error_code=?,
command_error_summary=?,
item_status=CASE WHEN task_id IS NULL AND run_id IS NULL AND target_create_request_id IS NULL
AND ? IN ('PENDING','VALIDATED') THEN 'FAILED'
WHEN run_id IS NULL THEN 'UNKNOWN' ELSE item_status END,
error_code=CASE WHEN run_id IS NULL THEN ? ELSE error_code END,
error_summary=CASE WHEN run_id IS NULL THEN ? ELSE error_summary END,
claim_token=NULL, claim_until=NULL, next_attempt_at=TIMESTAMPADD(SECOND,60,NOW(6)),
version=version+1, update_time=NOW(6)
WHERE collection_item_id=? AND org_scope_id=? AND create_by=? AND version=? AND claim_token=?
AND claim_until>NOW(6) AND del_flag='0'
""", observing ? command.phase() : "BLOCKED", errorCode, errorSummary, command.phase(), errorCode, errorSummary,
command.itemId(), command.orgId(), command.actorId(),
command.version(), command.token());
}
void rejectDdl(Command command, String code, String summary) {
int changed = jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET processing_phase='BLOCKED', item_status='FAILED',
target_create_state='REJECTED', retryable=0, error_code=?, error_summary=?,
claim_token=NULL, claim_until=NULL, version=version+1, update_time=NOW(6)
WHERE collection_item_id=? AND org_scope_id=? AND create_by=? AND version=? AND claim_token=?
AND claim_until>NOW(6) AND processing_phase='TARGET_DISPATCHING' AND run_id IS NULL AND del_flag='0'
""", BatchIngestionPolicy.safeErrorCode(code, "TARGET_CREATE_REJECTED"), BatchIngestionPolicy.safeSummary(summary),
command.itemId(), command.orgId(), command.actorId(), command.version(), command.token());
if (changed != 1) throw BatchIngestionException.conflict("采集命令已变化或租约已过期");
}
void requestObservation(BatchActor actor, long collectionId) {
requireCollection(actor, collectionId);
// A blocked pre-dispatch command has no external execution to reconcile. Never replay it.
// DDL reservation and task/run identities are durable fences: any such evidence stays UNKNOWN.
jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item SET item_status='FAILED', retryable=0,
version=version+1, update_time=NOW(6)
WHERE collection_id=? AND org_scope_id=? AND create_by=? AND del_flag='0'
AND processing_phase='BLOCKED' AND item_status='UNKNOWN'
AND task_id IS NULL AND run_id IS NULL AND target_create_request_id IS NULL
AND external_job_id IS NULL AND target_create_state IS NULL
""", collectionId, actor.orgScopeId(), actor.actorId());
jdbcTemplate.update("""
UPDATE ing_ingestion_collection_item i
JOIN ing_batch_task t ON t.task_id=i.task_id AND t.org_scope_id=i.org_scope_id AND t.del_flag='0'
AND t.task_status='SUCCEEDED'
JOIN ops_job_run r ON r.run_id=i.run_id AND r.definition_id=t.definition_id
AND r.create_dept=i.org_scope_id AND r.actor_id=i.create_by
AND r.run_status='SUCCEEDED' AND r.del_flag='0'
AND EXISTS (SELECT 1 FROM dev_job_snapshot s
WHERE s.snapshot_id=r.snapshot_id AND s.definition_id=r.definition_id
AND s.create_dept=i.org_scope_id AND s.del_flag='0')
SET i.item_status='SUCCEEDED',
i.processing_phase=CASE WHEN i.processing_phase='DONE' THEN 'OBSERVING' ELSE i.processing_phase END,
i.observe_requested_at=NOW(6), i.next_attempt_at=NOW(6), i.claim_token=NULL, i.claim_until=NULL,
i.version=i.version+1, i.update_time=NOW(6)
WHERE i.collection_id=? AND i.org_scope_id=? AND i.create_by=?
AND i.run_id IS NOT NULL AND i.task_id IS NOT NULL
AND i.processing_phase IN ('OBSERVING','TARGET_DISPATCHING','DONE')
AND i.del_flag='0'
AND EXISTS (SELECT 1 FROM ing_batch_submission_journal j
WHERE j.run_id=i.run_id AND j.task_id=i.task_id AND j.org_scope_id=i.org_scope_id
AND j.submission_phase='VERIFIED' AND j.del_flag='0')
""", collectionId, actor.orgScopeId(), actor.actorId());
}
public CollectionPage page(BatchActor actor, String keyword, CollectionStatus status, int pageNum, int pageSize) {
String normalized = keyword == null || keyword.isBlank() ? null : keyword.trim();
String statusValue = status == null ? null : status.name();
String cte = collectionStatusCte();
Long total = jdbcTemplate.queryForObject(cte + """
SELECT COUNT(*) FROM collection_statuses WHERE (? IS NULL OR effective_status=?)
""", Long.class, actor.orgScopeId(), normalized, normalized, statusValue, statusValue);
List<Long> ids = jdbcTemplate.query(cte + """
SELECT collection_id FROM collection_statuses
WHERE (? IS NULL OR effective_status=?)
ORDER BY create_time DESC, collection_id DESC LIMIT ? OFFSET ?
""", (rs, rowNum) -> rs.getLong(1), actor.orgScopeId(), normalized, normalized,
statusValue, statusValue, pageSize, (pageNum - 1) * pageSize);
List<CollectionSummary> rows = ids.stream().map(id -> summary(detail(actor, id))).toList();
return new CollectionPage(rows, total == null ? 0 : total);
}
public CollectionDetail detail(BatchActor actor, long collectionId) {
CollectionRow collection = requireCollection(actor, collectionId);
List<CollectionItem> items = jdbcTemplate.query(itemSelect() + """
WHERE i.collection_id=? AND i.org_scope_id=? AND i.del_flag='0'
ORDER BY i.item_order
""", this::mapItem, collectionId, actor.orgScopeId());
if (items.size() != collection.itemCount())
throw BatchIngestionException.conflict("采集集合子项数量不一致,请联系管理员核验");
int accepted = (int) items.stream().filter(item -> item.taskId() != null).count();
int failed = (int) items.stream().filter(item -> "FAILED".equals(item.status())).count();
CollectionStatus status = IngestionCollectionPolicy.status(items.stream().map(CollectionItem::status).toList());
Metric rows = IngestionCollectionPolicy.aggregate(items.stream().map(CollectionItem::rows).toList());
Metric bytes = IngestionCollectionPolicy.aggregate(items.stream().map(CollectionItem::bytes).toList());
return new CollectionDetail(collection.collectionId(), collection.name(), status, List.copyOf(items),
accepted, failed, rows, bytes, collection.createdAt(), collection.updatedAt());
}
public void recordBytes(BatchActor actor, long itemId, long runId, ByteMetricObservation observation) {
IngestionCollectionPolicy.validateByteObservation(observation);
Objects.requireNonNull(transactionTemplate.execute(status -> {
List<Long> authorized = jdbcTemplate.query("""
SELECT i.collection_item_id
FROM ing_ingestion_collection_item i
JOIN ing_batch_task t ON t.task_id=i.task_id AND t.org_scope_id=i.org_scope_id AND t.del_flag='0'
JOIN ops_job_run r ON r.run_id=? AND r.definition_id=t.definition_id AND r.del_flag='0'
WHERE i.collection_item_id=? AND i.org_scope_id=? AND i.del_flag='0'
FOR UPDATE
""", (rs, rowNum) -> rs.getLong(1), runId, itemId, actor.orgScopeId());
if (authorized.size() != 1) throw BatchIngestionException.notFound();
Long existing = jdbcTemplate.queryForObject("""
SELECT COUNT(*) FROM ing_ingestion_collection_metric
WHERE collection_item_id=? AND run_id=? AND org_scope_id=? AND metric_type='DATA_BYTES'
AND metric_value <=> ? AND metric_status=? AND evidence_source_type=?
AND evidence_source=? AND observed_at=? AND evidence_ref <=> ? AND del_flag='0'
""", Long.class, itemId, runId, actor.orgScopeId(), observation.value(),
observation.status().name(), observation.sourceType().name(), observation.source().trim(),
Timestamp.valueOf(observation.observedAt()), safeEvidenceRef(observation.evidenceRef()));
if (existing != null && existing > 0) return Boolean.TRUE;
jdbcTemplate.update("""
INSERT INTO ing_ingestion_collection_metric(
metric_id, collection_item_id, run_id, org_scope_id, metric_type, metric_value,
metric_status, evidence_source_type, evidence_source, observed_at, evidence_ref,
error_code, error_summary, create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, 'DATA_BYTES', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), itemId, runId, actor.orgScopeId(), observation.value(),
observation.status().name(), observation.sourceType().name(), observation.source().trim(),
Timestamp.valueOf(observation.observedAt()), safeEvidenceRef(observation.evidenceRef()),
BatchIngestionPolicy.safeErrorCode(observation.errorCode(), null),
BatchIngestionPolicy.safeSummary(observation.errorSummary()), actor.orgScopeId(),
actor.actorId(), actor.actorId());
return Boolean.TRUE;
}));
}
private CollectionRow findByKey(BatchActor actor, String idempotencyKey) {
List<CollectionRow> rows = jdbcTemplate.query(collectionSelect() + """
WHERE actor_id=? AND org_scope_id=? AND idempotency_key=? AND del_flag='0'
""", this::mapCollection, actor.actorId(), actor.orgScopeId(), idempotencyKey);
if (rows.size() > 1) throw BatchIngestionException.conflict("采集集合幂等记录不唯一");
return rows.isEmpty() ? null : rows.getFirst();
}
private CollectionRow requireCollection(BatchActor actor, long collectionId) {
List<CollectionRow> rows = jdbcTemplate.query(collectionSelect() + """
WHERE collection_id=? AND org_scope_id=? AND del_flag='0'
""", this::mapCollection, collectionId, actor.orgScopeId());
if (rows.isEmpty()) throw BatchIngestionException.notFound();
if (rows.size() > 1) throw BatchIngestionException.conflict("采集集合记录不唯一");
return rows.getFirst();
}
private static Reservation replay(CollectionRow existing, String requestHash) {
if (!Objects.equals(existing.requestHash(), requestHash))
throw BatchIngestionException.conflict("同一幂等键对应的采集集合载荷不同");
return new Reservation(existing.collectionId(), false);
}
private static CollectionSummary summary(CollectionDetail detail) {
return new CollectionSummary(detail.collectionId(), detail.name(), detail.status(), detail.items().size(),
detail.accepted(), detail.failed(), detail.rows(), detail.bytes(), detail.submittedAt(), detail.updatedAt());
}
private static String collectionSelect() {
return """
SELECT collection_id, collection_name, request_sha256, item_count, create_time, update_time
FROM ing_ingestion_collection
""";
}
private static String collectionStatusCte() {
return """
WITH collection_statuses AS (
SELECT c.collection_id, c.create_time,
CASE
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status)='SUBMITTING' THEN 1 ELSE 0 END) > 0
THEN 'SUBMITTING'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status)='SUCCEEDED' THEN 1 ELSE 0 END)=COUNT(*)
THEN 'SUCCEEDED'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status)='FAILED' THEN 1 ELSE 0 END)=COUNT(*)
THEN 'FAILED'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status)='CANCELED' THEN 1 ELSE 0 END)=COUNT(*)
THEN 'CANCELED'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status)='UNKNOWN' THEN 1 ELSE 0 END)=COUNT(*)
THEN 'UNKNOWN'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status) IN ('FAILED','CANCELED','UNKNOWN') THEN 1 ELSE 0 END) > 0
THEN 'PARTIAL'
WHEN SUM(CASE WHEN COALESCE(r.run_status, i.item_status) IN ('RUNNING','SUCCEEDED') THEN 1 ELSE 0 END) > 0
THEN 'RUNNING'
ELSE 'SUBMITTED'
END AS effective_status
FROM ing_ingestion_collection c
JOIN ing_ingestion_collection_item i ON i.collection_id=c.collection_id
AND i.org_scope_id=c.org_scope_id AND i.del_flag='0'
LEFT JOIN ing_batch_task t ON t.task_id=i.task_id
AND t.org_scope_id=i.org_scope_id AND t.del_flag='0'
LEFT JOIN ops_job_run r ON r.run_id=i.run_id
AND r.definition_id=t.definition_id AND r.create_dept=i.org_scope_id
AND r.actor_id=i.create_by AND r.del_flag='0'
AND EXISTS(SELECT 1 FROM dev_job_snapshot s
WHERE s.snapshot_id=r.snapshot_id AND s.definition_id=r.definition_id
AND s.create_dept=i.org_scope_id AND s.del_flag='0')
WHERE c.org_scope_id=? AND c.del_flag='0'
AND (? IS NULL OR c.collection_name LIKE CONCAT('%', ?, '%'))
GROUP BY c.collection_id, c.create_time
)
""";
}
private static String itemSelect() {
return """
SELECT i.collection_item_id, i.item_order, i.source_id, i.source_version, i.source_name,
i.source_database, i.source_table, i.target_resource_id, i.target_space_id,
i.target_type, i.target_layer, i.target_database, i.target_table, i.layer_id,
i.layer_name, i.target_create_request_id, i.target_create_state,
COALESCE(r.run_status, i.item_status) AS effective_status,
i.task_id, r.run_id AS effective_run_id,
COALESCE(r.seatunnel_job_id, i.external_job_id) AS effective_external_job_id,
CASE WHEN i.retryable=1 OR EXISTS(
SELECT 1 FROM ing_batch_request q
WHERE q.response_type='RUN' AND q.response_ref_id=r.run_id
AND q.run_id=r.run_id AND q.task_id=t.task_id
AND q.actor_id=r.actor_id AND q.create_dept=i.org_scope_id
AND q.retryable=1 AND q.del_flag='0'
) THEN 1 ELSE 0 END AS effective_retryable,
CASE WHEN r.run_status='SUCCEEDED' THEN NULL ELSE COALESCE(r.error_code, i.error_code) END AS effective_error_code,
CASE WHEN r.run_status='SUCCEEDED' THEN NULL ELSE COALESCE(r.error_summary, i.error_summary) END AS effective_error_summary,
v.validation_status, v.target_count, v.evidence_at AS arrival_observed_at,
m.metric_value AS byte_value, m.metric_status AS byte_status,
m.evidence_source_type AS byte_source_type, m.evidence_source AS byte_source,
m.observed_at AS byte_observed_at
FROM ing_ingestion_collection_item i
LEFT JOIN ing_batch_task t ON t.task_id=i.task_id AND t.org_scope_id=i.org_scope_id AND t.del_flag='0'
LEFT JOIN ops_job_run r ON r.run_id=i.run_id
AND r.definition_id=t.definition_id AND r.create_dept=i.org_scope_id
AND r.actor_id=i.create_by AND r.del_flag='0'
AND EXISTS(SELECT 1 FROM dev_job_snapshot s
WHERE s.snapshot_id=r.snapshot_id AND s.definition_id=r.definition_id
AND s.create_dept=i.org_scope_id AND s.del_flag='0')
LEFT JOIN ops_batch_arrival_validation v ON v.validation_id=(
SELECT vv.validation_id FROM ops_batch_arrival_validation vv
WHERE vv.run_id=r.run_id AND vv.task_id=t.task_id
AND vv.create_dept=i.org_scope_id AND vv.del_flag='0'
ORDER BY vv.create_time DESC, vv.validation_id DESC LIMIT 1
)
LEFT JOIN ing_ingestion_collection_metric m ON m.metric_id=(
SELECT mm.metric_id FROM ing_ingestion_collection_metric mm
WHERE mm.collection_item_id=i.collection_item_id
AND mm.run_id=r.run_id AND mm.org_scope_id=i.org_scope_id
AND mm.metric_type='DATA_BYTES' AND mm.del_flag='0'
ORDER BY mm.observed_at DESC, mm.metric_id DESC LIMIT 1
)
""";
}
private CollectionRow mapCollection(ResultSet rs, int rowNum) throws SQLException {
return new CollectionRow(rs.getLong("collection_id"), rs.getString("collection_name"),
rs.getString("request_sha256"), rs.getInt("item_count"),
localDateTime(rs, "create_time"), localDateTime(rs, "update_time"));
}
private CollectionItem mapItem(ResultSet rs, int rowNum) throws SQLException {
Long targetCount = nullableLong(rs, "target_count");
LocalDateTime arrivalObservedAt = localDateTime(rs, "arrival_observed_at");
Metric rows = targetCount != null && arrivalObservedAt != null
? new Metric(targetCount, MetricStatus.OBSERVED,
MetricSourceType.ARRIVAL_VALIDATION, "ops_batch_arrival_validation",
arrivalObservedAt)
: rs.getString("validation_status") == null ? IngestionCollectionPolicy.notObserved()
: new Metric(null, MetricStatus.UNKNOWN, MetricSourceType.ARRIVAL_VALIDATION,
"ops_batch_arrival_validation", arrivalObservedAt);
Metric bytes = rs.getString("byte_status") == null ? IngestionCollectionPolicy.notObserved()
: new Metric(nullableLong(rs, "byte_value"), MetricStatus.valueOf(rs.getString("byte_status")),
MetricSourceType.valueOf(rs.getString("byte_source_type")), rs.getString("byte_source"),
localDateTime(rs, "byte_observed_at"));
return new CollectionItem(rs.getLong("collection_item_id"), rs.getInt("item_order"),
rs.getLong("source_id"), rs.getLong("source_version"), rs.getString("source_name"),
rs.getString("source_database"), rs.getString("source_table"),
rs.getLong("target_resource_id"), rs.getLong("target_space_id"),
StorageResourceType.valueOf(rs.getString("target_type")), Layer.valueOf(rs.getString("target_layer")),
rs.getString("target_database"), rs.getString("target_table"), nullableLong(rs, "layer_id"),
rs.getString("layer_name"), rs.getString("target_create_request_id"),
rs.getString("target_create_state"), rs.getString("effective_status"), nullableLong(rs, "task_id"),
nullableLong(rs, "effective_run_id"), rs.getString("effective_external_job_id"),
rs.getBoolean("effective_retryable"), rs.getString("effective_error_code"),
BatchIngestionPolicy.safeSummary(rs.getString("effective_error_summary")), rows, bytes);
}
private static String safeEvidenceRef(String value) {
if (value == null || value.isBlank()) return null;
String trimmed = value.trim();
if (trimmed.length() > 512 || trimmed.chars().anyMatch(Character::isISOControl))
throw BatchIngestionException.validation("数据字节证据引用无效");
return trimmed;
}
private static Long nullableLong(ResultSet rs, String column) throws SQLException {
long value = rs.getLong(column);
return rs.wasNull() ? null : value;
}
private static LocalDateTime localDateTime(ResultSet rs, String column) throws SQLException {
Timestamp value = rs.getTimestamp(column);
return value == null ? null : value.toLocalDateTime();
}
public record Reservation(long collectionId, boolean created) { }
private record CollectionRow(long collectionId, String name, String requestHash, int itemCount,
LocalDateTime createdAt, LocalDateTime updatedAt) { }
}
@@ -0,0 +1,329 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.TargetEngine;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/** Deterministic dataops-to-integration production bridge for batch execution evidence. */
@Component
public class IntegrationBatchIngestionGateway implements BatchIntegrationGateway {
@DubboReference(check = false, timeout = 190_000, retries = 0)
private DataCollectionIntegrationService integration;
@DubboReference(check = false, timeout = 8_000, retries = 0)
private DataCollectionIntegrationService observationIntegration;
@Autowired
private StorageTableFileReferenceDirectory storageReferences;
@Value("${datagov.batch-ingestion.hive-metastore-uri:}")
private String hiveMetastoreUri;
IntegrationBatchIngestionGateway(DataCollectionIntegrationService integration) {
this.integration = integration;
this.observationIntegration = integration;
}
IntegrationBatchIngestionGateway(DataCollectionIntegrationService integration,
StorageTableFileReferenceDirectory storageReferences) {
this.integration = integration;
this.observationIntegration = integration;
this.storageReferences = storageReferences;
}
public IntegrationBatchIngestionGateway() {
}
@Override
public DataCollectionIntegrationService.BatchObservationResult observe(
DataCollectionIntegrationService.BatchObservationRequest request
) {
try {
var result = observationIntegration.observeBatch(request);
return result == null ? BatchIntegrationGateway.super.observe(request) : result;
} catch (RuntimeException | LinkageError exception) {
return BatchIntegrationGateway.super.observe(request);
}
}
@Override
public CapabilityCheckResult checkCapabilities(CapabilityCheckRequest request) {
return checkCapabilities(request, null);
}
@Override
public CapabilityCheckResult checkCapabilities(VerifiedIngestionCommandActor verified, CapabilityCheckRequest request) {
requireCommandIdentity(verified, request.actorId(), request.orgScopeId());
return checkCapabilities(request, verified);
}
private CapabilityCheckResult checkCapabilities(CapabilityCheckRequest request, VerifiedIngestionCommandActor verified) {
try {
var profile = targetProfile(request.actorId(), request.orgScopeId(), request.targetRefId(), request.snapshot(), verified);
var snapshot = snapshot(request.actorId(), request.orgScopeId(), request.sourceRefId(), request.sourceConnector(),
request.targetConnector(), request.snapshot());
if (verified != null) verified.checkSubmit();
var result = integration.checkBatchCapabilities(
new DataCollectionIntegrationService.BatchCapabilityRequest(request.actorId(), request.orgScopeId(),
request.taskId(), request.sourceRefId(), request.targetRefId(), request.sourceConnector(),
request.targetConnector(), request.externalActionKey(), snapshot, profile));
if (verified != null && !java.util.Objects.equals(profile,
targetProfile(request.actorId(), request.orgScopeId(), request.targetRefId(), request.snapshot(), verified)))
return unknownCapability("BATCH_TARGET_REFERENCE_DRIFT");
if (result == null) return unknownCapability("BATCH_CAPABILITY_RESPONSE_MISSING");
return new CapabilityCheckResult(state(result.sourceState()), state(result.targetState()),
state(result.connectorState()), result.checkedAt(), result.expiresAt(),
result.errorCode(), result.errorSummary(), result.fieldIssue());
} catch (RuntimeException | LinkageError exception) {
return unknownCapability("BATCH_GATEWAY_UNAVAILABLE");
}
}
@Override
public SubmissionResult submit(SubmissionRequest request) {
return submit(request, null);
}
@Override
public SubmissionResult submit(VerifiedIngestionCommandActor verified, SubmissionRequest request) {
requireCommandIdentity(verified, request.actorId(), request.orgScopeId());
return submit(request, verified);
}
private SubmissionResult submit(SubmissionRequest request, VerifiedIngestionCommandActor verified) {
try {
var profile = targetProfile(request.actorId(), request.orgScopeId(), request.targetRefId(), request.snapshot(), verified);
var snapshot = snapshot(request.actorId(), request.orgScopeId(), request.sourceRefId(), request.sourceConnector(),
request.targetConnector(), request.snapshot());
if (verified != null) verified.checkSubmit();
return submission(integration.submitBatch(new DataCollectionIntegrationService.BatchSubmissionRequest(
request.actorId(), request.orgScopeId(), request.taskId(), request.definitionId(),
request.snapshotId(), request.runId(), request.requestId(), request.externalActionKey(),
request.snapshotSha256(), request.sourceRefId(), request.targetRefId(), request.sourceConnector(),
request.targetConnector(), snapshot, profile,
request.batchNo())));
} catch (RuntimeException | LinkageError exception) {
return unknownSubmission("BATCH_GATEWAY_UNAVAILABLE");
}
}
@Override
public CheckpointEvidence checkpointEvidence(CheckpointRequest request) {
try {
var result = integration.batchCheckpoint(new DataCollectionIntegrationService.BatchCheckpointRequest(
request.taskId(), request.runId(), request.snapshotId(), request.externalJobId(),
request.externalActionKey()));
if (result == null) return unknownCheckpoint(request, "BATCH_CHECKPOINT_RESPONSE_MISSING");
return new CheckpointEvidence(result.runId(), result.externalJobId(), result.completed(),
result.checkpointId(), result.checkpointSequence(), result.evidenceAt(), result.evidenceRef(),
result.errorCode(), result.errorSummary());
} catch (RuntimeException | LinkageError exception) {
return unknownCheckpoint(request, "BATCH_GATEWAY_UNAVAILABLE");
}
}
@Override
public SubmissionResult resume(ResumeRequest request) {
try {
return submission(integration.resumeBatch(new DataCollectionIntegrationService.BatchResumeRequest(
request.actorId(), request.orgScopeId(), request.taskId(), request.parentRunId(),
request.resumedRunId(), request.snapshotId(), request.requestId(), request.externalJobId(),
request.checkpointId(), request.reason(), request.externalActionKey(), request.snapshotSha256(),
request.sourceRefId(), request.targetRefId(), request.sourceConnector(), request.targetConnector(),
snapshot(request.actorId(), request.orgScopeId(), request.sourceRefId(), request.sourceConnector(),
request.targetConnector(), request.snapshot()),
targetProfile(request.actorId(), request.orgScopeId(), request.targetRefId(), request.snapshot()),
request.batchNo())));
} catch (RuntimeException | LinkageError exception) {
return unknownSubmission("BATCH_GATEWAY_UNAVAILABLE");
}
}
@Override
public ArrivalEvidence validateArrival(ArrivalValidationRequest request) {
try {
var result = integration.validateBatchArrival(new DataCollectionIntegrationService.BatchArrivalRequest(
request.taskId(), request.runId(), request.snapshotId(), request.externalJobId(),
request.externalActionKey(), request.batchNo()));
if (result == null) return unknownArrival("BATCH_ARRIVAL_RESPONSE_MISSING");
return new ArrivalEvidence(result.batchNo(), result.sourceCount(), result.targetCount(), result.checksum(),
result.duplicateCount(), result.evidenceAt(), result.evidenceRef(), result.retryable(),
result.errorCode(), result.errorSummary());
} catch (RuntimeException | LinkageError exception) {
return unknownArrival("BATCH_GATEWAY_UNAVAILABLE");
}
}
private static CapabilityState state(String value) {
try {
return value == null ? CapabilityState.UNKNOWN : CapabilityState.valueOf(value);
} catch (IllegalArgumentException exception) {
return CapabilityState.UNKNOWN;
}
}
private static BatchIngestionStatus status(String value) {
try {
return value == null ? BatchIngestionStatus.UNKNOWN : BatchIngestionStatus.valueOf(value);
} catch (IllegalArgumentException exception) {
return BatchIngestionStatus.UNKNOWN;
}
}
private static SubmissionResult submission(DataCollectionIntegrationService.BatchSubmissionResult result) {
return result == null ? unknownSubmission("BATCH_SUBMISSION_RESPONSE_MISSING") :
new SubmissionResult(result.externalJobId(), result.sourceStatus(), status(result.normalizedStatus()),
result.retryable(), result.errorCode(), result.errorSummary(), result.submissionEvidence());
}
private static CapabilityCheckResult unknownCapability(String code) {
LocalDateTime now = LocalDateTime.now();
return new CapabilityCheckResult(CapabilityState.UNKNOWN, CapabilityState.UNKNOWN, CapabilityState.UNKNOWN,
now, now, code, "批量采集集成证据暂不可用");
}
private static SubmissionResult unknownSubmission(String code) {
return new SubmissionResult(null, "UNKNOWN", BatchIngestionStatus.UNKNOWN, true, code,
"批量采集集成证据暂不可用");
}
private static CheckpointEvidence unknownCheckpoint(CheckpointRequest request, String code) {
return new CheckpointEvidence(request.runId(), request.externalJobId(), false, null, 0,
null, null, code, "批量采集checkpoint证据暂不可用");
}
private static ArrivalEvidence unknownArrival(String code) {
return new ArrivalEvidence(null, null, null, null, null, null, null, true, code,
"批量采集到数证据暂不可用");
}
private DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
long actorId, long orgScopeId, long resourceId, BatchIngestionPolicy.TaskConfig snapshot
) {
return targetProfile(actorId, orgScopeId, resourceId, snapshot, null);
}
private static void requireCommandIdentity(VerifiedIngestionCommandActor verified, long actorId, long orgId) {
if (verified == null) throw BatchIngestionException.forbidden();
verified.checkSubmit();
if (verified.actorId() != actorId || verified.orgId() != orgId) throw BatchIngestionException.forbidden();
}
private DataCollectionIntegrationService.StorageExecutionProfile targetProfile(
long actorId, long orgScopeId, long resourceId, BatchIngestionPolicy.TaskConfig snapshot,
VerifiedIngestionCommandActor verified
) {
if (verified != null) {
requireCommandIdentity(verified, actorId, orgScopeId);
if (storageReferences == null || snapshot == null || snapshot.targetObject() == null)
throw BatchIngestionException.forbidden();
}
if (storageReferences == null || snapshot == null || snapshot.targetObject() == null) return null;
String[] object = snapshot.targetObject().split("\\.", -1);
if (object.length != 2 || object[0].isBlank() || object[1].isBlank()) {
if (verified != null) throw BatchIngestionException.forbidden();
return null;
}
var resolved = verified == null ? storageReferences.resolveObject(actorId, orgScopeId, resourceId, object[0])
: storageReferences.resolveObjectForIngestion(actorId, orgScopeId, resourceId, object[0]);
if (verified != null) {
if (resolved == null || resolved.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED ||
resolved.spaceId() == null || !object[0].equals(resolved.externalSpaceId()) ||
!snapshot.targetConnector().equals(resolved.resourceType())) throw BatchIngestionException.forbidden();
verified.checkSubmit();
}
if (resolved.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED) return null;
return new DataCollectionIntegrationService.StorageExecutionProfile(resourceId, resolved.spaceId(),
resolved.resourceType(), resolved.catalogName(), resolved.externalSpaceId(), resolved.locationUri(),
resolved.endpointHost(), resolved.endpointPort(), resolved.serviceAccount(), resolved.secretRef(),
resolved.tlsEnabled(), metastoreUri(resolved.resourceType(), hiveMetastoreUri));
}
static String metastoreUri(String resourceType, String configured) {
return "HIVE".equals(resourceType) && configured != null && !configured.isBlank()
? configured.trim() : null;
}
private DataCollectionIntegrationService.BatchExecutionSnapshot snapshot(
long actorId, long orgScopeId, long sourceRefId, String sourceConnector, String targetConnector,
BatchIngestionPolicy.TaskConfig value
) {
if (value == null) return null;
// Old binary request constructors carry no actor scope. Preserve their explicit 9-field compatibility
// snapshot; every current MYSQL/JDBC production request must use an owner-authorized JDBC column snapshot.
if (actorId <= 0 || orgScopeId <= 0 || sourceRefId <= 0) return legacySnapshot(value);
if (!List.of("MYSQL", "JDBC").contains(upper(sourceConnector)))
throw BatchIngestionException.validation("当前字段映射仅支持已适配的JDBC数据源");
String[] object = value.sourceObject() == null ? new String[0] : value.sourceObject().split("\\.", -1);
if ((object.length != 2 && object.length != 3) || java.util.Arrays.stream(object).anyMatch(String::isBlank))
throw BatchIngestionException.validation("源对象不完整,请重新读取结构");
List<Column> source = integration.sourceSchema(new DataCollectionIntegrationService.SourceSchemaRequest(
actorId, orgScopeId, sourceRefId, object[0], String.join(".", java.util.Arrays.copyOfRange(object, 1, object.length))));
if (source == null || source.isEmpty() || source.size() > 500 || source.stream().anyMatch(java.util.Objects::isNull))
throw BatchIngestionException.external("源结构暂不可读取,请刷新后重试");
TargetEngine engine;
try { engine = TargetEngine.valueOf(upper(targetConnector)); }
catch (IllegalArgumentException exception) { throw BatchIngestionException.validation("请选择Hive或Doris目标"); }
return snapshot(value, source, engine);
}
static DataCollectionIntegrationService.BatchExecutionSnapshot snapshot(
BatchIngestionPolicy.TaskConfig value, List<Column> source, TargetEngine engine
) {
Map<String, Column> sourceByName = new LinkedHashMap<>();
for (Column column : source) {
String key = column.name() == null ? "" : column.name().toLowerCase(Locale.ROOT);
if (key.isBlank() || sourceByName.putIfAbsent(key, column) != null)
throw BatchIngestionException.validation("源结构存在重复或无效字段,请重新读取结构");
}
return new DataCollectionIntegrationService.BatchExecutionSnapshot(value.dataDomainCode(),
value.sourceObject(), value.targetObject(), value.mode().name(),
value.incrementalField(), value.partitionField(), value.parallelism(), value.checkpointEnabled(),
value.checkpointIntervalSeconds(), value.mappings().stream().map(mapping -> {
Column column = sourceByName.get(mapping.sourceField().toLowerCase(Locale.ROOT));
if (column == null) throw BatchIngestionException.conflict("源字段“" + mapping.sourceField() + "”已不存在,请重新读取结构");
return executionField(mapping, column, engine);
}).toList());
}
static DataCollectionIntegrationService.BatchFieldExecution executionField(
BatchIngestionPolicy.MappingConfig mapping, Column source, TargetEngine engine
) {
var mapped = BatchTargetTypePolicy.canonical(source, engine);
if (!BatchTargetTypePolicy.declaredTypeMatches(mapped.targetType(), mapping.targetType()))
throw BatchIngestionException.validation("字段“" + source.name() + "”的目标类型与统一映射不一致,请重新生成草稿");
return new DataCollectionIntegrationService.BatchFieldExecution(mapping.order(), mapping.sourceField(),
mapping.targetField(), mapped.sourceType(), mapped.targetType(), mapping.transform().name(),
mapping.defaultValue(), mapping.filterOperator() == null ? null : mapping.filterOperator().name(),
mapping.filterValues(), source.nativeType(), source.precision(), source.scale(), source.octetLength());
}
private static DataCollectionIntegrationService.BatchExecutionSnapshot legacySnapshot(
BatchIngestionPolicy.TaskConfig value
) {
return new DataCollectionIntegrationService.BatchExecutionSnapshot(value.dataDomainCode(),
value.sourceObject(), value.targetObject(), value.mode().name(), value.incrementalField(),
value.partitionField(), value.parallelism(), value.checkpointEnabled(), value.checkpointIntervalSeconds(),
value.mappings().stream().map(mapping -> new DataCollectionIntegrationService.BatchFieldExecution(
mapping.order(), mapping.sourceField(), mapping.targetField(), mapping.sourceType(), mapping.targetType(),
mapping.transform().name(), mapping.defaultValue(),
mapping.filterOperator() == null ? null : mapping.filterOperator().name(), mapping.filterValues())).toList());
}
private static String upper(String value) {
return value == null ? "" : value.trim().toUpperCase(Locale.ROOT);
}
}
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.governance.api.metadataingestion.MetadataIngestionOrchestrationService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
class MetadataIngestionOrchestrationGateway {
@DubboReference(version = MetadataIngestionOrchestrationService.VERSION,
group = MetadataIngestionOrchestrationService.GROUP, timeout = 10_000, retries = 0, check = false)
private MetadataIngestionOrchestrationService service;
MetadataIngestionOrchestrationService.OrchestrationResult ensureAndRun(
long actorId, long orgId, long sourceId, long sourceVersion, String database, String table,
String requestId, long collectionId, long itemId, long runId) {
return service.ensureAndRun(new MetadataIngestionOrchestrationService.OrchestrationCommand(
actorId, orgId, sourceId, sourceVersion, database, table, requestId, collectionId, itemId, runId));
}
}
@@ -0,0 +1,49 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.BatchIngestionStatus;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/** Production-safe fallback: missing integration is UNKNOWN and never a static success. */
@Component
@ConditionalOnMissingBean(BatchIntegrationGateway.class)
public class UnavailableBatchIntegrationGateway implements BatchIntegrationGateway {
private static final String CODE = "BATCH_GATEWAY_UNAVAILABLE";
private static final String SUMMARY = "批量采集集成能力不可用";
@Override
public CapabilityCheckResult checkCapabilities(CapabilityCheckRequest request) {
LocalDateTime now = LocalDateTime.now();
return new CapabilityCheckResult(CapabilityState.UNKNOWN, CapabilityState.UNKNOWN,
CapabilityState.UNKNOWN, now, now, CODE, SUMMARY);
}
@Override
public SubmissionResult submit(SubmissionRequest request) {
return unknown();
}
@Override
public CheckpointEvidence checkpointEvidence(CheckpointRequest request) {
return new CheckpointEvidence(request.runId(), request.externalJobId(), false, null, 0,
null, null, CODE, SUMMARY);
}
@Override
public SubmissionResult resume(ResumeRequest request) {
return unknown();
}
@Override
public ArrivalEvidence validateArrival(ArrivalValidationRequest request) {
return new ArrivalEvidence(null, null, null, null, null, null, null, true, CODE, SUMMARY);
}
private static SubmissionResult unknown() {
return new SubmissionResult(null, "GATEWAY_UNAVAILABLE", BatchIngestionStatus.UNKNOWN,
true, CODE, SUMMARY);
}
}
@@ -0,0 +1,33 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.system.api.RemoteUserService;
import java.time.Instant;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
public class UnifiedIngestionCommandAuthority {
@DubboReference(check = false, timeout = 5000, retries = 0)
private RemoteUserService users;
VerifiedIngestionCommandActor verify(IngestionCollectionRepository.Command command, boolean observing) {
Runnable check = () -> requireCurrent(command.actorId(), command.orgId(), command.itemId(), observing);
check.run();
return new VerifiedIngestionCommandActor(command.actorId(), command.orgId(), observing, check);
}
void requireCurrent(long user, long org, long command, boolean observing) {
String purpose = observing ? "UNIFIED_INGESTION_OBSERVE" : "UNIFIED_INGESTION_SUBMIT";
try {
var result = users.resolveIngestionCommandActor(user, org, command, purpose);
Instant now = Instant.now();
if (result != null && result.active() && result.allowed() && result.userId() == user &&
result.deptId() == org && result.commandId() == command && purpose.equals(result.purpose()) &&
result.checkedAt() != null && !result.checkedAt().isBefore(now.minusSeconds(10)) &&
!result.checkedAt().isAfter(now.plusSeconds(5))) return;
} catch (RuntimeException | LinkageError ignored) {
// Shared same-token errors are never copied into evidence or application logs.
}
throw BatchIngestionException.forbidden();
}
}
@@ -0,0 +1,13 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
/** Stable, redacted diagnostic for a bounded command stage; never carries provider details. */
final class UnifiedIngestionCommandStageException extends RuntimeException {
private final String errorCode;
UnifiedIngestionCommandStageException(String errorCode, String message, RuntimeException cause) {
super(message, cause);
this.errorCode = errorCode;
}
String errorCode() { return errorCode; }
}
@@ -0,0 +1,91 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/** Bounded consumer of previously accepted commands. No DAG, backfill, or automatic resubmission API. */
@Component
@Slf4j
@ConditionalOnProperty(name = "datagov.ingestion.commands.enabled", havingValue = "true")
public class UnifiedIngestionCommandWorker implements SmartLifecycle {
private final IngestionCollectionRepository repository;
private final UnifiedIngestionCommandAuthority authority;
private final UnifiedIngestionService service;
private volatile boolean running;
private ScheduledExecutorService executor;
public UnifiedIngestionCommandWorker(IngestionCollectionRepository repository,
UnifiedIngestionCommandAuthority authority, UnifiedIngestionService service) {
this.repository = repository;
this.authority = authority;
this.service = service;
}
boolean consumeOne() { return process(false); }
boolean observeOne() { return process(true); }
private boolean process(boolean observing) {
var command = repository.claim(observing);
if (command == null) return false;
log.info("Unified ingestion command claimed; observing={}, collectionId={}, itemId={}, runId={}, phase={}",
observing, command.collectionId(), command.itemId(), command.runId(), command.phase());
long started = System.nanoTime();
try {
command.request();
var actor = authority.verify(command, observing);
log.info("Unified ingestion command observe started; observing={}, collectionId={}, itemId={}, runId={}, phase={}",
observing, command.collectionId(), command.itemId(), command.runId(), command.phase());
if (observing) service.observeCommand(command, actor);
else service.advanceCommand(command, actor);
} catch (RuntimeException | LinkageError exception) {
if (exception instanceof cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors.DirectoryBusy &&
java.util.Set.of("VALIDATED", "TARGET_CONFIRMED", "TASK_BOUND", "READY", "TARGET_DISPATCHING", "OBSERVING")
.contains(command.phase())) {
repository.deferDirectoryRead(command);
return true;
}
log.warn("Unified ingestion command blocked; observing={}, stage={}, category={}", observing,
observing ? "observe" : "advance", exception.getClass().getSimpleName());
if (exception instanceof UnifiedIngestionCommandStageException stage) {
repository.block(command, observing, stage.errorCode(), stage.getMessage());
} else {
repository.block(command, observing);
}
} finally {
log.info("Unified ingestion stage timing; observing={}, collectionId={}, itemId={}, phase={}, elapsedMs={}",
observing, command.collectionId(), command.itemId(), command.phase(),
TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started));
}
return true;
}
@Override public synchronized void start() {
if (running) return;
running = true;
executor = Executors.newScheduledThreadPool(4, r -> {
var thread = new Thread(r, "unified-ingestion-command-consumer");
thread.setDaemon(true);
return thread;
});
for (int i = 0; i < 4; i++) {
executor.scheduleWithFixedDelay(() -> {
try { if (running) consumeOne(); }
catch (RuntimeException | LinkageError exception) {
log.warn("Unified ingestion worker cycle failed; stage=scheduled, category={}",
exception.getClass().getSimpleName());
}
}, 250, 250, TimeUnit.MILLISECONDS);
}
}
@Override public synchronized void stop() {
running = false;
if (executor != null) executor.shutdown();
}
@Override public boolean isRunning() { return running; }
}
@@ -0,0 +1,87 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
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.dataops.api.batchingestion.UnifiedIngestionApi.*;
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceType;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/unified-ingestions")
public class UnifiedIngestionController {
private final UnifiedIngestionService service;
@GetMapping("/sources")
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
public R<SourcePage> sources(@RequestParam(required = false) String keyword) {
return R.ok(service.sources(keyword));
}
@GetMapping("/sources/{sourceId}/tables")
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
public R<SourceTablePage> tables(@PathVariable long sourceId, @RequestParam String sourceDatabase,
@RequestParam(required = false) String keyword, @RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.sourceTables(sourceId, sourceDatabase, keyword, pageNum, pageSize));
}
@GetMapping("/targets")
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
public R<TargetPage> targets(@RequestParam StorageResourceType type) { return R.ok(service.targets(type)); }
@GetMapping("/collections")
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
public R<CollectionPage> collections(@RequestParam(required = false) String keyword,
@RequestParam(required = false) CollectionStatus status,
@RequestParam(defaultValue = "1") int pageNum,
@RequestParam(defaultValue = "20") int pageSize) {
return R.ok(service.collections(keyword, status, pageNum, pageSize));
}
@GetMapping("/collections/{collectionId}")
@SaCheckPermission("aixun:dataops:batch-ingestion:view")
public R<CollectionDetail> collection(@PathVariable long collectionId) {
return R.ok(service.collection(collectionId));
}
@GetMapping("/collections/{collectionId}/configuration-copy")
@SaCheckPermission(value = {"aixun:dataops:batch-ingestion:view", "aixun:dataops:batch-ingestion:create"},
mode = cn.dev33.satoken.annotation.SaMode.AND)
public R<CollectionConfigurationCopy> configurationCopy(@PathVariable long collectionId) {
return R.ok(service.configurationCopy(collectionId));
}
@PostMapping("/collections/{collectionId}/refresh")
@SaCheckPermission(value = {"aixun:dataops:batch-ingestion:view", "aixun:dataops:batch-ingestion:update",
"aixun:dataops:batch-ingestion:submit"}, mode = cn.dev33.satoken.annotation.SaMode.AND)
@Log(title = "统一采集状态与指标回收", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
public R<CollectionDetail> refreshCollection(@PathVariable long collectionId) {
return R.ok(service.refreshCollection(collectionId));
}
@PostMapping("/draft")
@SaCheckPermission("aixun:dataops:batch-ingestion:create")
public R<Draft> draft(@RequestBody DraftRequest request) { return R.ok(service.draft(request)); }
@PostMapping("/databases")
@SaCheckPermission("aixun:dataops:batch-ingestion:create")
@Log(title = "数据采集新建目标数据库", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
public R<CreateDatabaseResult> createDatabase(@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody CreateDatabaseRequest request) {
return R.ok(service.createDatabase(idempotencyKey, request));
}
@PostMapping("/submit")
@SaCheckPermission(value = {"aixun:dataops:batch-ingestion:create", "aixun:dataops:batch-ingestion:update",
"aixun:dataops:batch-ingestion:submit"}, mode = cn.dev33.satoken.annotation.SaMode.AND)
@Log(title = "数据采集批量提交", businessType = BusinessType.OTHER,
isSaveRequestData = false, isSaveResponseData = false)
public R<SubmitResult> submit(@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody SubmitRequest request) { return R.ok(service.submit(idempotencyKey, request)); }
}
@@ -0,0 +1,52 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.maintenance.JdbcMaintenanceLeaseRepository;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobDefinition;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobKind;
import cn.aixunkeji.datagov.maintenance.MaintenanceJobRunner;
import cn.aixunkeji.datagov.maintenance.MaintenanceRunRequest;
import cn.aixunkeji.datagov.maintenance.ScheduledIdempotencyKey;
import java.time.Clock;
import java.time.Duration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
/** Status/arrival observations only. The maintenance callback cannot submit new work. */
@Component
@ConditionalOnProperty(name = "datagov.ingestion.commands.enabled", havingValue = "true")
public class UnifiedIngestionReconciliationMaintenance implements AutoCloseable {
private static final String NAME = "ingestion.command-status-reconciliation";
private final Clock clock = Clock.systemUTC();
private final UnifiedIngestionCommandWorker worker;
private final MaintenanceJobRunner runner;
@Value("${datagov.ingestion.observation-delay-ms:5000}")
private long observationDelayMs = 5000;
private final MaintenanceJobDefinition definition = new MaintenanceJobDefinition(
1761500000000000111L, NAME, MaintenanceJobKind.STATUS_RECONCILIATION,
Duration.ofMinutes(10), Duration.ofMinutes(11));
public UnifiedIngestionReconciliationMaintenance(UnifiedIngestionCommandWorker worker, JdbcTemplate jdbc) {
this.worker = worker;
runner = new MaintenanceJobRunner("aixun-dataops-ingestion", new JdbcMaintenanceLeaseRepository(jdbc), clock);
}
@Scheduled(fixedDelayString = "${datagov.ingestion.observation-delay-ms:5000}")
public void reconcile() {
var key = ScheduledIdempotencyKey.forWindow(NAME, clock.instant(), observationWindow(observationDelayMs));
runner.run(definition, MaintenanceRunRequest.scheduled(key), context -> {
for (int count = 0; count < 20; count++) {
context.checkDeadline(clock.instant());
if (!worker.observeOne()) break;
}
});
}
static Duration observationWindow(long delayMs) {
return Duration.ofSeconds(Math.max(1, delayMs / 1000 + (delayMs % 1000 > 0 ? 1 : 0)));
}
@Override public void close() { runner.close(); }
}
@@ -0,0 +1,789 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.dataops.api.batchingestion.*;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.SourceTableComment;
import cn.aixunkeji.datagov.dataops.api.batchingestion.UnifiedIngestionApi.*;
import cn.aixunkeji.datagov.dataops.api.storage.StorageResourceType;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.*;
import cn.aixunkeji.datagov.dataops.storage.StorageResourceService;
import cn.aixunkeji.datagov.dataops.storage.StoragePhysicalSpaceApplicationService;
import cn.aixunkeji.datagov.dataops.storage.StorageConflictException;
import cn.aixunkeji.datagov.dataops.storage.StorageNotFoundException;
import cn.aixunkeji.datagov.dataops.storage.StorageScopeException;
import cn.aixunkeji.datagov.dataops.storage.StorageValidationException;
import cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerService;
import cn.aixunkeji.datagov.dataops.api.lakehouse.LakehouseLayerApi.LayerType;
import cn.aixunkeji.datagov.dataops.api.storage.StoragePhysicalSpaceCreateRequest;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileService;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.TargetEngine;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
public class UnifiedIngestionService {
private static final Pattern BYTE_EVIDENCE = Pattern.compile(
"seatunnel://jobs/([0-9]{1,19})/metrics/bytes/([0-9]{1,19})");
private final BatchActorProvider actors;
private final UnifiedIngestionSourceGateway sources;
private final StorageResourceService storage;
private final StoragePhysicalSpaceApplicationService physicalSpaces;
private final TableFileService tables;
private final BatchIngestionService batches;
private final LakehouseLayerService layers;
private final IngestionCollectionRepository collections;
private final MetadataIngestionOrchestrationGateway metadataOrchestration;
@Autowired
UnifiedIngestionService(BatchActorProvider actors, UnifiedIngestionSourceGateway sources,
StorageResourceService storage, StoragePhysicalSpaceApplicationService physicalSpaces,
TableFileService tables, BatchIngestionService batches, LakehouseLayerService layers,
IngestionCollectionRepository collections) {
this(actors, sources, storage, physicalSpaces, tables, batches, layers, collections, null);
}
UnifiedIngestionService(BatchActorProvider actors, UnifiedIngestionSourceGateway sources,
StorageResourceService storage, StoragePhysicalSpaceApplicationService physicalSpaces,
TableFileService tables, BatchIngestionService batches, LakehouseLayerService layers,
IngestionCollectionRepository collections, MetadataIngestionOrchestrationGateway metadataOrchestration) {
this.actors = actors; this.sources = sources; this.storage = storage; this.physicalSpaces = physicalSpaces;
this.tables = tables; this.batches = batches; this.layers = layers; this.collections = collections;
this.metadataOrchestration = metadataOrchestration;
}
@org.springframework.beans.factory.annotation.Value("${datagov.ingestion.commands.enabled:false}")
private boolean commandsEnabled;
@org.springframework.beans.factory.annotation.Value("${AIXUN_DATAGOV_INGESTION_PILOT_SOURCE_ID:0}")
private String pilotSourceIds = "0";
static boolean pilotSourceEnabled(String configured, long sourceId) {
return sourceId > 0 && configured != null && java.util.Arrays.stream(configured.split(","))
.map(String::trim).anyMatch(Long.toString(sourceId)::equals);
}
public SourcePage sources(String keyword) {
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)
throw BatchIngestionException.external("数据源目录暂不可用,请稍后重试");
List<Source> rows = result.entries().stream().map(item -> {
boolean mysql = "MYSQL".equalsIgnoreCase(item.type());
boolean sqlServer = "SQLSERVER".equalsIgnoreCase(item.type());
boolean pilot = item.id() != null && pilotSourceEnabled(pilotSourceIds, item.id())
&& 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();
String reason = mysql ? item.previewReason() : sqlServer ? "请先配置数据库凭据并通过连接测试"
: "该数据源类型暂不可用于数据采集";
return new Source(item.id(), item.name(), item.type(), item.status(), item.databaseName(), available,
available ? null : reason, item.version());
}).toList();
return new SourcePage(rows, rows.size());
}
public CollectionConfigurationCopy configurationCopy(long collectionId) {
BatchActor actor = actors.current();
var copy = collections.configurationCopy(actor, positive(collectionId, "采集集合ID"));
var request = copy.configuration();
try {
validateSubmit(request);
validateNewCommand(request);
if (!Set.of(StorageResourceType.HIVE, StorageResourceType.DORIS).contains(request.targetType()))
throw IngestionCollectionRepository.unavailableCopy();
for (var item : request.items()) {
Map<String, ColumnDefinition> columns = new LinkedHashMap<>();
Set<String> columnNames = new HashSet<>();
for (var column : item.columns()) {
if (column.type() == null || column.nullable() == null ||
columns.put(identifier(column.name(), "字段"), column) != null ||
!columnNames.add(normalized(column.name())) ||
column.precision() != null && column.precision() <= 0 ||
column.scale() != null && (column.scale() < 0 || column.precision() != null && column.scale() > column.precision()) ||
column.comment() != null && column.comment().length() > 500)
throw IngestionCollectionRepository.unavailableCopy();
}
Set<String> sourceFields = new HashSet<>(), targetFields = new HashSet<>();
for (var mapping : item.mappings()) {
if (mapping == null || mapping.transform() != BatchFieldTransform.NONE || mapping.defaultValue() != null ||
mapping.filterOperator() != null || mapping.filterValues() == null || !mapping.filterValues().isEmpty() ||
mapping.sourceType() == null || !mapping.sourceType().matches("[A-Za-z0-9_(), ]{1,128}") ||
mapping.targetType() == null || !mapping.targetType().matches("[A-Za-z0-9_(), ]{1,128}") ||
!sourceFields.add(normalized(identifier(mapping.sourceField(), "源字段"))) ||
!targetFields.add(normalized(identifier(mapping.targetField(), "目标字段"))) || !columns.containsKey(mapping.targetField()))
throw IngestionCollectionRepository.unavailableCopy();
}
if (targetFields.size() != columns.size()) throw IngestionCollectionRepository.unavailableCopy();
}
} catch (RuntimeException exception) {
throw IngestionCollectionRepository.unavailableCopy();
}
// Reauthorize current references without reusing READY or mutating the historical versions.
var ids = request.items().stream().map(SubmitItem::sourceId).distinct().toList();
var currentSources = sources.sources(actor.actorId(), actor.orgScopeId(), ids, null, 200);
if (currentSources == null || !"AVAILABLE".equals(currentSources.status()) || currentSources.entries() == null)
throw BatchIngestionException.external("当前数据源目录暂不可用,未复制配置");
var currentIds = currentSources.entries().stream().map(entry -> entry.id()).collect(java.util.stream.Collectors.toSet());
if (!currentIds.containsAll(ids)) throw BatchIngestionException.notFound();
try {
var target = storage.detailForIngestion(actor.actorId(), actor.orgScopeId(), request.targetResourceId());
if (target.spaces().stream().noneMatch(space -> space.spaceId().equals(request.targetSpaceId())))
throw BatchIngestionException.notFound();
} catch (StorageScopeException | StorageNotFoundException exception) {
throw BatchIngestionException.notFound();
}
return copy;
}
public SourceTablePage sourceTables(long sourceId, String sourceDatabase, String keyword, int pageNum, int pageSize) {
BatchActor actor = actors.current();
var result = sources.tables(actor.actorId(), actor.orgScopeId(), positive(sourceId, "数据源ID"),
identifier(sourceDatabase, "源数据库"), optionalKeyword(keyword), page(pageNum), size(pageSize));
if (result == null || !"AVAILABLE".equals(result.status()))
throw BatchIngestionException.external(result == null ? "源表暂不可读取" : result.errorSummary());
return new SourceTablePage(result.rows().stream().map(row ->
new SourceTable(row.catalog(), row.schema() == null ? row.name() : row.schema() + "." + row.name(), row.kind()))
.toList(), result.total(), result.pageNum(), result.pageSize());
}
public TargetPage targets(StorageResourceType type) {
if (type != StorageResourceType.HIVE && type != StorageResourceType.DORIS)
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());
List<TargetDatabase> databases = detail.spaces().stream().filter(space -> space.enabled())
.map(space -> new TargetDatabase(space.spaceId(), space.name(), space.externalObjectId(), space.version()))
.toList();
Long accessVersion = detail.accessProfile() == null ? null : detail.accessProfile().version();
return new Target(resource.resourceId(), resource.name(), resource.resourceType(), resource.version(),
accessVersion, databases);
}).toList();
return new TargetPage(rows, page.getTotal());
}
public CreateDatabaseResult createDatabase(String idempotencyKey, CreateDatabaseRequest request) {
if (request == null || request.resourceId() <= 0 || request.resourceVersion() < 0 ||
request.accessVersion() < 0) throw BatchIngestionException.validation("新建数据库参数不完整");
String name = identifier(request.name(), "数据库名称");
try {
return new CreateDatabaseResult(physicalSpaces.create(request.resourceId(),
BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey),
new StoragePhysicalSpaceCreateRequest(name, name, 0L, true,
request.resourceVersion(), request.accessVersion())));
} catch (StorageValidationException exception) {
throw BatchIngestionException.validation(exception.getMessage());
} catch (StorageConflictException exception) {
throw BatchIngestionException.conflict(exception.getMessage());
} catch (StorageScopeException exception) {
throw BatchIngestionException.forbidden();
} catch (StorageNotFoundException exception) {
throw BatchIngestionException.notFound();
}
}
public Draft draft(DraftRequest request) {
if (request == null || request.targetType() == null ||
!Set.of(StorageResourceType.HIVE, StorageResourceType.DORIS).contains(request.targetType()) ||
request.items() == null || request.items().isEmpty() || request.items().size() > 50)
throw BatchIngestionException.validation("请选择1到50张源表和目标类型");
BatchActor actor = actors.current();
TargetEngine targetEngine = targetEngine(request.targetType());
Set<String> unique = new HashSet<>();
List<DraftItem> items = new ArrayList<>();
for (SourceSelection selection : request.items()) {
SourceSelection item = validateSourceSelection(selection);
String identity = item.sourceId() + "|" + item.sourceDatabase().toLowerCase(Locale.ROOT) + "|" +
item.table().toLowerCase(Locale.ROOT);
if (!unique.add(identity)) throw BatchIngestionException.validation("同一数据源的源表不能重复");
try {
verifySource(actor, item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase());
var schema = schema(actor, item.sourceId(), item.sourceDatabase(), item.table());
List<ColumnDefinition> columns = schema.columns().stream()
.map(column -> BatchTargetTypePolicy.propose(column, targetEngine)).toList();
List<BatchFieldMappingCommand> mappings = BatchTargetWizardService.matchColumns(schema.columns(),
new cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult(
cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.State.CONFIRMED,
List.of(item.table()), columns.stream().map(UnifiedIngestionService::directoryColumn).toList(), 1, null),
targetEngine);
String target = item.table().replace('.', '_').toLowerCase(Locale.ROOT);
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
item.table(), target, fingerprint(item.sourceId(), item.sourceDatabase(), item.table(),
schema.columns(), schema.tableComment()), columns, mappings, null,
schema.tableComment().value(), schema.tableComment().state().name()));
} catch (RuntimeException exception) {
items.add(new DraftItem(item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(),
item.table(), item.table().replace('.', '_').toLowerCase(Locale.ROOT), null, List.of(), List.of(),
BatchIngestionPolicy.safeSummary(exception.getMessage())));
}
}
return new Draft(List.copyOf(items));
}
/** Structural validation only; a saved draft is not an ingestion command. */
public void validateDraft(SubmitRequest request) { validateSubmit(request); validateNewCommand(request); }
public SubmitResult submit(String idempotencyKey, SubmitRequest request) {
String baseKey = BatchIngestionPolicy.requireIdempotencyKey(idempotencyKey);
validateSubmit(request);
BatchActor actor = actors.current();
String requestHash = BatchIngestionPolicy.sha256("COLLECTION_SUBMIT\n" + request);
Long replayedCollectionId = collections.replayedCollectionId(actor, baseKey, requestHash);
if (replayedCollectionId != null)
return toSubmitResult(collections.detail(actor, replayedCollectionId), true);
if (!commandsEnabled)
throw BatchIngestionException.external("采集提交暂不可用,请联系管理员启用处理服务");
validateNewCommand(request);
verifyTargetVersion(actor, request);
try {
layers.validateIngestionLayer(request.targetResourceId(), request.targetSpaceId(), LayerType.valueOf(request.layer().name()));
} catch (cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Conflict
| cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Validation exception) {
throw BatchIngestionException.conflict(exception.getMessage());
}
var reservation = collections.reserve(actor, baseKey, requestHash, request);
return toSubmitResult(collections.detail(actor, reservation.collectionId()), !reservation.created());
}
/** JSON contains only the typed request's checked source metadata and Owner versions, never credentials. */
record CommandContext(SelectedFields selected, SourceTableComment tableComment, long accessVersion,
String database, cn.aixunkeji.datagov.dataops.api.lakehouse.LakehouseLayerApi.LayerView layer,
CreateCommand ddl) { }
void advanceCommand(IngestionCollectionRepository.Command command, VerifiedIngestionCommandActor verified) {
verified.checkSubmit();
var request = command.request();
validateSubmit(request);
validateNewCommand(request);
var item = command.item();
var actor = verified.batchActor();
long accessVersion = verifyTargetVersion(actor, request);
long expectedAccess = "PENDING".equals(command.phase()) ? accessVersion : command.validated().accessVersion();
var expectedLayer = "PENDING".equals(command.phase()) ? null : command.validated().layer();
var commandIdentity = verified;
verified = verified.withOwnerCheck(() -> {
if (verifyTargetVersion(actor, request) != expectedAccess)
throw BatchIngestionException.conflict("原目标访问配置版本已变化");
if (expectedLayer != null) layers.verifyForIngestion(commandIdentity, expectedLayer);
});
verifySource(actor, item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase());
var current = schema(actor, item.sourceId(), item.sourceDatabase(), item.sourceTable());
if (!fingerprint(item.sourceId(), item.sourceDatabase(), item.sourceTable(), current.columns(), current.tableComment())
.equals(item.sourceFingerprint())) throw BatchIngestionException.conflict("源结构已变化,请重新生成映射");
verified = verified.withSourceSchema(item.sourceId(), item.sourceDatabase(), item.sourceTable(), current.columns());
var selected = selectedFields(current.columns(), item, request.targetType());
String key = BatchIngestionPolicy.sha256(command.key() + '|' + item.sourceId() + '|' +
item.sourceDatabase() + '|' + item.sourceTable() + '|' + item.targetTable());
if ("PENDING".equals(command.phase())) {
var space = storage.detailForIngestion(actor.actorId(), actor.orgScopeId(), request.targetResourceId())
.spaces().stream().filter(s -> s.spaceId().equals(request.targetSpaceId())).findFirst().orElseThrow();
collections.advance(command, "VALIDATED", new CommandContext(selected, current.tableComment(),
accessVersion, space.externalObjectId(), null, null), null, null, null);
return;
}
var context = command.validated();
if (context.layer() != null) layers.verifyForIngestion(verified, context.layer());
if (context.accessVersion() != accessVersion || !selected.equals(context.selected()) ||
!java.util.Objects.equals(current.tableComment(), context.tableComment()))
throw BatchIngestionException.conflict("原采集配置已变化");
EngineType engine = EngineType.valueOf(request.targetType().name());
switch (command.phase()) {
case "VALIDATED" -> {
cn.aixunkeji.datagov.dataops.api.lakehouse.LakehouseLayerApi.LayerView layer;
try {
layer = layers.ensureForIngestion(verified, key + "-layer", request.targetResourceId(),
request.targetSpaceId(), LayerType.valueOf(request.layer().name()));
} catch (RuntimeException exception) {
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_LAYER_REFERENCE",
exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Conflict
|| exception instanceof cn.aixunkeji.datagov.dataops.lakehouse.LakehouseLayerErrors.Validation
? exception.getMessage() : "目标分层引用暂不可确认,请核验存储资源与空间配置", exception);
}
if (!layer.enabled() || layer.layerId() == null || layer.layerId() <= 0 || layer.lastValidatedAt() == null ||
layer.mappingStatus() != cn.aixunkeji.datagov.dataops.api.lakehouse.LakehouseLayerApi.MappingStatus.CONFIRMED)
throw BatchIngestionException.conflict("目标分层尚未确认");
var next = new CommandContext(selected, current.tableComment(), accessVersion, context.database(), layer, null);
try {
log.info("Unified ingestion target browse requested; collectionId={}, itemId={}, sourceId={}, targetResourceId={}, targetSpaceId={}, targetDatabase={}, targetTable={}",
command.collectionId(), command.itemId(), item.sourceId(), request.targetResourceId(), request.targetSpaceId(),
context.database(), item.targetTable());
matchCommandTarget(verified, request, item, selected);
collections.advance(command, "TARGET_CONFIRMED", next, null, null, null);
return;
} catch (TableFileErrors.Reference missing) {
if (!item.createTarget()) {
throw new UnifiedIngestionCommandStageException("INGESTION_VALIDATED_TARGET_DIRECTORY",
"目标目录暂不可确认,请核验目标表与字段结构", missing);
}
}
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));
}
case "TARGET_RESERVED" -> {
if (command.ddlId() == null || context.ddl() == null) throw BatchIngestionException.conflict("原建表关联缺失");
verified.checkSubmit();
// Commit the one-way fence before invoking CREATE. Even a crash before POST may only observe afterward.
collections.advance(command, "TARGET_DISPATCHING", null, null, null, null);
tables.executeCommandCreate(verified, key + "-table", command.ddlId(), context.ddl());
}
case "TARGET_CONFIRMED" -> {
matchCommandTarget(verified, request, item, selected);
var create = new BatchTaskCreateCommand(taskName(request.name(), item.sourceTable(), key), null,
item.sourceId(), request.targetResourceId(), "JDBC", request.targetType().name(),
item.sourceDatabase() + "." + item.sourceTable(), context.database() + "." + item.targetTable(),
BatchIngestionMode.FULL, null, null, 1, false, null, selected.mappings());
batches.create(verified, key + "-task", create,
id -> collections.advance(command, "TASK_BOUND", null, id, null, null));
}
case "TASK_BOUND" -> {
if (command.taskId() == null) throw BatchIngestionException.conflict("原采集任务关联缺失");
var task = batches.find(verified, command.taskId());
if (task.status() != BatchIngestionStatus.READY)
task = batches.ready(verified, task.taskId(), key + "-ready", new BatchReadyCommand(task.version()));
if (task.status() != BatchIngestionStatus.READY) throw BatchIngestionException.conflict("原任务校验未完成");
collections.advance(command, "READY", null, null, null, null);
}
case "READY" -> {
if (command.taskId() == null) throw BatchIngestionException.conflict("原采集任务关联缺失");
batches.reserveSubmission(verified, command.taskId(), key + "-submit",
id -> collections.advance(command, "RUN_BOUND", null, null, id, null));
}
case "RUN_BOUND" -> {
if (command.runId() == null) throw BatchIngestionException.conflict("原运行关联缺失");
batches.dispatch(verified, command.runId(),
() -> collections.advance(command, "OBSERVING", null, null, null, null));
}
default -> throw BatchIngestionException.conflict("采集命令阶段不可提交");
}
}
private void matchCommandTarget(VerifiedIngestionCommandActor verified, SubmitRequest request,
SubmitItem item, SelectedFields selected) {
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()));
}
static CreateCommand commandDdl(SubmitRequest request, SubmitItem item, CommandContext context) {
String comment;
try {
comment = requireTableComment(context.tableComment());
} catch (BatchIngestionException exception) {
throw new UnifiedIngestionCommandStageException("INGESTION_SOURCE_TABLE_COMMENT_UNVERIFIED",
"源表注释尚未可靠读取,无法新建目标表;请重新读取源结构后提交", exception);
}
for (int index = 0; index < context.selected().sourceColumns().size(); index++) {
var column = context.selected().sourceColumns().get(index);
BatchTargetTypePolicy.requireSourceComment(column);
if (!sameDefinition(BatchTargetTypePolicy.propose(column, targetEngine(request.targetType())),
context.selected().targetColumns().get(index), true))
throw BatchIngestionException.validation("源字段建表定义或注释已变化");
}
EngineType engine = EngineType.valueOf(request.targetType().name());
return new CreateCommand(item.targetTable(), ObjectType.TABLE, context.layer().layerId(), request.targetResourceId(),
request.targetSpaceId(), engine, engine == EngineType.HIVE ? StorageFormat.ORC : StorageFormat.DORIS_NATIVE,
context.layer().catalogName(), context.layer().namespaceName(), null, request.layer().name() + " 数据采集目标表",
context.selected().targetColumns(), null, null, comment);
}
void observeCommand(IngestionCollectionRepository.Command command, VerifiedIngestionCommandActor verified) {
verified.check();
log.info("Unified ingestion observe entered; collectionId={}, itemId={}, runId={}, phase={}",
command.collectionId(), command.itemId(), command.runId(), command.phase());
if ("TARGET_DISPATCHING".equals(command.phase())) {
var request = command.request();
var context = command.validated();
if (context.layer() == null) throw BatchIngestionException.conflict("原分层关联缺失");
layers.verifyForIngestion(verified, context.layer());
if (verifyTargetVersion(verified.batchActor(), request) != context.accessVersion())
throw BatchIngestionException.conflict("原目标配置已变化");
var item = command.item();
String key = BatchIngestionPolicy.sha256(command.key() + '|' + item.sourceId() + '|' +
item.sourceDatabase() + '|' + item.sourceTable() + '|' + item.targetTable());
if (command.ddlId() == null || context.ddl() == null) throw BatchIngestionException.conflict("原建表请求不可验证");
var operation = tables.commandCreateResult(verified, key + "-table", command.ddlId(), context.ddl());
if (operation == null)
throw BatchIngestionException.conflict("原建表请求不可验证");
if ("REJECTED".equals(operation.state())) {
collections.rejectDdl(command, operation.errorCode(), operation.errorSummary());
return;
}
matchCommandTarget(verified, request, command.item(), context.selected());
collections.advance(command, "TARGET_CONFIRMED", null, null, null, null);
return;
}
if (!"OBSERVING".equals(command.phase()) || command.runId() == null)
throw BatchIngestionException.conflict("原运行关联缺失");
var run = batches.run(verified, command.runId());
if (run.status() != BatchIngestionStatus.SUCCEEDED && run.status() != BatchIngestionStatus.FAILED &&
run.status() != BatchIngestionStatus.CANCELED)
run = batches.observe(verified, run.runId(), new BatchObservationCommand(run.version()));
if (run.status() == BatchIngestionStatus.SUCCEEDED) {
var validation = batches.validateArrival(verified, run.runId(),
"unified-refresh-" + command.collectionId() + "-" + command.itemId(),
new BatchArrivalValidationCommand("统一采集集合状态与指标回收"));
var item = collections.detail(verified.batchActor(), command.collectionId()).items().stream()
.filter(i -> i.itemId() == command.itemId()).findFirst().orElseThrow();
recordByteEvidence(verified.batchActor(), item, run, validation);
String orchestrationKey = "collection-" + command.collectionId() + "-item-" + command.itemId()
+ "-run-" + run.runId();
try {
if (metadataOrchestration != null) {
log.info("Metadata orchestration invoke started; collectionId={}, itemId={}, runId={}, key={}, stage={}",
command.collectionId(), command.itemId(), run.runId(), orchestrationKey, "ensure-and-run");
var orchestration = metadataOrchestration.ensureAndRun(verified.batchActor().actorId(), verified.batchActor().orgScopeId(),
item.sourceId(), item.sourceVersion(), item.sourceDatabase(), item.sourceTable(),
orchestrationKey, command.collectionId(), command.itemId(), run.runId());
log.info("Metadata orchestration result; collectionId={}, itemId={}, runId={}, key={}, outcome={}, stage={}, errorCode={}",
command.collectionId(), command.itemId(), run.runId(), orchestrationKey,
orchestration.status(), "ensure-and-run", orchestration.errorCode());
} else {
log.warn("Metadata orchestration unavailable; collectionId={}, itemId={}, runId={}, key={}, errorCode={}",
command.collectionId(), command.itemId(), run.runId(), orchestrationKey,
"METADATA_ORCHESTRATION_REFERENCE_UNAVAILABLE");
}
} catch (RuntimeException exception) {
// Preserve the terminal batch result; refresh retries the same stable orchestration key.
log.warn("Metadata orchestration deferred; collectionId={}, itemId={}, runId={}, key={}, errorCode={}, exceptionType={}",
command.collectionId(), command.itemId(), run.runId(), orchestrationKey,
safeMetadataError(exception), exception.getClass().getSimpleName());
}
}
boolean terminal = run.status() == BatchIngestionStatus.SUCCEEDED || run.status() == BatchIngestionStatus.FAILED ||
run.status() == BatchIngestionStatus.CANCELED;
collections.advance(command, terminal ? "DONE" : "OBSERVING", null, null, null, null);
}
private static String safeMetadataError(RuntimeException exception) {
return "METADATA_ORCHESTRATION_DEFERRED";
}
TargetPreparation prepareTarget(String itemKey, long resourceId, long spaceId, EngineType engine,
TargetEngine targetEngine, String targetTable, String layer,
long layerId, String catalog, String namespace,
boolean createTarget, SelectedFields selected) {
return prepareTarget(itemKey, resourceId, spaceId, engine, targetEngine, targetTable, layer, layerId,
catalog, namespace, createTarget, selected, SourceTableComment.unknown());
}
TargetPreparation prepareTarget(String itemKey, long resourceId, long spaceId, EngineType engine,
TargetEngine targetEngine, String targetTable, String layer,
long layerId, String catalog, String namespace,
boolean createTarget, SelectedFields selected, SourceTableComment tableComment) {
try {
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) {
if (!createTarget) throw exception;
}
// Only actual creation needs comment authority. Existing compatible tables above remain untouched.
String physicalComment = requireTableComment(tableComment);
for (int index = 0; index < selected.sourceColumns().size(); index++) {
Column source = selected.sourceColumns().get(index);
BatchTargetTypePolicy.requireSourceComment(source);
if (!sameDefinition(BatchTargetTypePolicy.propose(source, targetEngine), selected.targetColumns().get(index), true))
throw BatchIngestionException.validation("字段“" + source.name() + "”的建表定义或注释已偏离源结构,请重新生成草稿");
}
if (layerId <= 0) throw BatchIngestionException.conflict("目标分层尚未确认,请重新选择入仓位置");
var operation = tables.create(itemKey + "-table", new CreateCommand(targetTable, ObjectType.TABLE,
layerId, resourceId, spaceId, engine,
engine == EngineType.HIVE ? StorageFormat.ORC : StorageFormat.DORIS_NATIVE,
catalog, namespace, null, layer + " 数据采集目标表",
selected.targetColumns(), null, null, physicalComment));
var created = operation.result().tableFile();
String state = created.executionState().name();
boolean retryable = targetCreateRetryable(operation.retryable(), created.executionState(),
created.errorCode());
if (created.executionState() != ExecutionState.CONFIRMED) {
if (created.executionState() != ExecutionState.REJECTED) {
try {
var observed = tables.targetDirectory(resourceId, spaceId, engine, targetTable, null, 1, 20);
BatchTargetWizardService.matchColumns(selected.sourceColumns(), observed, targetEngine);
return new TargetPreparation(observed, operation, operation.requestId(),
ExecutionState.CONFIRMED.name(), false);
} catch (BatchIngestionException exception) {
throw exception;
} catch (RuntimeException ignored) {
// Preserve the original non-terminal operation when exact external readback is also unavailable.
}
}
return new TargetPreparation(null, operation, operation.requestId(), state, retryable);
}
var confirmed = tables.targetDirectory(resourceId, spaceId, engine, targetTable, null, 1, 20);
BatchTargetWizardService.matchColumns(selected.sourceColumns(), confirmed, targetEngine);
return new TargetPreparation(confirmed, operation, operation.requestId(), state, retryable);
}
// Historical read-only callers may inspect an existing target; creation always requires a real layer.
TargetPreparation prepareTarget(String itemKey, long resourceId, long spaceId, EngineType engine,
TargetEngine targetEngine, String targetTable, String layer,
boolean createTarget, SelectedFields selected) {
return prepareTarget(itemKey, resourceId, spaceId, engine, targetEngine, targetTable, layer,
0L, null, null, createTarget, selected);
}
static boolean targetCreateRetryable(boolean operationRetryable, ExecutionState state, String errorCode) {
return operationRetryable || state == ExecutionState.RETRYABLE || state == ExecutionState.UNKNOWN ||
"HIVE_TEMPORAL_PRECISION_UNSUPPORTED".equals(errorCode);
}
record TargetPreparation(
cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryResult target,
OperationView operation, String requestId, String state, boolean retryable) { }
private void verifySource(BatchActor actor, long sourceId, long expected, String sourceName,
String sourceDatabase) {
var result = sources.sources(actor.actorId(), actor.orgScopeId(), List.of(sourceId), null, 1);
if (result == null || !"AVAILABLE".equals(result.status()) || result.entries() == null || result.entries().size() != 1 ||
result.entries().getFirst() == null || !Long.valueOf(sourceId).equals(result.entries().getFirst().id()) ||
"PAUSED".equals(result.entries().getFirst().status()) || "CANCELED".equals(result.entries().getFirst().status()) ||
result.entries().getFirst().version() != expected ||
!sourceName.equals(result.entries().getFirst().name()) ||
!sourceDatabase.equals(result.entries().getFirst().databaseName()))
throw BatchIngestionException.conflict("数据源版本已变化,请刷新后重试");
}
private long verifyTargetVersion(BatchActor actor, SubmitRequest request) {
var detail = storage.detailForIngestion(actor.actorId(), actor.orgScopeId(), request.targetResourceId());
if (!detail.resource().enabled() || detail.resource().version() != request.targetResourceVersion() ||
detail.resource().resourceType() != request.targetType() || detail.accessProfile() == null ||
!detail.accessProfile().credentialConfigured() || detail.spaces().stream().noneMatch(space ->
space.spaceId().equals(request.targetSpaceId()) && space.version() == request.targetSpaceVersion() && space.enabled()))
throw BatchIngestionException.conflict("目标资源或数据库版本已变化,请刷新后重试");
return detail.accessProfile().version();
}
private static void validateNewCommand(SubmitRequest request) {
for (var item : request.items()) {
if (item.sourceFingerprint() == null || !item.sourceFingerprint().matches("[a-f0-9]{64}") ||
item.columns() == null || item.columns().isEmpty() || item.columns().size() > 100 ||
item.columns().stream().anyMatch(java.util.Objects::isNull) ||
item.mappings() == null || item.mappings().isEmpty() || item.mappings().size() > 100 ||
item.mappings().stream().anyMatch(java.util.Objects::isNull))
throw BatchIngestionException.validation("逐表配置不完整");
}
}
private cn.aixunkeji.datagov.integration.api.tablefile.UnifiedIngestionSourceService.SchemaResult schema(
BatchActor actor, long sourceId, String catalog, String table) {
var result = sources.schema(actor.actorId(), actor.orgScopeId(), positive(sourceId, "数据源ID"),
identifier(catalog, "源数据库"), sourceTable(table));
if (result == null || !"AVAILABLE".equals(result.status()) || result.columns() == null || result.columns().isEmpty())
throw BatchIngestionException.external(result == null ? "源结构暂不可读取" : result.errorSummary());
return result;
}
private static cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryColumn directoryColumn(
ColumnDefinition column) {
String type = column.type().name() + (column.precision() == null ? "" : column.scale() == null
? "(" + column.precision() + ")" : "(" + column.precision() + "," + column.scale() + ")");
if (column.type() == cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.ColumnType.DATETIME)
type = "DATETIME(" + (column.scale() == null ? 0 : column.scale()) + ")";
return new cn.aixunkeji.datagov.integration.api.tablefile.TableFileIntegrationService.DirectoryColumn(
column.name(), type, column.precision() == null ? 0 : column.precision(),
column.scale() == null ? 0 : column.scale(), column.nullable());
}
private static String fingerprint(long sourceId, String catalog, String table, Object columns, SourceTableComment comment) {
return BatchIngestionPolicy.sha256(sourceId + "|" + catalog + "|" + table + "|" + columns + "|" + comment);
}
static String requireTableComment(SourceTableComment comment) {
if (comment == null || comment.state() == cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.CommentState.UNKNOWN ||
comment.state() == cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.CommentState.UNSUPPORTED)
throw BatchIngestionException.validation("源表注释无法原样保留,请重新读取结构或选择已有目标表");
return comment.value();
}
static String taskName(String baseName, String sourceTable, String itemKey) {
String descriptive = baseName + "-" + sourceTable;
String suffix = "-" + itemKey.substring(0, 8);
return descriptive.substring(0, Math.min(descriptive.length(), 96 - suffix.length())) + suffix;
}
static SelectedFields selectedFields(List<Column> current, SubmitItem item, StorageResourceType targetType) {
if (current == null || current.isEmpty() || item == null || item.columns() == null ||
item.mappings() == null || item.mappings().isEmpty() || item.mappings().size() > 100 ||
item.columns().size() != item.mappings().size())
throw BatchIngestionException.validation("请至少选择一个字段,且字段定义必须与映射一一对应");
Map<String, Column> sourceByName = new LinkedHashMap<>();
for (Column column : current) {
if (column == null || sourceByName.putIfAbsent(normalized(column.name()), column) != null)
throw BatchIngestionException.validation("源结构存在重复或无效字段,请重新读取结构");
}
Map<String, ColumnDefinition> targetByName = new LinkedHashMap<>();
for (ColumnDefinition column : item.columns()) {
if (column == null || column.type() == null ||
targetByName.putIfAbsent(normalized(identifier(column.name(), "目标字段")), column) != null)
throw BatchIngestionException.validation("目标字段重复或定义不完整,请重新选择字段");
}
Set<String> selectedSources = new HashSet<>();
Set<String> selectedTargets = new HashSet<>();
List<Column> sourceColumns = new ArrayList<>();
List<ColumnDefinition> targetColumns = new ArrayList<>();
for (BatchFieldMappingCommand mapping : item.mappings()) {
if (mapping == null || mapping.transform() != BatchFieldTransform.NONE || mapping.defaultValue() != null ||
mapping.filterOperator() != null || mapping.filterValues() == null || !mapping.filterValues().isEmpty())
throw BatchIngestionException.validation("统一采集字段仅支持原样写入,请重新生成映射");
String sourceName = identifier(mapping.sourceField(), "源字段");
String targetName = identifier(mapping.targetField(), "目标字段");
if (!selectedSources.add(normalized(sourceName)) || !selectedTargets.add(normalized(targetName)))
throw BatchIngestionException.validation("源字段或目标字段不能重复");
Column source = sourceByName.get(normalized(sourceName));
ColumnDefinition target = targetByName.get(normalized(targetName));
if (source == null) throw BatchIngestionException.conflict("源字段“" + sourceName + "”已不存在,请重新生成映射");
if (target == null) throw BatchIngestionException.validation("目标字段“" + targetName + "”缺少定义,请重新选择字段");
TargetEngine engine = targetEngine(targetType);
var mapped = BatchTargetTypePolicy.canonical(source, engine);
ColumnDefinition proposed = BatchTargetTypePolicy.propose(source, engine);
BatchTargetTypePolicy.requireFits(proposed, target);
if (item.createTarget() && !sameDefinition(proposed, target, false))
throw BatchIngestionException.validation("字段“" + sourceName + "”的建表类型已偏离当前统一映射,请重新生成草稿");
if (!BatchTargetTypePolicy.declaredTypeMatches(mapped.targetType(), mapping.sourceType()) ||
!BatchTargetTypePolicy.declaredTypeMatches(mapped.targetType(), mapping.targetType()))
throw BatchIngestionException.validation("字段“" + sourceName + "”的映射类型与当前结构不一致,请重新生成映射");
sourceColumns.add(source);
targetColumns.add(target);
}
if (selectedTargets.size() != targetByName.size())
throw BatchIngestionException.validation("存在未映射的目标字段定义,请重新选择字段");
if (targetType == StorageResourceType.DORIS &&
Set.of(ColumnType.FLOAT, ColumnType.DOUBLE, ColumnType.STRING).contains(targetColumns.getFirst().type()))
throw BatchIngestionException.validation("Doris目标首列需为整数、日期或定长字段,请调整所选字段顺序");
return new SelectedFields(List.copyOf(sourceColumns), List.copyOf(targetColumns), List.copyOf(item.mappings()));
}
record SelectedFields(List<Column> sourceColumns, List<ColumnDefinition> targetColumns,
List<BatchFieldMappingCommand> mappings) { }
private static boolean sameDefinition(ColumnDefinition expected, ColumnDefinition actual, boolean compareComment) {
return expected.name().equals(actual.name()) && expected.type() == actual.type() &&
expected.nullable().equals(actual.nullable()) && java.util.Objects.equals(expected.precision(), actual.precision()) &&
java.util.Objects.equals(expected.scale(), actual.scale()) &&
(!compareComment || java.util.Objects.equals(expected.comment(), actual.comment()));
}
private static TargetEngine targetEngine(StorageResourceType type) {
try { return TargetEngine.valueOf(type.name()); }
catch (RuntimeException exception) { throw BatchIngestionException.validation("请选择Hive或Doris目标"); }
}
private static void validateSubmit(SubmitRequest request) {
if (request == null || request.name() == null || request.name().isBlank() || request.name().length() > 96 ||
request.targetResourceId() <= 0 || request.targetResourceVersion() < 0 ||
request.targetSpaceId() <= 0 || request.targetSpaceVersion() < 0 ||
request.targetType() == null || request.layer() == null || request.items() == null ||
request.items().isEmpty() || request.items().size() > 50)
throw BatchIngestionException.validation("采集提交参数不完整");
Set<String> unique = new HashSet<>();
for (SubmitItem item : request.items()) {
if (item == null) throw BatchIngestionException.validation("逐表来源参数不完整");
SourceSelection source = validateSourceSelection(new SourceSelection(item.sourceId(), item.sourceVersion(),
item.sourceName(), item.sourceDatabase(), item.sourceTable()));
identifier(item.targetTable(), "目标表");
String identity = source.sourceId() + "|" + source.sourceDatabase().toLowerCase(Locale.ROOT) + "|" +
source.table().toLowerCase(Locale.ROOT);
if (!unique.add(identity)) throw BatchIngestionException.validation("同一数据源的源表不能重复");
}
}
private static SourceSelection validateSourceSelection(SourceSelection item) {
if (item == null || item.sourceId() <= 0 || item.sourceVersion() < 0 || item.sourceName() == null ||
item.sourceName().isBlank() || item.sourceName().length() > 128 ||
item.sourceName().chars().anyMatch(Character::isISOControl))
throw BatchIngestionException.validation("逐表来源参数不完整");
return new SourceSelection(item.sourceId(), item.sourceVersion(), item.sourceName().trim(),
identifier(item.sourceDatabase(), "源数据库"), sourceTable(item.table()));
}
private static String sourceTable(String value) {
if (value == null || !value.matches("[A-Za-z_][A-Za-z0-9_$]{0,127}(?:\\.[A-Za-z_][A-Za-z0-9_$]{0,127})?"))
throw BatchIngestionException.validation("请选择有效的源表");
return value;
}
public CollectionPage collections(String keyword, CollectionStatus status, int pageNum, int pageSize) {
return collections.page(actors.current(), optionalKeyword(keyword), status, page(pageNum), size(pageSize));
}
public CollectionDetail collection(long collectionId) {
return collections.detail(actors.current(), positive(collectionId, "采集集合ID"));
}
public CollectionDetail refreshCollection(long collectionId) {
BatchActor actor = actors.current();
long normalizedId = positive(collectionId, "采集集合ID");
collections.requestObservation(actor, normalizedId);
return collections.detail(actor, normalizedId);
}
private void recordByteEvidence(BatchActor actor, CollectionItem item, BatchRunView run,
BatchArrivalValidationView validation) {
String evidenceRef = validation.evidenceRef();
Matcher matcher = evidenceRef == null ? null : BYTE_EVIDENCE.matcher(evidenceRef);
boolean observed = matcher != null && matcher.matches() &&
matcher.group(1).equals(run.externalJobId());
Long value = observed ? Long.valueOf(matcher.group(2)) : null;
collections.recordBytes(actor, item.itemId(), run.runId(), new ByteMetricObservation(value,
observed ? MetricStatus.OBSERVED : MetricStatus.UNKNOWN,
observed ? MetricSourceType.EXTERNAL_ENGINE : MetricSourceType.INTEGRATION,
"seatunnel-job-info", validation.evidenceAt() == null ? validation.createdAt() : validation.evidenceAt(),
evidenceRef, observed ? null : "SEATUNNEL_BYTE_METRIC_UNAVAILABLE",
observed ? null : "SeaTunnel未提供可归属当前作业的目标字节指标"));
}
public void recordBytes(long itemId, long runId, ByteMetricObservation observation) {
collections.recordBytes(actors.current(), positive(itemId, "采集子项ID"), positive(runId, "运行ID"), observation);
}
private static SubmitResult toSubmitResult(CollectionDetail detail, boolean replayed) {
List<SubmitItemResult> items = detail.items().stream().map(item -> new SubmitItemResult(
item.sourceId(), item.sourceVersion(), item.sourceName(), item.sourceDatabase(), item.sourceTable(),
item.targetTable(), item.status(), item.taskId(), item.runId(), item.externalJobId(), item.errorCode(),
item.errorSummary(), item.targetCreateRequestId(), item.targetCreateState(), item.targetDatabase(),
item.layerId(), item.layerName(), item.retryable()
)).toList();
return new SubmitResult(detail.collectionId(), detail.status(), items, detail.accepted(), detail.failed(),
detail.submittedAt(), replayed);
}
private static long positive(long value, String label) {
if (value <= 0) throw BatchIngestionException.validation(label + "无效");
return value;
}
private static String identifier(String value, String label) {
if (value == null || !value.matches("[A-Za-z_][A-Za-z0-9_$]{0,127}"))
throw BatchIngestionException.validation(label + "无效");
return value;
}
private static String normalized(String value) {
return identifier(value, "字段").toLowerCase(Locale.ROOT);
}
private static String optionalKeyword(String value) {
if (value == null || value.isBlank()) return null;
if (value.length() > 64 || value.chars().anyMatch(Character::isISOControl))
throw BatchIngestionException.validation("关键词无效");
return value.trim();
}
private static int page(int value) { return Math.max(1, value); }
private static int size(int value) {
if (value < 1 || value > 100) throw BatchIngestionException.validation("分页大小无效");
return value;
}
}
@@ -0,0 +1,28 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceDirectoryService;
import cn.aixunkeji.datagov.integration.api.tablefile.UnifiedIngestionSourceService;
import java.util.List;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
class UnifiedIngestionSourceGateway {
@DubboReference(check = false, timeout = 3_000, retries = 0)
private DataSourceDirectoryService directory;
@DubboReference(check = false, timeout = 8_000, retries = 0,
version = UnifiedIngestionSourceService.VERSION, group = UnifiedIngestionSourceService.GROUP)
private UnifiedIngestionSourceService objects;
DataSourceDirectoryService.Result sources(long actorId, long orgId, List<Long> ids, String keyword, int limit) {
return directory.query(actorId, orgId, ids, keyword, limit);
}
UnifiedIngestionSourceService.DirectoryResult tables(long actorId, long orgId, long sourceId,
String catalog, String keyword, int pageNum, int pageSize) {
return objects.tables(actorId, orgId, sourceId, catalog, keyword, pageNum, pageSize);
}
UnifiedIngestionSourceService.SchemaResult schema(long actorId, long orgId, long sourceId,
String catalog, String table) {
return objects.schema(actorId, orgId, sourceId, catalog, table);
}
}
@@ -0,0 +1,52 @@
package cn.aixunkeji.datagov.dataops.batchingestion;
/** Internal, non-serializable scope. Only the command authority can issue it inside this package. */
public final class VerifiedIngestionCommandActor {
private final long actorId;
private final long orgId;
private final boolean observing;
private final Runnable recheck;
private final SourceSchema sourceSchema;
private record SourceSchema(long id, String database, String table,
java.util.List<cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column> columns) { }
VerifiedIngestionCommandActor(long actorId, long orgId, boolean observing, Runnable recheck) {
this(actorId, orgId, observing, recheck, null);
}
private VerifiedIngestionCommandActor(long actorId, long orgId, boolean observing, Runnable recheck, SourceSchema sourceSchema) {
this.actorId = actorId;
this.orgId = orgId;
this.observing = observing;
this.recheck = recheck;
this.sourceSchema = sourceSchema;
}
public long actorId() { return actorId; }
VerifiedIngestionCommandActor withOwnerCheck(Runnable ownerCheck) {
return new VerifiedIngestionCommandActor(actorId, orgId, observing, () -> {
recheck.run();
ownerCheck.run();
}, sourceSchema);
}
VerifiedIngestionCommandActor withSourceSchema(long id, String database, String table,
java.util.List<cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column> columns) {
checkSubmit();
return new VerifiedIngestionCommandActor(actorId, orgId, observing, recheck,
new SourceSchema(id, database, table, java.util.List.copyOf(columns)));
}
java.util.List<cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column> sourceSchema(
long id, String database, String table) {
checkSubmit();
return sourceSchema != null && sourceSchema.id() == id && java.util.Objects.equals(sourceSchema.database(), database)
&& java.util.Objects.equals(sourceSchema.table(), table) ? sourceSchema.columns() : null;
}
public long orgId() { return orgId; }
public void check() { recheck.run(); }
public void checkSubmit() {
if (observing) throw BatchIngestionException.forbidden();
recheck.run();
}
BatchActor batchActor() { return new BatchActor(actorId, orgId); }
}
@@ -0,0 +1,20 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class BatchJobActorProvider {
BatchJobActor current() {
Long actorId = LoginHelper.getUserId();
Long orgId = LoginHelper.getDeptId();
if (actorId == null || orgId == null || actorId <= 0 || orgId <= 0) {
throw BatchJobDomainException.forbidden();
}
return new BatchJobActor(actorId, orgId, LoginHelper.isSuperAdmin(actorId));
}
record BatchJobActor(long actorId, long orgId, boolean unrestricted) {
}
}
@@ -0,0 +1,116 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.PageResult;
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.dataops.api.batchjob.BatchJobApi.BatchJobCreateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobDeleteRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobParameterRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobReadyRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobUpdateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/batch-jobs")
public class BatchJobController {
private final BatchJobService service;
@SaCheckPermission("aixun:dataops:batch-job:view")
@GetMapping("/source-fields")
public R<java.util.List<String>> sourceFields(@RequestParam Long dataSourceId,
@RequestParam Long sourceVersion, @RequestParam String database, @RequestParam String table) {
return R.ok(service.sourceFields(new cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.MySqlSource(
dataSourceId, sourceVersion, database, table)));
}
@SaCheckPermission("aixun:dataops:batch-job:view")
@GetMapping
public R<PageResult<BatchJobView>> list(
@RequestParam(required = false) String keyword,
@RequestParam(required = false) String status,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.list(keyword, status, pageNum, pageSize));
}
@SaCheckPermission("aixun:dataops:batch-job:view")
@GetMapping("/{jobId}")
public R<BatchJobView> get(@PathVariable long jobId) {
return R.ok(service.get(jobId));
}
@Log(title = "批处理作业创建", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-job:create")
@PostMapping
public R<BatchJobView> create(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchJobCreateRequest request
) {
return R.ok(service.create(idempotencyKey, request));
}
@Log(title = "批处理作业更新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-job:update")
@PutMapping("/{jobId}")
public R<BatchJobView> update(
@PathVariable long jobId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchJobUpdateRequest request
) {
return R.ok(service.update(jobId, idempotencyKey, request));
}
@Log(title = "批处理作业参数更新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-job:parameter")
@PutMapping("/{jobId}/parameters")
public R<BatchJobView> updateParameters(
@PathVariable long jobId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchJobParameterRequest request
) {
return R.ok(service.updateParameters(jobId, idempotencyKey, request));
}
@Log(title = "批处理作业就绪校验", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-job:validate")
@PostMapping("/{jobId}/validate")
public R<BatchJobView> validateReady(
@PathVariable long jobId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchJobReadyRequest request
) {
return R.ok(service.validateReady(jobId, idempotencyKey, request));
}
@Log(title = "批处理作业删除", businessType = BusinessType.DELETE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:batch-job:delete")
@DeleteMapping("/{jobId}")
public R<BatchJobView> delete(
@PathVariable long jobId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody BatchJobDeleteRequest request
) {
return R.ok(service.delete(jobId, idempotencyKey, request));
}
}
@@ -0,0 +1,34 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobStatus;
import org.springframework.stereotype.Component;
/** Owner-side data-testing reference. It returns only an immutable definition identity. */
@Component
public class BatchJobDataTestingReferenceDirectory {
private final BatchJobJdbcRepository repository;
BatchJobDataTestingReferenceDirectory(BatchJobJdbcRepository repository) {
this.repository = repository;
}
public Resolution resolve(long actorId, long orgId, boolean unrestricted, long jobId) {
try {
BatchJobView job = repository.require(new BatchJobActorProvider.BatchJobActor(actorId, orgId, unrestricted), jobId);
if (job.status() != JobStatus.READY) return Resolution.notExecutable();
return new Resolution(State.AUTHORIZED, job.jobId(), String.valueOf(job.version()),
job.definitionSha256());
} catch (RuntimeException exception) {
return Resolution.unavailable();
}
}
public enum State { AUTHORIZED, NOT_EXECUTABLE, UNAVAILABLE }
public record Resolution(State state, Long referenceId, String ownerVersion, String ownerSha256) {
static Resolution notExecutable() { return new Resolution(State.NOT_EXECUTABLE, null, null, null); }
static Resolution unavailable() { return new Resolution(State.UNAVAILABLE, null, null, null); }
}
}
@@ -0,0 +1,53 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import org.springframework.http.HttpStatus;
final class BatchJobDomainException extends RuntimeException {
static final int VALIDATION_CODE = 120401;
static final int FORBIDDEN_CODE = 120403;
static final int NOT_FOUND_CODE = 120404;
static final int CONFLICT_CODE = 120409;
static final int REFERENCE_UNAVAILABLE_CODE = 120450;
private final int code;
private final HttpStatus status;
private BatchJobDomainException(int code, HttpStatus status, String message) {
super(message);
this.code = code;
this.status = status;
}
static BatchJobDomainException validation(String message) {
return new BatchJobDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static BatchJobDomainException forbidden() {
return new BatchJobDomainException(FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问批处理作业");
}
static BatchJobDomainException notFound() {
return new BatchJobDomainException(NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "批处理作业不存在");
}
static BatchJobDomainException conflict(String message) {
return new BatchJobDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
static BatchJobDomainException referenceUnavailable() {
return new BatchJobDomainException(
REFERENCE_UNAVAILABLE_CODE,
HttpStatus.SERVICE_UNAVAILABLE,
"表文件校验暂不可用,写入已拒绝"
);
}
int code() {
return code;
}
HttpStatus status() {
return status;
}
}
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes = BatchJobController.class)
class BatchJobExceptionHandler {
@ExceptionHandler(BatchJobDomainException.class)
ResponseEntity<R<Void>> handle(BatchJobDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,27 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.R;
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/batch-jobs")
public class BatchJobExecutionController {
private final BatchJobActorProvider actors;
private final BatchJobScheduledExecution executions;
@GetMapping("/{jobId}/executions")
@SaCheckPermission("aixun:dataops:batch-job:view")
public R<List<BatchJobScheduledExecution.ExecutionView>> list(@PathVariable long jobId) {
return R.ok(executions.history(actors.current(), jobId, null));
}
@GetMapping("/{jobId}/executions/{executionId}")
@SaCheckPermission("aixun:dataops:batch-job:view")
public R<BatchJobScheduledExecution.ExecutionView> get(@PathVariable long jobId, @PathVariable long executionId) {
var rows = executions.history(actors.current(), jobId, executionId);
if (rows.isEmpty()) throw BatchJobDomainException.notFound();
return R.ok(rows.getFirst());
}
}
@@ -0,0 +1,501 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.ExecutionEngine;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobParameters;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobStatus;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SinkDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SourceDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.TransformDefinition;
import cn.aixunkeji.datagov.dataops.api.datatesting.DataTestingApi.OwnerType;
import cn.aixunkeji.datagov.dataops.api.scheduling.SchedulingApi.NodeType;
import cn.aixunkeji.datagov.dataops.batchjob.BatchJobActorProvider.BatchJobActor;
import cn.aixunkeji.datagov.dataops.batchjob.BatchJobModel.Definition;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.databind.JsonNode;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
@Repository
@RequiredArgsConstructor
class BatchJobJdbcRepository {
private static final String COLUMNS = """
job_id, job_name, org_id, project_id, project_code, data_domain_code,
environment_id, environment_code, execution_engine, source_json, transform_json,
sink_json, parameters_json, definition_sha256, job_status, version, create_time, update_time
""";
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
private final BatchJobPolicy policy;
PageResult<BatchJobView> page(
BatchJobActor actor,
String keyword,
JobStatus status,
int pageNum,
int pageSize
) {
StringBuilder where = new StringBuilder(" WHERE j.del_flag='0' AND j.org_id=?");
List<Object> arguments = new ArrayList<>();
arguments.add(actor.orgId());
if (!actor.unrestricted()) {
where.append(" AND j.create_by=?");
arguments.add(actor.actorId());
}
if (keyword != null) {
where.append(" AND j.job_name LIKE ? ESCAPE '='");
String contains = "%" + keyword.replace("=", "==").replace("%", "=%").replace("_", "=_") + "%";
arguments.add(contains);
}
if (status != null) {
where.append(" AND j.job_status=?");
arguments.add(status.name());
}
Long total = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM dev_batch_job j" + where,
Long.class,
arguments.toArray()
);
List<Object> pageArguments = new ArrayList<>(arguments);
pageArguments.add(pageSize);
pageArguments.add((pageNum - 1) * pageSize);
List<BatchJobView> rows = jdbcTemplate.query(
"SELECT " + COLUMNS + " FROM dev_batch_job j" + where +
" ORDER BY j.update_time DESC, j.job_id DESC LIMIT ? OFFSET ?",
(resultSet, rowNum) -> map(resultSet),
pageArguments.toArray()
);
return PageResult.build(rows, total == null ? 0 : total);
}
BatchJobView require(BatchJobActor actor, long jobId) {
return require(actor, jobId, false);
}
private BatchJobView require(BatchJobActor actor, long jobId, boolean lock) {
StringBuilder sql = new StringBuilder(
"SELECT " + COLUMNS + " FROM dev_batch_job j WHERE j.job_id=? AND j.org_id=? AND j.del_flag='0'"
);
List<Object> arguments = new ArrayList<>();
arguments.add(jobId);
arguments.add(actor.orgId());
if (!actor.unrestricted()) {
sql.append(" AND j.create_by=?");
arguments.add(actor.actorId());
}
if (lock) {
sql.append(" FOR UPDATE");
}
List<BatchJobView> rows = jdbcTemplate.query(sql.toString(), (resultSet, rowNum) -> map(resultSet), arguments.toArray());
if (!rows.isEmpty()) {
return rows.getFirst();
}
Integer existing = jdbcTemplate.queryForObject(
"SELECT COUNT(*) FROM dev_batch_job WHERE job_id=? AND del_flag='0'",
Integer.class,
jobId
);
if (existing != null && existing > 0) {
throw BatchJobDomainException.forbidden();
}
throw BatchJobDomainException.notFound();
}
BatchJobView create(
BatchJobActor actor,
String idempotencyKey,
String requestHash,
Definition definition,
String definitionSha256
) {
return idempotent(actor, "POST", "/api/dataops/v1/batch-jobs", idempotencyKey, requestHash, () -> {
long jobId = IdGeneratorUtil.nextLongId();
try {
jdbcTemplate.update("""
INSERT INTO dev_batch_job(
job_id, job_name, org_id, project_id, project_code, data_domain_code,
environment_id, environment_code, execution_engine, source_json, transform_json,
sink_json, parameters_json, definition_sha256, job_status, active_marker,
create_dept, create_by, create_time, update_by, update_time, del_flag, version
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'DRAFT', '1', ?, ?, NOW(), ?, NOW(), '0', 0)
""",
jobId, definition.name(), actor.orgId(), null, null,
definition.dataDomainCode(), null, null,
definition.executionEngine().name(), policy.json(definition.source()), policy.json(definition.transform()),
policy.json(definition.sink()), policy.json(definition.parameters()), definitionSha256,
actor.orgId(), actor.actorId(), actor.actorId()
);
} catch (DuplicateKeyException exception) {
throw BatchJobDomainException.conflict("当前组织内已存在同名批处理作业");
}
BatchJobView result = require(actor, jobId);
insertSnapshot(actor, result, "CREATE");
return result;
});
}
BatchJobView update(
BatchJobActor actor,
long jobId,
String idempotencyKey,
String requestHash,
Definition definition,
String definitionSha256,
long expectedVersion
) {
String path = "/api/dataops/v1/batch-jobs/" + jobId;
return idempotent(actor, "PUT", path, idempotencyKey, requestHash, () -> {
requireDraft(require(actor, jobId));
int changed;
try {
changed = jdbcTemplate.update("""
UPDATE dev_batch_job
SET job_name=?, project_id=?, project_code=?, data_domain_code=?, environment_id=?,
environment_code=?, execution_engine=?, source_json=?, transform_json=?, sink_json=?,
parameters_json=?, definition_sha256=?, update_by=?, update_time=NOW(), version=version+1
WHERE job_id=? AND org_id=? AND (create_by=? OR ?=1) AND job_status='DRAFT'
AND version=? AND del_flag='0'
""",
definition.name(), null, null, definition.dataDomainCode(),
null, null, definition.executionEngine().name(),
policy.json(definition.source()), policy.json(definition.transform()), policy.json(definition.sink()),
policy.json(definition.parameters()), definitionSha256, actor.actorId(), jobId, actor.orgId(),
actor.actorId(), actor.unrestricted() ? 1 : 0, expectedVersion
);
} catch (DuplicateKeyException exception) {
throw BatchJobDomainException.conflict("当前组织内已存在同名批处理作业");
}
requireChanged(changed);
BatchJobView result = require(actor, jobId);
insertSnapshot(actor, result, "UPDATE");
return result;
});
}
BatchJobView updateParameters(
BatchJobActor actor,
long jobId,
String idempotencyKey,
String requestHash,
JobParameters parameters,
String definitionSha256,
long expectedVersion
) {
String path = "/api/dataops/v1/batch-jobs/" + jobId + "/parameters";
return idempotent(actor, "PUT", path, idempotencyKey, requestHash, () -> {
requireDraft(require(actor, jobId));
int changed = jdbcTemplate.update("""
UPDATE dev_batch_job
SET parameters_json=?, definition_sha256=?, update_by=?, update_time=NOW(), version=version+1
WHERE job_id=? AND org_id=? AND (create_by=? OR ?=1) AND job_status='DRAFT'
AND version=? AND del_flag='0'
""", policy.json(parameters), definitionSha256, actor.actorId(), jobId, actor.orgId(), actor.actorId(),
actor.unrestricted() ? 1 : 0, expectedVersion);
requireChanged(changed);
BatchJobView result = require(actor, jobId);
insertSnapshot(actor, result, "PARAMETER");
return result;
});
}
BatchJobView markReady(
BatchJobActor actor,
long jobId,
String idempotencyKey,
String requestHash,
long expectedVersion
) {
String path = "/api/dataops/v1/batch-jobs/" + jobId + "/validate";
return idempotent(actor, "POST", path, idempotencyKey, requestHash, () -> {
requireDraft(require(actor, jobId));
int changed = jdbcTemplate.update("""
UPDATE dev_batch_job
SET job_status='READY', update_by=?, update_time=NOW(), version=version+1
WHERE job_id=? AND org_id=? AND (create_by=? OR ?=1) AND job_status='DRAFT'
AND version=? AND del_flag='0'
""", actor.actorId(), jobId, actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0,
expectedVersion);
requireChanged(changed);
BatchJobView result = require(actor, jobId);
insertSnapshot(actor, result, "READY");
return result;
});
}
BatchJobView delete(
BatchJobActor actor,
long jobId,
String idempotencyKey,
String requestHash,
long expectedVersion
) {
String path = "/api/dataops/v1/batch-jobs/" + jobId;
return idempotent(actor, "DELETE", path, idempotencyKey, requestHash, () -> {
// Consumers accept READY only, and READY never returns to DRAFT. Locking the
// owner row serializes deletion with edits and the conditional READY update.
BatchJobView before = require(actor, jobId, true);
if (before.version() != expectedVersion) {
throw BatchJobDomainException.conflict("作业版本已变化,请刷新后重试");
}
if (before.status() != JobStatus.DRAFT) {
throw BatchJobDomainException.conflict("作业已就绪,不能删除");
}
requireNoDeletionReferences(actor, jobId);
int changed = jdbcTemplate.update("""
UPDATE dev_batch_job
SET active_marker=NULL, del_flag='1', update_by=?, update_time=NOW(), version=version+1
WHERE job_id=? AND org_id=? AND (create_by=? OR ?=1) AND job_status='DRAFT'
AND version=? AND del_flag='0'
""", actor.actorId(), jobId, actor.orgId(), actor.actorId(), actor.unrestricted() ? 1 : 0,
expectedVersion);
requireChanged(changed);
insertSnapshot(actor, before, "DELETE", before.version() + 1);
return before;
});
}
private void requireNoDeletionReferences(BatchJobActor actor, long jobId) {
try {
// Creation and draft edits remain as audit evidence and do not block deletion.
refuseDeletionIfPresent("""
SELECT EXISTS (
SELECT 1 FROM dev_batch_job_snapshot
WHERE org_id=? AND job_id=? AND snapshot_kind NOT IN ('CREATE', 'UPDATE', 'PARAMETER')
)
""", "作业存在就绪或其他不可删除的历史记录", actor.orgId(), jobId);
refuseDeletionIfPresent("""
SELECT EXISTS (
SELECT 1 FROM dev_schedule_node_execution_evidence
WHERE org_id=? AND node_type='BATCH_JOB'
AND (reference_id=? OR reference_id IS NULL OR reference_id<=0)
)
""", "作业存在执行记录或执行关联无法确认,不能删除", actor.orgId(), jobId);
// A missing immutable snapshot must not turn an untraceable run into 'no history'.
refuseDeletionIfPresent("""
SELECT EXISTS (
SELECT 1 FROM dev_schedule_run_request r
WHERE r.org_id=? AND NOT EXISTS (
SELECT 1 FROM dev_schedule_snapshot s
WHERE s.snapshot_id=r.snapshot_id AND s.schedule_id=r.schedule_id AND s.org_id=r.org_id)
UNION ALL
SELECT 1 FROM dev_schedule_external_mapping m
WHERE m.org_id=? AND NOT EXISTS (
SELECT 1 FROM dev_schedule_snapshot s
WHERE s.snapshot_id=m.snapshot_id AND s.schedule_id=m.schedule_id AND s.org_id=m.org_id)
UNION ALL
SELECT 1 FROM dev_data_test_run_request r
WHERE r.org_id=? AND NOT EXISTS (
SELECT 1 FROM dev_data_test_snapshot s
WHERE s.snapshot_id=r.snapshot_id AND s.test_id=r.test_id AND s.org_id=r.org_id)
)
""", "提交或执行历史关联不完整,暂不能确认作业是否可删除",
actor.orgId(), actor.orgId(), actor.orgId());
// Never filter historical consumers by del_flag or by the deleting actor's visibility.
refuseDeletionIfPresent("""
SELECT EXISTS (
SELECT 1 FROM dev_schedule_node
WHERE org_id=? AND node_type='BATCH_JOB'
AND (reference_id=? OR reference_id IS NULL OR reference_id<=0)
UNION ALL
SELECT 1 FROM dev_data_test_definition
WHERE org_id=? AND owner_type='BATCH_JOB' AND target_id=?
)
""", "作业被调度或数据测试引用,不能删除", actor.orgId(), jobId, actor.orgId(), jobId);
// Parse each node as one object: separate type/ID contains checks can match different nodes.
jdbcTemplate.query("""
SELECT nodes_json FROM dev_schedule_definition WHERE org_id=?
UNION ALL
SELECT JSON_EXTRACT(definition_json, '$.nodes') AS nodes_json
FROM dev_schedule_snapshot WHERE org_id=?
""", resultSet -> {
JsonNode nodes = policy.read(resultSet.getString("nodes_json"), JsonNode.class);
if (nodes == null || !nodes.isArray() || nodes.isEmpty()) {
throw deletionHistoryUnavailable();
}
for (JsonNode node : nodes) {
String typeName = node.path("type").asText();
if (!node.isObject() || typeName == null) {
throw deletionHistoryUnavailable();
}
NodeType type = NodeType.valueOf(typeName);
if (type == NodeType.BATCH_JOB && referenceId(node.path("referenceId")) == jobId) {
throw BatchJobDomainException.conflict("作业被调度定义或历史快照引用,不能删除");
}
}
}, actor.orgId(), actor.orgId());
jdbcTemplate.query("""
SELECT definition_json FROM dev_data_test_snapshot WHERE org_id=?
""", resultSet -> {
JsonNode snapshot = policy.read(resultSet.getString("definition_json"), JsonNode.class);
if (snapshot == null || !snapshot.path("summary").isObject()) {
throw deletionHistoryUnavailable();
}
JsonNode summary = snapshot.path("summary");
String typeName = summary.path("ownerType").asText();
if (typeName == null) {
throw deletionHistoryUnavailable();
}
OwnerType type = OwnerType.valueOf(typeName);
long targetId = referenceId(summary.path("targetId"));
if (type == OwnerType.BATCH_JOB && targetId == jobId) {
throw BatchJobDomainException.conflict("作业被数据测试历史快照引用,不能删除");
}
}, actor.orgId());
} catch (DataAccessException | IllegalStateException | IllegalArgumentException exception) {
throw deletionHistoryUnavailable();
}
}
private void refuseDeletionIfPresent(String sql, String reason, Object... arguments) {
Boolean present = jdbcTemplate.queryForObject(sql, Boolean.class, arguments);
if (present == null) {
throw deletionHistoryUnavailable();
}
if (present) {
throw BatchJobDomainException.conflict(reason);
}
}
private static long referenceId(JsonNode node) {
// Accept numeric/string long IDs without floating-point coercion or overflow truncation.
String value = node.asText();
if (value == null || !value.matches("[1-9][0-9]{0,18}")) {
throw deletionHistoryUnavailable();
}
return Long.parseLong(value);
}
private static BatchJobDomainException deletionHistoryUnavailable() {
return BatchJobDomainException.conflict("引用或执行历史无法完整核实,暂不能删除作业");
}
private <T> T idempotent(
BatchJobActor actor,
String method,
String path,
String key,
String hash,
Supplier<T> action
) {
return transactionTemplate.execute(status -> {
T replay = replay(actor, method, path, key, hash);
if (replay != null) {
return replay;
}
long requestId = IdGeneratorUtil.nextLongId();
try {
jdbcTemplate.update("""
INSERT INTO dev_batch_job_request(
request_id, actor_id, org_id, request_method, request_path, idempotency_key,
request_sha256, request_status, create_dept, create_by, create_time,
update_by, update_time, del_flag, version
) VALUES (?, ?, ?, ?, ?, ?, ?, 'IN_PROGRESS', ?, ?, NOW(), ?, NOW(), '0', 0)
""", requestId, actor.actorId(), actor.orgId(), method, path, key, hash,
actor.orgId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) {
T concurrentReplay = replay(actor, method, path, key, hash);
if (concurrentReplay != null) {
return concurrentReplay;
}
throw BatchJobDomainException.conflict("幂等请求正在处理,请稍后重试");
}
T result = action.get();
jdbcTemplate.update("""
UPDATE dev_batch_job_request
SET request_status='COMPLETED', response_json=?, update_by=?, update_time=NOW(), version=version+1
WHERE request_id=? AND request_status='IN_PROGRESS' AND del_flag='0'
""", policy.json(result), actor.actorId(), requestId);
return result;
});
}
@SuppressWarnings("unchecked")
private <T> T replay(BatchJobActor actor, String method, String path, String key, String hash) {
List<RequestRow> rows = jdbcTemplate.query("""
SELECT request_sha256, request_status, response_json
FROM dev_batch_job_request
WHERE actor_id=? AND org_id=? AND request_method=? AND request_path=?
AND idempotency_key=? AND del_flag='0'
""", (resultSet, rowNum) -> new RequestRow(
resultSet.getString(1), resultSet.getString(2), resultSet.getString(3)
), actor.actorId(), actor.orgId(), method, path, key);
if (rows.isEmpty()) {
return null;
}
RequestRow row = rows.getFirst();
if (!row.hash().equals(hash)) {
throw BatchJobDomainException.conflict("同一幂等键不能用于不同请求");
}
if (!"COMPLETED".equals(row.status()) || row.responseJson() == null) {
throw BatchJobDomainException.conflict("幂等请求正在处理,请稍后重试");
}
return (T) policy.read(row.responseJson(), BatchJobView.class);
}
private void insertSnapshot(BatchJobActor actor, BatchJobView view, String kind) {
insertSnapshot(actor, view, kind, view.version());
}
private void insertSnapshot(BatchJobActor actor, BatchJobView view, String kind, long snapshotVersion) {
jdbcTemplate.update("""
INSERT INTO dev_batch_job_snapshot(
snapshot_id, job_id, job_version, snapshot_kind, definition_json,
definition_sha256, org_id, create_dept, create_by, create_time, del_flag
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), '0')
""", IdGeneratorUtil.nextLongId(), view.jobId(), snapshotVersion, kind, policy.json(view),
view.definitionSha256(), actor.orgId(), actor.orgId(), actor.actorId());
}
private static void requireDraft(BatchJobView view) {
if (view.status() != JobStatus.DRAFT) {
throw BatchJobDomainException.conflict("只有DRAFT作业可编辑、校验或删除");
}
}
private static void requireChanged(int changed) {
if (changed != 1) {
throw BatchJobDomainException.conflict("作业版本已变化,请刷新后重试");
}
}
private BatchJobView map(ResultSet resultSet) throws SQLException {
return new BatchJobView(
resultSet.getLong("job_id"),
resultSet.getString("job_name"),
resultSet.getLong("org_id"),
resultSet.getString("data_domain_code"),
ExecutionEngine.valueOf(resultSet.getString("execution_engine")),
policy.read(resultSet.getString("source_json"), SourceDefinition.class),
policy.read(resultSet.getString("transform_json"), TransformDefinition.class),
policy.read(resultSet.getString("sink_json"), SinkDefinition.class),
policy.read(resultSet.getString("parameters_json"), JobParameters.class),
resultSet.getString("definition_sha256"),
JobStatus.valueOf(resultSet.getString("job_status")),
resultSet.getLong("version"),
localDateTime(resultSet.getTimestamp("create_time")),
localDateTime(resultSet.getTimestamp("update_time"))
);
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
private record RequestRow(String hash, String status, String responseJson) {
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.ExecutionEngine;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobParameters;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SinkDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SourceDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.TransformDefinition;
final class BatchJobModel {
private BatchJobModel() {
}
record Definition(
String name,
String dataDomainCode,
ExecutionEngine executionEngine,
SourceDefinition source,
TransformDefinition transform,
SinkDefinition sink,
JobParameters parameters
) {
}
}
@@ -0,0 +1,66 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.MySqlSource;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceDirectoryService;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
/** Reuses the Integration owner APIs; never accepts a client supplied connection or schema. */
@Component
class BatchJobMySqlSourceDirectory {
@DubboReference(check = false, timeout = 3_000, retries = 0)
private DataSourceDirectoryService sources;
@DubboReference(check = false, timeout = 8_000, retries = 0)
private DataCollectionIntegrationService integration;
@Autowired
BatchJobMySqlSourceDirectory() { }
BatchJobMySqlSourceDirectory(DataSourceDirectoryService sources, DataCollectionIntegrationService integration) {
this.sources = sources;
this.integration = integration;
}
List<String> fields(BatchJobActorProvider.BatchJobActor actor, MySqlSource identity) {
return columns(actor, identity).stream().map(column -> column.name()).toList();
}
List<Column> columns(
BatchJobActorProvider.BatchJobActor actor, MySqlSource identity) {
try {
requireCurrent(actor, identity);
var columns = integration.sourceSchema(new DataCollectionIntegrationService.SourceSchemaRequest(
actor.actorId(), actor.orgId(), identity.dataSourceId(), identity.database(), identity.table()));
if (columns == null || columns.isEmpty() || columns.size() > 100
|| columns.stream().anyMatch(c -> c == null || c.name() == null || c.name().isBlank()
|| c.type() == null || c.nullable() == null)
|| columns.stream().map(c -> c.name()).distinct().count() != columns.size()) {
throw BatchJobDomainException.validation("源表结构不可用,请重新选择真实MySQL表");
}
requireCurrent(actor, identity);
return List.copyOf(columns);
} catch (BatchJobDomainException exception) {
throw exception;
} catch (RuntimeException | LinkageError exception) {
throw BatchJobDomainException.referenceUnavailable();
}
}
private void requireCurrent(BatchJobActorProvider.BatchJobActor actor, MySqlSource identity) {
var result = sources.query(actor.actorId(), actor.orgId(), List.of(identity.dataSourceId()), null, 1);
if (result == null || !"AVAILABLE".equals(result.status()) || result.entries() == null
|| result.entries().size() != 1) throw BatchJobDomainException.referenceUnavailable();
var source = result.entries().getFirst();
if (source == null || !identity.dataSourceId().equals(source.id()) || !"MYSQL".equals(source.type())
|| !source.credentialConfigured() || !source.previewEligible()
|| !"SUCCEEDED".equals(source.status()) || source.version() != identity.sourceVersion()
|| !identity.database().equals(source.databaseName())) {
throw BatchJobDomainException.validation("MySQL源不可见、未通过连接测试或版本已变化,请重新选择");
}
}
}
@@ -0,0 +1,357 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobCreateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobUpdateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.FieldMapping;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.FilterOperator;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.FilterRule;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobParameters;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobStatus;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SinkDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SourceDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.TransformDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.TransformOperation;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.MapperFeature;
import tools.jackson.databind.SerializationFeature;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Pattern;
@Component
class BatchJobPolicy {
private static final Pattern IDEMPOTENCY_KEY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
private static final Pattern FIELD = Pattern.compile("[A-Za-z_][A-Za-z0-9_.]{0,127}");
private static final Pattern SENSITIVE = Pattern.compile(
"(?i).*(password|passwd|pwd|token|secret|credential|authorization|private[_-]?key|access[_-]?key|connection[_-]?string).*"
);
private static final Pattern FORBIDDEN_CONTENT = Pattern.compile(
"(?is).*(jdbc:|[a-z][a-z0-9+.-]*://|;|--|/\\*|\\*/|`|\\$\\(|\\b(select|insert|update|delete|drop|alter|" +
"truncate|create|exec|execute|call|merge|grant|revoke|shell|bash|powershell|cmd\\.exe|sh\\s+-c)\\b).*"
);
private final JsonMapper mapper;
BatchJobPolicy(JsonMapper jsonMapper) {
this.mapper = jsonMapper.rebuild()
.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)
.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
.build();
}
String name(String value) {
String normalized = required(value, "作业名称", 128);
rejectUnsafe(normalized, "作业名称");
return normalized;
}
long positive(Long value, String label) {
if (value == null || value <= 0) {
throw BatchJobDomainException.validation(label + "无效");
}
return value;
}
long version(Long value) {
if (value == null || value < 0) {
throw BatchJobDomainException.validation("版本不能为空且不得小于0");
}
return value;
}
void idempotencyKey(String value) {
if (value == null || !IDEMPOTENCY_KEY.matcher(value).matches()) {
throw BatchJobDomainException.validation("幂等键格式无效");
}
}
int pageNum(Integer value) {
return value == null ? 1 : bounded(value, 1, 10_000, "页码");
}
int pageSize(Integer value) {
return value == null ? 20 : bounded(value, 1, 100, "分页大小");
}
String keyword(String value) {
if (value == null || value.isBlank()) {
return null;
}
String normalized = value.trim();
if (normalized.length() > 100) {
throw BatchJobDomainException.validation("检索词不得超过100个字符");
}
rejectUnsafe(normalized, "检索词");
return normalized;
}
JobStatus queryStatus(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return JobStatus.valueOf(value.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException exception) {
throw BatchJobDomainException.validation("作业状态只允许DRAFT或READY");
}
}
BatchJobCreateRequest create(BatchJobCreateRequest value) {
if (value == null || value.executionEngine() == null) {
throw BatchJobDomainException.validation("执行引擎不能为空");
}
return new BatchJobCreateRequest(
name(value.name()),
value.executionEngine(),
source(value.source()),
transform(value.transform()),
sink(value.sink()),
parameters(value.parameters())
);
}
BatchJobUpdateRequest update(BatchJobUpdateRequest value) {
if (value == null || value.executionEngine() == null) {
throw BatchJobDomainException.validation("执行引擎不能为空");
}
return new BatchJobUpdateRequest(
name(value.name()),
value.executionEngine(),
source(value.source()),
transform(value.transform()),
sink(value.sink()),
parameters(value.parameters()),
version(value.version())
);
}
SourceDefinition source(SourceDefinition value) {
if (value == null || value.readMode() == null) {
throw BatchJobDomainException.validation("数据源定义不完整");
}
if (value.mysqlSource() != null) {
var mysql = value.mysqlSource();
if (value.inputTableFileIds() == null || !value.inputTableFileIds().isEmpty()
|| mysql.dataSourceId() == null || mysql.dataSourceId() <= 0
|| mysql.sourceVersion() == null || mysql.sourceVersion() < 0
|| mysql.database() == null || !mysql.database().matches("[A-Za-z_][A-Za-z0-9_]{0,127}")
|| mysql.table() == null || !mysql.table().matches("[A-Za-z_][A-Za-z0-9_]{0,127}")) {
throw BatchJobDomainException.validation("请选择有效MySQL源库表,且不得混用表文件输入");
}
return new SourceDefinition(List.of(), value.readMode(), mysql);
}
return new SourceDefinition(ids(value.inputTableFileIds(), "输入表文件"), value.readMode());
}
TransformDefinition transform(TransformDefinition value) {
if (value == null) {
throw BatchJobDomainException.validation("转换定义不能为空");
}
List<FieldMapping> mappings = value.fieldMappings() == null ? List.of() : value.fieldMappings().stream()
.map(this::mapping)
.toList();
List<FilterRule> filters = value.filters() == null ? List.of() : value.filters().stream()
.map(this::filter)
.toList();
if (mappings.size() > 256 || filters.size() > 32) {
throw BatchJobDomainException.validation("转换规则数量超过上限");
}
Set<String> targets = new LinkedHashSet<>();
if (mappings.stream().anyMatch(item -> !targets.add(item.targetField()))) {
throw BatchJobDomainException.validation("目标字段不得重复");
}
return new TransformDefinition(mappings, filters);
}
SinkDefinition sink(SinkDefinition value) {
if (value == null || value.writeMode() == null) {
throw BatchJobDomainException.validation("输出定义不完整");
}
return new SinkDefinition(ids(value.outputTableFileIds(), "输出表文件"), value.writeMode());
}
JobParameters parameters(JobParameters value) {
if (value == null || value.faultTolerance() == null) {
throw BatchJobDomainException.validation("运行参数不完整");
}
return new JobParameters(
bounded(value.parallelism(), 1, 128, "并行度"),
bounded(value.coordinatorMemoryMb(), 256, 16_384, "协调端内存"),
bounded(value.workerMemoryMb(), 256, 65_536, "工作端内存"),
bounded(value.workerCpuMillicores(), 100, 16_000, "工作端CPU"),
bounded(value.timeoutSeconds(), 1, 86_400, "超时时间"),
bounded(value.retryCount(), 0, 10, "重试次数"),
bounded(value.retryIntervalSeconds(), 1, 3_600, "重试间隔"),
value.faultTolerance()
);
}
void requireDistinctEndpoints(SourceDefinition source, SinkDefinition sink) {
Set<Long> overlap = new LinkedHashSet<>(source.inputTableFileIds());
overlap.retainAll(sink.outputTableFileIds());
if (!overlap.isEmpty()) {
throw BatchJobDomainException.validation("输入和输出表文件不得相同");
}
}
void requireCompatible(FieldMapping mapping, String sourceType, Boolean sourceNullable,
String targetType, Boolean targetNullable) {
if (sourceNullable == null || targetNullable == null
|| (sourceNullable && !targetNullable)) {
throw BatchJobDomainException.validation("源字段可空性与目标字段不兼容");
}
String from = sourceType == null ? "UNKNOWN" : sourceType.toUpperCase(java.util.Locale.ROOT);
String to = targetType.toUpperCase(java.util.Locale.ROOT);
List<String> text = List.of("STRING", "VARCHAR", "CHAR", "TEXT");
List<String> integers = List.of("TINYINT", "SMALLINT", "INT", "BIGINT");
boolean compatible;
if (mapping.operation() == TransformOperation.CAST) {
compatible = mapping.targetType() != null && mapping.targetType().name().equals(to);
} else if (mapping.operation() != TransformOperation.COPY) {
compatible = text.contains(from) && text.contains(to);
} else {
compatible = from.equals(to) || (text.contains(from) && text.contains(to))
|| (integers.contains(from) && integers.contains(to) && integers.indexOf(to) >= integers.indexOf(from))
|| ("FLOAT".equals(from) && "DOUBLE".equals(to))
|| (List.of("DATE", "TIMESTAMP").contains(from) && "DATETIME".equals(to));
}
if (!compatible) throw BatchJobDomainException.validation("源字段类型与目标字段不兼容,请重新映射或指定转换类型");
}
void requireCapacity(FieldMapping mapping,
cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects.Column source,
cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.ColumnDefinition target) {
if (mapping.operation() == TransformOperation.CAST) return; // Explicit conversion is checked against the target type.
String type = target.type().name();
boolean compatible = true;
if (List.of("CHAR", "VARCHAR").contains(type)) {
compatible = source.octetLength() != null && target.precision() != null
&& source.octetLength() > 0 && source.octetLength() <= target.precision();
} else if ("DECIMAL".equals(type)) {
compatible = source.precision() != null && source.scale() != null
&& target.precision() != null && target.scale() != null
&& source.scale() <= target.scale()
&& source.precision() - source.scale() <= target.precision() - target.scale();
} else if (List.of("DATETIME", "TIMESTAMP").contains(type) && !"DATE".equals(source.type())) {
compatible = source.scale() != null && source.scale() >= 0
&& source.scale() <= (target.scale() == null ? 0 : target.scale());
}
if (!compatible) throw BatchJobDomainException.validation("字段长度或精度不兼容或证据缺失,请核对源表和目标表");
}
String requestHash(Object value) {
return sha256(json(value));
}
String json(Object value) {
try {
return mapper.writeValueAsString(value);
} catch (JacksonException exception) {
throw BatchJobDomainException.validation("结构化作业定义无法序列化");
}
}
<T> T read(String json, Class<T> type) {
try {
return mapper.readValue(json, type);
} catch (JacksonException exception) {
throw new IllegalStateException("已保存的批处理作业无法读取", exception);
}
}
private FieldMapping mapping(FieldMapping value) {
if (value == null || value.operation() == null) {
throw BatchJobDomainException.validation("字段映射不完整");
}
String sourceField = field(value.sourceField(), "源字段");
String targetField = field(value.targetField(), "目标字段");
if (value.operation() == TransformOperation.CAST && value.targetType() == null) {
throw BatchJobDomainException.validation("类型转换必须选择目标类型");
}
if (value.operation() != TransformOperation.CAST && value.targetType() != null) {
throw BatchJobDomainException.validation("非类型转换不得设置目标类型");
}
return new FieldMapping(sourceField, targetField, value.operation(), value.targetType());
}
private FilterRule filter(FilterRule value) {
if (value == null || value.operator() == null) {
throw BatchJobDomainException.validation("过滤规则不完整");
}
String field = field(value.field(), "过滤字段");
boolean nullOperator = value.operator() == FilterOperator.IS_NULL || value.operator() == FilterOperator.NOT_NULL;
if (nullOperator && value.value() != null && !value.value().isBlank()) {
throw BatchJobDomainException.validation("空值判断不得设置比较值");
}
String scalar = nullOperator ? null : required(value.value(), "过滤值", 256);
if (scalar != null) {
rejectUnsafe(scalar, "过滤值");
}
return new FilterRule(field, value.operator(), scalar);
}
private List<Long> ids(List<Long> values, String label) {
if (values == null || values.isEmpty() || values.size() > 32) {
throw BatchJobDomainException.validation(label + "数量必须为1到32");
}
Set<Long> unique = new LinkedHashSet<>();
for (Long value : values) {
if (value == null || value <= 0 || !unique.add(value)) {
throw BatchJobDomainException.validation(label + "ID无效或重复");
}
}
return List.copyOf(unique);
}
private String field(String value, String label) {
if (value == null || !FIELD.matcher(value.trim()).matches()) {
throw BatchJobDomainException.validation(label + "格式无效");
}
String normalized = value.trim();
rejectUnsafe(normalized, label);
return normalized;
}
private String required(String value, String label, int maxLength) {
if (value == null || value.isBlank()) {
throw BatchJobDomainException.validation(label + "不能为空");
}
String normalized = value.trim();
if (normalized.length() > maxLength) {
throw BatchJobDomainException.validation(label + "不得超过" + maxLength + "个字符");
}
return normalized;
}
private void rejectUnsafe(String value, String label) {
if (SENSITIVE.matcher(value).matches() || FORBIDDEN_CONTENT.matcher(value).matches()) {
throw BatchJobDomainException.validation(label + "包含敏感信息、连接串、SQL或命令形态");
}
}
private int bounded(Integer value, int minimum, int maximum, String label) {
if (value == null || value < minimum || value > maximum) {
throw BatchJobDomainException.validation(label + "必须在" + minimum + "到" + maximum + "之间");
}
return value;
}
private static String sha256(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256不可用", exception);
}
}
}
@@ -0,0 +1,10 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.Instant;
@Component
class BatchJobRunAssistAuthority {
@DubboReference(check=false,timeout=5000,retries=0) private RemoteUserService users;
void require(BatchJobActorProvider.BatchJobActor actor){String purpose="BATCH_JOB_RUN_ASSIST_VIEW";try{var d=users.resolveAssetActor(actor.actorId(),actor.orgId(),purpose);var now=Instant.now();if(d!=null&&d.allowed()&&d.userId()==actor.actorId()&&d.deptId()==actor.orgId()&&purpose.equals(d.purpose())&&d.checkedAt()!=null&&!d.checkedAt().isBefore(now.minusSeconds(10))&&!d.checkedAt().isAfter(now.plusSeconds(5)))return;}catch(RuntimeException unavailable){}throw BatchJobDomainException.forbidden();}
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobRunAssistDirectory.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController @RequestMapping("/api/dataops/v1/batch-job-run-assist")
@SaCheckPermission("aixun:dataops:batch-job:view")
class BatchJobRunAssistController {
private final BatchJobRunAssistService service;BatchJobRunAssistController(BatchJobRunAssistService service){this.service=service;}
@GetMapping("/candidates")R<List<Candidate>> choices(@RequestParam String jobId,@RequestParam long version){return R.ok(service.choices(jobId,version));}
@PostMapping("/context")R<Context> current(@RequestBody Selection selection){return R.ok(service.current(selection));}
@ExceptionHandler(BatchJobDomainException.class)org.springframework.http.ResponseEntity<R<Void>> error(BatchJobDomainException e){return org.springframework.http.ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
}
@@ -0,0 +1,8 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobRunAssistDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=BatchJobRunAssistDirectory.VERSION)
public class BatchJobRunAssistDubboService implements BatchJobRunAssistDirectory {
private final BatchJobRunAssistService service;public BatchJobRunAssistDubboService(BatchJobRunAssistService service){this.service=service;}
public Context current(Selection selection){return service.current(selection);}
}
@@ -0,0 +1,47 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobRunAssistDirectory.*;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.aixunkeji.datagov.dataops.api.scheduling.SchedulingApi.*;
import cn.aixunkeji.datagov.dataops.scheduling.BatchJobRunEvidenceOwner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@Service
class BatchJobRunAssistService {
private final BatchJobActorProvider actors;private final BatchJobJdbcRepository jobs;private final BatchJobRunEvidenceOwner runs;
private final BatchJobRunAssistAuthority authority;private final ObjectMapper json;
@org.springframework.beans.factory.annotation.Autowired private BatchJobScheduledExecution executions;
BatchJobRunAssistService(BatchJobActorProvider actors,BatchJobJdbcRepository jobs,BatchJobRunEvidenceOwner runs,BatchJobRunAssistAuthority authority,ObjectMapper json){this.actors=actors;this.jobs=jobs;this.runs=runs;this.authority=authority;this.json=json;}
List<Candidate> choices(String jobId,long version){var a=actors.current();authority.require(a);var job=job(a,id(jobId),version);List<Candidate> result;try{result=runs.candidates(job.jobId());}catch(RuntimeException denied){throw unavailable();}authority.require(a);if(!a.equals(actors.current())||!job.equals(job(a,job.jobId(),version)))throw unavailable();return result;}
@Transactional(readOnly=true,propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public Context current(Selection s){if(s==null||s.jobVersion()<0||s.evidenceVersion()<0)throw invalid();long jobId=id(s.jobId()),runId=id(s.runId()),evidenceId=id(s.evidenceId());var a=actors.current();authority.require(a);var job=job(a,jobId,s.jobVersion());var before=read(jobId,runId,evidenceId,s.evidenceVersion());String fingerprint=hash(List.of(job,before));
var e=before.evidence();boolean sameSnapshot=Objects.equals(before.run().snapshotId(),before.definition().summary().currentSnapshotId());boolean ready=before.definition().summary().status()==DefinitionStatus.READY;boolean runFailed=before.run().status()==RunStatus.FAILED;
var currentBinding = executionBinding(a, jobId);
fingerprint = hash(List.of(job, before, currentBinding == null ? "UNAVAILABLE" : currentBinding));
String binding=e.ownerVersion()==null||e.ownerHash()==null?"NOT_RECORDED":currentBinding != null && e.ownerVersion().equals(currentBinding.version()) && e.ownerHash().equals(currentBinding.sha256())?"CURRENT_MATCH":"HISTORICAL_DIFFERENCE";
boolean currentNode=before.definition().nodes().stream().filter(n->n.nodeKey().equals(e.nodeKey())&&n.type()==NodeType.BATCH_JOB&&Objects.equals(n.referenceId(),jobId)).count()==1;
var facts=List.of(new Fact("F1","RECORD_KIND",e.kind(),e.observedAt()),new Fact("F2","NODE_STATUS",e.status(),e.observedAt()),new Fact("F3","ERROR_CLASS",errorClass(e.errorCode()),e.observedAt()),new Fact("F4","RUN_STATUS",before.run().status().name(),time(before.run().updatedAt())),new Fact("F5","CURRENT_SNAPSHOT",sameSnapshot?"MATCH":"CHANGED",null),new Fact("F6","OWNER_VERSION_BINDING",binding,e.observedAt()),new Fact("F7","BATCH_EXECUTION_ENTRY",currentBinding == null ? "UNAVAILABLE" : "AVAILABLE",null),new Fact("F8","SAME_INSTANCE_FAILED_OBSERVATION",before.sameInstanceFailure()?"PRESENT":"ABSENT",null),new Fact("F9","CURRENT_SCHEDULE",ready?"READY":"NOT_READY",null),new Fact("F10","CURRENT_NODE_BINDING",currentNode?"MATCH":"CHANGED",null));
var checks=List.of(new Check("CURRENT_SCHEDULE_READY",ready,List.of("F9")),new Check("CURRENT_SNAPSHOT_MATCH",sameSnapshot,List.of("F5")),new Check("ORIGINAL_RUN_FAILED",runFailed,List.of("F4")),new Check("SAME_INSTANCE_FAILED_OBSERVATION",before.sameInstanceFailure(),List.of("F1","F8")),new Check("CURRENT_NODE_MATCH",currentNode,List.of("F10")),new Check("BATCH_EXECUTION_ENTRY_AVAILABLE",currentBinding != null,List.of("F7")));
if (!Objects.equals(currentBinding, executionBinding(a, jobId))) throw unavailable();
authority.require(a);if(!a.equals(actors.current())||!fingerprint.equals(hash(List.of(job(a,jobId,s.jobVersion()),read(jobId,runId,evidenceId,s.evidenceVersion()),currentBinding == null ? "UNAVAILABLE" : currentBinding))))throw unavailable();
return new Context(s,fingerprint,Long.toString(e.scheduleId()),e.nodeKey(),facts,checks,"SAVED_NODE_EVIDENCE_NO_EXECUTION_OR_RECOVERY_PROOF");}
private BatchJobScheduledExecution.Binding executionBinding(BatchJobActorProvider.BatchJobActor actor, long job) {
try { return executions == null ? null : executions.binding(actor.actorId(), actor.orgId(), job); }
catch (RuntimeException | LinkageError unavailable) { return null; }
}
private BatchJobView job(BatchJobActorProvider.BatchJobActor a,long id,long version){var j=jobs.require(a,id);if(j==null||!Objects.equals(j.jobId(),id)||!Objects.equals(j.orgId(),a.orgId())||j.version()==null||j.version()!=version)throw unavailable();return j;}
private BatchJobRunEvidenceOwner.Snapshot read(long job,long run,long evidence,long version){try{return runs.current(job,run,evidence,version);}catch(RuntimeException unavailable){throw unavailable();}}
static long id(String value){try{long id=Long.parseLong(value);if(id>0&&Long.toString(id).equals(value))return id;}catch(RuntimeException ignored){}throw invalid();}
static String errorClass(String code){if(code==null||code.isBlank())return "NOT_RECORDED";return switch(code){case "SCHEDULING_OWNER_EXECUTION_UNAVAILABLE"->"OWNER_EXECUTION_UNAVAILABLE";case "SCHEDULING_CALLBACK_INVALID","SCHEDULING_CALLBACK_BINDING_REJECTED"->"CALLBACK_BINDING_REJECTED";case "DOLPHINSCHEDULER_TASK_FAILURE"->"EXTERNAL_NODE_FAILURE";default->"OTHER_RECORDED_ERROR";};}
private String hash(Object value){try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsString(value).getBytes(StandardCharsets.UTF_8)));}catch(Exception error){throw unavailable();}}
private static String time(java.time.LocalDateTime value){return value==null?null:value.toString();}
private static BatchJobDomainException invalid(){return BatchJobDomainException.validation("请选择精确批作业、运行和节点证据版本");}
private static BatchJobDomainException unavailable(){return BatchJobDomainException.conflict("当前批作业或运行证据不可读或已变化,请重新选择");}
}
@@ -0,0 +1,162 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.*;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileBatchJobReferenceDirectory;
import cn.aixunkeji.datagov.dataops.storage.StorageTableFileReferenceDirectory;
import cn.aixunkeji.datagov.integration.api.DataCollectionIntegrationService.*;
import cn.aixunkeji.datagov.integration.api.datasource.DataSourceObjects;
import cn.aixunkeji.datagov.integration.api.scheduling.BatchJobExecutionService;
import cn.aixunkeji.datagov.integration.api.scheduling.SchedulingOwnerExecutionService.*;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;
import java.util.*;
@Component
@RequiredArgsConstructor
public class BatchJobScheduledExecution {
private final BatchJobJdbcRepository jobs;
private final BatchJobMySqlSourceDirectory sources;
private final BatchJobPolicy policy;
private final TableFileBatchJobReferenceDirectory tables;
private final StorageTableFileReferenceDirectory storage;
private final JdbcTemplate jdbc;
private final TransactionTemplate transactions;
@DubboReference(check = false, timeout = 60_000, retries = 0) private BatchJobExecutionService gateway;
public void validate(long actor, long org, long id) { prepare(actor, org, id); }
public record Binding(String version, String sha256) { }
public Binding binding(long actor, long org, long id) {
var p = prepare(actor, org, id);
return new Binding(p.job.version().toString(), p.sha);
}
public Outcome execute(long actor, long org, long id, String version, String sha, String key, long run, boolean observe) {
Execution existing = find(actor, org, key);
if (existing != null) {
if (existing.jobId != id || !existing.version.equals(version) || !existing.sha.equals(sha))
throw new IllegalArgumentException("批作业执行键与原快照不一致");
if (Set.of("SUCCEEDED", "FAILED", "CANCELED").contains(existing.status)) return outcome(existing, run);
return sync(existing, run);
}
if (observe) return new Outcome(State.UNKNOWN, run, null, "BATCH_JOB_RECEIPT_NOT_FOUND", "未找到原批作业请求,请核查运行记录", LocalDateTime.now());
var prepared = prepare(actor, org, id);
if (!version.equals(prepared.job.version().toString()) || !sha.equals(prepared.sha))
throw new IllegalArgumentException("批作业版本已变化,请重新发布流程");
long execution = IdGeneratorUtil.nextLongId();
String request = UUID.randomUUID().toString().replace("-", "");
Boolean fresh = transactions.execute(tx -> {
// Same job serialization also prevents a duplicate key race across concurrent callbacks.
jdbc.queryForObject("SELECT job_id FROM dev_batch_job WHERE job_id=? FOR UPDATE", Long.class, id);
if (find(actor, org, key) != null) return false;
jdbc.update("""
INSERT INTO dev_batch_job_execution(execution_id,org_id,actor_id,job_id,owner_version,owner_sha256,
idempotency_key,request_id,execution_status,source_id,create_time,observed_at,create_dept,create_by,update_by)
VALUES(?,?,?,?,?,?,?,?, 'SUBMITTING',?,NOW(6),NOW(6),?,?,?)
""", execution, org, actor, id, version, sha, key, request, prepared.job.source().mysqlSource().dataSourceId(), org, actor, actor);
return true;
});
if (!Boolean.TRUE.equals(fresh)) return sync(find(actor, org, key), run);
BatchJobExecutionService.Result result;
try {
result = gateway.submit(new BatchJobExecutionService.Command(actor, org, id, execution, request, sha,
prepared.job.source().mysqlSource().dataSourceId(), prepared.job.source().mysqlSource().sourceVersion(),
prepared.snapshot, prepared.target));
} catch (RuntimeException | LinkageError failure) {
result = new BatchJobExecutionService.Result("UNKNOWN", null, "BATCH_JOB_SUBMISSION_UNKNOWN", LocalDateTime.now());
}
update(execution, result);
return outcome(find(actor, org, key), run);
}
private Outcome sync(Execution original, long run) {
var result = gateway.observe(new BatchJobExecutionService.Observation(original.actor, original.org,
original.jobId, original.id, original.request, original.sha, original.sourceId, original.external));
update(original.id, result);
return outcome(find(original.actor, original.org, original.key), run);
}
private Prepared prepare(long actor, long org, long id) {
var principal = new BatchJobActorProvider.BatchJobActor(actor, org, false);
var job = jobs.require(principal, id);
requireSupported(job);
var columns = sources.columns(principal, job.source().mysqlSource());
var detail = tables.executionTarget(actor, org, job.sink().outputTableFileIds().getFirst());
var table = detail.tableFile();
var access = storage.resolveForIngestion(actor, org, table.storageResourceId(), table.storageSpaceId());
if (access.status() != StorageTableFileReferenceDirectory.Status.AUTHORIZED || !"DORIS".equals(access.resourceType())
|| !table.namespaceName().equals(access.externalSpaceId()))
throw new IllegalArgumentException("批作业目标连接不可用");
List<BatchFieldExecution> fields = new ArrayList<>();
for (var mapping : job.transform().fieldMappings()) {
var column = columns.stream().filter(c -> c.name().equals(mapping.sourceField())).findFirst().orElseThrow();
var mapped = DataSourceObjects.mysqlTargetType(column, DataSourceObjects.TargetEngine.DORIS);
if (!mapped.supported()) throw new IllegalArgumentException("源字段类型不能无损映射");
var targetColumn = detail.columns().stream().filter(c -> c.name().equals(mapping.targetField())).findFirst().orElseThrow();
policy.requireCompatible(mapping, column.type(), column.nullable(), targetColumn.type().name(), targetColumn.nullable());
policy.requireCapacity(mapping, column, targetColumn);
var filters = job.transform().filters().stream().filter(f -> f.field().equals(mapping.sourceField())).toList();
if (filters.size() > 1) throw new IllegalArgumentException("每个字段当前只支持一个执行过滤条件");
var filter = filters.isEmpty() ? null : filters.getFirst();
fields.add(new BatchFieldExecution(fields.size() + 1, mapping.sourceField(), mapping.targetField(),
column.type(), mapped.targetType(), mapping.operation() == TransformOperation.COPY ? "NONE" : mapping.operation().name(),
null, filter == null ? null : filter.operator().name(),
filter == null || filter.value() == null ? List.of() : List.of(filter.value()),
column.nativeType(), column.precision(), column.scale(), column.octetLength()));
}
if (job.transform().filters().stream().anyMatch(f -> fields.stream().noneMatch(m -> m.sourceField().equals(f.field()))))
throw new IllegalArgumentException("过滤字段必须包含在映射中,不能忽略未映射过滤条件");
var snapshot = new BatchExecutionSnapshot(job.dataDomainCode(), job.source().mysqlSource().database() + '.' + job.source().mysqlSource().table(),
table.namespaceName() + '.' + table.name(), "FULL", null, null, 1, false, null, List.copyOf(fields));
var target = new StorageExecutionProfile(table.storageResourceId(), table.storageSpaceId(), "DORIS", access.catalogName(),
access.externalSpaceId(), access.locationUri(), access.endpointHost(), access.endpointPort(), access.serviceAccount(), access.secretRef(), access.tlsEnabled());
String sha = policy.requestHash(List.of(job.definitionSha256(), columns, detail, target));
return new Prepared(job, snapshot, target, sha);
}
static void requireSupported(BatchJobView job) {
var p = job.parameters();
if (job.status() != JobStatus.READY || job.source().mysqlSource() == null || job.sink().outputTableFileIds().size() != 1
|| job.sink().writeMode() != WriteMode.APPEND || p.parallelism() != 1 || p.retryCount() != 0
|| p.timeoutSeconds() != 3600 || p.faultTolerance() != FaultTolerance.FAIL_FAST
|| p.coordinatorMemoryMb() != 1024 || p.workerMemoryMb() != 2048 || p.workerCpuMillicores() != 1000
|| job.transform().fieldMappings().stream().anyMatch(m -> m.operation() == TransformOperation.CAST))
throw new IllegalArgumentException("当前调度支持MySQL到Doris追加、单并行、默认资源档、60分钟、失败即停且不自动重试;覆盖、CAST及其他参数请先调整");
}
private Execution find(long actor, long org, String key) {
var rows = jdbc.query("SELECT * FROM dev_batch_job_execution WHERE actor_id=? AND org_id=? AND idempotency_key=?",
(r, n) -> new Execution(r.getLong("execution_id"), r.getLong("actor_id"), r.getLong("org_id"), r.getLong("job_id"),
r.getString("owner_version"), r.getString("owner_sha256"), r.getString("idempotency_key"), r.getString("request_id"),
r.getString("execution_status"), r.getLong("source_id"), r.getString("external_job_id"), r.getString("error_code"), r.getTimestamp("observed_at").toLocalDateTime()), actor, org, key);
return rows.isEmpty() ? null : rows.getFirst();
}
private void update(long id, BatchJobExecutionService.Result result) {
if (result == null) return;
String state = Set.of("SUBMITTED", "RUNNING", "SUCCEEDED", "FAILED", "CANCELED").contains(result.status()) ? result.status() : "UNKNOWN";
jdbc.update("UPDATE dev_batch_job_execution SET execution_status=?,external_job_id=COALESCE(?,external_job_id),error_code=?,observed_at=?,version=version+1 WHERE execution_id=? AND execution_status NOT IN ('SUCCEEDED','FAILED','CANCELED')",
state, result.externalJobId(), result.errorCode(), result.observedAt() == null ? LocalDateTime.now() : result.observedAt(), id);
}
public record ExecutionView(String executionId, String jobId, String ownerVersion, String status,
String externalJobId, String errorCode, LocalDateTime observedAt) { }
List<ExecutionView> history(BatchJobActorProvider.BatchJobActor actor, long jobId, Long executionId) {
jobs.require(actor, jobId);
return jdbc.query("SELECT * FROM dev_batch_job_execution WHERE org_id=? AND job_id=? AND actor_id=?"
+ (executionId == null ? "" : " AND execution_id=?") + " ORDER BY create_time DESC,execution_id DESC LIMIT 100",
(r, n) -> new ExecutionView(r.getString("execution_id"), r.getString("job_id"), r.getString("owner_version"),
r.getString("execution_status"), r.getString("external_job_id"), r.getString("error_code"), r.getTimestamp("observed_at").toLocalDateTime()),
executionId == null ? new Object[]{actor.orgId(), jobId, actor.actorId()} : new Object[]{actor.orgId(), jobId, actor.actorId(), executionId});
}
private static Outcome outcome(Execution r, long run) {
State state = switch (r.status) { case "SUCCEEDED" -> State.SUCCEEDED; case "FAILED", "CANCELED" -> State.FAILED;
case "SUBMITTING", "SUBMITTED", "RUNNING" -> State.RUNNING; default -> State.UNKNOWN; };
return new Outcome(state, run, "/api/dataops/v1/batch-jobs/" + r.jobId + "/executions/" + r.id, r.error,
r.error == null ? null : "请查看批作业原运行记录", r.at);
}
private record Prepared(BatchJobView job, BatchExecutionSnapshot snapshot, StorageExecutionProfile target, String sha) { }
private record Execution(long id, long actor, long org, long jobId, String version, String sha, String key,
String request, String status, long sourceId, String external, String error, LocalDateTime at) { }
}
@@ -0,0 +1,42 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobStatus;
import org.springframework.stereotype.Component;
/** Read-only owner boundary used by scheduling; it never exposes a job body or credentials. */
@Component
public class BatchJobSchedulingReferenceDirectory {
private final BatchJobJdbcRepository repository;
BatchJobSchedulingReferenceDirectory(BatchJobJdbcRepository repository) {
this.repository = repository;
}
public Resolution resolve(long actorId, long orgId, boolean unrestricted, long jobId) {
try {
BatchJobView job = repository.require(
new BatchJobActorProvider.BatchJobActor(actorId, orgId, unrestricted), jobId);
if (job.status() != JobStatus.READY) {
return Resolution.notExecutable();
}
return new Resolution(State.AUTHORIZED, job.jobId(),
String.valueOf(job.version()), job.definitionSha256());
} catch (RuntimeException exception) {
return Resolution.unavailable();
}
}
public enum State { AUTHORIZED, NOT_EXECUTABLE, UNAVAILABLE }
public record Resolution(State state, Long referenceId, String ownerVersion, String ownerSha256) {
static Resolution notExecutable() {
return new Resolution(State.NOT_EXECUTABLE, null, null, null);
}
static Resolution unavailable() {
return new Resolution(State.UNAVAILABLE, null, null, null);
}
}
}
@@ -0,0 +1,227 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobCreateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobDeleteRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobParameterRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobReadyRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobUpdateRequest;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.BatchJobView;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.JobParameters;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.MySqlSource;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SourceDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.SinkDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.TransformDefinition;
import cn.aixunkeji.datagov.dataops.api.batchjob.BatchJobApi.ReadMode;
import cn.aixunkeji.datagov.dataops.api.tablefile.TableFileApi.ColumnDefinition;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileErrors;
import cn.aixunkeji.datagov.dataops.batchjob.BatchJobActorProvider.BatchJobActor;
import cn.aixunkeji.datagov.dataops.batchjob.BatchJobModel.Definition;
import cn.aixunkeji.datagov.dataops.tablefile.TableFileBatchJobReferenceDirectory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
class BatchJobService {
private final BatchJobActorProvider actorProvider;
private final BatchJobPolicy policy;
private final BatchJobJdbcRepository repository;
private final TableFileBatchJobReferenceDirectory tableFileDirectory;
private final BatchJobMySqlSourceDirectory mysqlSources;
List<String> sourceFields(MySqlSource source) {
var normalized = policy.source(new SourceDefinition(List.of(), ReadMode.SNAPSHOT, source));
return mysqlSources.fields(actorProvider.current(), normalized.mysqlSource());
}
PageResult<BatchJobView> list(
String keyword,
String status,
Integer pageNum,
Integer pageSize
) {
BatchJobActor actor = actorProvider.current();
return repository.page(
actor,
policy.keyword(keyword),
policy.queryStatus(status),
policy.pageNum(pageNum),
policy.pageSize(pageSize)
);
}
BatchJobView get(long jobId) {
return repository.require(actorProvider.current(), positiveJobId(jobId));
}
BatchJobView create(String idempotencyKey, BatchJobCreateRequest request) {
BatchJobActor actor = actorProvider.current();
policy.idempotencyKey(idempotencyKey);
BatchJobCreateRequest normalized = policy.create(request);
policy.requireDistinctEndpoints(normalized.source(), normalized.sink());
Definition definition = definition(actor, normalized);
return repository.create(
actor,
idempotencyKey,
policy.requestHash(normalized),
definition,
policy.requestHash(definition)
);
}
BatchJobView update(long jobId, String idempotencyKey, BatchJobUpdateRequest request) {
BatchJobActor actor = actorProvider.current();
policy.idempotencyKey(idempotencyKey);
BatchJobUpdateRequest normalized = policy.update(request);
policy.requireDistinctEndpoints(normalized.source(), normalized.sink());
Definition definition = definition(actor, normalized);
return repository.update(
actor,
positiveJobId(jobId),
idempotencyKey,
policy.requestHash(normalized),
definition,
policy.requestHash(definition),
normalized.version()
);
}
BatchJobView updateParameters(long jobId, String idempotencyKey, BatchJobParameterRequest request) {
BatchJobActor actor = actorProvider.current();
policy.idempotencyKey(idempotencyKey);
if (request == null) {
throw BatchJobDomainException.validation("参数请求不能为空");
}
JobParameters parameters = policy.parameters(request.parameters());
long version = policy.version(request.version());
BatchJobView current = repository.require(actor, positiveJobId(jobId));
Definition definition = definition(actor, current, parameters);
return repository.updateParameters(
actor,
jobId,
idempotencyKey,
policy.requestHash(request),
parameters,
policy.requestHash(definition),
version
);
}
BatchJobView validateReady(long jobId, String idempotencyKey, BatchJobReadyRequest request) {
BatchJobActor actor = actorProvider.current();
policy.idempotencyKey(idempotencyKey);
if (request == null) {
throw BatchJobDomainException.validation("校验请求不能为空");
}
long version = policy.version(request.version());
BatchJobView current = repository.require(actor, positiveJobId(jobId));
policy.source(current.source());
policy.transform(current.transform());
policy.sink(current.sink());
policy.parameters(current.parameters());
policy.requireDistinctEndpoints(current.source(), current.sink());
validateReferences(actor, current.source(), current.sink());
validateMySqlFields(actor, current.source(), current.sink(), current.transform());
return repository.markReady(actor, jobId, idempotencyKey, policy.requestHash(request), version);
}
BatchJobView delete(long jobId, String idempotencyKey, BatchJobDeleteRequest request) {
BatchJobActor actor = actorProvider.current();
policy.idempotencyKey(idempotencyKey);
if (request == null) {
throw BatchJobDomainException.validation("删除请求不能为空");
}
long version = policy.version(request.version());
return repository.delete(actor, positiveJobId(jobId), idempotencyKey, policy.requestHash(request), version);
}
private Definition definition(BatchJobActor actor, BatchJobCreateRequest request) {
validateReferences(actor, request.source(), request.sink());
validateMySqlFields(actor, request.source(), request.sink(), request.transform());
return new Definition(
request.name(), null, request.executionEngine(), request.source(),
request.transform(), request.sink(), request.parameters()
);
}
private Definition definition(BatchJobActor actor, BatchJobUpdateRequest request) {
validateReferences(actor, request.source(), request.sink());
validateMySqlFields(actor, request.source(), request.sink(), request.transform());
return new Definition(
request.name(), null, request.executionEngine(), request.source(),
request.transform(), request.sink(), request.parameters()
);
}
private Definition definition(BatchJobActor actor, BatchJobView current, JobParameters parameters) {
validateReferences(actor, current.source(), current.sink());
validateMySqlFields(actor, current.source(), current.sink(), current.transform());
return new Definition(
current.name(), current.dataDomainCode(), current.executionEngine(), current.source(),
current.transform(), current.sink(), parameters
);
}
private void validateReferences(
BatchJobActor actor,
SourceDefinition source,
SinkDefinition sink
) {
if (source.mysqlSource() != null) return; // Both owners are checked together below.
final TableFileBatchJobReferenceDirectory.Resolution tables;
try {
tables = tableFileDirectory.resolve(
actor.actorId(), actor.orgId(), actor.unrestricted(),
source.inputTableFileIds(), sink.outputTableFileIds()
);
} catch (RuntimeException exception) {
throw BatchJobDomainException.referenceUnavailable();
}
if (tables.status() == TableFileBatchJobReferenceDirectory.Status.OUTSIDE_SCOPE) {
throw BatchJobDomainException.forbidden();
}
if (tables.status() != TableFileBatchJobReferenceDirectory.Status.AUTHORIZED) {
throw BatchJobDomainException.validation("输入或输出表文件不存在、未确认或不属于当前组织");
}
}
private void validateMySqlFields(BatchJobActor actor,
SourceDefinition source, SinkDefinition sink, TransformDefinition transform) {
if (source.mysqlSource() == null) return;
var columns = mysqlSources.columns(actor, source.mysqlSource());
var fields = columns.stream().map(column -> column.name()).toList();
final List<ColumnDefinition> outputs;
try {
outputs = tableFileDirectory.requireDorisOutputColumns(actor.actorId(), actor.orgId(),
actor.unrestricted(), sink.outputTableFileIds());
} catch (TableFileErrors.Scope exception) {
throw BatchJobDomainException.forbidden();
} catch (TableFileErrors.Validation | TableFileErrors.NotFound exception) {
throw BatchJobDomainException.validation("请选择一个已确认且可见的Doris目标表");
} catch (RuntimeException exception) {
throw BatchJobDomainException.referenceUnavailable();
}
if (transform.fieldMappings().isEmpty() || transform.fieldMappings().stream().anyMatch(mapping ->
!fields.contains(mapping.sourceField()) || outputs.stream().noneMatch(column -> mapping.targetField().equals(column.name())))
|| transform.filters().stream().anyMatch(filter -> !fields.contains(filter.field()))) {
throw BatchJobDomainException.validation("请根据当前源表和目标表的真实字段重新配置映射与过滤");
}
for (var mapping : transform.fieldMappings()) {
var from = columns.stream().filter(column -> mapping.sourceField().equals(column.name())).findFirst().orElseThrow();
var to = outputs.stream().filter(column -> mapping.targetField().equals(column.name())).findFirst().orElseThrow();
policy.requireCompatible(mapping, from.type(), from.nullable(), to.type().name(), to.nullable());
policy.requireCapacity(mapping, from, to);
}
}
private long positiveJobId(long jobId) {
if (jobId <= 0) {
throw BatchJobDomainException.validation("作业ID无效");
}
return jobId;
}
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.dataops.batchjob;
import cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextReader;
import cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextDirectory.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import static cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextReader.*;
@Component @RequiredArgsConstructor
final class P09OwnerContext implements PageAssistContextReader {
private final BatchJobService service;
@Override public String pageId(){return "P09";}
@Override public Snapshot read(Request r){
qualifiers(r);var v=service.get(numeric(r));
return snapshot(r,v.version(),"status",v.status(),"version",v.version(),"updatedAt",v.updatedAt());
}
}
@@ -0,0 +1,20 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class ChainMetricActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long orgId = LoginHelper.getDeptId();
if (actorId == null || orgId == null || actorId <= 0 || orgId <= 0) {
throw ChainMetricDomainException.forbidden();
}
return new Actor(actorId, orgId, LoginHelper.isSuperAdmin(actorId));
}
record Actor(long actorId, long orgId, boolean unrestricted) {
}
}
@@ -0,0 +1,85 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
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.dataops.api.chainmetric.ChainMetricApi.OverviewView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshRequest;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotDetailView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotPageView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyView;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/dataops/v1/chain-metrics")
public class ChainMetricController {
private final ChainMetricService service;
@SaCheckPermission("aixun:dataops:chain-metric:view")
@GetMapping("/overview")
public R<OverviewView> overview(
@RequestParam(required = false) String source,
@RequestParam(required = false) String status,
@RequestParam(required = false) String taskType,
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startedFrom,
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startedTo
) {
return R.ok(service.overview(source, status, null, taskType, startedFrom, startedTo));
}
@SaCheckPermission("aixun:dataops:chain-metric:view")
@GetMapping
public R<SnapshotPageView> list(
@RequestParam(required = false) String source,
@RequestParam(required = false) String status,
@RequestParam(required = false) String taskType,
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startedFrom,
@RequestParam(required = false)
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startedTo,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize
) {
return R.ok(service.list(source, status, null, taskType, startedFrom, startedTo, pageNum, pageSize));
}
@SaCheckPermission("aixun:dataops:chain-metric:view")
@GetMapping("/{snapshotId}")
public R<SnapshotDetailView> detail(@PathVariable long snapshotId) {
return R.ok(service.detail(snapshotId));
}
@SaCheckPermission("aixun:dataops:chain-metric:topology")
@GetMapping("/{snapshotId}/topology")
public R<TopologyView> topology(@PathVariable long snapshotId) {
return R.ok(service.topology(snapshotId));
}
@Log(title = "链路指标刷新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:dataops:chain-metric:refresh")
@PostMapping("/refresh")
public R<RefreshView> refresh(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody RefreshRequest request
) {
return R.ok(service.refresh(idempotencyKey, request));
}
}
@@ -0,0 +1,54 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import org.springframework.http.HttpStatus;
final class ChainMetricDomainException extends RuntimeException {
private final int code;
private final HttpStatus status;
private ChainMetricDomainException(int code, HttpStatus status, String message) {
super(message);
this.code = code;
this.status = status;
}
static ChainMetricDomainException validation(String message) {
return new ChainMetricDomainException(126101, HttpStatus.BAD_REQUEST, message);
}
static ChainMetricDomainException forbidden() {
return new ChainMetricDomainException(126103, HttpStatus.FORBIDDEN, "无权访问链路指标");
}
static ChainMetricDomainException notFound() {
return new ChainMetricDomainException(126104, HttpStatus.NOT_FOUND, "指标快照不存在");
}
static ChainMetricDomainException conflict(String message) {
return new ChainMetricDomainException(126109, HttpStatus.CONFLICT, message);
}
static ChainMetricDomainException ownerUnavailable() {
return new ChainMetricDomainException(126150, HttpStatus.SERVICE_UNAVAILABLE,
"运行事实来源暂不可用,本次计算已停止");
}
static ChainMetricDomainException observationUnavailable() {
return new ChainMetricDomainException(126151, HttpStatus.SERVICE_UNAVAILABLE,
"指标观察请求暂不可记录,本次刷新已停止");
}
static ChainMetricDomainException ownerVolumeExceeded() {
return new ChainMetricDomainException(126152, HttpStatus.PAYLOAD_TOO_LARGE,
"当前范围运行记录过多,请缩小时间或筛选范围");
}
int code() {
return code;
}
HttpStatus status() {
return status;
}
}
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes = ChainMetricController.class)
class ChainMetricExceptionHandler {
@ExceptionHandler(ChainMetricDomainException.class)
ResponseEntity<R<Void>> handle(ChainMetricDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,56 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.BaseMetrics;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.LatencyStats;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.TaskSummary;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public final class ChainMetricFormula {
private static final Set<Status> TERMINAL = Set.of(Status.SUCCEEDED, Status.FAILED, Status.CANCELED);
private static final Set<Status> BACKLOG = Set.of(Status.PENDING, Status.SUBMITTED, Status.RUNNING);
private ChainMetricFormula() {
}
public static BaseMetrics calculate(List<TaskSummary> runs, LocalDateTime from, LocalDateTime to) {
List<TaskSummary> facts = runs == null ? List.of() : List.copyOf(runs);
long windowMillis = Duration.between(from, to).toMillis();
if (windowMillis <= 0) throw ChainMetricDomainException.validation("指标时间范围必须大于零");
long terminalCount = facts.stream().filter(run -> TERMINAL.contains(run.status())).count();
long failedCount = facts.stream().filter(run -> run.status() == Status.FAILED).count();
long backlogCount = facts.stream().filter(run -> BACKLOG.contains(run.status())).count();
List<Long> durations = new ArrayList<>();
for (TaskSummary run : facts) {
if (run.startedAt() == null || run.completedAt() == null) continue;
long duration = Duration.between(run.startedAt(), run.completedAt()).toMillis();
if (duration < 0) continue;
durations.add(duration);
}
LatencyStats latency = null;
if (!durations.isEmpty()) {
long minimum = durations.stream().mapToLong(Long::longValue).min().orElseThrow();
long maximum = durations.stream().mapToLong(Long::longValue).max().orElseThrow();
BigDecimal sum = durations.stream().map(BigDecimal::valueOf).reduce(BigDecimal.ZERO, BigDecimal::add);
latency = new LatencyStats(durations.size(), minimum,
sum.divide(BigDecimal.valueOf(durations.size()), 2, RoundingMode.HALF_UP), maximum);
}
BigDecimal throughput = BigDecimal.valueOf(terminalCount)
.multiply(BigDecimal.valueOf(3_600_000L))
.divide(BigDecimal.valueOf(windowMillis), 6, RoundingMode.HALF_UP);
BigDecimal errorRate = terminalCount == 0 ? null : BigDecimal.valueOf(failedCount)
.divide(BigDecimal.valueOf(terminalCount), 6, RoundingMode.HALF_UP);
return new BaseMetrics(facts.size(), terminalCount, failedCount, backlogCount, latency, throughput, errorRate);
}
}
@@ -0,0 +1,187 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.MetricCategory;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.ObservedMetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotState;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyEdge;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyNode;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricOwnerAggregator.OwnerAggregate;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricPolicy.MetricQuery;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.EdgeEvidence;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.MetricEvidence;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.NodeEvidence;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.ObservationCommand;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.ObservationResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
@Component
class ChainMetricObservationGateway {
static final int MAX_METRICS = 100;
static final int MAX_NODES = 500;
static final int MAX_EDGES = 1_000;
private static final Pattern KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}");
private static final Pattern REFERENCE = Pattern.compile("[A-Za-z0-9._:-]{1,256}");
private static final Pattern SOURCE = Pattern.compile("[A-Za-z0-9._:-]{1,64}");
private static final Pattern INTERNAL_PATH = Pattern.compile("/datagov/[A-Za-z0-9/_-]{1,200}");
@DubboReference(check = false, timeout = 6_000, retries = 0)
private ChainMetricObservationService service;
ChainMetricObservationGateway() {
}
ChainMetricObservationGateway(ChainMetricObservationService service) {
this.service = service;
}
Observation observe(long requestId, Actor actor, MetricQuery query, OwnerAggregate aggregate) {
try {
ObservationResult result = service.observe(new ObservationCommand(requestId, actor.actorId(),
actor.orgId(), query.source() == null ? null : query.source().name(),
query.status() == null ? null : query.status().name(), query.projectRef(), query.taskType(),
query.startedFrom(), query.startedTo(), aggregate.ownerRuns(), aggregate.ownerRunsTruncated()));
return normalize(result);
} catch (RuntimeException | LinkageError exception) {
return unknown("CHAIN_METRIC_GATEWAY_UNAVAILABLE", "当前无法确认外部指标或链路信息");
}
}
private static Observation normalize(ObservationResult result) {
if (result == null || result.state() == null) {
return unknown("CHAIN_METRIC_RESPONSE_MISSING", "外部观察响应不完整");
}
if (result.state() != ChainMetricObservationService.State.AVAILABLE) {
SnapshotState state = result.state() == ChainMetricObservationService.State.UNSUPPORTED
? SnapshotState.UNSUPPORTED : SnapshotState.UNKNOWN;
return new Observation(state, List.of(), List.of(), List.of(), false,
result.observedAt() == null ? LocalDateTime.now() : result.observedAt(), null, null,
safe(result.errorCode(), 64), safe(result.errorSummary(), 512));
}
if (result.observedAt() == null || !matches(SOURCE, result.source())
|| !matches(REFERENCE, result.evidenceRef())) {
return unknown("CHAIN_METRIC_EVIDENCE_INCOMPLETE", "外部观察缺少来源、时间或证据引用");
}
List<ObservedMetric> metrics = normalizeMetrics(result.metrics());
if (metrics == null) return unknown("CHAIN_METRIC_VALUE_INVALID", "外部资源或成本证据不完整");
Map<String, TopologyNode> nodes = normalizeNodes(result.nodes());
if (nodes == null) return unknown("CHAIN_METRIC_NODE_INVALID", "外部节点证据不完整或重复");
List<TopologyEdge> edges = normalizeEdges(result.edges(), nodes.keySet());
if (edges == null) return unknown("CHAIN_METRIC_EDGE_INVALID", "外部链路边缺少证据或存在悬空端点");
if (metrics.isEmpty() && nodes.isEmpty() && edges.isEmpty()) {
return unknown("CHAIN_METRIC_EVIDENCE_EMPTY", "外部观察没有可证明的指标或链路");
}
metrics = metrics.stream().sorted(Comparator.comparing(ObservedMetric::metricKey)
.thenComparing(value -> value.category().name())).toList();
List<TopologyNode> sortedNodes = nodes.values().stream().sorted(Comparator.comparing(TopologyNode::nodeId))
.toList();
edges = edges.stream().sorted(Comparator.comparing(TopologyEdge::sourceNodeId)
.thenComparing(TopologyEdge::targetNodeId).thenComparing(TopologyEdge::relationType)
.thenComparing(TopologyEdge::evidenceRef)).toList();
boolean truncated = result.truncated() || metrics.size() > MAX_METRICS || sortedNodes.size() > MAX_NODES
|| edges.size() > MAX_EDGES;
if (metrics.size() > MAX_METRICS) metrics = List.copyOf(metrics.subList(0, MAX_METRICS));
if (sortedNodes.size() > MAX_NODES) sortedNodes = List.copyOf(sortedNodes.subList(0, MAX_NODES));
Set<String> retainedNodes = sortedNodes.stream().map(TopologyNode::nodeId).collect(java.util.stream.Collectors.toSet());
List<TopologyEdge> retainedEdges = edges.stream().filter(edge -> retainedNodes.contains(edge.sourceNodeId())
&& retainedNodes.contains(edge.targetNodeId())).limit(MAX_EDGES).toList();
if (retainedEdges.size() != edges.size()) truncated = true;
return new Observation(SnapshotState.AVAILABLE, metrics, sortedNodes, retainedEdges, truncated,
result.observedAt(), result.source(), result.evidenceRef(), safe(result.errorCode(), 64),
safe(result.errorSummary(), 512));
}
private static List<ObservedMetric> normalizeMetrics(List<MetricEvidence> values) {
List<ObservedMetric> result = new ArrayList<>();
Set<String> keys = new HashSet<>();
for (MetricEvidence value : values == null ? List.<MetricEvidence>of() : values) {
if (value == null || !matches(KEY, value.metricKey()) || value.category() == null || value.value() == null
|| value.value().signum() < 0 || !matches(KEY, value.unit()) || value.observedAt() == null
|| !matches(SOURCE, value.source()) || !matches(REFERENCE, value.evidenceRef())) return null;
String unique = value.category().name() + ':' + value.metricKey();
if (!keys.add(unique)) return null;
MetricCategory category = value.category() == ChainMetricObservationService.MetricCategory.RESOURCE
? MetricCategory.RESOURCE : MetricCategory.COST;
result.add(new ObservedMetric(value.metricKey(), category, value.value(), value.unit(),
value.observedAt(), value.source(), value.evidenceRef()));
}
return result;
}
private static Map<String, TopologyNode> normalizeNodes(List<NodeEvidence> values) {
Map<String, TopologyNode> result = new HashMap<>();
for (NodeEvidence value : values == null ? List.<NodeEvidence>of() : values) {
if (value == null || !matches(KEY, value.nodeId()) || !matches(KEY, value.nodeType())
|| value.displayName() == null || value.displayName().isBlank() || value.observedAt() == null
|| !matches(REFERENCE, value.evidenceRef())
|| (!blank(value.ownerReference()) && !matches(REFERENCE, value.ownerReference()))
|| (!blank(value.externalReference()) && !matches(REFERENCE, value.externalReference()))
|| (!blank(value.internalPath()) && !INTERNAL_PATH.matcher(value.internalPath()).matches())) return null;
TopologyNode node = new TopologyNode(value.nodeId(), value.nodeType(), safe(value.displayName(), 128),
value.ownerReference(), value.externalReference(), value.observedAt(), value.evidenceRef(),
blank(value.internalPath()) ? null : value.internalPath());
if (result.putIfAbsent(node.nodeId(), node) != null) return null;
}
return result;
}
private static List<TopologyEdge> normalizeEdges(List<EdgeEvidence> values, Set<String> nodeIds) {
List<TopologyEdge> result = new ArrayList<>();
Set<String> keys = new HashSet<>();
for (EdgeEvidence value : values == null ? List.<EdgeEvidence>of() : values) {
if (value == null || !matches(KEY, value.sourceNodeId()) || !matches(KEY, value.targetNodeId())
|| !matches(KEY, value.relationType()) || !matches(REFERENCE, value.evidenceRef())
|| !nodeIds.contains(value.sourceNodeId()) || !nodeIds.contains(value.targetNodeId())) return null;
String key = value.sourceNodeId() + '|' + value.targetNodeId() + '|' + value.relationType() + '|'
+ value.evidenceRef();
if (!keys.add(key)) return null;
result.add(new TopologyEdge(value.sourceNodeId(), value.targetNodeId(), value.relationType(),
value.evidenceRef()));
}
return result;
}
private static Observation unknown(String code, String summary) {
return new Observation(SnapshotState.UNKNOWN, List.of(), List.of(), List.of(), false, LocalDateTime.now(),
null, null, code, summary);
}
private static boolean matches(Pattern pattern, String value) {
return value != null && pattern.matcher(value).matches();
}
private static boolean blank(String value) {
return value == null || value.isBlank();
}
private static String safe(String value, int maximum) {
return ChainMetricSanitizer.safe(value, maximum);
}
record Observation(SnapshotState state, List<ObservedMetric> metrics, List<TopologyNode> nodes,
List<TopologyEdge> edges, boolean truncated, LocalDateTime observedAt, String source,
String evidenceRef, String errorCode, String errorSummary) {
Observation {
metrics = metrics == null ? List.of() : List.copyOf(metrics);
nodes = nodes == null ? List.of() : List.copyOf(nodes);
edges = edges == null ? List.of() : List.copyOf(edges);
}
}
}
@@ -0,0 +1,101 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.BaseMetrics;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.OverviewView;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.TaskSummary;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.DirectoryState;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.OwnerListResult;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogOwnerDirectory.OwnerQuery;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricPolicy.MetricQuery;
import cn.aixunkeji.datagov.integration.api.chainmetric.ChainMetricObservationService.OwnerRunReference;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Component
@RequiredArgsConstructor
class ChainMetricOwnerAggregator {
static final int MAX_OWNER_ROWS_PER_SOURCE = 50_000;
static final int MAX_EXTERNAL_OWNER_REFERENCES = 500;
private static final Comparator<TaskSummary> ORDER = Comparator
.comparing(TaskSummary::updatedAt, Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(row -> row.source().name())
.thenComparing(TaskSummary::runId, Comparator.reverseOrder());
private final List<TaskLogOwnerDirectory> directories;
OwnerAggregate aggregate(Actor actor, MetricQuery query) {
List<TaskSummary> runs = new ArrayList<>();
for (Source source : query.source() == null ? List.of(Source.values()) : List.of(query.source())) {
OwnerListResult result = directory(source).list(new OwnerQuery(actor.actorId(), actor.orgId(),
actor.unrestricted(), null, query.status(), query.projectRef(), query.taskType(), query.startedFrom(),
query.startedTo(), MAX_OWNER_ROWS_PER_SOURCE + 1));
if (result.state() != DirectoryState.AVAILABLE) throw ChainMetricDomainException.ownerUnavailable();
if (result.total() > MAX_OWNER_ROWS_PER_SOURCE || result.rows().size() > MAX_OWNER_ROWS_PER_SOURCE) {
throw ChainMetricDomainException.ownerVolumeExceeded();
}
result.rows().forEach(row -> validateAndAdd(actor, query, source, row, runs));
}
runs.sort(ORDER);
ensureUnique(runs);
BaseMetrics metrics = ChainMetricFormula.calculate(runs, query.startedFrom(), query.startedTo());
List<OwnerRunReference> references = runs.stream().limit(MAX_EXTERNAL_OWNER_REFERENCES)
.map(ChainMetricOwnerAggregator::reference).toList();
return new OwnerAggregate(new OverviewView(query.view(), metrics, LocalDateTime.now()), references,
runs.size() > references.size());
}
private TaskLogOwnerDirectory directory(Source source) {
List<TaskLogOwnerDirectory> matches = directories.stream().filter(value -> value.source() == source).toList();
if (matches.size() != 1) throw ChainMetricDomainException.ownerUnavailable();
return matches.getFirst();
}
private static void validateAndAdd(Actor actor, MetricQuery query, Source source, TaskSummary row,
List<TaskSummary> target) {
if (row == null || row.source() != source || row.runId() == null || row.runId() <= 0 || row.status() == null) {
throw ChainMetricDomainException.ownerUnavailable();
}
if (source == Source.M2_GOLDEN) {
if (!actor.unrestricted() || row.orgId() != null) throw ChainMetricDomainException.ownerUnavailable();
} else if (row.orgId() == null || row.orgId() != actor.orgId()) {
throw ChainMetricDomainException.ownerUnavailable();
}
LocalDateTime effectiveStart = row.startedAt() == null ? row.createdAt() : row.startedAt();
if (effectiveStart == null) throw ChainMetricDomainException.ownerUnavailable();
if (effectiveStart.isBefore(query.startedFrom()) || effectiveStart.isAfter(query.startedTo())) return;
target.add(row);
}
private static void ensureUnique(List<TaskSummary> runs) {
Set<String> keys = new HashSet<>();
for (TaskSummary run : runs) {
if (!keys.add(run.source().name() + ':' + run.runId())) {
throw ChainMetricDomainException.ownerUnavailable();
}
}
}
private static OwnerRunReference reference(TaskSummary run) {
return new OwnerRunReference(run.source().name(), run.runId(), run.source().name() + ':' + run.runId(),
run.dolphinSchedulerInstanceId(), run.seaTunnelJobId(), run.status().name(), run.startedAt(),
run.completedAt());
}
record OwnerAggregate(OverviewView overview, List<OwnerRunReference> ownerRuns, boolean ownerRunsTruncated) {
OwnerAggregate {
ownerRuns = ownerRuns == null ? List.of() : List.copyOf(ownerRuns);
}
}
}
@@ -0,0 +1,97 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.QueryView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshRequest;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Locale;
import java.util.regex.Pattern;
@Component
class ChainMetricPolicy {
private static final Pattern IDEMPOTENCY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
MetricQuery query(String source, String status, String projectRef, String taskType,
LocalDateTime startedFrom, LocalDateTime startedTo) {
return query(source, status, projectRef, taskType, startedFrom, startedTo, LocalDateTime.now());
}
MetricQuery query(RefreshRequest request) {
if (request == null) throw ChainMetricDomainException.validation("刷新条件不能为空");
return query(request.source(), request.status(), null, request.taskType(),
request.startedFrom(), request.startedTo());
}
MetricQuery query(String source, String status, String projectRef, String taskType,
LocalDateTime startedFrom, LocalDateTime startedTo, LocalDateTime now) {
LocalDateTime to = startedTo == null ? now : startedTo;
LocalDateTime from = startedFrom == null ? to.minusHours(24) : startedFrom;
if (!from.isBefore(to) || from.isBefore(to.minusDays(31))) {
throw ChainMetricDomainException.validation("时间范围不合法或超过31天");
}
return new MetricQuery(enumValue(Source.class, source, "来源"), enumValue(Status.class, status, "状态"),
text(projectRef, 64, "项目"), text(taskType, 32, "任务类型"), from, to);
}
int pageNum(Integer value) {
int result = value == null ? 1 : value;
if (result < 1 || result > 1_000) throw ChainMetricDomainException.validation("页码不合法");
return result;
}
int pageSize(Integer value) {
int result = value == null ? 20 : value;
if (result < 1 || result > 100) throw ChainMetricDomainException.validation("每页数量必须在1到100之间");
return result;
}
long snapshotId(long value) {
if (value <= 0) throw ChainMetricDomainException.validation("快照ID不合法");
return value;
}
String idempotencyKey(String value) {
if (value == null || !IDEMPOTENCY.matcher(value.trim()).matches()) {
throw ChainMetricDomainException.validation("Idempotency-Key不合法");
}
return value.trim();
}
String requestHash(MetricQuery query) {
return ChainMetricSanitizer.sha256((query.source() == null ? "" : query.source().name()) + '|'
+ (query.status() == null ? "" : query.status().name()) + '|'
+ nullToEmpty(query.projectRef()) + '|' + nullToEmpty(query.taskType()) + '|'
+ query.startedFrom() + '|' + query.startedTo());
}
private static <E extends Enum<E>> E enumValue(Class<E> type, String value, String label) {
if (value == null || value.isBlank()) return null;
try {
return Enum.valueOf(type, value.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException exception) {
throw ChainMetricDomainException.validation(label + "不合法");
}
}
private static String text(String value, int maximum, String label) {
if (value == null || value.isBlank()) return null;
String result = value.trim();
if (result.length() > maximum) throw ChainMetricDomainException.validation(label + "长度超过限制");
return result;
}
private static String nullToEmpty(String value) {
return value == null ? "" : value;
}
record MetricQuery(Source source, Status status, String projectRef, String taskType,
LocalDateTime startedFrom, LocalDateTime startedTo) {
QueryView view() {
return new QueryView(source, status, projectRef, taskType, startedFrom, startedTo);
}
}
}
@@ -0,0 +1,359 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.BaseMetrics;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.LatencyStats;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.MetricCategory;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.ObservedMetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.QueryView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotDetailView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotPageView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotState;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotSummary;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyEdge;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyNode;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyView;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Source;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.Status;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricObservationGateway.Observation;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricPolicy.MetricQuery;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Repository
class ChainMetricRepository {
private static final String SUMMARY_SELECT = """
SELECT s.snapshot_id, s.snapshot_state, s.run_count, s.terminal_count, s.failed_count,
s.backlog_count, s.latency_sample_count, s.latency_min_ms, s.latency_average_ms,
s.latency_max_ms, s.throughput_per_hour, s.error_rate, s.external_source,
s.evidence_ref, s.error_code, s.error_summary, s.observed_at, s.create_time,
s.truncated_flag, q.source_type, q.run_status, q.project_ref, q.task_type,
q.window_from, q.window_to
FROM ops_chain_metric_snapshot s
JOIN ops_chain_metric_observation_request q
ON q.observation_request_id=s.observation_request_id
""";
private static final String REFRESH_SELECT = """
SELECT q.observation_request_id, q.request_status, q.error_code AS request_error_code,
q.error_summary AS request_error_summary, q.create_time,
s.snapshot_id, s.snapshot_state, s.error_code AS snapshot_error_code,
s.error_summary AS snapshot_error_summary, s.observed_at, s.truncated_flag
FROM ops_chain_metric_observation_request q
LEFT JOIN ops_chain_metric_snapshot s
ON s.observation_request_id=q.observation_request_id AND s.del_flag='0'
""";
private final JdbcTemplate jdbcTemplate;
private final TransactionTemplate transactionTemplate;
ChainMetricRepository(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.transactionTemplate = transactionTemplate;
}
Reservation reserve(Actor actor, MetricQuery query, String idempotencyKey, String requestHash) {
try {
Reservation result = transactionTemplate.execute(status -> {
RefreshView replay = replay(actor, idempotencyKey, requestHash);
if (replay != null) return new Reservation(replay, false);
long requestId = IdGeneratorUtil.nextLongId();
jdbcTemplate.update("""
INSERT INTO ops_chain_metric_observation_request (
observation_request_id, actor_id, org_id, source_type, run_status, project_ref,
task_type, window_from, window_to, idempotency_key, request_sha256, request_status,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?)
""", requestId, actor.actorId(), actor.orgId(), name(query.source()), name(query.status()),
query.projectRef(), query.taskType(), Timestamp.valueOf(query.startedFrom()),
Timestamp.valueOf(query.startedTo()), idempotencyKey, requestHash, actor.orgId(),
actor.actorId(), actor.actorId());
return new Reservation(requireRefresh(actor, requestId), true);
});
if (result == null) throw ChainMetricDomainException.observationUnavailable();
return result;
} catch (DuplicateKeyException exception) {
RefreshView replay = replay(actor, idempotencyKey, requestHash);
if (replay == null) throw ChainMetricDomainException.observationUnavailable();
return new Reservation(replay, false);
}
}
RefreshView complete(long requestId, Actor actor, BaseMetrics baseMetrics, Observation observation) {
try {
RefreshView result = transactionTemplate.execute(status -> {
RefreshView current = requireRefresh(actor, requestId);
if (current.snapshotId() != null) return current;
long snapshotId = IdGeneratorUtil.nextLongId();
LatencyStats latency = baseMetrics.latency();
String contentHash = contentHash(baseMetrics, observation);
jdbcTemplate.update("""
INSERT INTO ops_chain_metric_snapshot (
snapshot_id, observation_request_id, snapshot_state, run_count, terminal_count,
failed_count, backlog_count, latency_sample_count, latency_min_ms, latency_average_ms,
latency_max_ms, throughput_per_hour, error_rate, external_source, evidence_ref,
content_sha256, truncated_flag, error_code, error_summary, observed_at,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", snapshotId, requestId, observation.state().name(), baseMetrics.runCount(),
baseMetrics.terminalCount(), baseMetrics.failedCount(), baseMetrics.backlogCount(),
latency == null ? 0 : latency.sampleCount(), latency == null ? null : latency.minimumMs(),
latency == null ? null : latency.averageMs(), latency == null ? null : latency.maximumMs(),
baseMetrics.throughputPerHour(), baseMetrics.errorRate(), observation.source(),
observation.evidenceRef(), contentHash, observation.truncated() ? "1" : "0",
ChainMetricSanitizer.safe(observation.errorCode(), 64),
ChainMetricSanitizer.safe(observation.errorSummary(), 512),
Timestamp.valueOf(observation.observedAt() == null ? LocalDateTime.now() : observation.observedAt()),
actor.orgId(), actor.actorId(), actor.actorId());
insertMetrics(snapshotId, actor, observation.metrics());
insertNodes(snapshotId, actor, observation.nodes());
insertEdges(snapshotId, actor, observation.edges());
jdbcTemplate.update("""
UPDATE ops_chain_metric_observation_request
SET request_status=?, error_code=?, error_summary=?, update_by=?, version=version+1
WHERE observation_request_id=? AND actor_id=? AND org_id=? AND del_flag='0'
""", observation.state().name(), ChainMetricSanitizer.safe(observation.errorCode(), 64),
ChainMetricSanitizer.safe(observation.errorSummary(), 512), actor.actorId(), requestId,
actor.actorId(), actor.orgId());
return requireRefresh(actor, requestId);
});
if (result == null) throw ChainMetricDomainException.observationUnavailable();
return result;
} catch (DuplicateKeyException exception) {
return requireRefresh(actor, requestId);
}
}
RefreshView fail(long requestId, Actor actor, String errorCode, String errorSummary) {
jdbcTemplate.update("""
UPDATE ops_chain_metric_observation_request
SET request_status='UNKNOWN', error_code=?, error_summary=?, update_by=?, version=version+1
WHERE observation_request_id=? AND actor_id=? AND org_id=? AND request_status='PENDING' AND del_flag='0'
""", ChainMetricSanitizer.safe(errorCode, 64), ChainMetricSanitizer.safe(errorSummary, 512),
actor.actorId(), requestId, actor.actorId(), actor.orgId());
return requireRefresh(actor, requestId);
}
SnapshotPageView list(Actor actor, MetricQuery query, int pageNum, int pageSize) {
StringBuilder where = new StringBuilder(" WHERE s.del_flag='0' AND q.del_flag='0' AND q.org_id=?");
List<Object> parameters = new ArrayList<>();
parameters.add(actor.orgId());
if (!actor.unrestricted()) {
where.append(" AND q.actor_id=?");
parameters.add(actor.actorId());
}
appendFilter(where, parameters, "q.source_type", name(query.source()));
appendFilter(where, parameters, "q.run_status", name(query.status()));
appendFilter(where, parameters, "q.project_ref", query.projectRef());
appendFilter(where, parameters, "q.task_type", query.taskType());
where.append(" AND q.window_from<=? AND q.window_to>=?");
parameters.add(Timestamp.valueOf(query.startedTo()));
parameters.add(Timestamp.valueOf(query.startedFrom()));
Long total = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM ops_chain_metric_snapshot s "
+ "JOIN ops_chain_metric_observation_request q ON q.observation_request_id=s.observation_request_id"
+ where, Long.class, parameters.toArray());
List<Object> pageParameters = new ArrayList<>(parameters);
pageParameters.add(pageSize);
pageParameters.add((pageNum - 1) * pageSize);
List<SnapshotSummary> rows = jdbcTemplate.query(SUMMARY_SELECT + where
+ " ORDER BY s.observed_at DESC, s.snapshot_id DESC LIMIT ? OFFSET ?",
(resultSet, rowNum) -> mapSummary(resultSet), pageParameters.toArray());
return new SnapshotPageView(rows, total == null ? 0 : total);
}
SnapshotDetailView detail(Actor actor, long snapshotId) {
SnapshotSummary summary = requireSummary(actor, snapshotId);
List<ObservedMetric> metrics = jdbcTemplate.query("""
SELECT metric_key, metric_category, metric_value, metric_unit, observed_at, source_type, evidence_ref
FROM ops_chain_metric_value
WHERE snapshot_id=? AND del_flag='0'
ORDER BY metric_category, metric_key
""", (resultSet, rowNum) -> new ObservedMetric(resultSet.getString("metric_key"),
MetricCategory.valueOf(resultSet.getString("metric_category")), resultSet.getBigDecimal("metric_value"),
resultSet.getString("metric_unit"), localDateTime(resultSet.getTimestamp("observed_at")),
resultSet.getString("source_type"), resultSet.getString("evidence_ref")), snapshotId);
return new SnapshotDetailView(summary, metrics);
}
TopologyView topology(Actor actor, long snapshotId) {
SnapshotSummary summary = requireSummary(actor, snapshotId);
List<TopologyNode> nodes = jdbcTemplate.query("""
SELECT node_id, node_type, display_name, owner_reference, external_reference, observed_at,
evidence_ref, internal_path
FROM ops_chain_metric_node
WHERE snapshot_id=? AND del_flag='0'
ORDER BY node_id
""", (resultSet, rowNum) -> new TopologyNode(resultSet.getString("node_id"),
resultSet.getString("node_type"), resultSet.getString("display_name"),
resultSet.getString("owner_reference"), resultSet.getString("external_reference"),
localDateTime(resultSet.getTimestamp("observed_at")), resultSet.getString("evidence_ref"),
resultSet.getString("internal_path")), snapshotId);
List<TopologyEdge> edges = jdbcTemplate.query("""
SELECT source_node_id, target_node_id, relation_type, evidence_ref
FROM ops_chain_metric_edge
WHERE snapshot_id=? AND del_flag='0'
ORDER BY source_node_id, target_node_id, relation_type, evidence_ref
""", (resultSet, rowNum) -> new TopologyEdge(resultSet.getString("source_node_id"),
resultSet.getString("target_node_id"), resultSet.getString("relation_type"),
resultSet.getString("evidence_ref")), snapshotId);
return new TopologyView(summary.state(), nodes, edges, summary.truncated(), summary.observedAt(),
summary.externalSource(), summary.evidenceRef(), summary.errorCode(), summary.errorSummary());
}
private RefreshView replay(Actor actor, String idempotencyKey, String requestHash) {
List<RequestHashRow> rows = jdbcTemplate.query("""
SELECT observation_request_id, request_sha256
FROM ops_chain_metric_observation_request
WHERE actor_id=? AND org_id=? AND idempotency_key=? AND del_flag='0'
""", (resultSet, rowNum) -> new RequestHashRow(resultSet.getLong(1), resultSet.getString(2)),
actor.actorId(), actor.orgId(), idempotencyKey);
if (rows.isEmpty()) return null;
RequestHashRow row = rows.getFirst();
assertReplayHash(requestHash, row.requestHash());
return requireRefresh(actor, row.requestId());
}
static void assertReplayHash(String requested, String recorded) {
if (!requested.equals(recorded)) {
throw ChainMetricDomainException.conflict("同一幂等键不能用于不同指标观察请求");
}
}
private RefreshView requireRefresh(Actor actor, long requestId) {
List<RefreshView> rows = jdbcTemplate.query(REFRESH_SELECT + """
WHERE q.observation_request_id=? AND q.actor_id=? AND q.org_id=? AND q.del_flag='0'
""", (resultSet, rowNum) -> mapRefresh(resultSet), requestId, actor.actorId(), actor.orgId());
if (rows.isEmpty()) throw ChainMetricDomainException.observationUnavailable();
return rows.getFirst();
}
private SnapshotSummary requireSummary(Actor actor, long snapshotId) {
String scope = actor.unrestricted() ? "" : " AND q.actor_id=?";
List<Object> parameters = new ArrayList<>(List.of(snapshotId, actor.orgId()));
if (!actor.unrestricted()) parameters.add(actor.actorId());
List<SnapshotSummary> rows = jdbcTemplate.query(SUMMARY_SELECT
+ " WHERE s.snapshot_id=? AND s.del_flag='0' AND q.org_id=? AND q.del_flag='0'" + scope,
(resultSet, rowNum) -> mapSummary(resultSet), parameters.toArray());
if (rows.isEmpty()) throw ChainMetricDomainException.notFound();
return rows.getFirst();
}
private void insertMetrics(long snapshotId, Actor actor, List<ObservedMetric> metrics) {
for (ObservedMetric metric : metrics) {
jdbcTemplate.update("""
INSERT INTO ops_chain_metric_value (
metric_value_id, snapshot_id, metric_key, metric_category, metric_value, metric_unit,
observed_at, source_type, evidence_ref, create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), snapshotId, metric.metricKey(), metric.category().name(),
metric.value(), metric.unit(), Timestamp.valueOf(metric.observedAt()), metric.source(),
metric.evidenceRef(), actor.orgId(), actor.actorId(), actor.actorId());
}
}
private void insertNodes(long snapshotId, Actor actor, List<TopologyNode> nodes) {
for (TopologyNode node : nodes) {
jdbcTemplate.update("""
INSERT INTO ops_chain_metric_node (
metric_node_id, snapshot_id, node_id, node_type, display_name, owner_reference,
external_reference, observed_at, evidence_ref, internal_path, create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), snapshotId, node.nodeId(), node.nodeType(), node.displayName(),
node.ownerReference(), node.externalReference(), Timestamp.valueOf(node.observedAt()),
node.evidenceRef(), node.internalPath(), actor.orgId(), actor.actorId(), actor.actorId());
}
}
private void insertEdges(long snapshotId, Actor actor, List<TopologyEdge> edges) {
for (TopologyEdge edge : edges) {
jdbcTemplate.update("""
INSERT INTO ops_chain_metric_edge (
metric_edge_id, snapshot_id, source_node_id, target_node_id, relation_type, evidence_ref,
create_dept, create_by, update_by
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", IdGeneratorUtil.nextLongId(), snapshotId, edge.sourceNodeId(), edge.targetNodeId(),
edge.relationType(), edge.evidenceRef(), actor.orgId(), actor.actorId(), actor.actorId());
}
}
private static RefreshView mapRefresh(ResultSet resultSet) throws SQLException {
String snapshotState = resultSet.getString("snapshot_state");
String snapshotErrorCode = resultSet.getString("snapshot_error_code");
String snapshotErrorSummary = resultSet.getString("snapshot_error_summary");
return new RefreshView(resultSet.getLong("observation_request_id"), nullableLong(resultSet, "snapshot_id"),
SnapshotState.valueOf(snapshotState == null ? resultSet.getString("request_status") : snapshotState),
snapshotErrorCode == null ? resultSet.getString("request_error_code") : snapshotErrorCode,
snapshotErrorSummary == null ? resultSet.getString("request_error_summary") : snapshotErrorSummary,
localDateTime(resultSet.getTimestamp("observed_at")),
localDateTime(resultSet.getTimestamp("create_time")), "1".equals(resultSet.getString("truncated_flag")));
}
private static SnapshotSummary mapSummary(ResultSet resultSet) throws SQLException {
long latencySamples = resultSet.getLong("latency_sample_count");
LatencyStats latency = latencySamples == 0 ? null : new LatencyStats(latencySamples,
resultSet.getLong("latency_min_ms"), resultSet.getBigDecimal("latency_average_ms"),
resultSet.getLong("latency_max_ms"));
BaseMetrics metrics = new BaseMetrics(resultSet.getLong("run_count"),
resultSet.getLong("terminal_count"), resultSet.getLong("failed_count"),
resultSet.getLong("backlog_count"), latency, resultSet.getBigDecimal("throughput_per_hour"),
resultSet.getBigDecimal("error_rate"));
QueryView query = new QueryView(enumValue(Source.class, resultSet.getString("source_type")),
enumValue(Status.class, resultSet.getString("run_status")), resultSet.getString("project_ref"),
resultSet.getString("task_type"), localDateTime(resultSet.getTimestamp("window_from")),
localDateTime(resultSet.getTimestamp("window_to")));
return new SnapshotSummary(resultSet.getLong("snapshot_id"),
SnapshotState.valueOf(resultSet.getString("snapshot_state")), query, metrics,
resultSet.getString("external_source"), resultSet.getString("evidence_ref"),
resultSet.getString("error_code"), resultSet.getString("error_summary"),
localDateTime(resultSet.getTimestamp("observed_at")),
localDateTime(resultSet.getTimestamp("create_time")), "1".equals(resultSet.getString("truncated_flag")));
}
private static String contentHash(BaseMetrics metrics, Observation observation) {
return ChainMetricSanitizer.sha256(metrics + "|" + observation.state() + "|" + observation.metrics()
+ "|" + observation.nodes() + "|" + observation.edges() + "|" + observation.source() + "|"
+ observation.evidenceRef() + "|" + observation.observedAt() + "|" + observation.truncated());
}
private static void appendFilter(StringBuilder where, List<Object> parameters, String column, String value) {
if (value == null) return;
where.append(" AND ").append(column).append("=?");
parameters.add(value);
}
private static String name(Enum<?> value) {
return value == null ? null : value.name();
}
private static <E extends Enum<E>> E enumValue(Class<E> type, String value) {
return value == null ? null : Enum.valueOf(type, value);
}
private static Long nullableLong(ResultSet resultSet, String column) throws SQLException {
long value = resultSet.getLong(column);
return resultSet.wasNull() ? null : value;
}
private static LocalDateTime localDateTime(Timestamp value) {
return value == null ? null : value.toLocalDateTime();
}
record Reservation(RefreshView view, boolean newRequest) {
}
private record RequestHashRow(long requestId, String requestHash) {
}
}
@@ -0,0 +1,38 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.regex.Pattern;
final class ChainMetricSanitizer {
private static final Pattern HEADER = Pattern.compile(
"(?i)\\b(authorization|cookie|set-cookie)\\b\\s*[:=]\\s*[^,;\\r\\n]+"
);
private static final Pattern KEY_VALUE = Pattern.compile(
"(?i)\\b(password|passwd|pwd|token|secret|credential|private[_-]?key)\\b\\s*[:=]\\s*"
+ "(?:\"[^\"]*\"|'[^']*'|[^,;\\s]+)"
);
private ChainMetricSanitizer() {
}
static String safe(String value, int maximum) {
if (value == null) return null;
String redacted = HEADER.matcher(value).replaceAll("$1=[REDACTED]");
redacted = KEY_VALUE.matcher(redacted).replaceAll("$1=[REDACTED]");
redacted = redacted.replace('\r', ' ').replace('\n', ' ').trim();
return redacted.length() <= maximum ? redacted : redacted.substring(0, maximum);
}
static String sha256(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest((value == null ? "" : value).getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("SHA-256 is unavailable", exception);
}
}
}
@@ -0,0 +1,91 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.OverviewView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshRequest;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.RefreshView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotDetailView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.SnapshotPageView;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainMetricApi.TopologyView;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricActorProvider.Actor;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricOwnerAggregator.OwnerAggregate;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricPolicy.MetricQuery;
import cn.aixunkeji.datagov.dataops.chainmetric.ChainMetricRepository.Reservation;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
@Service
@RequiredArgsConstructor
class ChainMetricService {
private final ChainMetricActorProvider actorProvider;
private final ChainMetricPolicy policy;
private final ChainMetricOwnerAggregator ownerAggregator;
private final ChainMetricObservationGateway observationGateway;
private final ChainMetricRepository repository;
OverviewView overview(String source, String status, String projectRef, String taskType,
LocalDateTime startedFrom, LocalDateTime startedTo) {
Actor actor = actorProvider.current();
MetricQuery query = policy.query(source, status, projectRef, taskType, startedFrom, startedTo);
return ownerAggregator.aggregate(actor, query).overview();
}
SnapshotPageView list(String source, String status, String projectRef, String taskType,
LocalDateTime startedFrom, LocalDateTime startedTo, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
MetricQuery query = policy.query(source, status, projectRef, taskType, startedFrom, startedTo);
return repository.list(actor, query, policy.pageNum(pageNum), policy.pageSize(pageSize));
}
SnapshotDetailView detail(long snapshotId) {
return repository.detail(actorProvider.current(), policy.snapshotId(snapshotId));
}
TopologyView topology(long snapshotId) {
return repository.topology(actorProvider.current(), policy.snapshotId(snapshotId));
}
RefreshView refresh(String idempotencyKey, RefreshRequest request) {
Actor actor = actorProvider.current();
MetricQuery query = policy.query(request);
String key = policy.idempotencyKey(idempotencyKey);
Reservation reservation;
try {
reservation = repository.reserve(actor, query, key, policy.requestHash(query));
} catch (ChainMetricDomainException exception) {
throw exception;
} catch (RuntimeException exception) {
throw ChainMetricDomainException.observationUnavailable();
}
if (!reservation.newRequest()) return reservation.view();
OwnerAggregate aggregate;
try {
aggregate = ownerAggregator.aggregate(actor, query);
} catch (ChainMetricDomainException exception) {
failReservation(reservation.view().observationRequestId(), actor, "CHAIN_OWNER_FACTS_UNAVAILABLE",
exception.getMessage());
throw exception;
}
var observation = observationGateway.observe(reservation.view().observationRequestId(), actor, query,
aggregate);
try {
return repository.complete(reservation.view().observationRequestId(), actor, aggregate.overview().metrics(),
observation);
} catch (ChainMetricDomainException exception) {
throw exception;
} catch (RuntimeException exception) {
throw ChainMetricDomainException.observationUnavailable();
}
}
private void failReservation(long requestId, Actor actor, String code, String summary) {
try {
repository.fail(requestId, actor, code, summary);
} catch (RuntimeException ignored) {
// The original Owner failure remains authoritative; no external call was made.
}
}
}
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.system.api.RemoteUserService;
import java.time.Instant;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
class ChainStageEvidenceAuthority {
@DubboReference(check=false,timeout=3000,retries=0) private RemoteUserService users;
void require(ChainMetricActorProvider.Actor actor){
String purpose="CHAIN_STAGE_VIEW";
try {var d=users.resolveAssetActor(actor.actorId(),actor.orgId(),purpose);var now=Instant.now();
if(d!=null&&d.allowed()&&d.userId()==actor.actorId()&&d.deptId()==actor.orgId()&&purpose.equals(d.purpose())&&d.checkedAt()!=null&&!d.checkedAt().isBefore(now.minusSeconds(10))&&!d.checkedAt().isAfter(now.plusSeconds(5)))return;
}catch(RuntimeException ignored){}throw ChainMetricDomainException.forbidden();
}
}
@@ -0,0 +1,11 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainStageEvidenceDirectory.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/dataops/v1/chain-metrics/stage-evidence")
public class ChainStageEvidenceController {
private final ChainStageEvidenceService service;public ChainStageEvidenceController(ChainStageEvidenceService service){this.service=service;}
@PostMapping @SaCheckPermission("aixun:dataops:chain-metric:view") public R<Context> current(@RequestBody Selection selection){return R.ok(service.current(selection));}
@ExceptionHandler(ChainMetricDomainException.class)org.springframework.http.ResponseEntity<R<Void>> error(ChainMetricDomainException e){return org.springframework.http.ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
}
@@ -0,0 +1,8 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainStageEvidenceDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=ChainStageEvidenceDirectory.VERSION,timeout=20000,retries=0)
public class ChainStageEvidenceDubboService implements ChainStageEvidenceDirectory {
private final ChainStageEvidenceService service;public ChainStageEvidenceDubboService(ChainStageEvidenceService service){this.service=service;}
@Override public Context current(Selection selection){return service.current(selection);}
}
@@ -0,0 +1,26 @@
package cn.aixunkeji.datagov.dataops.chainmetric;
import cn.aixunkeji.datagov.dataops.api.chainmetric.ChainStageEvidenceDirectory.*;
import cn.aixunkeji.datagov.dataops.api.tasklog.TaskLogApi.*;
import java.time.Duration;
import java.util.*;
final class ChainStageEvidencePolicy {
static final int MAX_ROWS=5000,MAX_CANDIDATES=100;
static final String BOUNDARY="CURRENT_SAVED_M2_STAGES_ONLY";
private ChainStageEvidencePolicy() { }
static Selection normalize(Selection value){
if(value==null||value.scope()==null||value.references()==null||value.references().size()>20)throw invalid();var s=value.scope();
if(s.projectRef()!=null&&!s.projectRef().isBlank())throw ChainMetricDomainException.validation("原链路页面未应用项目过滤,本项不接受非空项目范围");
if(s.startedFrom()==null||s.startedTo()==null||!s.startedFrom().isBefore(s.startedTo())||Duration.between(s.startedFrom(),s.startedTo()).compareTo(Duration.ofDays(31))>0)throw invalid();
String source=enumeration(Source.class,s.source()),status=enumeration(Status.class,s.status());String type=s.taskType()==null||s.taskType().isBlank()?null:s.taskType().trim();
if(type!=null&&(type.length()>32||type.chars().anyMatch(Character::isISOControl)))throw invalid();
var refs=new ArrayList<Reference>();var seen=new HashSet<String>();
for(var r:value.references()){if(r==null||!seen.add(r.runId())||r.fingerprint()==null||!r.fingerprint().matches("[a-f0-9]{64}"))throw invalid();id(r.runId());refs.add(r);}
refs.sort(Comparator.comparingLong(r->id(r.runId())));
return new Selection(new Scope(source,status,null,type,s.startedFrom(),s.startedTo()),List.copyOf(refs));
}
static boolean supported(Scope s){return s.source()==null||"M2_GOLDEN".equals(s.source());}
static long id(String value){try{long id=Long.parseLong(value);if(id>0&&Long.toString(id).equals(value))return id;}catch(RuntimeException ignored){}throw invalid();}
private static <T extends Enum<T>> String enumeration(Class<T> type,String value){if(value==null||value.isBlank())return null;try{return Enum.valueOf(type,value.trim().toUpperCase(Locale.ROOT)).name();}catch(RuntimeException ignored){throw invalid();}}
static ChainMetricDomainException invalid(){return ChainMetricDomainException.validation("请选择当前已应用窗口中至多20个明确运行引用");}
static ChainMetricDomainException changed(){return ChainMetricDomainException.validation("所选窗口、运行或权限已变化,请重新读取阶段依据");}
}

某些文件未显示,因为此 diff 中更改的文件太多 显示更多